text
string
size
int64
token_count
int64
#include "Epoll.h" #include <assert.h> #include <errno.h> #include <netinet/in.h> #include <string.h> #include <sys/epoll.h> #include <sys/socket.h> #include <deque> #include <queue> #include "utils/SocketUtils.h" #include "utils/Logging.h" #include <arpa/inet.h> #include <iostream> //typedef shared_ptr<Event> SP_Event; define in Event.h // epoll_create1(flag) // EPOLL_CLOECEC: close epollfd on exec // this epollfd will close after fork a thread and exec this thread. Epoll::Epoll() : epollFd_(epoll_create1(EPOLL_CLOEXEC)), events_(EVENTSNUM) { assert(epollFd_ > 0); } Epoll::~Epoll() {} void Epoll::epoll_add(SP_Event request, int timeout) { int fd = request->getFd(); if (timeout > 0) { add_timer(request, timeout); fd2http_[fd] = request->getHttpHolder(); } struct epoll_event event; event.data.fd = fd; event.events = request->getEvents(); request->EqualAndUpdateLastEvents(); fd2event_[fd] = request; if (epoll_ctl(epollFd_, EPOLL_CTL_ADD, fd, &event) < 0) { perror("epoll_add error"); fd2event_[fd].reset(); } } void Epoll::epoll_mod(SP_Event request, int timeout) { if (timeout > 0) add_timer(request, timeout); int fd = request->getFd(); if (!request->EqualAndUpdateLastEvents()) { struct epoll_event event; event.data.fd = fd; event.events = request->getEvents(); if (epoll_ctl(epollFd_, EPOLL_CTL_MOD, fd, &event) < 0){ perror("epoll_mod error"); fd2event_[fd].reset(); } } } void Epoll::epoll_del(SP_Event request) { int fd = request->getFd(); struct epoll_event event; event.data.fd = fd; event.events = request->getLastEvents(); if (epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, &event) < 0) { perror("epoll_del error"); } fd2event_[fd].reset(); fd2http_[fd].reset(); } std::vector<SP_Event> Epoll::exec_epoll_wait() { while (true) { // std::vector's iterator is pointer int event_count = epoll_wait(epollFd_, &*events_.begin(), events_.size(), EPOLLWAIT_TIME); if (event_count < 0) perror("epoll wait error"); std::vector<SP_Event> req_data = getEventsRequest(event_count); if (req_data.size() > 0) return req_data; } } void Epoll::handleExpired() { timerManager_.handleExpiredEvent(); } std::vector<SP_Event> Epoll::getEventsRequest(int events_num) { std::vector<SP_Event> req_data; for (int i = 0; i < events_num; ++i) { // get fd which has a event create int fd = events_[i].data.fd; SP_Event cur_req = fd2event_[fd]; if (cur_req) { cur_req->setRevents(events_[i].events); cur_req->setEvents(0); req_data.push_back(cur_req); } else { LOG << "SP cur_req is invalid"; } } return req_data; } void Epoll::add_timer(SP_Event request_data, int timeout) { std::shared_ptr<HttpData> t = request_data->getHttpHolder(); if (t) timerManager_.addTimer(t, timeout); else LOG << "timer add fail"; }
2,813
1,188
#include"../localedef.h" namespace fast_io_i18n { namespace { inline constexpr std::size_t monetary_mon_grouping_storage[]{3}; inline constexpr lc_all lc_all_global{.identification={.title=tsc("Slovenian locale for Slovenia"),.source=tsc("USM//MZT\t\t;\t\tfast_io"),.address=tsc("Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc("fast_io"),.email=tsc("bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(""),.fax=tsc(""),.language=tsc("Slovenian"),.territory=tsc("Slovenia"),.revision=tsc("1.0"),.date=tsc("2000-06-29")},.monetary={.int_curr_symbol=tsc("EUR "),.currency_symbol=tsc("€"),.mon_decimal_point=tsc(","),.mon_thousands_sep=tsc("."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(""),.negative_sign=tsc("-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(","),.thousands_sep=tsc(".")},.time={.abday={tsc("ned"),tsc("pon"),tsc("tor"),tsc("sre"),tsc("čet"),tsc("pet"),tsc("sob")},.day={tsc("nedelja"),tsc("ponedeljek"),tsc("torek"),tsc("sreda"),tsc("četrtek"),tsc("petek"),tsc("sobota")},.abmon={tsc("jan"),tsc("feb"),tsc("mar"),tsc("apr"),tsc("maj"),tsc("jun"),tsc("jul"),tsc("avg"),tsc("sep"),tsc("okt"),tsc("nov"),tsc("dec")},.mon={tsc("januar"),tsc("februar"),tsc("marec"),tsc("april"),tsc("maj"),tsc("junij"),tsc("julij"),tsc("avgust"),tsc("september"),tsc("oktober"),tsc("november"),tsc("december")},.d_t_fmt=tsc("%a %d %b %Y %T"),.d_fmt=tsc("%d. %m. %Y"),.t_fmt=tsc("%T"),.t_fmt_ampm=tsc(""),.date_fmt=tsc("%a %d %b %Y %T %Z"),.am_pm={tsc(""),tsc("")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc("^[+1YyJj]"),.noexpr=tsc("^[-0Nn]"),.yesstr=tsc("da"),.nostr=tsc("ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc("+%c %a %l"),.int_select=tsc("00"),.int_prefix=tsc("386")},.name={.name_fmt=tsc("%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc("%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc("Slovenija"),.country_ab2=tsc("SI"),.country_ab3=tsc("SVN"),.country_num=705,.country_car=tsc("SLO"),.lang_name=tsc("slovenščina"),.lang_ab=tsc("sl"),.lang_term=tsc("slv"),.lang_lib=tsc("slv")},.measurement={.measurement=1}}; inline constexpr wlc_all wlc_all_global{.identification={.title=tsc(L"Slovenian locale for Slovenia"),.source=tsc(L"USM//MZT\t\t;\t\tfast_io"),.address=tsc(L"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(L"fast_io"),.email=tsc(L"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(L""),.fax=tsc(L""),.language=tsc(L"Slovenian"),.territory=tsc(L"Slovenia"),.revision=tsc(L"1.0"),.date=tsc(L"2000-06-29")},.monetary={.int_curr_symbol=tsc(L"EUR "),.currency_symbol=tsc(L"€"),.mon_decimal_point=tsc(L","),.mon_thousands_sep=tsc(L"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(L""),.negative_sign=tsc(L"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(L","),.thousands_sep=tsc(L".")},.time={.abday={tsc(L"ned"),tsc(L"pon"),tsc(L"tor"),tsc(L"sre"),tsc(L"čet"),tsc(L"pet"),tsc(L"sob")},.day={tsc(L"nedelja"),tsc(L"ponedeljek"),tsc(L"torek"),tsc(L"sreda"),tsc(L"četrtek"),tsc(L"petek"),tsc(L"sobota")},.abmon={tsc(L"jan"),tsc(L"feb"),tsc(L"mar"),tsc(L"apr"),tsc(L"maj"),tsc(L"jun"),tsc(L"jul"),tsc(L"avg"),tsc(L"sep"),tsc(L"okt"),tsc(L"nov"),tsc(L"dec")},.mon={tsc(L"januar"),tsc(L"februar"),tsc(L"marec"),tsc(L"april"),tsc(L"maj"),tsc(L"junij"),tsc(L"julij"),tsc(L"avgust"),tsc(L"september"),tsc(L"oktober"),tsc(L"november"),tsc(L"december")},.d_t_fmt=tsc(L"%a %d %b %Y %T"),.d_fmt=tsc(L"%d. %m. %Y"),.t_fmt=tsc(L"%T"),.t_fmt_ampm=tsc(L""),.date_fmt=tsc(L"%a %d %b %Y %T %Z"),.am_pm={tsc(L""),tsc(L"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(L"^[+1YyJj]"),.noexpr=tsc(L"^[-0Nn]"),.yesstr=tsc(L"da"),.nostr=tsc(L"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(L"+%c %a %l"),.int_select=tsc(L"00"),.int_prefix=tsc(L"386")},.name={.name_fmt=tsc(L"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(L"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(L"Slovenija"),.country_ab2=tsc(L"SI"),.country_ab3=tsc(L"SVN"),.country_num=705,.country_car=tsc(L"SLO"),.lang_name=tsc(L"slovenščina"),.lang_ab=tsc(L"sl"),.lang_term=tsc(L"slv"),.lang_lib=tsc(L"slv")},.measurement={.measurement=1}}; inline constexpr u8lc_all u8lc_all_global{.identification={.title=tsc(u8"Slovenian locale for Slovenia"),.source=tsc(u8"USM//MZT\t\t;\t\tfast_io"),.address=tsc(u8"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(u8"fast_io"),.email=tsc(u8"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(u8""),.fax=tsc(u8""),.language=tsc(u8"Slovenian"),.territory=tsc(u8"Slovenia"),.revision=tsc(u8"1.0"),.date=tsc(u8"2000-06-29")},.monetary={.int_curr_symbol=tsc(u8"EUR "),.currency_symbol=tsc(u8"€"),.mon_decimal_point=tsc(u8","),.mon_thousands_sep=tsc(u8"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(u8""),.negative_sign=tsc(u8"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u8","),.thousands_sep=tsc(u8".")},.time={.abday={tsc(u8"ned"),tsc(u8"pon"),tsc(u8"tor"),tsc(u8"sre"),tsc(u8"čet"),tsc(u8"pet"),tsc(u8"sob")},.day={tsc(u8"nedelja"),tsc(u8"ponedeljek"),tsc(u8"torek"),tsc(u8"sreda"),tsc(u8"četrtek"),tsc(u8"petek"),tsc(u8"sobota")},.abmon={tsc(u8"jan"),tsc(u8"feb"),tsc(u8"mar"),tsc(u8"apr"),tsc(u8"maj"),tsc(u8"jun"),tsc(u8"jul"),tsc(u8"avg"),tsc(u8"sep"),tsc(u8"okt"),tsc(u8"nov"),tsc(u8"dec")},.mon={tsc(u8"januar"),tsc(u8"februar"),tsc(u8"marec"),tsc(u8"april"),tsc(u8"maj"),tsc(u8"junij"),tsc(u8"julij"),tsc(u8"avgust"),tsc(u8"september"),tsc(u8"oktober"),tsc(u8"november"),tsc(u8"december")},.d_t_fmt=tsc(u8"%a %d %b %Y %T"),.d_fmt=tsc(u8"%d. %m. %Y"),.t_fmt=tsc(u8"%T"),.t_fmt_ampm=tsc(u8""),.date_fmt=tsc(u8"%a %d %b %Y %T %Z"),.am_pm={tsc(u8""),tsc(u8"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(u8"^[+1YyJj]"),.noexpr=tsc(u8"^[-0Nn]"),.yesstr=tsc(u8"da"),.nostr=tsc(u8"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u8"+%c %a %l"),.int_select=tsc(u8"00"),.int_prefix=tsc(u8"386")},.name={.name_fmt=tsc(u8"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(u8"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(u8"Slovenija"),.country_ab2=tsc(u8"SI"),.country_ab3=tsc(u8"SVN"),.country_num=705,.country_car=tsc(u8"SLO"),.lang_name=tsc(u8"slovenščina"),.lang_ab=tsc(u8"sl"),.lang_term=tsc(u8"slv"),.lang_lib=tsc(u8"slv")},.measurement={.measurement=1}}; inline constexpr u16lc_all u16lc_all_global{.identification={.title=tsc(u"Slovenian locale for Slovenia"),.source=tsc(u"USM//MZT\t\t;\t\tfast_io"),.address=tsc(u"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(u"fast_io"),.email=tsc(u"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(u""),.fax=tsc(u""),.language=tsc(u"Slovenian"),.territory=tsc(u"Slovenia"),.revision=tsc(u"1.0"),.date=tsc(u"2000-06-29")},.monetary={.int_curr_symbol=tsc(u"EUR "),.currency_symbol=tsc(u"€"),.mon_decimal_point=tsc(u","),.mon_thousands_sep=tsc(u"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(u""),.negative_sign=tsc(u"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u","),.thousands_sep=tsc(u".")},.time={.abday={tsc(u"ned"),tsc(u"pon"),tsc(u"tor"),tsc(u"sre"),tsc(u"čet"),tsc(u"pet"),tsc(u"sob")},.day={tsc(u"nedelja"),tsc(u"ponedeljek"),tsc(u"torek"),tsc(u"sreda"),tsc(u"četrtek"),tsc(u"petek"),tsc(u"sobota")},.abmon={tsc(u"jan"),tsc(u"feb"),tsc(u"mar"),tsc(u"apr"),tsc(u"maj"),tsc(u"jun"),tsc(u"jul"),tsc(u"avg"),tsc(u"sep"),tsc(u"okt"),tsc(u"nov"),tsc(u"dec")},.mon={tsc(u"januar"),tsc(u"februar"),tsc(u"marec"),tsc(u"april"),tsc(u"maj"),tsc(u"junij"),tsc(u"julij"),tsc(u"avgust"),tsc(u"september"),tsc(u"oktober"),tsc(u"november"),tsc(u"december")},.d_t_fmt=tsc(u"%a %d %b %Y %T"),.d_fmt=tsc(u"%d. %m. %Y"),.t_fmt=tsc(u"%T"),.t_fmt_ampm=tsc(u""),.date_fmt=tsc(u"%a %d %b %Y %T %Z"),.am_pm={tsc(u""),tsc(u"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(u"^[+1YyJj]"),.noexpr=tsc(u"^[-0Nn]"),.yesstr=tsc(u"da"),.nostr=tsc(u"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u"+%c %a %l"),.int_select=tsc(u"00"),.int_prefix=tsc(u"386")},.name={.name_fmt=tsc(u"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(u"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(u"Slovenija"),.country_ab2=tsc(u"SI"),.country_ab3=tsc(u"SVN"),.country_num=705,.country_car=tsc(u"SLO"),.lang_name=tsc(u"slovenščina"),.lang_ab=tsc(u"sl"),.lang_term=tsc(u"slv"),.lang_lib=tsc(u"slv")},.measurement={.measurement=1}}; inline constexpr u32lc_all u32lc_all_global{.identification={.title=tsc(U"Slovenian locale for Slovenia"),.source=tsc(U"USM//MZT\t\t;\t\tfast_io"),.address=tsc(U"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(U"fast_io"),.email=tsc(U"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(U""),.fax=tsc(U""),.language=tsc(U"Slovenian"),.territory=tsc(U"Slovenia"),.revision=tsc(U"1.0"),.date=tsc(U"2000-06-29")},.monetary={.int_curr_symbol=tsc(U"EUR "),.currency_symbol=tsc(U"€"),.mon_decimal_point=tsc(U","),.mon_thousands_sep=tsc(U"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(U""),.negative_sign=tsc(U"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(U","),.thousands_sep=tsc(U".")},.time={.abday={tsc(U"ned"),tsc(U"pon"),tsc(U"tor"),tsc(U"sre"),tsc(U"čet"),tsc(U"pet"),tsc(U"sob")},.day={tsc(U"nedelja"),tsc(U"ponedeljek"),tsc(U"torek"),tsc(U"sreda"),tsc(U"četrtek"),tsc(U"petek"),tsc(U"sobota")},.abmon={tsc(U"jan"),tsc(U"feb"),tsc(U"mar"),tsc(U"apr"),tsc(U"maj"),tsc(U"jun"),tsc(U"jul"),tsc(U"avg"),tsc(U"sep"),tsc(U"okt"),tsc(U"nov"),tsc(U"dec")},.mon={tsc(U"januar"),tsc(U"februar"),tsc(U"marec"),tsc(U"april"),tsc(U"maj"),tsc(U"junij"),tsc(U"julij"),tsc(U"avgust"),tsc(U"september"),tsc(U"oktober"),tsc(U"november"),tsc(U"december")},.d_t_fmt=tsc(U"%a %d %b %Y %T"),.d_fmt=tsc(U"%d. %m. %Y"),.t_fmt=tsc(U"%T"),.t_fmt_ampm=tsc(U""),.date_fmt=tsc(U"%a %d %b %Y %T %Z"),.am_pm={tsc(U""),tsc(U"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(U"^[+1YyJj]"),.noexpr=tsc(U"^[-0Nn]"),.yesstr=tsc(U"da"),.nostr=tsc(U"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(U"+%c %a %l"),.int_select=tsc(U"00"),.int_prefix=tsc(U"386")},.name={.name_fmt=tsc(U"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(U"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(U"Slovenija"),.country_ab2=tsc(U"SI"),.country_ab3=tsc(U"SVN"),.country_num=705,.country_car=tsc(U"SLO"),.lang_name=tsc(U"slovenščina"),.lang_ab=tsc(U"sl"),.lang_term=tsc(U"slv"),.lang_lib=tsc(U"slv")},.measurement={.measurement=1}}; } } #include"../main.h"
11,238
6,185
#include "LitesqlMethodPanel.h" #include "objectmodel.hpp" using namespace xml; LitesqlMethodPanel::LitesqlMethodPanel( wxWindow* parent , Method::Ptr& pMethod) : MethodPanel( parent ), m_pMethod(pMethod) { m_textCtrlName->SetValidator(StdStringValidator(wxFILTER_ALPHANUMERIC,&m_pMethod->name)); }
303
111
// // Created by daniel on 24.09.21. // #include "items.hpp" namespace items { Listbox::Item create_inventory_item(INVENTORY_ITEM item_type) { Listbox::Item item; switch (item_type) { case INVENTORY_ITEM::GATE_PART: item = create_gate_part(INVENTORY_ITEM::GATE_PART); break; case INVENTORY_ITEM::APPLE: item = create_apple(INVENTORY_ITEM::APPLE); break; case INVENTORY_ITEM::CARROT: item = create_carrot(INVENTORY_ITEM::CARROT); break; case INVENTORY_ITEM::CARROT_SEED: item = create_carrot_seed(INVENTORY_ITEM::CARROT_SEED); break; case INVENTORY_ITEM::INVENTORY_BACK: item = create_back_entry(INVENTORY_ITEM::INVENTORY_BACK); break; } return item; } Listbox::Item create_sidemenu_item(SIDEMENU_ITEM item_type, uint8_t save_id) { Listbox::Item item; switch (item_type) { case SIDEMENU_ITEM::INVENTORY: item = create_inventory_entry(SIDEMENU_ITEM::INVENTORY); break; case SIDEMENU_ITEM::GEAR: item = create_gear_entry(SIDEMENU_ITEM::GEAR); break; case SIDEMENU_ITEM::SAVE: item = create_save_entry(SIDEMENU_ITEM::SAVE, save_id); break; case SIDEMENU_ITEM::SIDEMENU_OPTIONS: item = create_options_entry(SIDEMENU_ITEM::SIDEMENU_BACK, save_id); break; case SIDEMENU_ITEM::SIDEMENU_BACK: item = create_back_entry(SIDEMENU_ITEM::SIDEMENU_BACK); break; case SIDEMENU_ITEM::QUIT: item = create_quit_entry(SIDEMENU_ITEM::QUIT); break; } return item; } Listbox::Item create_menu_item(MENU_ITEM item_type, uint8_t save_id) { std::string save_id_str = std::to_string(save_id); Listbox::Item item; switch (item_type) { case MENU_ITEM::LOAD_SAVE: item = create_load_entry(MENU_ITEM::LOAD_SAVE, save_id); break; case MENU_ITEM::NEW_SAVE: item = create_new_save_entry(MENU_ITEM::NEW_SAVE, save_id); break; case MENU_ITEM::MENU_OPTIONS: item = create_options_entry(MENU_ITEM::MENU_OPTIONS); break; } return item; } Listbox::Item create_options_item(OPTIONS_ITEM item_type, uint8_t save_id) { Listbox::Item item; switch (item_type) { case OPTIONS_ITEM::SHOW_FPS: item = create_show_fps_entry(OPTIONS_ITEM::SHOW_FPS); break; case OPTIONS_ITEM::SHOW_TIME: item = create_show_time_entry(OPTIONS_ITEM::SHOW_TIME); break; case OPTIONS_ITEM::OPTIONS_BACK: item = create_options_exit_entry(OPTIONS_ITEM::OPTIONS_BACK, save_id); break; case RESET_ALL: item = create_reset_all_entries(OPTIONS_ITEM::RESET_ALL); break; } return item; } Listbox::Item create_combat_item(COMBAT_ITEM item_type, uint8_t save_id, combat::Player *player, combat::Enemy *enemy) { Listbox::Item item; switch (item_type) { case COMBAT_ITEM::ESCAPE: item = create_combat_escape(item_type, save_id); break; case ATTACK_SWORD: item = create_combat_attack_sword(item_type, player, enemy); break; case ATTACK_SPEAR: item = create_combat_attack_spear(item_type, player, enemy); break; case ATTACK_ARROW: item = create_combat_attack_arrow(item_type, player, enemy); break; case ATTACK_DAGGER: item = create_combat_attack_dagger(item_type, player, enemy); break; case ATTACK_MAGIC: item = create_combat_attack_magic(item_type, player, enemy); break; case ATTACK_FIRE: item = create_combat_attack_fire(item_type, player, enemy); break; case ATTACK_ICE: item = create_combat_attack_ice(item_type, player, enemy); break; case ATTACK_SHOCK: item = create_combat_attack_shock(item_type, player, enemy); break; } return item; } Listbox::Item create_gear_item(GEAR_TYPE item_type) { Listbox::Item item; switch (item_type) { case GEAR_SWORD: item = create_gear_sword(item_type); break; case GEAR_SPEAR: item = create_gear_spear(item_type); break; case GEAR_ARROW: item = create_gear_arrow(item_type); break; case GEAR_DAGGER: item = create_gear_dagger(item_type); break; case GEAR_MAGIC: item = create_gear_magic(item_type); break; case GEAR_FIRE: item = create_gear_fire(item_type); break; case GEAR_ICE: item = create_gear_ice(item_type); break; case GEAR_SHOCK: item = create_gear_shock(item_type); break; case GEAR_NAVIGATE_BACK: item = create_back_entry(item_type); break; default: break; } return item; } Listbox::Item create_shop_item(SHOP_ITEM item_type) { Listbox::Item item; switch (item_type) { case SHOP_APPLE: item = create_shop_apple(item_type); break; case SHOP_CARROT: item = create_shop_carrot(item_type); break; case SHOP_CARROT_SEED: item = create_shop_carrot_seed(item_type); break; case SHOP_SWORD: item = create_shop_sword(item_type); break; case SHOP_DAGGER: item = create_shop_dagger(item_type); break; case SHOP_ARROW: item = create_shop_arrow(item_type); break; case SHOP_SPEAR: item = create_shop_spear(item_type); break; case SHOP_BACK: item = create_back_entry(item_type); break; } return item; } }
5,145
2,525
// // ulib - a collection of useful classes // Copyright (C) 2008-2014,2017 Michael Fink // /// \file FileFinder.cpp File finder // // includes #include "stdafx.h" #include <ulib/FileFinder.hpp> #include <ulib/Path.hpp> std::vector<CString> FileFinder::FindAllInPath(const CString& path, const CString& fileSpec, bool findFolders, bool recursive) { std::vector<CString> filenamesList; FileFinder finder(path, fileSpec); if (finder.IsValid()) { do { if (finder.IsDot()) continue; if (recursive && finder.IsFolder()) { std::vector<CString> subfolderFilenamesList = FindAllInPath(finder.Filename(), fileSpec, findFolders, true); if (!subfolderFilenamesList.empty()) filenamesList.insert(filenamesList.end(), subfolderFilenamesList.begin(), subfolderFilenamesList.end()); } if (findFolders && finder.IsFile()) continue; if (!findFolders && finder.IsFolder()) continue; filenamesList.push_back(finder.Filename()); } while (finder.Next()); } return filenamesList; }
1,159
386
/* test4014.SysFile.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: HCore Mini // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/test/test.h> #include <CCore/inc/sys/SysFile.h> namespace App { namespace Private_4014 { /* class File */ class File : NoCopy { Sys::File file; bool ok; public: File() : ok(false) {} void open(StrLen file_name,FileOpenFlags oflags) { if( ok ) return; FileError fe=file.open(file_name,oflags); Printf(Con,"open(#.q;,#;) : #;\n",file_name,oflags,fe); ok=!fe; } void close(bool preserve_file=false) { if( !ok ) return; FileMultiError errout; file.close(errout,preserve_file); Printf(Con,"close(#;) : #;\n",preserve_file,errout); ok=false; } ulen write(const uint8 *buf,ulen len) { if( !ok ) return 0; auto result=file.write(buf,len); Printf(Con,"write(...,#;) : #; #;\n",len,result.error,result.len); return result.len; } ulen read(uint8 *buf,ulen len) { if( !ok ) return 0; auto result=file.read(buf,len); Printf(Con,"read(...,#;) : #; #;\n",len,result.error,result.len); return result.len; } FilePosType getLen() { if( !ok ) return 0; auto result=file.getLen(); Printf(Con,"getLen() : #; #;\n",result.error,result.pos); return result.pos; } FilePosType getPos() { if( !ok ) return 0; auto result=file.getPos(); Printf(Con,"getPos() : #; #;\n",result.error,result.pos); return result.pos; } void setPos(FilePosType pos) { if( !ok ) return; FileError fe=file.setPos(pos); Printf(Con,"setPos(#;) : #;\n",pos,fe); } }; /* test1() */ void test1() { File file; // 1 file.open("not_exist.txt",Open_Read); file.open("z:not_exist.txt",Open_Read); file.open("no_write.txt",Open_Write); file.open("no_write.txt",Open_Read); file.close(); // 2 file.open("no_read.txt",Open_Read); file.open("no_read.txt",Open_Write); file.close(); // 3 file.open("temp.txt",Open_Write|Open_AutoDelete|Open_New); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Pos); file.getLen(); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Erase); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Erase|Open_Pos); file.getLen(); file.close(); // 4 const ulen Len = 100 ; uint8 buf[Len]; Range(buf).set('1'); // 5 file.open("temp_saved.txt",Open_Write|Open_New); file.close(); file.open("temp_saved.txt",Open_Write|Open_Pos); file.write(buf,Len); file.getLen(); file.close(); file.open("temp_saved.txt",Open_Write|Open_Create|Open_Pos); file.getLen(); file.close(); file.open("temp_saved.txt",Open_Write|Open_Erase|Open_Pos); file.getLen(); file.write(buf,Len); file.close(); file.open("temp_saved.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Erase|Open_Pos); file.getLen(); file.close(true); } /* test2() */ void test2() { const ulen WLen = 100 ; const ulen RLen = 200 ; uint8 wbuf[WLen]; uint8 rbuf[RLen]; Range(wbuf).set('1'); // file File file; file.open("temp.txt",Open_AutoDelete); file.close(); file.open("temp.txt",Open_Create|Open_Write); file.write(wbuf,WLen); file.read(rbuf,RLen); file.setPos(WLen/2); file.close(); file.open("temp.txt",Open_Read); file.read(rbuf,RLen); if( !Range(wbuf).equal(Range(rbuf,WLen)) ) Printf(Con,"not equal\n"); file.close(); } /* test3() */ void test3() { const ulen WLen = 100 ; uint8 wbuf[WLen]; Range(wbuf).set('1'); // file File file; file.open("temp.txt",Open_ToWrite|Open_Pos|Open_AutoDelete); file.write(wbuf,WLen); file.getLen(); file.setPos(WLen/2); file.getPos(); file.setPos(WLen); file.getPos(); file.setPos(0); file.getPos(); file.close(); } } // namespace Private_4014 using namespace Private_4014; /* Testit<4014> */ template<> const char *const Testit<4014>::Name="Test4014 SysFile"; template<> bool Testit<4014>::Main() { test1(); test2(); test3(); return true; } } // namespace App
4,657
1,911
#include <algorithm> #include <regex> #include <sstream> #include <string> #include <net/if.h> #include "logger.h" #include "producerstatetable.h" #include "macaddress.h" #include "vxlanmgr.h" #include "exec.h" #include "tokenize.h" #include "shellcmd.h" #include "warm_restart.h" using namespace std; using namespace swss; // Fields name #define VXLAN_TUNNEL "vxlan_tunnel" #define SOURCE_IP "src_ip" #define VNI "vni" #define VNET "vnet" #define VXLAN "vxlan" #define VXLAN_IF "vxlan_if" #define VXLAN_NAME_PREFIX "Vxlan" #define VXLAN_IF_NAME_PREFIX "Brvxlan" static std::string getVxlanName(const swss::VxlanMgr::VxlanInfo & info) { return std::string("") + VXLAN_NAME_PREFIX + info.m_vni; } static std::string getVxlanIfName(const swss::VxlanMgr::VxlanInfo & info) { return std::string("") + VXLAN_IF_NAME_PREFIX + info.m_vni; } // Commands #define RET_SUCCESS 0 #define EXECUTE(CMD, RESULT) swss::exec(std::string() + BASH_CMD + " -c \"" + CMD + "\"", RESULT); static int cmdCreateVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link add {{VXLAN}} type vxlan id {{VNI}} [local {{SOURCE IP}}] dstport 4789 const std::string cmd = std::string("") + IP_CMD " link add " + info.m_vxlan + " type vxlan id " + info.m_vni + " " + (info.m_sourceIp.empty() ? "" : (" local " + info.m_sourceIp)) + " dstport 4789"; return EXECUTE(cmd, res); } static int cmdUpVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN}} up const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlan + " up"; return EXECUTE(cmd, res); } static int cmdCreateVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link add {{VXLAN_IF}} type bridge const std::string cmd = std::string("") + IP_CMD " link add " + info.m_vxlanIf + " type bridge"; return EXECUTE(cmd, res); } static int cmdAddVxlanIntoVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // brctl addif {{VXLAN_IF}} {{VXLAN}} const std::string cmd = std::string("") + BRCTL_CMD " addif " + info.m_vxlanIf + " " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdAttachVxlanIfToVnet(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} master {{VNET}} const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " master " + info.m_vnet; return EXECUTE(cmd, res); } static int cmdUpVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} up const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " up"; return EXECUTE(cmd, res); } static int cmdDeleteVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link del dev {{VXLAN}} const std::string cmd = std::string("") + IP_CMD " link del dev " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdDeleteVxlanFromVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // brctl delif {{VXLAN_IF}} {{VXLAN}} const std::string cmd = std::string("") + BRCTL_CMD " delif " + info.m_vxlanIf + " " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdDeleteVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link del {{VXLAN_IF}} const std::string cmd = std::string("") + IP_CMD " link del " + info.m_vxlanIf; return EXECUTE(cmd, res); } static int cmdDetachVxlanIfFromVnet(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} nomaster const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " nomaster"; return EXECUTE(cmd, res); } // Vxlanmgr VxlanMgr::VxlanMgr(DBConnector *cfgDb, DBConnector *appDb, DBConnector *stateDb, const vector<std::string> &tables) : Orch(cfgDb, tables), m_appVxlanTunnelTable(appDb, APP_VXLAN_TUNNEL_TABLE_NAME), m_appVxlanTunnelMapTable(appDb, APP_VXLAN_TUNNEL_MAP_TABLE_NAME), m_cfgVxlanTunnelTable(cfgDb, CFG_VXLAN_TUNNEL_TABLE_NAME), m_cfgVnetTable(cfgDb, CFG_VNET_TABLE_NAME), m_stateVrfTable(stateDb, STATE_VRF_TABLE_NAME), m_stateVxlanTable(stateDb, STATE_VXLAN_TABLE_NAME) { // Clear old vxlan devices that were created at last time. clearAllVxlanDevices(); } VxlanMgr::~VxlanMgr() { clearAllVxlanDevices(); } void VxlanMgr::doTask(Consumer &consumer) { SWSS_LOG_ENTER(); const string & table_name = consumer.getTableName(); auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { bool task_result = false; auto t = it->second; const std::string & op = kfvOp(t); if (op == SET_COMMAND) { if (table_name == CFG_VNET_TABLE_NAME) { task_result = doVxlanCreateTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_TABLE_NAME) { task_result = doVxlanTunnelCreateTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_MAP_TABLE_NAME) { task_result = doVxlanTunnelMapCreateTask(t); } else { SWSS_LOG_ERROR("Unknown table : %s", table_name.c_str()); } } else if (op == DEL_COMMAND) { if (table_name == CFG_VNET_TABLE_NAME) { task_result = doVxlanDeleteTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_TABLE_NAME) { task_result = doVxlanTunnelDeleteTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_MAP_TABLE_NAME) { task_result = doVxlanTunnelMapDeleteTask(t); } else { SWSS_LOG_ERROR("Unknown table : %s", table_name.c_str()); } } else { SWSS_LOG_ERROR("Unknown command : %s", op.c_str()); } if (task_result == true) { it = consumer.m_toSync.erase(it); } else { ++it; } } } bool VxlanMgr::doVxlanCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); VxlanInfo info; info.m_vnet = kfvKey(t); for (auto i : kfvFieldsValues(t)) { const std::string & field = fvField(i); const std::string & value = fvValue(i); if (field == VXLAN_TUNNEL) { info.m_vxlanTunnel = value; } else if (field == VNI) { info.m_vni = value; } } // If all information of vnet has been set if (info.m_vxlanTunnel.empty() || info.m_vni.empty()) { SWSS_LOG_DEBUG("Vnet %s information is incomplete", info.m_vnet.c_str()); // if the information is incomplete, just ignore this message // because all information will be sent if the information was // completely set. return true; } // If the vxlan tunnel has been created auto it = m_vxlanTunnelCache.find(info.m_vxlanTunnel); if (it == m_vxlanTunnelCache.end()) { SWSS_LOG_DEBUG("Vxlan tunnel %s has not been created", info.m_vxlanTunnel.c_str()); // Suspend this message util the vxlan tunnel is created return false; } // If the VRF(Vnet is a special VRF) has been created if (!isVrfStateOk(info.m_vnet)) { SWSS_LOG_DEBUG("Vrf %s has not been created", info.m_vnet.c_str()); // Suspend this message util the vrf is created return false; } auto sourceIp = std::find_if( it->second.begin(), it->second.end(), [](const FieldValueTuple & fvt){ return fvt.first == SOURCE_IP; }); if (sourceIp != it->second.end()) { info.m_sourceIp = sourceIp->second; } info.m_vxlan = getVxlanName(info); info.m_vxlanIf = getVxlanIfName(info); // If this vxlan has been created if (isVxlanStateOk(info.m_vxlan)) { // Because the vxlan has been create, so this message is to update // the information of vxlan. // This program just delete the old vxlan and create a new one // according to this message. doVxlanDeleteTask(t); } if (!createVxlan(info)) { SWSS_LOG_ERROR("Cannot create vxlan %s", info.m_vxlan.c_str()); return true; } m_vnetCache[info.m_vnet] = info; SWSS_LOG_INFO("Create vxlan %s", info.m_vxlan.c_str()); return true; } bool VxlanMgr::doVxlanDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vnetName = kfvKey(t); auto it = m_vnetCache.find(vnetName); if (it == m_vnetCache.end()) { SWSS_LOG_WARN("Vxlan(Vnet %s) hasn't been created ", vnetName.c_str()); return true; } const VxlanInfo & info = it->second; if (isVxlanStateOk(info.m_vxlan)) { if ( ! deleteVxlan(info)) { SWSS_LOG_ERROR("Cannot delete vxlan %s", info.m_vxlan.c_str()); return false; } } else { SWSS_LOG_WARN("Vxlan %s hasn't been created ", info.m_vxlan.c_str()); } m_vnetCache.erase(it); SWSS_LOG_INFO("Delete vxlan %s", info.m_vxlan.c_str()); return true; } bool VxlanMgr::doVxlanTunnelCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vxlanTunnelName = kfvKey(t); m_appVxlanTunnelTable.set(vxlanTunnelName, kfvFieldsValues(t)); // Update vxlan tunnel cache m_vxlanTunnelCache[vxlanTunnelName] = kfvFieldsValues(t); SWSS_LOG_INFO("Create vxlan tunnel %s", vxlanTunnelName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vxlanTunnelName = kfvKey(t); m_appVxlanTunnelTable.del(vxlanTunnelName); auto it = m_vxlanTunnelCache.find(vxlanTunnelName); if (it != m_vxlanTunnelCache.end()) { m_vxlanTunnelCache.erase(it); } SWSS_LOG_INFO("Delete vxlan tunnel %s", vxlanTunnelName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelMapCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); std::string vxlanTunnelMapName = kfvKey(t); std::replace(vxlanTunnelMapName.begin(), vxlanTunnelMapName.end(), config_db_key_delimiter, delimiter); m_appVxlanTunnelMapTable.set(vxlanTunnelMapName, kfvFieldsValues(t)); SWSS_LOG_NOTICE("Create vxlan tunnel map %s", vxlanTunnelMapName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelMapDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); std::string vxlanTunnelMapName = kfvKey(t); std::replace(vxlanTunnelMapName.begin(), vxlanTunnelMapName.end(), config_db_key_delimiter, delimiter); m_appVxlanTunnelMapTable.del(vxlanTunnelMapName); SWSS_LOG_NOTICE("Delete vxlan tunnel map %s", vxlanTunnelMapName.c_str()); return true; } bool VxlanMgr::isVrfStateOk(const std::string & vrfName) { SWSS_LOG_ENTER(); std::vector<FieldValueTuple> temp; if (m_stateVrfTable.get(vrfName, temp)) { SWSS_LOG_DEBUG("Vrf %s is ready", vrfName.c_str()); return true; } SWSS_LOG_DEBUG("Vrf %s is not ready", vrfName.c_str()); return false; } bool VxlanMgr::isVxlanStateOk(const std::string & vxlanName) { SWSS_LOG_ENTER(); std::vector<FieldValueTuple> temp; if (m_stateVxlanTable.get(vxlanName, temp)) { SWSS_LOG_DEBUG("Vxlan %s is ready", vxlanName.c_str()); return true; } SWSS_LOG_DEBUG("Vxlan %s is not ready", vxlanName.c_str()); return false; } bool VxlanMgr::createVxlan(const VxlanInfo & info) { SWSS_LOG_ENTER(); std::string res; int ret = 0; // Create Vxlan ret = cmdCreateVxlan(info, res); if (ret != RET_SUCCESS) { SWSS_LOG_WARN( "Failed to create vxlan %s (vni: %s, source ip %s)", info.m_vxlan.c_str(), info.m_vni.c_str(), info.m_sourceIp.c_str()); return false; } // Up Vxlan ret = cmdUpVxlan(info, res); if (ret != RET_SUCCESS) { cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to up vxlan %s", info.m_vxlan.c_str()); return false; } // Create Vxlan Interface ret = cmdCreateVxlanIf(info, res); if (ret != RET_SUCCESS) { cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to create vxlan interface %s", info.m_vxlanIf.c_str()); return false; } // Add vxlan into vxlan interface ret = cmdAddVxlanIntoVxlanIf(info, res); if ( ret != RET_SUCCESS ) { cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to add %s into %s", info.m_vxlan.c_str(), info.m_vxlanIf.c_str()); return false; } // Attach vxlan interface to vnet ret = cmdAttachVxlanIfToVnet(info, res); if ( ret != RET_SUCCESS ) { cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to set %s master %s", info.m_vxlanIf.c_str(), info.m_vnet.c_str()); return false; } // Up Vxlan Interface ret = cmdUpVxlanIf(info, res); if ( ret != RET_SUCCESS ) { cmdDetachVxlanIfFromVnet(info, res); cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to up bridge %s", info.m_vxlanIf.c_str()); return false; } std::vector<FieldValueTuple> fvVector; fvVector.emplace_back("state", "ok"); m_stateVxlanTable.set(info.m_vxlan, fvVector); return true; } bool VxlanMgr::deleteVxlan(const VxlanInfo & info) { SWSS_LOG_ENTER(); std::string res; cmdDetachVxlanIfFromVnet(info, res); cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); m_stateVxlanTable.del(info.m_vxlan); return true; } void VxlanMgr::clearAllVxlanDevices() { std::string stdout; const std::string cmd = std::string("") + IP_CMD + " link"; int ret = EXECUTE(cmd, stdout); if (ret != 0) { SWSS_LOG_ERROR("Cannot get devices by command : %s", cmd.c_str()); return; } std::regex device_name_pattern("^\\d+:\\s+([^:]+)"); std::smatch match_result; auto lines = tokenize(stdout, '\n'); for (const std::string & line : lines) { if (!std::regex_search(line, match_result, device_name_pattern)) { continue; } std::string res; std::string device_name = match_result[1]; VxlanInfo info; if (device_name.find(VXLAN_NAME_PREFIX) == 0) { info.m_vxlan = device_name; cmdDeleteVxlan(info, res); } else if (device_name.find(VXLAN_IF_NAME_PREFIX) == 0) { info.m_vxlanIf = device_name; cmdDeleteVxlanIf(info, res); } } }
15,657
5,932
/* * Copyright (c) 2019-2020, Fei Wu <f.eiwu@yahoo.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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. */ #include <AK/String.h> #include <AK/StringBuilder.h> #include <LibCore/ArgsParser.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main(int argc, char** argv) { const char* username = nullptr; bool remove_home = false; Core::ArgsParser args_parser; args_parser.add_option(remove_home, "Remove home directory", "remove", 'r'); args_parser.add_positional_argument(username, "Login user identity (username)", "login"); args_parser.parse(argc, argv); char temp_filename[] = "/etc/passwd.XXXXXX"; auto fd = mkstemp(temp_filename); if (fd == -1) { perror("failed to create temporary file"); return 1; } FILE* temp_file = fdopen(fd, "w"); if (!temp_file) { perror("fdopen"); if (unlink(temp_filename) < 0) { perror("unlink"); } return 1; } bool user_exists = false; String home_directory; int rc = 0; setpwent(); for (auto* pw = getpwent(); pw; pw = getpwent()) { if (strcmp(pw->pw_name, username)) { if (putpwent(pw, temp_file) != 0) { perror("failed to put an entry in the temporary passwd file"); rc = 1; break; } } else { user_exists = true; if (remove_home) home_directory = pw->pw_dir; } } endpwent(); if (fclose(temp_file)) { perror("fclose"); if (!rc) rc = 1; } if (rc == 0 && !user_exists) { fprintf(stderr, "specified user doesn't exist\n"); rc = 6; } if (rc == 0 && chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) { perror("chmod"); rc = 1; } if (rc == 0 && rename(temp_filename, "/etc/passwd") < 0) { perror("failed to rename the temporary passwd file"); rc = 1; } if (rc) { if (unlink(temp_filename) < 0) { perror("unlink"); } return rc; } if (remove_home) { if (home_directory == "/") { fprintf(stderr, "home directory is /, not deleted!\n"); return 12; } if (access(home_directory.characters(), F_OK) != -1) { auto child = fork(); if (child < 0) { perror("fork"); return 12; } if (!child) { int rc = execl("/bin/rm", "rm", "-r", home_directory.characters(), nullptr); ASSERT(rc < 0); perror("execl"); exit(127); } int wstatus; if (waitpid(child, &wstatus, 0) < 0) { perror("waitpid"); return 12; } if (WEXITSTATUS(wstatus)) { fprintf(stderr, "failed to remove the home directory\n"); return 12; } } } return 0; }
4,498
1,585
#include <iostream> using std::cin; using std::cout; int get_sum(int a, int b) { int n = (a < b ? b - a : a - b) + 1; return n * (a + b) / 2; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); }
228
106
#include <algorithm> #include <cstdio> #include <cstring> typedef long long ll; const int N = 1e6 + 61; int n, l, r, a[N]; ll k, c; int main() { scanf("%d%lld", &n, &k); if ((c = n * (n + 1ll) / 2) > k) return puts("-1"), 0; for (int i = 1; i <= n; i++) a[i] = i; l = 1, r = n; for (; l < r && c < k; l++, r--) { int rb = std::min((ll)r - l, k - c); std::swap(a[l], a[l + rb]), c += rb; } printf("%lld\n", c); for (int i = 1; i <= n; i++) printf("%d%c", i, " \n"[i == n]); for (int i = 1; i <= n; i++) printf("%d ", a[i]); }
539
284
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license * * Copyright (C) 2021 Elisha Riedlinger * * 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. */ #define RESHADE_FILE_LIST #include "runtime.hpp" #include "runtime_config.hpp" #include "runtime_objects.hpp" #include "Resources\sh2-enhce.h" #include <cassert> #include <fstream> #include <sstream> #include <iostream> extern DWORD GammaLevel; struct { bool loaded = false; reshade::ini_file cache; }g_ini_cache; reshade::ini_file::ini_file() { load(); } reshade::ini_file::~ini_file() {} void reshade::ini_file::load() { if (g_ini_cache.loaded) { return; } _sections.clear(); _modified = false; std::string GammaSection("[GammaLevel" + std::to_string(GammaLevel) + "]"); std::string file, section, line; g_ini_cache.loaded = read_resource(IDR_RESHADE_INI, file); std::istringstream s_file(file.c_str()); while (std::getline(s_file, line)) { trim(line); if (line.empty() || line[0] == ';' || line[0] == '/' || line[0] == '#') { continue; } if (line.compare(GammaSection) == 0) { line.assign("[" + GammaEffectName + ".fx]"); } // Read section name if (line[0] == '[') { section = trim(line.substr(0, line.find(']')), " \t[]"); continue; } // Read section content const auto assign_index = line.find('='); if (assign_index != std::string::npos) { const std::string key = trim(line.substr(0, assign_index)); const std::string value = trim(line.substr(assign_index + 1)); // Append to key if it already exists reshade::ini_file::value &elements = _sections[section][key]; for (size_t offset = 0, base = 0, len = value.size(); offset <= len;) { // Treat ",," as an escaped comma and only split on single "," const size_t found = std::min(value.find_first_of(',', offset), len); if (found + 1 < len && value[found + 1] == ',') { offset = found + 2; } else { std::string &element = elements.emplace_back(); element.reserve(found - base); while (base < found) { const char c = value[base++]; element += c; if (c == ',' && base < found && value[base] == ',') { base++; // Skip second comma in a ",," escape sequence } } base = offset = found + 1; } } } else { _sections[section].insert({ line, {} }); } } } void reshade::ini_file::reset_config() { g_ini_cache.loaded = false; g_ini_cache.cache.load(); } reshade::ini_file &reshade::ini_file::load_cache() { if (!g_ini_cache.loaded) { g_ini_cache.cache.load(); } return g_ini_cache.cache; }
3,482
1,345
class CfgVehicles { class Flag_White_F; class GVAR(Flag): Flag_White_F { author = ECSTRING(main, author); displayName = CSTRING(display); scopecurator = public; scope = public; class EventHandlers { init = QUOTE((_this select 0) setFlagTexture QUOTE(QPATHTOF(data\61stFlag.paa))); }; }; class GVAR(FlagYellow): GVAR(Flag){ displayName = CSTRING(displayYellow); class EventHandlers { init = QUOTE((_this select 0) setFlagTexture QUOTE(QPATHTOF(data\61stFlagY.paa))); }; }; };
503
213
/* * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details. * * 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 <znc/znc.h> #include <znc/User.h> using std::set; class CClientNotifyMod : public CModule { protected: CString m_sMethod; bool m_bNewOnly; bool m_bOnDisconnect; set<CString> m_sClientsSeen; void SaveSettings() { SetNV("method", m_sMethod); SetNV("newonly", m_bNewOnly ? "1" : "0"); SetNV("ondisconnect", m_bOnDisconnect ? "1" : "0"); } void SendNotification(const CString& sMessage) { if(m_sMethod == "message") { GetUser()->PutStatus(sMessage, NULL, GetClient()); } else if(m_sMethod == "notice") { GetUser()->PutStatusNotice(sMessage, NULL, GetClient()); } } public: MODCONSTRUCTOR(CClientNotifyMod) { AddHelpCommand(); AddCommand("Method", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnMethodCommand), "<message|notice|off>", "Sets the notify method"); AddCommand("NewOnly", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnNewOnlyCommand), "<on|off>", "Turns notifies for unseen IP addresses only on or off"); AddCommand("OnDisconnect", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnDisconnectCommand), "<on|off>", "Turns notifies on disconnecting clients on or off"); AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnShowCommand), "", "Show the current settings"); } bool OnLoad(const CString& sArgs, CString& sMessage) override { m_sMethod = GetNV("method"); if(m_sMethod != "notice" && m_sMethod != "message" && m_sMethod != "off") { m_sMethod = "message"; } // default = off for these: m_bNewOnly = (GetNV("newonly") == "1"); m_bOnDisconnect = (GetNV("ondisconnect") == "1"); return true; } void OnClientLogin() override { CString sRemoteIP = GetClient()->GetRemoteIP(); if(!m_bNewOnly || m_sClientsSeen.find(sRemoteIP) == m_sClientsSeen.end()) { SendNotification("Another client authenticated as your user. " "Use the 'ListClients' command to see all " + CString(GetUser()->GetAllClients().size()) + " clients."); // the set<> will automatically disregard duplicates: m_sClientsSeen.insert(sRemoteIP); } } void OnClientDisconnect() override { if(m_bOnDisconnect) { SendNotification("A client disconnected from your user. " "Use the 'ListClients' command to see the " + CString(GetUser()->GetAllClients().size()) + " remaining client(s)."); } } void OnMethodCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg != "notice" && sArg != "message" && sArg != "off") { PutModule("Usage: Method <message|notice|off>"); return; } m_sMethod = sArg; SaveSettings(); PutModule("Saved."); } void OnNewOnlyCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg.empty()) { PutModule("Usage: NewOnly <on|off>"); return; } m_bNewOnly = sArg.ToBool(); SaveSettings(); PutModule("Saved."); } void OnDisconnectCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg.empty()) { PutModule("Usage: OnDisconnect <on|off>"); return; } m_bOnDisconnect = sArg.ToBool(); SaveSettings(); PutModule("Saved."); } void OnShowCommand(const CString& sLine) { PutModule("Current settings: Method: " + m_sMethod + ", for unseen IP addresses only: " + CString(m_bNewOnly) + ", notify on disconnecting clients: " + CString(m_bOnDisconnect)); } }; template<> void TModInfo<CClientNotifyMod>(CModInfo& Info) { Info.SetWikiPage("clientnotify"); } USERMODULEDEFS(CClientNotifyMod, "Notifies you when another IRC client logs into or out of your account. Configurable.")
4,274
1,588
/*============================================================================= Copyright (c) 2001-2006 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_SEQUENCE_GENERATION_10022005_0615) #define FUSION_SEQUENCE_GENERATION_10022005_0615 #include <boost/fusion/container/generation/cons_tie.hpp> #include <boost/fusion/container/generation/ignore.hpp> #include <boost/fusion/container/generation/list_tie.hpp> #include <boost/fusion/container/generation/make_cons.hpp> #include <boost/fusion/container/generation/make_list.hpp> #include <boost/fusion/container/generation/make_map.hpp> #include <boost/fusion/container/generation/make_vector.hpp> #include <boost/fusion/container/generation/vector_tie.hpp> #include <boost/fusion/container/generation/make_set.hpp> #endif
1,021
356
#ifndef INC_DATA_HANDLING_HPP_ #define INC_DATA_HANDLING_HPP_ #include <stdlib.h> #include <cstring> #include "stdio.h" #include "main.h" enum struct HeartBeat { Buffer1, Buffer2, Buffer3, DEFAULT, FRAME_BY_FRAME }; class Data_management { private: // Buffers containing data and states. uint8_t DataBuffer1[32] = {0}; uint8_t DataBuffer2[32] = {0}; uint8_t DataBuffer3[32] = {0}; uint8_t StateBuffer1[10] = { 0 }; uint8_t StateBuffer2[10] = { 0 }; uint8_t StateBuffer3[10] = { 0 }; public: // flags used to track arriving frames. Each bit represent corresponding frame. uint8_t DataBuffer1_flag = 0; uint8_t DataBuffer2_flag = 0; uint8_t DataBuffer3_flag = 0; // Const values indicating full state of a buffer. const uint8_t Buffer1_full = 63; const uint8_t Buffer2_full = 3; const uint8_t Buffer3_full = 255; /* Methods */ void Init(); uint8_t * Check_Buffer1(); uint8_t * Check_Buffer2(); uint8_t * Check_Buffer3(); uint8_t * return_state1_pointer() {return StateBuffer1;} uint8_t * return_state2_pointer() {return StateBuffer2;} uint8_t * return_state3_pointer() {return StateBuffer3;} void Clear_msg1(); void Clear_msg2(); void Clear_msg3(); }; void Send_Frame(); void Cycle_frames(); #endif
1,251
529
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "tier0/dbg.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include "choreoevent.h" #include "choreoactor.h" #include "choreochannel.h" #include "minmax.h" #include "mathlib/mathlib.h" #include "tier1/strtools.h" #include "choreoscene.h" #include "ichoreoeventcallback.h" #include "tier1/utlbuffer.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" int CChoreoEvent::s_nGlobalID = 1; //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CEventRelativeTag::CEventRelativeTag( CChoreoEvent *owner, const char *name, float percentage ) { Assert( owner ); Assert( name ); Assert( percentage >= 0.0f ); Assert( percentage <= 1.0f ); m_Name = name; m_flPercentage = percentage; m_pOwner = owner; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CEventRelativeTag::CEventRelativeTag( const CEventRelativeTag& src ) { m_Name = src.m_Name; m_flPercentage = src.m_flPercentage; m_pOwner = src.m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CEventRelativeTag::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventRelativeTag::GetPercentage( void ) { return m_flPercentage; } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventRelativeTag::SetPercentage( float percentage ) { m_flPercentage = percentage; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CEventRelativeTag::GetOwner( void ) { return m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventRelativeTag::SetOwner( CChoreoEvent *event ) { m_pOwner = event; } //----------------------------------------------------------------------------- // Purpose: Returns the corrected time based on the owner's length and start time // Output : float //----------------------------------------------------------------------------- float CEventRelativeTag::GetStartTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); return ( ownerstart + ownerduration * m_flPercentage ); } //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CFlexTimingTag::CFlexTimingTag( CChoreoEvent *owner, const char *name, float percentage, bool locked ) : BaseClass( owner, name, percentage ) { m_bLocked = locked; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CFlexTimingTag::CFlexTimingTag( const CFlexTimingTag& src ) : BaseClass( src ) { m_bLocked = src.m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexTimingTag::GetLocked( void ) { return m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Input : locked - //----------------------------------------------------------------------------- void CFlexTimingTag::SetLocked( bool locked ) { m_bLocked = locked; } //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CEventAbsoluteTag::CEventAbsoluteTag( CChoreoEvent *owner, const char *name, float t ) { Assert( owner ); Assert( name ); Assert( t >= 0.0f ); m_Name = name; m_flPercentage = t; m_pOwner = owner; m_bLocked = false; m_bLinear = false; m_bEntry = false; m_bExit = false; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CEventAbsoluteTag::CEventAbsoluteTag( const CEventAbsoluteTag& src ) { m_Name = src.m_Name; m_flPercentage = src.m_flPercentage; m_pOwner = src.m_pOwner; m_bLocked = src.m_bLocked; m_bLinear = src.m_bLinear; m_bEntry = src.m_bEntry; m_bExit = src.m_bExit; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CEventAbsoluteTag::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetPercentage( void ) { return m_flPercentage; } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetPercentage( float percentage ) { m_flPercentage = percentage; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetEventTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerduration = m_pOwner->GetDuration(); return (m_flPercentage * ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetEventTime( float t ) { Assert( m_pOwner ); if ( !m_pOwner ) { return; } float ownerduration = m_pOwner->GetDuration(); m_flPercentage = (t / ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetAbsoluteTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); return (ownerstart + m_flPercentage * ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetAbsoluteTime( float t ) { Assert( m_pOwner ); if ( !m_pOwner ) { return; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); m_flPercentage = (t - ownerstart) / ownerduration; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CEventAbsoluteTag::GetOwner( void ) { return m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetOwner( CChoreoEvent *event ) { m_pOwner = event; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetLocked( bool bLocked ) { m_bLocked = bLocked; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetLocked( void ) { return m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetLinear( bool bLinear ) { m_bLinear = bLinear; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetLinear( void ) { return m_bLinear; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetEntry( bool bEntry ) { m_bEntry = bEntry; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetEntry( void ) { return m_bEntry; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetExit( bool bExit ) { m_bExit = bExit; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetExit( void ) { return m_bExit; } // FLEX ANIMATIONS //----------------------------------------------------------------------------- // Purpose: Constructor // Input : *event - //----------------------------------------------------------------------------- CFlexAnimationTrack::CFlexAnimationTrack( CChoreoEvent *event ) { m_pEvent = event; m_pControllerName = NULL; m_bActive = false; m_bCombo = false; m_bServerSide = false; m_nFlexControllerIndex[ 0 ] = m_nFlexControllerIndex[ 1 ] = -1; m_nFlexControllerIndexRaw[ 0 ] = m_nFlexControllerIndexRaw[ 1 ] = LocalFlexController_t(-1); // base track has range, combo is always 0..1 m_flMin = 0.0f; m_flMax = 0.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CFlexAnimationTrack::CFlexAnimationTrack( const CFlexAnimationTrack* src ) { m_pControllerName = NULL; SetFlexControllerName( src->m_pControllerName ? src->m_pControllerName : "" ); m_bActive = src->m_bActive; m_bCombo = src->m_bCombo; m_bServerSide = src->m_bServerSide; for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].Purge(); for ( int i = 0 ;i < src->m_Samples[ t ].Size(); i++ ) { CExpressionSample s = src->m_Samples[ t ][ i ]; m_Samples[ t ].AddToTail( s ); } } for ( int side = 0; side < 2; side++ ) { m_nFlexControllerIndex[ side ] = src->m_nFlexControllerIndex[ side ]; m_nFlexControllerIndexRaw[ side ] = src->m_nFlexControllerIndexRaw[ side ]; } m_flMin = src->m_flMin; m_flMax = src->m_flMax; m_EdgeInfo[ 0 ] = src->m_EdgeInfo[ 0 ]; m_EdgeInfo[ 1 ] = src->m_EdgeInfo[ 1 ]; m_pEvent = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CFlexAnimationTrack::~CFlexAnimationTrack( void ) { delete[] m_pControllerName; for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].Purge(); } } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetEvent( CChoreoEvent *event ) { m_pEvent = event; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::Clear( void ) { for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].RemoveAll(); } } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CFlexAnimationTrack::RemoveSample( int index, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); m_Samples[ type ].Remove( index ); } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetFlexControllerName( const char *name ) { delete[] m_pControllerName; int len = Q_strlen( name ) + 1; m_pControllerName = new char[ len ]; Q_strncpy( m_pControllerName, name, len ); } //----------------------------------------------------------------------------- // Purpose: // Output : char const //----------------------------------------------------------------------------- const char *CFlexAnimationTrack::GetFlexControllerName( void ) { return m_pControllerName ? m_pControllerName : ""; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CFlexAnimationTrack::GetNumSamples( int type /*=0*/ ) { Assert( type == 0 || type == 1 ); return m_Samples[ type ].Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::GetSample( int index, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); if ( index < 0 || index >= GetNumSamples( type ) ) return NULL; return &m_Samples[ type ][ index ]; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsTrackActive( void ) { return m_bActive; } //----------------------------------------------------------------------------- // Purpose: // Input : active - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetTrackActive( bool active ) { m_bActive = active; } void CFlexAnimationTrack::SetEdgeInfo( bool leftEdge, int curveType, float zero ) { int idx = leftEdge ? 0 : 1; m_EdgeInfo[ idx ].m_CurveType = curveType; m_EdgeInfo[ idx ].m_flZeroPos = zero; } void CFlexAnimationTrack::GetEdgeInfo( bool leftEdge, int& curveType, float& zero ) const { int idx = leftEdge ? 0 : 1; curveType = m_EdgeInfo[ idx ].m_CurveType; zero = m_EdgeInfo[ idx ].m_flZeroPos; } void CFlexAnimationTrack::SetEdgeActive( bool leftEdge, bool state ) { int idx = leftEdge ? 0 : 1; m_EdgeInfo[ idx ].m_bActive = state; } bool CFlexAnimationTrack::IsEdgeActive( bool leftEdge ) const { int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_bActive; } int CFlexAnimationTrack::GetEdgeCurveType( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return CURVE_DEFAULT; } int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_CurveType; } float CFlexAnimationTrack::GetEdgeZeroValue( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return 0.0f; } int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_flZeroPos; } float CFlexAnimationTrack::GetDefaultEdgeZeroPos() const { float zero = 0.0f; if ( m_flMin != m_flMax ) { zero = ( 0.0f - m_flMin ) / ( m_flMax - m_flMin ); } return zero; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetZeroValue( int type, bool leftSide ) { // Stereo track is always clamped to 0.5 and doesn't care about l/r settings if ( type == 1 ) { return 0.5f; } if ( IsEdgeActive( leftSide ) ) { return GetEdgeZeroValue( leftSide ); } return GetDefaultEdgeZeroPos(); } //----------------------------------------------------------------------------- // Purpose: // Input : number - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::GetBoundedSample( int number, bool& bClamped, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); if ( number < 0 ) { // Search for two samples which span time f static CExpressionSample nullstart; nullstart.time = 0.0f; nullstart.value = GetZeroValue( type, true ); if ( type == 0 ) { nullstart.SetCurveType( GetEdgeCurveType( true ) ); } else { nullstart.SetCurveType( CURVE_DEFAULT ); } bClamped = true; return &nullstart; } else if ( number >= GetNumSamples( type ) ) { static CExpressionSample nullend; nullend.time = m_pEvent->GetDuration(); nullend.value = GetZeroValue( type, false ); if ( type == 0 ) { nullend.SetCurveType( GetEdgeCurveType( false ) ); } else { nullend.SetCurveType( CURVE_DEFAULT ); } bClamped = true; return &nullend; } bClamped = false; return GetSample( number, type ); } //----------------------------------------------------------------------------- // Purpose: // Input : time - // type - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetIntensityInternal( float time, int type ) { Assert( type == 0 || type == 1 ); float retval = 0.0f; // find samples that span the time if ( !m_pEvent || !m_pEvent->HasEndTime() || time < m_pEvent->GetStartTime() ) { retval = GetZeroValue( type, true );; } else if ( time > m_pEvent->GetEndTime() ) { retval = GetZeroValue( type, false );; } else { float elapsed = time - m_pEvent->GetStartTime(); retval = GetFracIntensity( elapsed, type ); } // scale if (type == 0 && m_flMin != m_flMax) { retval = retval * (m_flMax - m_flMin) + m_flMin; } return retval; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // type - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetFracIntensity( float time, int type ) { float zeroValueLeft = GetZeroValue( type, true ); Assert( type == 0 || type == 1 ); // find samples that span the time if ( !m_pEvent || !m_pEvent->HasEndTime() ) return zeroValueLeft; int rampCount = GetNumSamples( type ); if ( rampCount < 1 ) { return zeroValueLeft; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( i, dummy, type ); esEnd = GetBoundedSample( i + 1, dummy, type ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { if ( time == esEnd->time ) { ++i; esStart = GetBoundedSample( i, dummy, type ); esEnd = GetBoundedSample( i + 1, dummy, type ); } break; } } if (!esStart) { return zeroValueLeft; } int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( prev, bclamp[ 0 ], type ); CExpressionSample *esNext = GetBoundedSample( next, bclamp[ 1 ], type ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( esStart->GetCurveType(), dummy, earlypart ); Interpolator_CurveInterpolatorsForType( esEnd->GetCurveType(), laterpart, dummy ); if ( earlypart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vStart.y; } else if ( laterpart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vEnd.y; } else { bool sameCurveType = earlypart == laterpart ? true : false; if ( sameCurveType ) { Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut ); } else // curves differ, sigh { Vector vOut1, vOut2; Interpolator_CurveInterpolate( earlypart, vPre, vStart, vEnd, vNext, f2, vOut1 ); Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut2 ); VectorLerp( vOut1, vOut2, f2, vOut ); } } float retval = clamp( vOut.y, 0.0f, 1.0f ); return retval; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetSampleIntensity( float time ) { return GetIntensityInternal( time, 0 ); } //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetBalanceIntensity( float time ) { if ( IsComboType() ) { return GetIntensityInternal( time, 1 ); } return 1.0f; } // For a given time, computes 0->1 intensity value for the slider //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetIntensity( float time, int side ) { float mag = GetSampleIntensity( time ); float scale = 1.0f; if ( IsComboType() ) { float balance = GetBalanceIntensity( time ); // Asking for left but balance is to right, then fall off as we go // further right if ( side == 0 && balance > 0.5f ) { scale = (1.0f - balance ) / 0.5f; } // Asking for right, but balance is left, fall off as we go left. else if ( side == 1 && balance < 0.5f ) { scale = ( balance / 0.5f ); } } return mag * scale; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // value - //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::AddSample( float time, float value, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); CExpressionSample sample; sample.time = time; sample.value = value; sample.selected = false; int idx = m_Samples[ type ].AddToTail( sample ); // Resort( type ); return &m_Samples[ type ][ idx ]; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::Resort( int type /*=0*/ ) { Assert( type == 0 || type == 1 ); for ( int i = 0; i < m_Samples[ type ].Size(); i++ ) { for ( int j = i + 1; j < m_Samples[ type ].Size(); j++ ) { CExpressionSample src = m_Samples[ type ][ i ]; CExpressionSample dest = m_Samples[ type ][ j ]; if ( src.time > dest.time ) { m_Samples[ type ][ i ] = dest; m_Samples[ type ][ j ] = src; } } } // Make sure nothing is out of range RemoveOutOfRangeSamples( 0 ); RemoveOutOfRangeSamples( 1 ); } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CFlexAnimationTrack::GetEvent( void ) { return m_pEvent; } //----------------------------------------------------------------------------- // Purpose: // Input : side - // Output : int //----------------------------------------------------------------------------- int CFlexAnimationTrack::GetFlexControllerIndex( int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); if ( IsComboType() ) { return m_nFlexControllerIndex[ side ]; } return m_nFlexControllerIndex[ 0 ]; } //----------------------------------------------------------------------------- // Purpose: // Input : side - // Output : int //----------------------------------------------------------------------------- LocalFlexController_t CFlexAnimationTrack::GetRawFlexControllerIndex( int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); if ( IsComboType() ) { return m_nFlexControllerIndexRaw[ side ]; } return m_nFlexControllerIndexRaw[ 0 ]; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // side - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetFlexControllerIndex( LocalFlexController_t raw, int index, int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); m_nFlexControllerIndex[ side ] = index; // Model specific m_nFlexControllerIndexRaw[ side ] = raw; } //----------------------------------------------------------------------------- // Purpose: // Input : combo - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetComboType( bool combo ) { m_bCombo = combo; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsComboType( void ) { return m_bCombo; } //----------------------------------------------------------------------------- // Purpose: True if this should be simulated on the server side always // Input : state - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetServerSide( bool state ) { m_bServerSide = state; } //----------------------------------------------------------------------------- // Purpose: // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsServerSide() const { return m_bServerSide; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetMin( float value ) { m_flMin = value; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetMax( float value ) { m_flMax = value; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetMin( int type ) { if (type == 0) return m_flMin; else return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetMax( int type ) { if (type == 0) return m_flMax; else return 1.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsInverted( void ) { if (m_bInverted) return true; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetInverted( bool isInverted ) { m_bInverted = isInverted; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- void CFlexAnimationTrack::RemoveOutOfRangeSamples( int type ) { Assert( m_pEvent ); if ( !m_pEvent ) return; Assert( m_pEvent->HasEndTime() ); float duration = m_pEvent->GetDuration(); int c = m_Samples[ type ].Size(); for ( int i = c-1; i >= 0; i-- ) { CExpressionSample src = m_Samples[ type ][ i ]; if ( src.time < 0 || src.time > duration ) { m_Samples[ type ].Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene ) { Init( scene ); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *name - //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene, EVENTTYPE type, const char *name ) { Init( scene ); SetType( type ); SetName( name ); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *name - // *param - //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene, EVENTTYPE type, const char *name, const char *param ) { Init( scene ); SetType( type ); SetName( name ); SetParameters( param ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CChoreoEvent::~CChoreoEvent( void ) { RemoveAllTracks(); ClearEventDependencies(); delete m_pSubScene; } //----------------------------------------------------------------------------- // Purpose: Assignment // Input : src - // Output : CChoreoEvent& //----------------------------------------------------------------------------- CChoreoEvent& CChoreoEvent::operator=( const CChoreoEvent& src ) { MEM_ALLOC_CREDIT(); // Copy global id when copying entity m_nGlobalID = src.m_nGlobalID; m_pActor = NULL; m_pChannel = NULL; m_nDefaultCurveType = src.m_nDefaultCurveType; m_fType = src.m_fType; m_Name = src.m_Name; m_Parameters = src.m_Parameters; m_Parameters2= src.m_Parameters2; m_Parameters3= src.m_Parameters3; m_flStartTime = src.m_flStartTime; m_flEndTime = src.m_flEndTime; m_bFixedLength = src.m_bFixedLength; m_flGestureSequenceDuration = src.m_flGestureSequenceDuration; m_bResumeCondition = src.m_bResumeCondition; m_bLockBodyFacing = src.m_bLockBodyFacing; m_flDistanceToTarget = src.m_flDistanceToTarget; m_bForceShortMovement = src.m_bForceShortMovement; m_bSyncToFollowingGesture = src.m_bSyncToFollowingGesture; m_bPlayOverScript = src.m_bPlayOverScript; m_bUsesTag = src.m_bUsesTag; m_TagName = src.m_TagName; m_TagWavName = src.m_TagWavName; ClearAllRelativeTags(); ClearAllTimingTags(); int t; for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ ) { ClearAllAbsoluteTags( (AbsTagType)t ); } int i; for ( i = 0; i < src.m_RelativeTags.Size(); i++ ) { CEventRelativeTag newtag( src.m_RelativeTags[ i ] ); newtag.SetOwner( this ); m_RelativeTags.AddToTail( newtag ); } for ( i = 0; i < src.m_TimingTags.Size(); i++ ) { CFlexTimingTag newtag( src.m_TimingTags[ i ] ); newtag.SetOwner( this ); m_TimingTags.AddToTail( newtag ); } for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ ) { for ( i = 0; i < src.m_AbsoluteTags[ t ].Size(); i++ ) { CEventAbsoluteTag newtag( src.m_AbsoluteTags[ t ][ i ] ); newtag.SetOwner( this ); m_AbsoluteTags[ t ].AddToTail( newtag ); } } RemoveAllTracks(); for ( i = 0 ; i < src.m_FlexAnimationTracks.Size(); i++ ) { CFlexAnimationTrack *newtrack = new CFlexAnimationTrack( src.m_FlexAnimationTracks[ i ] ); newtrack->SetEvent( this ); m_FlexAnimationTracks.AddToTail( newtrack ); } m_bTrackLookupSet = src.m_bTrackLookupSet; // FIXME: Use a safe handle? //m_pSubScene = src.m_pSubScene; m_bProcessing = src.m_bProcessing; m_pMixer = src.m_pMixer; m_pScene = src.m_pScene; m_nPitch = src.m_nPitch; m_nYaw = src.m_nYaw; m_nNumLoops = src.m_nNumLoops; m_nLoopsRemaining = src.m_nLoopsRemaining; // Copy ramp over m_Ramp = src.m_Ramp; m_ccType = src.m_ccType; m_CCToken = src.m_CCToken; m_bUsingCombinedSoundFile = src.m_bUsingCombinedSoundFile; m_uRequiredCombinedChecksum = src.m_uRequiredCombinedChecksum; m_nNumSlaves = src.m_nNumSlaves; m_flLastSlaveEndTime = src.m_flLastSlaveEndTime; m_bCCTokenValid = src.m_bCCTokenValid; m_bCombinedUsingGenderToken = src.m_bCombinedUsingGenderToken; m_bSuppressCaptionAttenuation = src.m_bSuppressCaptionAttenuation; m_bActive = src.m_bActive; return *this; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::Init( CChoreoScene *scene ) { m_nGlobalID = s_nGlobalID++; m_nDefaultCurveType = CURVE_CATMULL_ROM_TO_CATMULL_ROM; m_fType = UNSPECIFIED; m_Name.Set(""); m_Parameters.Set(""); m_Parameters2.Set(""); m_Parameters3.Set(""); m_flStartTime = 0.0f; m_flEndTime = -1.0f; m_pActor = NULL; m_pChannel = NULL; m_pScene = scene; m_bFixedLength = false; m_bResumeCondition = false; SetUsingRelativeTag( false, 0, 0 ); m_bTrackLookupSet = false; m_bLockBodyFacing = false; m_flDistanceToTarget = 0.0f; m_bForceShortMovement = false; m_bSyncToFollowingGesture = false; m_bPlayOverScript = false; m_pSubScene = NULL; m_bProcessing = false; m_pMixer = NULL; m_flGestureSequenceDuration = 0.0f; m_nPitch = m_nYaw = 0; m_nNumLoops = -1; m_nLoopsRemaining = 0; // Close captioning/localization support m_CCToken.Set(""); m_ccType = CC_MASTER; m_bUsingCombinedSoundFile = false; m_uRequiredCombinedChecksum = 0; m_nNumSlaves = 0; m_flLastSlaveEndTime = 0.0f; m_bCCTokenValid = false; m_bCombinedUsingGenderToken = false; m_bSuppressCaptionAttenuation = false; m_bActive = true; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- CChoreoEvent::EVENTTYPE CChoreoEvent::GetType( void ) { return (EVENTTYPE)m_fType; } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void CChoreoEvent::SetType( EVENTTYPE type ) { m_fType = type; if ( m_fType == SPEAK || m_fType == SUBSCENE ) { m_bFixedLength = true; } else { m_bFixedLength = false; } } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CChoreoEvent::SetName( const char *name ) { m_Name = name; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters( const char *param ) { m_Parameters = param; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters( void ) { return m_Parameters.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters2( const char *param ) { int iLength = Q_strlen( param ); m_Parameters2 = param; // HACK: Remove trailing " " until faceposer is fixed if ( iLength > 0 ) { if ( param[iLength-1] == ' ' ) { char tmp[1024]; Q_strncpy( tmp, param, sizeof(tmp) ); tmp[iLength-1] = 0; m_Parameters2.Set(tmp); } } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters2( void ) { return m_Parameters2.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters3( const char *param ) { int iLength = Q_strlen( param ); m_Parameters3 = param; // HACK: Remove trailing " " until faceposer is fixed if ( iLength > 0 ) { if ( param[iLength-1] == ' ' ) { char tmp[1024]; Q_strncpy( tmp, param, sizeof(tmp) ); tmp[iLength-1] = 0; m_Parameters3.Set(tmp); } } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters3( void ) { return m_Parameters3.Get(); } //----------------------------------------------------------------------------- // Purpose: debugging description // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetDescription( void ) { static char description[ 256 ]; description[ 0 ] = 0; if ( !GetActor() ) { Q_snprintf( description,sizeof(description), "global %s", m_Name.Get() ); } else { Assert( m_pChannel ); Q_snprintf( description,sizeof(description), "%s : %s : %s -- %s \"%s\"", m_pActor->GetName(), m_pChannel->GetName(), GetName(), NameForType( GetType() ), GetParameters() ); if ( GetType() == EXPRESSION ) { char sz[ 256 ]; Q_snprintf( sz,sizeof(sz), " \"%s\"", GetParameters2() ); Q_strncat( description, sz, sizeof(description), COPY_ALL_CHARACTERS ); } } return description; } //----------------------------------------------------------------------------- // Purpose: // Input : starttime - //----------------------------------------------------------------------------- void CChoreoEvent::SetStartTime( float starttime ) { m_flStartTime = starttime; if ( m_flEndTime != -1.0f ) { if ( m_flEndTime < m_flStartTime ) { m_flEndTime = m_flStartTime; } } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetStartTime( ) { return m_flStartTime; } //----------------------------------------------------------------------------- // Purpose: // Input : endtime - //----------------------------------------------------------------------------- void CChoreoEvent::SetEndTime( float endtime ) { bool changed = m_flEndTime != endtime; m_flEndTime = endtime; if ( endtime != -1.0f ) { if ( m_flEndTime < m_flStartTime ) { m_flEndTime = m_flStartTime; } if ( changed ) { OnEndTimeChanged(); } } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetEndTime( ) { return m_flEndTime; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::HasEndTime( void ) { return m_flEndTime != -1.0f ? true : false; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetCompletion( float time ) { float t = (time - GetStartTime()) / (GetEndTime() - GetStartTime()); if (t < 0.0f) return 0.0f; else if (t > 1.0f) return 1.0f; return t; } // ICurveDataAccessor method bool CChoreoEvent::CurveHasEndTime() { return HasEndTime(); } //----------------------------------------------------------------------------- // Default curve type //----------------------------------------------------------------------------- void CChoreoEvent::SetDefaultCurveType( int nCurveType ) { m_nDefaultCurveType = nCurveType; } int CChoreoEvent::GetDefaultCurveType() { return m_nDefaultCurveType; } float CCurveData::GetIntensity( ICurveDataAccessor *data, float time ) { float zeroValue = 0.0f; // find samples that span the time if ( !data->CurveHasEndTime() ) { return zeroValue; } int rampCount = GetCount(); if ( rampCount < 1 ) { // Full intensity return 1.0f; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( data, i, dummy ); esEnd = GetBoundedSample( data, i + 1, dummy ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { break; } } if (!esStart) { return 1.0f; } int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( data, prev, bclamp[ 0 ] ); CExpressionSample *esNext = GetBoundedSample( data, next, bclamp[ 1 ] ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); if ( bclamp[ 0 ] ) { vPre.x = vStart.x; } if ( bclamp[ 1 ] ) { vNext.x = vEnd.x; } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; int startCurve = esStart->GetCurveType(); int endCurve = esEnd->GetCurveType(); if ( startCurve == CURVE_DEFAULT ) { startCurve = data->GetDefaultCurveType(); } if ( endCurve == CURVE_DEFAULT ) { endCurve = data->GetDefaultCurveType(); } // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( startCurve, dummy, earlypart ); Interpolator_CurveInterpolatorsForType( endCurve, laterpart, dummy ); if ( earlypart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vStart.y; } else if ( laterpart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vEnd.y; } else { bool sameCurveType = earlypart == laterpart ? true : false; if ( sameCurveType ) { Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut ); } else // curves differ, sigh { Vector vOut1, vOut2; Interpolator_CurveInterpolate( earlypart, vPre, vStart, vEnd, vNext, f2, vOut1 ); Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut2 ); VectorLerp( vOut1, vOut2, f2, vOut ); } } float retval = clamp( vOut.y, 0.0f, 1.0f ); return retval; } //----------------------------------------------------------------------------- // Purpose: Get intensity for event, bounded by scene global intensity // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetIntensity( float scenetime ) { float global_intensity = 1.0f; if ( m_pScene ) { global_intensity = m_pScene->GetSceneRampIntensity( scenetime ); } else { Assert( 0 ); } float event_intensity = _GetIntensity( scenetime ); return global_intensity * event_intensity; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::_GetIntensity( float scenetime ) { // Convert to event local time float time = scenetime - GetStartTime(); return m_Ramp.GetIntensity( this, time ); } float CChoreoEvent::GetIntensityArea( float scenetime ) { // Convert to event local time float time = scenetime - GetStartTime(); return m_Ramp.GetIntensityArea( this, time ); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CCurveData::GetIntensityArea( ICurveDataAccessor *data, float time ) { float zeroValue = 0.0f; // find samples that span the time if ( !data->CurveHasEndTime() ) { return zeroValue; } int rampCount = GetCount(); if ( rampCount < 1 ) { // Full intensity return 1.0f; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( data, i, dummy ); esEnd = GetBoundedSample( data, i + 1, dummy ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { break; } } UpdateIntensityArea( data ); float flTotal = 0.0f; flTotal = m_RampAccumulator[i+1]; int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( data, prev, bclamp[ 0 ] ); CExpressionSample *esNext = GetBoundedSample( data, next, bclamp[ 1 ] ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); if ( bclamp[ 0 ] ) { vPre.x = vStart.x; } if ( bclamp[ 1 ] ) { vNext.x = vEnd.x; } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; int startCurve = esStart->GetCurveType(); int endCurve = esEnd->GetCurveType(); if ( startCurve == CURVE_DEFAULT ) { startCurve = data->GetDefaultCurveType(); } if ( endCurve == CURVE_DEFAULT ) { endCurve = data->GetDefaultCurveType(); } // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( startCurve, dummy, earlypart ); Interpolator_CurveInterpolatorsForType( endCurve, laterpart, dummy ); // FIXME: needs other curve types Catmull_Rom_Spline_Integral_Normalize( vPre, vStart, vEnd, vNext, f2, vOut ); // Con_Printf( "Accum %f : Partial %f\n", flTotal, vOut.y * (vEnd.x - vStart.x) * f2 ); flTotal = flTotal + clamp( vOut.y, 0.0f, 1.0f ) * (vEnd.x - vStart.x); return flTotal; } void CCurveData::UpdateIntensityArea( ICurveDataAccessor *data ) { int rampCount = GetCount();; if ( rampCount < 1 ) { return; } if (m_RampAccumulator.Count() == rampCount + 2) { return; } m_RampAccumulator.SetCount( rampCount + 2 ); int i = -1; bool dummy; CExpressionSample *esPre = GetBoundedSample( data, i - 1, dummy ); CExpressionSample *esStart = GetBoundedSample( data, i, dummy ); CExpressionSample *esEnd = GetBoundedSample( data, MIN( i + 1, rampCount ), dummy ); Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vOut; for (i = -1; i < rampCount; i++) { CExpressionSample *esNext = GetBoundedSample( data, MIN( i + 2, rampCount ), dummy ); Vector vNext( esNext->time, esNext->value, 0 ); Catmull_Rom_Spline_Integral_Normalize( vPre, vStart, vEnd, vNext, 1.0f, vOut ); m_RampAccumulator[i+1] = clamp( vOut.y, 0.0f, 1.0f ) * (vEnd.x - vStart.x); vPre = vStart; vStart = vEnd; vEnd = vNext; } } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetStartTime( float dt ) { SetStartTime( GetStartTime() + dt ); } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetEndTime( float dt ) { if ( HasEndTime() ) { SetEndTime( GetEndTime() + dt ); } } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetTime( float dt ) { if ( HasEndTime() ) { m_flEndTime += dt; } m_flStartTime += dt; } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - //----------------------------------------------------------------------------- void CChoreoEvent::SetActor( CChoreoActor *actor ) { m_pActor = actor; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoActor //----------------------------------------------------------------------------- CChoreoActor *CChoreoEvent::GetActor( void ) { return m_pActor; } //----------------------------------------------------------------------------- // Purpose: // Input : *channel - //----------------------------------------------------------------------------- void CChoreoEvent::SetChannel( CChoreoChannel *channel ) { m_pChannel = channel; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoChannel //----------------------------------------------------------------------------- CChoreoChannel *CChoreoEvent::GetChannel( void ) { return m_pChannel; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CChoreoEvent::SetSubScene( CChoreoScene *scene ) { m_pSubScene = scene; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CChoreoEvent::GetSubScene( void ) { return m_pSubScene; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- struct EventNameMap_t { CChoreoEvent::EVENTTYPE type; char const *name; }; static EventNameMap_t g_NameMap[] = { { CChoreoEvent::UNSPECIFIED, "unspecified" }, // error condition!!! { CChoreoEvent::SECTION, "section" }, { CChoreoEvent::EXPRESSION, "expression" }, { CChoreoEvent::LOOKAT, "lookat" }, { CChoreoEvent::MOVETO, "moveto" }, { CChoreoEvent::SPEAK, "speak" }, { CChoreoEvent::GESTURE, "gesture" }, { CChoreoEvent::SEQUENCE, "sequence" }, { CChoreoEvent::FACE, "face" }, { CChoreoEvent::FIRETRIGGER, "firetrigger" }, { CChoreoEvent::FLEXANIMATION, "flexanimation" }, { CChoreoEvent::SUBSCENE, "subscene" }, { CChoreoEvent::LOOP, "loop" }, { CChoreoEvent::INTERRUPT, "interrupt" }, { CChoreoEvent::STOPPOINT, "stoppoint" }, { CChoreoEvent::PERMIT_RESPONSES, "permitresponses" }, { CChoreoEvent::GENERIC, "generic" }, }; //----------------------------------------------------------------------------- // Purpose: A simple class to verify the names data above at runtime //----------------------------------------------------------------------------- class CCheckEventNames { public: CCheckEventNames() { if ( ARRAYSIZE( g_NameMap ) != CChoreoEvent::NUM_TYPES ) { Error( "g_NameMap contains %llu entries, CChoreoEvent::NUM_TYPES == %i!", (uint64)(ARRAYSIZE( g_NameMap )), CChoreoEvent::NUM_TYPES ); } for ( int i = 0; i < CChoreoEvent::NUM_TYPES; ++i ) { if ( !g_NameMap[ i ].name ) { Error( "g_NameMap: Event type at %i has NULL name string!", i ); } if ( (CChoreoEvent::EVENTTYPE)(i) == g_NameMap[ i ].type ) continue; Error( "g_NameMap: Event type at %i has wrong value (%i)!", i, (int)g_NameMap[ i ].type ); } } }; static CCheckEventNames g_CheckNamesSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : int //----------------------------------------------------------------------------- CChoreoEvent::EVENTTYPE CChoreoEvent::TypeForName( const char *name ) { for ( int i = 0; i < NUM_TYPES; ++i ) { EventNameMap_t *slot = &g_NameMap[ i ]; if ( !Q_stricmp( name, slot->name ) ) return slot->type; } Assert( !"CChoreoEvent::TypeForName failed!!!" ); return UNSPECIFIED; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForType( EVENTTYPE type ) { int i = (int)type; if ( i < 0 || i >= NUM_TYPES ) { Assert( "!CChoreoEvent::NameForType: bogus type!" ); // returns "unspecified!!!"; return g_NameMap[ 0 ].name; } return g_NameMap[ i ].name; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- struct CCNameMap_t { CChoreoEvent::CLOSECAPTION type; char const *name; }; static CCNameMap_t g_CCNameMap[] = { { CChoreoEvent::CC_MASTER, "cc_master" }, // error condition!!! { CChoreoEvent::CC_SLAVE, "cc_slave" }, { CChoreoEvent::CC_DISABLED, "cc_disabled" }, }; //----------------------------------------------------------------------------- // Purpose: A simple class to verify the names data above at runtime //----------------------------------------------------------------------------- class CCheckCCNames { public: CCheckCCNames() { if ( ARRAYSIZE( g_CCNameMap ) != CChoreoEvent::NUM_CC_TYPES ) { Error( "g_CCNameMap contains %llu entries, CChoreoEvent::NUM_CC_TYPES == %i!", (uint64)(ARRAYSIZE( g_CCNameMap )), CChoreoEvent::NUM_CC_TYPES ); } for ( int i = 0; i < CChoreoEvent::NUM_CC_TYPES; ++i ) { if ( !g_CCNameMap[ i ].name ) { Error( "g_NameMap: CC type at %i has NULL name string!", i ); } if ( (CChoreoEvent::CLOSECAPTION)(i) == g_CCNameMap[ i ].type ) continue; Error( "g_CCNameMap: Event type at %i has wrong value (%i)!", i, (int)g_CCNameMap[ i ].type ); } } }; static CCheckCCNames g_CheckCCNamesSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : CLOSECAPTION //----------------------------------------------------------------------------- CChoreoEvent::CLOSECAPTION CChoreoEvent::CCTypeForName( const char *name ) { for ( int i = 0; i < NUM_CC_TYPES; ++i ) { CCNameMap_t *slot = &g_CCNameMap[ i ]; if ( !Q_stricmp( name, slot->name ) ) return slot->type; } Assert( !"CChoreoEvent::TypeForName failed!!!" ); return CC_MASTER; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForCCType( CLOSECAPTION type ) { int i = (int)type; if ( i < 0 || i >= NUM_CC_TYPES ) { Assert( "!CChoreoEvent::NameForType: bogus type!" ); // returns "unspecified!!!"; return g_CCNameMap[ 0 ].name; } return g_CCNameMap[ i ].name; } //----------------------------------------------------------------------------- // Purpose: Is the event something that can be sized ( a wave file, e.g. ) // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsFixedLength( void ) { return m_bFixedLength; } //----------------------------------------------------------------------------- // Purpose: // Input : isfixedlength - //----------------------------------------------------------------------------- void CChoreoEvent::SetFixedLength( bool isfixedlength ) { m_bFixedLength = isfixedlength; } //----------------------------------------------------------------------------- // Purpose: // Input : resumecondition - //----------------------------------------------------------------------------- void CChoreoEvent::SetResumeCondition( bool resumecondition ) { m_bResumeCondition = resumecondition; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsResumeCondition( void ) { return m_bResumeCondition; } //----------------------------------------------------------------------------- // Purpose: // Input : lockbodyfacing - //----------------------------------------------------------------------------- void CChoreoEvent::SetLockBodyFacing( bool lockbodyfacing ) { m_bLockBodyFacing = lockbodyfacing; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsLockBodyFacing( void ) { return m_bLockBodyFacing; } //----------------------------------------------------------------------------- // Purpose: // Input : distancetotarget - //----------------------------------------------------------------------------- void CChoreoEvent::SetDistanceToTarget( float distancetotarget ) { m_flDistanceToTarget = distancetotarget; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns ideal distance to target //----------------------------------------------------------------------------- float CChoreoEvent::GetDistanceToTarget( void ) { return m_flDistanceToTarget; } //----------------------------------------------------------------------------- // Purpose: // Input : set if small (sub-1/2 bbox) movements are forced //----------------------------------------------------------------------------- void CChoreoEvent::SetForceShortMovement( bool bForceShortMovement ) { m_bForceShortMovement = bForceShortMovement; } //----------------------------------------------------------------------------- // Purpose: // Output : get if small (sub-1/2 bbox) movements are forced //----------------------------------------------------------------------------- bool CChoreoEvent::GetForceShortMovement( void ) { return m_bForceShortMovement; } //----------------------------------------------------------------------------- // Purpose: // Input : set if the gesture should sync its exit tag with the following gestures entry tag //----------------------------------------------------------------------------- void CChoreoEvent::SetSyncToFollowingGesture( bool bSyncToFollowingGesture ) { m_bSyncToFollowingGesture = bSyncToFollowingGesture; } //----------------------------------------------------------------------------- // Purpose: // Output : get if the gesture should sync its exit tag with the following gestures entry tag //----------------------------------------------------------------------------- bool CChoreoEvent::GetSyncToFollowingGesture( void ) { return m_bSyncToFollowingGesture; } //----------------------------------------------------------------------------- // Purpose: // Input : set if the sequence should player overtop of an underlying SS //----------------------------------------------------------------------------- void CChoreoEvent::SetPlayOverScript( bool bPlayOverScript ) { m_bPlayOverScript = bPlayOverScript; } //----------------------------------------------------------------------------- // Purpose: // Output : get if the sequence should player overtop of an underlying SS //----------------------------------------------------------------------------- bool CChoreoEvent::GetPlayOverScript( void ) { return m_bPlayOverScript; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetDuration( void ) { if ( HasEndTime() ) { return GetEndTime() - GetStartTime(); } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllRelativeTags( void ) { m_RelativeTags.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumRelativeTags( void ) { return m_RelativeTags.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : tagnum - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CEventRelativeTag *CChoreoEvent::GetRelativeTag( int tagnum ) { Assert( tagnum >= 0 && tagnum < m_RelativeTags.Size() ); return &m_RelativeTags[ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // percentage - //----------------------------------------------------------------------------- void CChoreoEvent::AddRelativeTag( const char *tagname, float percentage ) { CEventRelativeTag rt( this, tagname, percentage ); m_RelativeTags.AddToTail( rt ); } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveRelativeTag( const char *tagname ) { for ( int i = 0; i < m_RelativeTags.Size(); i++ ) { CEventRelativeTag *prt = &m_RelativeTags[ i ]; if ( !prt ) continue; if ( !stricmp( prt->GetName(), tagname ) ) { m_RelativeTags.Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // Output : CEventRelativeTag * //----------------------------------------------------------------------------- CEventRelativeTag * CChoreoEvent::FindRelativeTag( const char *tagname ) { for ( int i = 0; i < m_RelativeTags.Size(); i++ ) { CEventRelativeTag *prt = &m_RelativeTags[ i ]; if ( !prt ) continue; if ( !stricmp( prt->GetName(), tagname ) ) { return prt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsUsingRelativeTag( void ) { return m_bUsesTag; } //----------------------------------------------------------------------------- // Purpose: // Input : usetag - // 0 - //----------------------------------------------------------------------------- void CChoreoEvent::SetUsingRelativeTag( bool usetag, const char *tagname /*= 0*/, const char *wavname /* = 0 */ ) { m_bUsesTag = usetag; if ( tagname ) { m_TagName = tagname; } else { m_TagName.Set(""); } if ( wavname ) { m_TagWavName = wavname; } else { m_TagWavName.Set(""); } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetRelativeTagName( void ) { return m_TagName.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetRelativeWavName( void ) { return m_TagWavName.Get(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllTimingTags( void ) { m_TimingTags.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumTimingTags( void ) { return m_TimingTags.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : tagnum - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CFlexTimingTag *CChoreoEvent::GetTimingTag( int tagnum ) { Assert( tagnum >= 0 && tagnum < m_TimingTags.Size() ); return &m_TimingTags[ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // percentage - //----------------------------------------------------------------------------- void CChoreoEvent::AddTimingTag( const char *tagname, float percentage, bool locked ) { CFlexTimingTag tt( this, tagname, percentage, locked ); m_TimingTags.AddToTail( tt ); // Sort tags CFlexTimingTag temp( (CChoreoEvent *)0x1, "", 0.0f, false ); // ugly bubble sort for ( int i = 0; i < m_TimingTags.Size(); i++ ) { for ( int j = i + 1; j < m_TimingTags.Size(); j++ ) { CFlexTimingTag *t1 = &m_TimingTags[ i ]; CFlexTimingTag *t2 = &m_TimingTags[ j ]; if ( t1->GetPercentage() > t2->GetPercentage() ) { temp = *t1; *t1 = *t2; *t2 = temp; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveTimingTag( const char *tagname ) { for ( int i = 0; i < m_TimingTags.Size(); i++ ) { CFlexTimingTag *ptt = &m_TimingTags[ i ]; if ( !ptt ) continue; if ( !stricmp( ptt->GetName(), tagname ) ) { m_TimingTags.Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // Output : CEventRelativeTag * //----------------------------------------------------------------------------- CFlexTimingTag * CChoreoEvent::FindTimingTag( const char *tagname ) { for ( int i = 0; i < m_TimingTags.Size(); i++ ) { CFlexTimingTag *ptt = &m_TimingTags[ i ]; if ( !ptt ) continue; if ( !stricmp( ptt->GetName(), tagname ) ) { return ptt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::OnEndTimeChanged( void ) { int c = GetNumFlexAnimationTracks(); for ( int i = 0; i < c; i++ ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( i ); Assert( track ); if ( !track ) continue; track->Resort( 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumFlexAnimationTracks( void ) { return m_FlexAnimationTracks.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::GetFlexAnimationTrack( int index ) { if ( index < 0 || index >= GetNumFlexAnimationTracks() ) return NULL; return m_FlexAnimationTracks[ index ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *controllername - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::AddTrack( const char *controllername ) { CFlexAnimationTrack *newTrack = new CFlexAnimationTrack( this ); newTrack->SetFlexControllerName( controllername ); m_FlexAnimationTracks.AddToTail( newTrack ); return newTrack; } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveTrack( int index ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( index ); if ( !track ) return; m_FlexAnimationTracks.Remove( index ); delete track; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::RemoveAllTracks( void ) { while ( GetNumFlexAnimationTracks() > 0 ) { RemoveTrack( 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *controllername - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::FindTrack( const char *controllername ) { for ( int i = 0; i < GetNumFlexAnimationTracks(); i++ ) { CFlexAnimationTrack *t = GetFlexAnimationTrack( i ); if ( t && !stricmp( t->GetFlexControllerName(), controllername ) ) { return t; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::GetTrackLookupSet( void ) { return m_bTrackLookupSet; } //----------------------------------------------------------------------------- // Purpose: // Input : set - //----------------------------------------------------------------------------- void CChoreoEvent::SetTrackLookupSet( bool set ) { m_bTrackLookupSet = set; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsProcessing( void ) const { return m_bProcessing; } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::StartProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( !m_bProcessing ); m_bProcessing = true; if ( cb ) { cb->StartEvent( t, scene, this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::ContinueProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( m_bProcessing ); if ( cb ) { cb->ProcessEvent( t, scene, this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::StopProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( m_bProcessing ); if ( cb ) { cb->EndEvent( t, scene, this ); } m_bProcessing = false; } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- bool CChoreoEvent::CheckProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { //Assert( !m_bProcessing ); if ( cb ) { return cb->CheckEvent( t, scene, this ); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ResetProcessing( void ) { if ( GetType() == LOOP ) { m_nLoopsRemaining = m_nNumLoops; } m_bProcessing = false; } //----------------------------------------------------------------------------- // Purpose: // Input : *mixer - //----------------------------------------------------------------------------- void CChoreoEvent::SetMixer( CAudioMixer *mixer ) { m_pMixer = mixer; } //----------------------------------------------------------------------------- // Purpose: // Output : CAudioMixer //----------------------------------------------------------------------------- CAudioMixer *CChoreoEvent::GetMixer( void ) const { return m_pMixer; } // Snap to scene framerate //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::SnapTimes() { if ( HasEndTime() && !IsFixedLength() ) { m_flEndTime = SnapTime( m_flEndTime ); } float oldstart = m_flStartTime; m_flStartTime = SnapTime( m_flStartTime ); // Don't snap end time for fixed length events, just set based on new start time if ( IsFixedLength() ) { float dt = m_flStartTime - oldstart; m_flEndTime += dt; } } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::SnapTime( float t ) { CChoreoScene *scene = GetScene(); if ( !scene) { Assert( 0 ); return t; } return scene->SnapTime( t ); } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CChoreoEvent::GetScene( void ) { return m_pScene; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CChoreoEvent::SetScene( CChoreoScene *scene ) { m_pScene = scene; } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : char const //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForAbsoluteTagType( AbsTagType t ) { switch ( t ) { case PLAYBACK: return "playback_time"; case ORIGINAL: return "shifted_time"; default: break; } return "AbsTagType(unknown)"; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : AbsTagType //----------------------------------------------------------------------------- CChoreoEvent::AbsTagType CChoreoEvent::TypeForAbsoluteTagName( const char *name ) { if ( !Q_strcasecmp( name, "playback_time" ) ) { return PLAYBACK; } else if ( !Q_strcasecmp( name, "shifted_time" ) ) { return ORIGINAL; } return (AbsTagType)-1; } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllAbsoluteTags( AbsTagType type ) { m_AbsoluteTags[ type ].Purge(); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumAbsoluteTags( AbsTagType type ) { return m_AbsoluteTags[ type ].Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // tagnum - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::GetAbsoluteTag( AbsTagType type, int tagnum ) { Assert( tagnum >= 0 && tagnum < m_AbsoluteTags[ type ].Size() ); return &m_AbsoluteTags[ type ][ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindAbsoluteTag( AbsTagType type, const char *tagname ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( !stricmp( ptag->GetName(), tagname ) ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - // t - //----------------------------------------------------------------------------- void CChoreoEvent::AddAbsoluteTag( AbsTagType type, const char *tagname, float t ) { CEventAbsoluteTag at( this, tagname, t ); m_AbsoluteTags[ type ].AddToTail( at ); // Sort tags CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f ); // ugly bubble sort for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { for ( int j = i + 1; j < m_AbsoluteTags[ type ].Size(); j++ ) { CEventAbsoluteTag *t1 = &m_AbsoluteTags[ type ][ i ]; CEventAbsoluteTag *t2 = &m_AbsoluteTags[ type ][ j ]; if ( t1->GetPercentage() > t2->GetPercentage() ) { temp = *t1; *t1 = *t2; *t2 = temp; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveAbsoluteTag( AbsTagType type, const char *tagname ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( !stricmp( ptag->GetName(), tagname ) ) { m_AbsoluteTags[ type ].Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: makes sure tags in PLAYBACK are in the same order as ORIGINAL // Input : // Output : true if they were in order, false if it has to reorder them //----------------------------------------------------------------------------- bool CChoreoEvent::VerifyTagOrder( ) { bool bInOrder = true; // Sort tags CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f ); for ( int i = 0; i < m_AbsoluteTags[ CChoreoEvent::ORIGINAL ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ CChoreoEvent::ORIGINAL ][ i ]; if ( !ptag ) continue; CEventAbsoluteTag *t1 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ i ]; if ( stricmp( ptag->GetName(), t1->GetName() ) == 0) continue; bInOrder = false; for ( int j = i + 1; j < m_AbsoluteTags[ CChoreoEvent::PLAYBACK ].Size(); j++ ) { CEventAbsoluteTag *t2 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ j ]; if ( stricmp( ptag->GetName(), t2->GetName() ) == 0 ) { temp = *t1; *t1 = *t2; *t2 = temp; break; } } } return bInOrder; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - //----------------------------------------------------------------------------- float CChoreoEvent::GetBoundedAbsoluteTagPercentage( AbsTagType type, int tagnum ) { if ( tagnum <= -2 ) { /* if (GetNumAbsoluteTags( type ) >= 1) { CEventAbsoluteTag *tag = GetAbsoluteTag( type, 0 ); Assert( tag ); return -tag->GetTime(); } */ return 0.0f; // -0.5f; } else if ( tagnum == -1 ) { return 0.0f; } else if ( tagnum == GetNumAbsoluteTags( type ) ) { return 1.0; } else if ( tagnum > GetNumAbsoluteTags( type ) ) { /* if (GetNumAbsoluteTags( type ) >= 1) { CEventAbsoluteTag *tag = GetAbsoluteTag( type, tagnum - 2 ); Assert( tag ); return 2.0 - tag->GetTime(); } */ return 1.0; // 1.5; } /* { float duration = GetDuration(); if ( type == SHIFTED ) { float seqduration; GetGestureSequenceDuration( seqduration ); return seqduration; } return duration; } */ CEventAbsoluteTag *tag = GetAbsoluteTag( type, tagnum ); Assert( tag ); return tag->GetPercentage(); } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetOriginalPercentageFromPlaybackPercentage( float t ) { Assert( GetType() == GESTURE ); if ( GetType() != GESTURE ) return t; int count = GetNumAbsoluteTags( PLAYBACK ); if ( count != GetNumAbsoluteTags( ORIGINAL ) ) { return t; } if ( count <= 0 ) { return t; } if ( t <= 0.0f ) return 0.0f; float s = 0.0f, n = 0.0f; // find what tags this is between int i; for ( i = -1 ; i < count; i++ ) { s = GetBoundedAbsoluteTagPercentage( PLAYBACK, i ); n = GetBoundedAbsoluteTagPercentage( PLAYBACK, i + 1 ); if ( t >= s && t <= n ) { break; } } int prev = i - 1; int start = i; int end = i + 1; int next = i + 2; prev = MAX( -2, prev ); start = MAX( -1, start ); end = MIN( end, count ); next = MIN( next, count + 1 ); CEventAbsoluteTag *pStartTag = NULL; CEventAbsoluteTag *pEndTag = NULL; // check for linear portion of lookup if (start >= 0 && start < count) { pStartTag = GetAbsoluteTag( PLAYBACK, start ); } if (end >= 0 && end < count) { pEndTag = GetAbsoluteTag( PLAYBACK, end ); } if (pStartTag && pEndTag) { if (pStartTag->GetLinear() && pEndTag->GetLinear()) { CEventAbsoluteTag *pOrigStartTag = GetAbsoluteTag( ORIGINAL, start ); CEventAbsoluteTag *pOrigEndTag = GetAbsoluteTag( ORIGINAL, end ); if (pOrigStartTag && pOrigEndTag) { s = ( t - pStartTag->GetPercentage() ) / (pEndTag->GetPercentage() - pStartTag->GetPercentage()); return (1 - s) * pOrigStartTag->GetPercentage() + s * pOrigEndTag->GetPercentage(); } } } float dt = n - s; Vector vPre( GetBoundedAbsoluteTagPercentage( PLAYBACK, prev ), GetBoundedAbsoluteTagPercentage( ORIGINAL, prev ), 0 ); Vector vStart( GetBoundedAbsoluteTagPercentage( PLAYBACK, start ), GetBoundedAbsoluteTagPercentage( ORIGINAL, start ), 0 ); Vector vEnd( GetBoundedAbsoluteTagPercentage( PLAYBACK, end ), GetBoundedAbsoluteTagPercentage( ORIGINAL, end ), 0 ); Vector vNext( GetBoundedAbsoluteTagPercentage( PLAYBACK, next ), GetBoundedAbsoluteTagPercentage( ORIGINAL, next ), 0 ); // simulate sections of either side of "linear" portion of ramp as linear slope if (pStartTag && pStartTag->GetLinear()) { vPre.Init( vStart.x - (vEnd.x - vStart.x), vStart.y - (vEnd.y - vStart.y), 0 ); } if (pEndTag && pEndTag->GetLinear()) { vNext.Init( vEnd.x + (vEnd.x - vStart.x), vEnd.y + (vEnd.y - vStart.y), 0 ); } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( t - s ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; Catmull_Rom_Spline_NormalizeX( vPre, vStart, vEnd, vNext, f2, vOut ); return vOut.y; /* float duration; GetGestureSequenceDuration( duration ); float retval = clamp( vOut.y, 0.0f, duration ); return retval; */ } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetPlaybackPercentageFromOriginalPercentage( float t ) { Assert( GetType() == GESTURE ); if ( GetType() != GESTURE ) return t; int count = GetNumAbsoluteTags( PLAYBACK ); if ( count != GetNumAbsoluteTags( ORIGINAL ) ) { return t; } if ( count <= 0 ) { return t; } if ( t <= 0.0f ) return 0.0f; float s = 0.0f, n = 0.0f; // find what tags this is between int i; for ( i = -1 ; i < count; i++ ) { s = GetBoundedAbsoluteTagPercentage( PLAYBACK, i ); n = GetBoundedAbsoluteTagPercentage( PLAYBACK, i + 1 ); if ( t >= s && t <= n ) { break; } } int prev = i - 1; int start = i; int end = i + 1; int next = i + 2; prev = MAX( -2, prev ); start = MAX( -1, start ); end = MIN( end, count ); next = MIN( next, count + 1 ); CEventAbsoluteTag *pStartTag = NULL; CEventAbsoluteTag *pEndTag = NULL; // check for linear portion of lookup if (start >= 0 && start < count) { pStartTag = GetAbsoluteTag( ORIGINAL, start ); } if (end >= 0 && end < count) { pEndTag = GetAbsoluteTag( ORIGINAL, end ); } // check for linear portion of lookup if (pStartTag && pEndTag) { if (pStartTag->GetLinear() && pEndTag->GetLinear()) { CEventAbsoluteTag *pPlaybackStartTag = GetAbsoluteTag( PLAYBACK, start ); CEventAbsoluteTag *pPlaybackEndTag = GetAbsoluteTag( PLAYBACK, end ); if (pPlaybackStartTag && pPlaybackEndTag) { s = ( t - pStartTag->GetPercentage() ) / (pEndTag->GetPercentage() - pStartTag->GetPercentage()); return (1 - s) * pPlaybackStartTag->GetPercentage() + s * pPlaybackEndTag->GetPercentage(); } } } float dt = n - s; Vector vPre( GetBoundedAbsoluteTagPercentage( ORIGINAL, prev ), GetBoundedAbsoluteTagPercentage( PLAYBACK, prev ), 0 ); Vector vStart( GetBoundedAbsoluteTagPercentage( ORIGINAL, start ), GetBoundedAbsoluteTagPercentage( PLAYBACK, start ), 0 ); Vector vEnd( GetBoundedAbsoluteTagPercentage( ORIGINAL, end ), GetBoundedAbsoluteTagPercentage( PLAYBACK, end ), 0 ); Vector vNext( GetBoundedAbsoluteTagPercentage( ORIGINAL, next ), GetBoundedAbsoluteTagPercentage( PLAYBACK, next ), 0 ); // simulate sections of either side of "linear" portion of ramp as linear slope if (pStartTag && pStartTag->GetLinear()) { vPre.Init( vStart.x - (vEnd.x - vStart.x), vStart.y - (vEnd.y - vStart.y), 0 ); } if (pEndTag && pEndTag->GetLinear()) { vNext.Init( vEnd.x + (vEnd.x - vStart.x), vEnd.y + (vEnd.y - vStart.y), 0 ); } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( t - s ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; Catmull_Rom_Spline_NormalizeX( vPre, vStart, vEnd, vNext, f2, vOut ); return vOut.y; /* float duration; GetGestureSequenceDuration( duration ); float retval = clamp( vOut.y, 0.0f, duration ); return retval; */ } //----------------------------------------------------------------------------- // Purpose: // Input : duration - //----------------------------------------------------------------------------- void CChoreoEvent::SetGestureSequenceDuration( float duration ) { m_flGestureSequenceDuration = duration; } //----------------------------------------------------------------------------- // Purpose: // Input : duration - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::GetGestureSequenceDuration( float& duration ) { bool valid = m_flGestureSequenceDuration != 0.0f; if ( !valid ) { duration = GetDuration(); } else { duration = m_flGestureSequenceDuration; } return valid; } //----------------------------------------------------------------------------- // Purpose: // Input : pitch - //----------------------------------------------------------------------------- int CChoreoEvent::GetPitch( void ) const { return m_nPitch; } //----------------------------------------------------------------------------- // Purpose: // Input : pitch - //----------------------------------------------------------------------------- void CChoreoEvent::SetPitch( int pitch ) { m_nPitch = pitch; } //----------------------------------------------------------------------------- // Purpose: // Input : yaw - //----------------------------------------------------------------------------- int CChoreoEvent::GetYaw( void ) const { return m_nYaw; } //----------------------------------------------------------------------------- // Purpose: // Input : yaw - //----------------------------------------------------------------------------- void CChoreoEvent::SetYaw( int yaw ) { m_nYaw = yaw; } //----------------------------------------------------------------------------- // Purpose: // Input : t - // -1 - //----------------------------------------------------------------------------- void CChoreoEvent::SetLoopCount( int numloops ) { Assert( GetType() == LOOP ); // Never below -1 m_nNumLoops = MAX( numloops, -1 ); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumLoopsRemaining( void ) { Assert( GetType() == LOOP ); return m_nLoopsRemaining; } //----------------------------------------------------------------------------- // Purpose: // Input : loops - //----------------------------------------------------------------------------- void CChoreoEvent::SetNumLoopsRemaining( int loops ) { Assert( GetType() == LOOP ); m_nLoopsRemaining = loops; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetLoopCount( void ) { Assert( GetType() == LOOP ); return m_nNumLoops; } EdgeInfo_t *CCurveData::GetEdgeInfo( int idx ) { return &m_RampEdgeInfo[ idx ]; } int CCurveData::GetCount( void ) { return m_Ramp.Count(); } CExpressionSample *CCurveData::Get( int index ) { if ( index < 0 || index >= GetCount() ) return NULL; return &m_Ramp[ index ]; } CExpressionSample *CCurveData::Add( float time, float value, bool selected ) { CExpressionSample sample; sample.time = time; sample.value = value; sample.selected = selected; int idx = m_Ramp.AddToTail( sample ); return &m_Ramp[ idx ]; } void CCurveData::Delete( int index ) { if ( index < 0 || index >= GetCount() ) return; m_Ramp.Remove( index ); } void CCurveData::Clear( void ) { m_Ramp.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CCurveData::Resort( ICurveDataAccessor *data ) { for ( int i = 0; i < m_Ramp.Size(); i++ ) { for ( int j = i + 1; j < m_Ramp.Size(); j++ ) { CExpressionSample src = m_Ramp[ i ]; CExpressionSample dest = m_Ramp[ j ]; if ( src.time > dest.time ) { m_Ramp[ i ] = dest; m_Ramp[ j ] = src; } } } RemoveOutOfRangeSamples( data ); // m_RampAccumulator.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : number - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CCurveData::GetBoundedSample( ICurveDataAccessor *data, int number, bool& bClamped ) { // Search for two samples which span time f if ( number < 0 ) { static CExpressionSample nullstart; nullstart.time = 0.0f; nullstart.value = GetEdgeZeroValue( true ); nullstart.SetCurveType( GetEdgeCurveType( true ) ); bClamped = true; return &nullstart; } else if ( number >= GetCount() ) { static CExpressionSample nullend; nullend.time = data->GetDuration(); nullend.value = GetEdgeZeroValue( false ); nullend.SetCurveType( GetEdgeCurveType( false ) ); bClamped = true; return &nullend; } bClamped = false; return Get( number ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CCurveData::RemoveOutOfRangeSamples( ICurveDataAccessor *data ) { float duration = data->GetDuration(); int c = GetCount(); for ( int i = c-1; i >= 0; i-- ) { CExpressionSample src = m_Ramp[ i ]; if ( src.time < 0 || src.time > duration + 0.01 ) { m_Ramp.Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::RescaleGestureTimes( float newstart, float newend, bool bMaintainAbsoluteTagPositions ) { if ( GetType() != CChoreoEvent::GESTURE ) return; // Did it actually change if ( newstart == GetStartTime() && newend == GetEndTime() ) { return; } float newduration = newend - newstart; float dt = 0.0f; //If the end is moving, leave tags stay where they are (dt == 0.0f) if ( newstart != GetStartTime() ) { // Otherwise, if the new start is later, then tags need to be shifted backwards dt -= ( newstart - GetStartTime() ); } if ( bMaintainAbsoluteTagPositions ) { int i; int count = GetNumAbsoluteTags( CChoreoEvent::PLAYBACK ); for ( i = 0; i < count; i++ ) { CEventAbsoluteTag *tag = GetAbsoluteTag( CChoreoEvent::PLAYBACK, i ); float tagtime = tag->GetPercentage() * GetDuration(); tagtime += dt; tagtime = clamp( tagtime / newduration, 0.0f, 1.0f ); tag->SetPercentage( tagtime ); } } } //----------------------------------------------------------------------------- // Purpose: Make sure tags aren't co-located or out of order //----------------------------------------------------------------------------- bool CChoreoEvent::PreventTagOverlap( void ) { bool bHadOverlap = false; // FIXME: limit to single frame? float minDp = 0.01; float minP = 1.00; int count = GetNumAbsoluteTags( CChoreoEvent::PLAYBACK ); for ( int i = count - 1; i >= 0; i-- ) { CEventAbsoluteTag *tag = GetAbsoluteTag( CChoreoEvent::PLAYBACK, i ); if (tag->GetPercentage() > minP) { tag->SetPercentage( minP ); minDp = MIN( 0.01, minP / (i + 1) ); bHadOverlap = true; } else { minP = tag->GetPercentage(); } minP = MAX( minP - minDp, 0 ); } return bHadOverlap; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindEntryTag( AbsTagType type ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( ptag->GetEntry() ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindExitTag( AbsTagType type ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( ptag->GetExit() ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : *style - // maxlen - //----------------------------------------------------------------------------- void CChoreoEvent::GetMovementStyle( char *style, int maxlen ) { Assert( GetType() == MOVETO ); style[0] = 0; const char *in = m_Parameters2.Get(); char *out = style; while ( *in && *in != '\0' && *in != ' ' ) { if ( out - style >= maxlen - 1 ) break; *out++ = *in++; } *out = 0; } //----------------------------------------------------------------------------- // Purpose: // Input : *style - // maxlen - //----------------------------------------------------------------------------- void CChoreoEvent::GetDistanceStyle( char *style, int maxlen ) { Assert( GetType() == MOVETO ); style[0]= 0; const char *in = Q_strstr( m_Parameters2.Get(), " " ); if ( !in ) return; in++; char *out = style; while ( *in && *in != '\0' ) { if ( out - style >= maxlen - 1 ) break; *out++ = *in++; } *out = 0; } void CChoreoEvent::SetCloseCaptionType( CLOSECAPTION type ) { Assert( m_fType == SPEAK ); m_ccType = type; } CChoreoEvent::CLOSECAPTION CChoreoEvent::GetCloseCaptionType() const { Assert( m_fType == SPEAK ); return (CLOSECAPTION)m_ccType; } void CChoreoEvent::SetCloseCaptionToken( char const *token ) { Assert( m_fType == SPEAK ); Assert( token ); m_CCToken = token; } char const *CChoreoEvent::GetCloseCaptionToken() const { Assert( m_fType == SPEAK ); return m_CCToken.Get(); } bool CChoreoEvent::GetPlaybackCloseCaptionToken( char *dest, int destlen ) { dest[0] = 0; Assert( m_fType == SPEAK ); switch ( m_ccType ) { default: case CC_DISABLED: { return false; } case CC_SLAVE: { // If it's a slave, then only disable if we're not using the combined wave if ( IsUsingCombinedFile() ) { return false; } if ( m_CCToken[ 0 ] != 0 ) { Q_strncpy( dest, m_CCToken.Get(), destlen ); } else { Q_strncpy( dest, m_Parameters.Get(), destlen ); } return true; } case CC_MASTER: { // Always use the override if we're the master, otherwise always use the default // parameter if ( m_CCToken[ 0 ] != 0 ) { Q_strncpy( dest, m_CCToken.Get(), destlen ); } else { Q_strncpy( dest, m_Parameters.Get(), destlen ); } return true; } } return false; } void CChoreoEvent::SetUsingCombinedFile( bool isusing ) { Assert( m_fType == SPEAK ); m_bUsingCombinedSoundFile = isusing; } bool CChoreoEvent::IsUsingCombinedFile() const { Assert( m_fType == SPEAK ); return m_bUsingCombinedSoundFile; } void CChoreoEvent::SetRequiredCombinedChecksum( unsigned int checksum ) { Assert( m_fType == SPEAK ); m_uRequiredCombinedChecksum = checksum; } unsigned int CChoreoEvent::GetRequiredCombinedChecksum() { Assert( m_fType == SPEAK ); return m_uRequiredCombinedChecksum; } void CChoreoEvent::SetNumSlaves( int num ) { Assert( m_fType == SPEAK ); Assert( num >= 0 ); m_nNumSlaves = num; } int CChoreoEvent::GetNumSlaves() const { Assert( m_fType == SPEAK ); return m_nNumSlaves; } void CChoreoEvent::SetLastSlaveEndTime( float t ) { Assert( m_fType == SPEAK ); m_flLastSlaveEndTime = t; } float CChoreoEvent::GetLastSlaveEndTime() const { Assert( m_fType == SPEAK ); return m_flLastSlaveEndTime; } void CChoreoEvent::SetCloseCaptionTokenValid( bool valid ) { Assert( m_fType == SPEAK ); m_bCCTokenValid = valid; } bool CChoreoEvent::GetCloseCaptionTokenValid() const { Assert( m_fType == SPEAK ); return m_bCCTokenValid; } //----------------------------------------------------------------------------- // Purpose: Removes characters which can't appear in windows filenames // Input : *in - // *dest - // destlen - // Output : static void //----------------------------------------------------------------------------- static void CleanupTokenName( char const *in, char *dest, int destlen ) { char *out = dest; while ( *in && ( out - dest ) < destlen ) { if ( V_isalnum( *in ) || // lowercase, uppercase, digits and underscore are valid *in == '_' ) { *out++ = *in; } else { *out++ = '_'; // Put underscores in for bogus characters } in++; } *out = 0; } bool CChoreoEvent::ComputeCombinedBaseFileName( char *dest, int destlen, bool creategenderwildcard ) { if ( m_fType != SPEAK ) return false; if ( m_ccType != CC_MASTER ) return false; if ( GetNumSlaves() == 0 ) return false; if ( !m_pScene ) return false; char vcdpath[ 512 ]; char cleanedtoken[ MAX_CCTOKEN_STRING ]; CleanupTokenName( m_CCToken.Get(), cleanedtoken, sizeof( cleanedtoken ) ); if ( Q_strlen( cleanedtoken ) <= 0 ) return false; Q_strncpy( vcdpath, m_pScene->GetFilename(), sizeof( vcdpath ) ); Q_StripFilename( vcdpath ); Q_FixSlashes( vcdpath, '/' ); char *pvcd = vcdpath; char *offset = Q_strstr( vcdpath, "scenes" ); if ( offset ) { pvcd = offset + 6; if ( *pvcd == '/' ) { ++pvcd; } } int len = Q_strlen( pvcd ); if ( len > 0 && ( len + 1 ) < ( sizeof( vcdpath ) - 1 ) ) { pvcd[ len ] = '/'; pvcd[ len + 1 ] = 0; } Assert( !Q_strstr( pvcd, ":" ) ); if ( creategenderwildcard ) { Q_snprintf( dest, destlen, "sound/combined/%s%s_$gender.wav", pvcd, cleanedtoken ); } else { Q_snprintf( dest, destlen, "sound/combined/%s%s.wav", pvcd, cleanedtoken ); } return true; } bool CChoreoEvent::IsCombinedUsingGenderToken() const { return m_bCombinedUsingGenderToken; } void CChoreoEvent::SetCombinedUsingGenderToken( bool using_gender ) { m_bCombinedUsingGenderToken = using_gender; } int CChoreoEvent::ValidateCombinedFile() { return 0; } bool CChoreoEvent::IsSuppressingCaptionAttenuation() const { return m_bSuppressCaptionAttenuation; } void CChoreoEvent::SetSuppressingCaptionAttenuation( bool suppress ) { m_bSuppressCaptionAttenuation = suppress; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearEventDependencies() { m_Dependencies.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : *other - //----------------------------------------------------------------------------- void CChoreoEvent::AddEventDependency( CChoreoEvent *other ) { if ( m_Dependencies.Find( other ) == m_Dependencies.InvalidIndex() ) { m_Dependencies.AddToTail( other ); } } //----------------------------------------------------------------------------- // Purpose: // Input : list - //----------------------------------------------------------------------------- void CChoreoEvent::GetEventDependencies( CUtlVector< CChoreoEvent * >& list ) { int c = m_Dependencies.Count(); for ( int i = 0; i < c; ++i ) { list.AddToTail( m_Dependencies[ i ] ); } } void CCurveData::SetEdgeInfo( bool leftEdge, int curveType, float zero ) { int idx = leftEdge ? 0 : 1; m_RampEdgeInfo[ idx ].m_CurveType = curveType; m_RampEdgeInfo[ idx ].m_flZeroPos = zero; } void CCurveData::GetEdgeInfo( bool leftEdge, int& curveType, float& zero ) const { int idx = leftEdge ? 0 : 1; curveType = m_RampEdgeInfo[ idx ].m_CurveType; zero = m_RampEdgeInfo[ idx ].m_flZeroPos; } void CCurveData::SetEdgeActive( bool leftEdge, bool state ) { int idx = leftEdge ? 0 : 1; m_RampEdgeInfo[ idx ].m_bActive = state; } bool CCurveData::IsEdgeActive( bool leftEdge ) const { int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_bActive; } int CCurveData::GetEdgeCurveType( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return CURVE_DEFAULT; } int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_CurveType; } float CCurveData::GetEdgeZeroValue( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return 0.0f; } int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_flZeroPos; } void CChoreoEvent::SaveToBuffer( CUtlBuffer& buf, CChoreoScene *pScene, IChoreoStringPool *pStringPool ) { buf.PutChar( GetType() ); buf.PutShort( pStringPool->FindOrAddString( GetName() ) ); float st = GetStartTime(); buf.PutFloat( st ); float et = GetEndTime(); buf.PutFloat( et ); buf.PutShort( pStringPool->FindOrAddString( GetParameters() ) ); buf.PutShort( pStringPool->FindOrAddString( GetParameters2() ) ); buf.PutShort( pStringPool->FindOrAddString( GetParameters3() ) ); m_Ramp.SaveToBuffer( buf, pStringPool ); int flags = 0; flags |= IsResumeCondition() ? 1<<0 : 0; flags |= IsLockBodyFacing() ? 1<<1 : 0; flags |= IsFixedLength() ? 1<<2 : 0; flags |= GetActive() ? 1<<3 : 0; flags |= GetForceShortMovement() ? 1<<4 : 0; flags |= GetPlayOverScript() ? 1<<5 : 0; buf.PutUnsignedChar( flags ); buf.PutFloat( GetDistanceToTarget() ); int numRelativeTags = GetNumRelativeTags(); Assert( numRelativeTags <= 255 ); buf.PutUnsignedChar( numRelativeTags ); for ( int t = 0; t < numRelativeTags; t++ ) { CEventRelativeTag *rt = GetRelativeTag( t ); Assert( rt ); buf.PutShort( pStringPool->FindOrAddString( rt->GetName() ) ); Assert( rt->GetPercentage() >= 0.0f && rt->GetPercentage() <= 1.0f ); unsigned char p = rt->GetPercentage() * 255.0f; buf.PutUnsignedChar( p ); } int numTimingTags = GetNumTimingTags(); Assert( numTimingTags <= 255 ); buf.PutUnsignedChar( numTimingTags ); for ( int t = 0; t < numTimingTags; t++ ) { CFlexTimingTag *tt = GetTimingTag( t ); Assert( tt ); buf.PutShort( pStringPool->FindOrAddString( tt->GetName() ) ); // save as u0.8 Assert( tt->GetPercentage() >= 0.0f && tt->GetPercentage() <= 1.0f ); unsigned char p = tt->GetPercentage() * 255.0f; buf.PutUnsignedChar( p ); // Don't save locked state, it's only used by the editor tt->GetLocked() } int tagtype; for ( tagtype = 0; tagtype < CChoreoEvent::NUM_ABS_TAG_TYPES; tagtype++ ) { int num = GetNumAbsoluteTags( (CChoreoEvent::AbsTagType)tagtype ); Assert( num <= 255 ); buf.PutUnsignedChar( num ); for ( int i = 0; i < num ; ++i ) { CEventAbsoluteTag *abstag = GetAbsoluteTag( (CChoreoEvent::AbsTagType)tagtype, i ); Assert( abstag ); buf.PutShort( pStringPool->FindOrAddString( abstag->GetName() ) ); // save as u4.12 Assert( abstag->GetPercentage() >= 0.0f && abstag->GetPercentage() <= 15.0f ); unsigned short p = abstag->GetPercentage() * 4096.0f; buf.PutUnsignedShort( p ); } } if ( GetType() == CChoreoEvent::GESTURE ) { float duration; if ( GetGestureSequenceDuration( duration ) ) { buf.PutFloat( duration ); } else { buf.PutFloat( -1.0f ); } } buf.PutChar( IsUsingRelativeTag() ? 1 : 0 ); if ( IsUsingRelativeTag() ) { buf.PutShort( pStringPool->FindOrAddString( GetRelativeTagName() ) ); buf.PutShort( pStringPool->FindOrAddString( GetRelativeWavName() ) ); } SaveFlexAnimationsToBuffer( buf, pStringPool ); if ( GetType() == LOOP ) { buf.PutChar( GetLoopCount() ); } if ( GetType() == CChoreoEvent::SPEAK ) { buf.PutChar( GetCloseCaptionType() ); buf.PutShort( pStringPool->FindOrAddString( GetCloseCaptionToken() ) ); flags = 0; if ( GetCloseCaptionType() != CChoreoEvent::CC_DISABLED && IsUsingCombinedFile() ) { flags |= ( 1<<0 ); } if ( IsCombinedUsingGenderToken() ) { flags |= ( 1<<1 ); } if ( IsSuppressingCaptionAttenuation() ) { flags |= ( 1<<2 ); } buf.PutChar( flags ); } } bool CChoreoEvent::RestoreFromBuffer( CUtlBuffer& buf, CChoreoScene *pScene, IChoreoStringPool *pStringPool ) { MEM_ALLOC_CREDIT(); SetType( (EVENTTYPE)buf.GetChar() ); char sz[ 256 ]; pStringPool->GetString( buf.GetShort(), sz, sizeof( sz ) ); SetName( sz ); SetStartTime( buf.GetFloat() ); SetEndTime( buf.GetFloat() ); char params[ 2048 ]; pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters( params ); pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters2( params ); pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters3( params ); if ( !m_Ramp.RestoreFromBuffer( buf, pStringPool ) ) return false; int flags = buf.GetUnsignedChar(); SetResumeCondition( ( flags & ( 1<<0 ) ) ? true : false ); SetLockBodyFacing( ( flags & ( 1<<1 ) ) ? true : false ); SetFixedLength( ( flags & ( 1<<2 ) ) ? true : false ); SetActive( ( flags & ( 1<<3 ) ) ? true : false ); SetForceShortMovement( ( flags & ( 1<<4 ) ) ? true : false ); SetPlayOverScript( ( flags & ( 1<<5 ) ) ? true : false ); SetDistanceToTarget( buf.GetFloat() ); int numRelTags = buf.GetUnsignedChar(); for ( int i = 0; i < numRelTags; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedChar() * 1.0f/255.0f; AddRelativeTag( tagName, percentage ); } int numTimingTags = buf.GetUnsignedChar(); for ( int i = 0; i < numTimingTags; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedChar() * 1.0f/255.0f; // Don't parse locked state, only used by editors AddTimingTag( tagName, percentage, false ); } int tagtype; for ( tagtype = 0; tagtype < CChoreoEvent::NUM_ABS_TAG_TYPES; tagtype++ ) { int num = buf.GetUnsignedChar(); for ( int i = 0; i < num; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedShort() * 1.0f/4096.0f; // Don't parse locked state, only used by editors AddAbsoluteTag( (CChoreoEvent::AbsTagType)tagtype, tagName, percentage ); } } if ( GetType() == CChoreoEvent::GESTURE ) { float duration = buf.GetFloat(); if ( duration != -1 ) { SetGestureSequenceDuration( duration ); } } if ( buf.GetChar() == 1 ) { char tagname[ 256 ]; char wavname[ 256 ]; pStringPool->GetString( buf.GetShort(), tagname, sizeof( tagname ) ); pStringPool->GetString( buf.GetShort(), wavname, sizeof( wavname ) ); SetUsingRelativeTag( true, tagname, wavname ); } if ( !RestoreFlexAnimationsFromBuffer( buf, pStringPool ) ) return false; if ( GetType() == LOOP ) { SetLoopCount( buf.GetChar() ); } if ( GetType() == CChoreoEvent::SPEAK ) { SetCloseCaptionType( (CLOSECAPTION)buf.GetChar() ); char cctoken[ 256 ]; pStringPool->GetString( buf.GetShort(), cctoken, sizeof( cctoken ) ); SetCloseCaptionToken( cctoken ); int flags = buf.GetChar(); if ( flags & ( 1<<0 ) ) { SetUsingCombinedFile( true ); } if ( flags & ( 1<<1 ) ) { SetCombinedUsingGenderToken( true ); } if ( flags & ( 1<<2 ) ) { SetSuppressingCaptionAttenuation( true ); } } return true; } void CCurveData::SaveToBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int c = GetCount(); Assert( c <= 255 ); buf.PutUnsignedChar( c ); for ( int i = 0; i < c; i++ ) { CExpressionSample *sample = Get( i ); buf.PutFloat( sample->time ); Assert( sample->value >= 0.0f && sample->value <= 1.0f ); unsigned char v = sample->value * 255.0f; buf.PutUnsignedChar( v ); } } bool CCurveData::RestoreFromBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int c = buf.GetUnsignedChar(); for ( int i = 0; i < c; i++ ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; Add( t, v, false ); } return true; } void CChoreoEvent::SaveFlexAnimationsToBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int numFlexAnimationTracks = GetNumFlexAnimationTracks(); Assert( numFlexAnimationTracks <= 255 ); buf.PutUnsignedChar( numFlexAnimationTracks ); for ( int i = 0; i < numFlexAnimationTracks; i++ ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( i ); buf.PutShort( pStringPool->FindOrAddString( track->GetFlexControllerName() ) ); int flags = 0; flags |= track->IsTrackActive() ? 1<<0 : 0; flags |= track->IsComboType() ? 1<<1 : 0; buf.PutUnsignedChar( flags ); buf.PutFloat( track->GetMin() ); buf.PutFloat( track->GetMax() ); buf.PutShort( track->GetNumSamples( 0 ) ); for ( int j = 0 ; j < track->GetNumSamples( 0 ) ; j++ ) { CExpressionSample *s = track->GetSample( j, 0 ); if ( !s ) continue; buf.PutFloat( s->time ); Assert( s->value >= 0.0f && s->value <= 1.0f ); unsigned char v = s->value * 255.0f; buf.PutUnsignedChar( v ); buf.PutUnsignedShort( s->GetCurveType() ); } // Write out combo samples if ( track->IsComboType() ) { int numSamples = track->GetNumSamples( 1 ); Assert( numSamples <= 32767 ); buf.PutUnsignedShort( numSamples ); for ( int j = 0; j < numSamples; j++ ) { CExpressionSample *s = track->GetSample( j, 1 ); if ( !s ) continue; buf.PutFloat( s->time ); Assert( s->value >= 0.0f && s->value <= 1.0f ); unsigned char v = s->value * 255.0f; buf.PutUnsignedChar( v ); buf.PutUnsignedShort( s->GetCurveType() ); } } } } bool CChoreoEvent::RestoreFlexAnimationsFromBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int numTracks = buf.GetUnsignedChar(); for ( int i = 0; i < numTracks; i++ ) { char name[ 256 ]; pStringPool->GetString( buf.GetShort(), name, sizeof( name ) ); CFlexAnimationTrack *track = AddTrack( name ); int flags = buf.GetUnsignedChar(); track->SetTrackActive( ( flags & ( 1<<0 ) ) ? true : false ); track->SetComboType( ( flags & ( 1<<1 ) ) ? true : false ); track->SetMin( buf.GetFloat() ); track->SetMax( buf.GetFloat() ); int s = buf.GetShort(); for ( int j = 0; j < s; ++j ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; CExpressionSample *pSample = track->AddSample( t, v, 0 ); pSample->SetCurveType( buf.GetUnsignedShort() ); } if ( track->IsComboType() ) { int s = buf.GetUnsignedShort(); for ( int j = 0; j < s; ++j ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; CExpressionSample *pSample = track->AddSample( t, v, 1 ); pSample->SetCurveType( buf.GetUnsignedShort() ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: Marks the event as enabled/disabled // Input : state - //----------------------------------------------------------------------------- void CChoreoEvent::SetActive( bool state ) { m_bActive = state; } bool CChoreoEvent::GetActive() const { return m_bActive; }
121,192
41,625
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include "InMemoryView.h" #include "watchman_error_category.h" namespace watchman { void InMemoryView::statPath( const std::shared_ptr<w_root_t>& root, SyncView::LockedPtr& view, PendingCollection::LockedPtr& coll, const w_string& full_path, struct timeval now, int flags, const watchman_dir_ent* pre_stat) { watchman::FileInformation st; std::error_code errcode; char path[WATCHMAN_NAME_MAX]; bool recursive = flags & W_PENDING_RECURSIVE; bool via_notify = flags & W_PENDING_VIA_NOTIFY; if (root->ignore.isIgnoreDir(full_path)) { w_log( W_LOG_DBG, "%.*s matches ignore_dir rules\n", int(full_path.size()), full_path.data()); return; } if (full_path.size() > sizeof(path) - 1) { w_log( W_LOG_FATAL, "path %.*s is too big\n", int(full_path.size()), full_path.data()); } memcpy(path, full_path.data(), full_path.size()); path[full_path.size()] = 0; auto dir_name = full_path.dirName(); auto file_name = full_path.baseName(); auto parentDir = resolveDir(view, dir_name, true); auto file = parentDir->getChildFile(file_name); auto dir_ent = parentDir->getChildDir(file_name); if (pre_stat && pre_stat->has_stat) { st = pre_stat->stat; } else { try { st = getFileInformation(path, root->case_sensitive); log(DBG, "getFileInformation(", path, ") file=", file, " dir=", dir_ent, "\n"); } catch (const std::system_error &exc) { errcode = exc.code(); log(DBG, "getFileInformation(", path, ") file=", file, " dir=", dir_ent, " failed: ", exc.what(), "\n"); } } if (errcode == watchman::error_code::no_such_file_or_directory || errcode == watchman::error_code::not_a_directory) { /* it's not there, update our state */ if (dir_ent) { markDirDeleted(view, dir_ent, now, true); watchman::log( watchman::DBG, "getFileInformation(", path, ") -> ", errcode.message(), " so stopping watch\n"); } if (file) { if (file->exists) { watchman::log( watchman::DBG, "getFileInformation(", path, ") -> ", errcode.message(), " so marking ", file->getName(), " deleted\n"); file->exists = false; markFileChanged(view, file, now); } } else { // It was created and removed before we could ever observe it // in the filesystem. We need to generate a deleted file // representation of it now, so that subscription clients can // be notified of this event file = getOrCreateChildFile(view, parentDir, file_name, now); log(DBG, "getFileInformation(", path, ") -> ", errcode.message(), " and file node was NULL. " "Generating a deleted node.\n"); file->exists = false; markFileChanged(view, file, now); } if (root->case_sensitive == CaseSensitivity::CaseInSensitive && !w_string_equal(dir_name, root->root_path) && parentDir->last_check_existed) { /* If we rejected the name because it wasn't canonical, * we need to ensure that we look in the parent dir to discover * the new item(s) */ w_log( W_LOG_DBG, "we're case insensitive, and %s is ENOENT, " "speculatively look at parent dir %.*s\n", path, int(dir_name.size()), dir_name.data()); coll->add(dir_name, now, W_PENDING_CRAWL_ONLY); } } else if (errcode.value()) { log(ERR, "getFileInformation(", path, ") failed and not handled! -> ", errcode.message(), " value=", errcode.value(), " category=", errcode.category().name(), "\n"); } else { if (!file) { file = getOrCreateChildFile(view, parentDir, file_name, now); } if (!file->exists) { /* we're transitioning from deleted to existing, * so we're effectively new again */ file->ctime.ticks = view->mostRecentTick; file->ctime.timestamp = now.tv_sec; /* if a dir was deleted and now exists again, we want * to crawl it again */ recursive = true; } if (!file->exists || via_notify || did_file_change(&file->stat, &st)) { w_log( W_LOG_DBG, "file changed exists=%d via_notify=%d stat-changed=%d isdir=%d %s\n", (int)file->exists, (int)via_notify, (int)(file->exists && !via_notify), st.isDir(), path); file->exists = true; markFileChanged(view, file, now); } memcpy(&file->stat, &st, sizeof(file->stat)); // check for symbolic link if (st.isSymlink()) { try { auto target = readSymbolicLink(path); bool symlink_changed = false; if (file->symlink_target != target) { symlink_changed = true; } file->symlink_target = target; if (symlink_changed && root->config.getBool("watch_symlinks", false)) { root->inner.pending_symlink_targets.wlock()->add(full_path, now, 0); } } catch (const std::system_error& exc) { log(ERR, "readlink(", path, ") failed: ", exc.what(), "\n"); file->symlink_target.reset(); } } else { file->symlink_target.reset(); } if (st.isDir()) { if (dir_ent == NULL) { recursive = true; } else { // Ensure that we believe that this node exists dir_ent->last_check_existed = true; } // Don't recurse if our parent is an ignore dir if (!root->ignore.isIgnoreVCS(dir_name) || // but do if we're looking at the cookie dir (stat_path is never // called for the root itself) w_string_equal(full_path, root->cookies.cookieDir())) { if (!(watcher_->flags & WATCHER_HAS_PER_FILE_NOTIFICATIONS)) { /* we always need to crawl, but may not need to be fully recursive */ coll->add( full_path, now, W_PENDING_CRAWL_ONLY | (recursive ? W_PENDING_RECURSIVE : 0)); } else { /* we get told about changes on the child, so we only * need to crawl if we've never seen the dir before. * An exception is that fsevents will only report the root * of a dir rename and not a rename event for all of its * children. */ if (recursive) { coll->add( full_path, now, W_PENDING_RECURSIVE | W_PENDING_CRAWL_ONLY); } } } } else if (dir_ent) { // We transitioned from dir to file (see fishy.php), so we should prune // our former tree here markDirDeleted(view, dir_ent, now, true); } if ((watcher_->flags & WATCHER_HAS_PER_FILE_NOTIFICATIONS) && !st.isDir() && !w_string_equal(dir_name, root->root_path) && parentDir->last_check_existed) { /* Make sure we update the mtime on the parent directory. * We're deliberately not propagating any of the flags through; we * definitely don't want this to be a recursive evaluation and we * won'd want to treat this as VIA_NOTIFY to avoid spuriously * marking the node as changed when only its atime was changed. * https://github.com/facebook/watchman/issues/305 and * https://github.com/facebook/watchman/issues/307 have more * context on why this is. */ coll->add(dir_name, now, 0); } } } } /* vim:ts=2:sw=2:et: */
7,760
2,498
///////////////////////////////////////////////////////////////////////////////////////////// // 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 "CPUTModelOGL.h" #include "CPUTMaterialEffectOGL.h" #include "CPUTFrustum.h" #include "CPUTAssetLibraryOGL.h" #include "CPUTTextureOGL.h" DrawModelCallBackFunc CPUTModel::mDrawModelCallBackFunc = CPUTModelOGL::DrawModelCallBack; //----------------------------------------------------------------------------- CPUTMeshOGL* CPUTModelOGL::GetMesh(const UINT index) const { return ( 0==mMeshCount || index > mMeshCount) ? NULL : (CPUTMeshOGL*)mpMesh[index]; } // Set the render state before drawing this object //----------------------------------------------------------------------------- void CPUTModelOGL::UpdateShaderConstants(CPUTRenderParameters &renderParams) { float4x4 world(*GetWorldMatrix()); float4x4 NormalMatrix(*GetWorldMatrix()); //Local transform if node baked into animation if(mSkeleton && mpCurrentAnimation) { world = GetParentsWorldMatrix(); NormalMatrix = GetParentsWorldMatrix(); } if( renderParams.mpPerModelConstants ) { CPUTBufferOGL *pBuffer = (CPUTBufferOGL*)(renderParams.mpPerModelConstants); CPUTModelConstantBuffer cb; cb.World = world; cb.InverseWorld = cb.World; cb.InverseWorld.invert(); CPUTCamera *pCamera = renderParams.mpCamera; if(pCamera) { cb.WorldViewProjection = cb.World * *pCamera->GetViewMatrix() * *pCamera->GetProjectionMatrix(); } float4x4 shadowView, shadowProjection; CPUTCamera *pShadowCamera = gpSample->GetShadowCamera(); if( pShadowCamera ) { shadowView = *pShadowCamera->GetViewMatrix(); shadowProjection = *pShadowCamera->GetProjectionMatrix(); cb.LightWorldViewProjection = cb.World * shadowView * shadowProjection; } cb.BoundingBoxCenterWorldSpace = float4(mBoundingBoxCenterWorldSpace, 0); cb.BoundingBoxHalfWorldSpace = float4(mBoundingBoxHalfWorldSpace, 0); cb.BoundingBoxCenterObjectSpace = float4(mBoundingBoxCenterObjectSpace, 0); cb.BoundingBoxHalfObjectSpace = float4(mBoundingBoxHalfObjectSpace, 0); //TODO: Should this process if object not visible? //Only do this if Model has a skin and is animated if(mSkeleton && mpCurrentAnimation) { ASSERT(0, _L("Skinning constant buffer temporarily disabled")); //ASSERT(mSkeleton->mNumberOfJoints < 255, _L("Skin Exceeds maximum number of allowable joints: 255")); //for(UINT i = 0; i < mSkeleton->mNumberOfJoints; ++i) //{ // CPUTJoint *pJoint = &mSkeleton->mJointsList[i]; // cb.SkinMatrix[i] = pJoint->mInverseBindPoseMatrix * pJoint->mScaleMatrix * pJoint->mRTMatrix; // float4x4 skinNormalMatrix = cb.SkinMatrix[i]; // skinNormalMatrix.invert(); skinNormalMatrix.transpose(); // cb.SkinNormalMatrix[i] = skinNormalMatrix; //} } #ifndef CPUT_FOR_OGLES2 pBuffer->SetSubData(0, sizeof(CPUTModelConstantBuffer), &cb); #else #warning "Need to do something with uniform buffers here" #endif } } // Render - render this model (only) //----------------------------------------------------------------------------- void CPUTModelOGL::Render(CPUTRenderParameters &renderParams, int materialIndex) { UpdateShaderConstants(renderParams); // loop over all meshes in this model and draw them for(UINT ii=0; ii<mMeshCount; ii++) { UINT finalMaterialIndex = GetMaterialIndex(ii, materialIndex); ASSERT( finalMaterialIndex < mpLayoutCount[ii], _L("material index out of range.")); CPUTMaterialEffect *pMaterialEffect = (CPUTMaterialEffect*)(mpMaterialEffect[ii][finalMaterialIndex]); mDrawModelCallBackFunc(this, renderParams, mpMesh[ii], pMaterialEffect, NULL, NULL); } } //----------------------------------------------------------------------------- // DrawModelCallBack - default model rendering code can be overridden by a callback set in user side code //----------------------------------------------------------------------------- bool CPUTModelOGL::DrawModelCallBack(CPUTModel* pModel, CPUTRenderParameters &renderParams, CPUTMesh* pMesh, CPUTMaterialEffect* pMaterial, CPUTMaterialEffect* , void* ) { pMaterial->SetRenderStates(renderParams); if( ((CPUTMaterialEffectOGL*)pMaterial)->Tessellated() ) ((CPUTMeshOGL*)pMesh)->DrawPatches(renderParams, pModel); else ((CPUTMeshOGL*)pMesh)->Draw(renderParams, pModel); return true; } #ifdef SUPPORT_DRAWING_BOUNDING_BOXES //----------------------------------------------------------------------------- void CPUTModelOGL::DrawBoundingBox(CPUTRenderParameters &renderParams) { SetRenderStates(renderParams); CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)mpBoundingBoxMaterial; mpBoundingBoxMaterial->SetRenderStates(renderParams); ((CPUTMeshOGL*)mpBoundingBoxMesh)->Draw(renderParams, this); } #endif // Load the set file definition of this object // 1. Parse the block of name/parent/transform info for model block // 2. Load the model's binary payload (i.e., the meshes) // 3. Assert the # of meshes matches # of materials // 4. Load each mesh's material //----------------------------------------------------------------------------- CPUTResult CPUTModelOGL::LoadModel(CPUTConfigBlock *pBlock, int *pParentID, CPUTModel *pMasterModel, int numSystemMaterials, cString *pSystemMaterialNames) { CPUTResult result = CPUT_SUCCESS; CPUTAssetLibraryOGL *pAssetLibrary = (CPUTAssetLibraryOGL*)CPUTAssetLibrary::GetAssetLibrary(); cString modelSuffix = ptoc(this); // set the model's name mName = pBlock->GetValueByName(_L("name"))->ValueAsString(); mName = mName + _L(".mdl"); // resolve the full path name cString modelLocation; cString resolvedPathAndFile; modelLocation = ((CPUTAssetLibraryOGL*)CPUTAssetLibrary::GetAssetLibrary())->GetModelDirectoryName(); modelLocation = modelLocation+mName; CPUTFileSystem::ResolveAbsolutePathAndFilename(modelLocation, &resolvedPathAndFile); // Get the parent ID. Note: the caller will use this to set the parent. *pParentID = pBlock->GetValueByName(_L("parent"))->ValueAsInt(); LoadParentMatrixFromParameterBlock( pBlock ); // Get the bounding box information float3 center(0.0f), half(0.0f); pBlock->GetValueByName(_L("BoundingBoxCenter"))->ValueAsFloatArray(center.f, 3); pBlock->GetValueByName(_L("BoundingBoxHalf"))->ValueAsFloatArray(half.f, 3); mBoundingBoxCenterObjectSpace = center; mBoundingBoxHalfObjectSpace = half; mMeshCount = pBlock->GetValueByName(_L("meshcount"))->ValueAsInt(); mpMesh = new CPUTMesh*[mMeshCount]; mpLayoutCount = new UINT[mMeshCount]; mpRootMaterial = new CPUTMaterial*[mMeshCount]; memset( mpRootMaterial, 0, mMeshCount * sizeof(CPUTMaterial*) ); mpMaterialEffect = new CPUTMaterialEffect**[mMeshCount]; memset( mpMaterialEffect, 0, mMeshCount * sizeof(CPUTMaterialEffect*) ); // get the material names, load them, and match them up with each mesh cString materialName,shadowMaterialName; char pNumber[4]; cString materialValueName; CPUTModelOGL *pMasterModelDX = (CPUTModelOGL*)pMasterModel; for(UINT ii=0; ii<mMeshCount; ii++) { if(pMasterModelDX) { // Reference the master model's mesh. Don't create a new one. mpMesh[ii] = pMasterModelDX->mpMesh[ii]; mpMesh[ii]->AddRef(); } else { mpMesh[ii] = new CPUTMeshOGL(); } } if( !pMasterModelDX ) { // Not a clone/instance. So, load the model's binary payload (i.e., vertex and index buffers) // TODO: Change to use GetModel() result = LoadModelPayload(resolvedPathAndFile); ASSERT( CPUTSUCCESS(result), _L("Failed loading model") ); } cString assetSetDirectoryName = pAssetLibrary->GetAssetSetDirectoryName(); cString modelDirectory = pAssetLibrary->GetModelDirectoryName(); cString materialDirectory = pAssetLibrary->GetMaterialDirectoryName(); cString textureDirectory = pAssetLibrary->GetTextureDirectoryName(); cString shaderDirectory = pAssetLibrary->GetShaderDirectoryName(); cString fontDirectory = pAssetLibrary->GetFontDirectoryName(); cString up2MediaDirName = assetSetDirectoryName + _L("../../"); pAssetLibrary->SetMediaDirectoryName( up2MediaDirName ); // mpShadowCastMaterial = pAssetLibrary->GetMaterial( _L("shadowCast"), false ); pAssetLibrary->SetAssetSetDirectoryName( assetSetDirectoryName ); pAssetLibrary->SetModelDirectoryName( modelDirectory ); pAssetLibrary->SetMaterialDirectoryName( materialDirectory ); pAssetLibrary->SetTextureDirectoryName( textureDirectory ); pAssetLibrary->SetShaderDirectoryName( shaderDirectory ); pAssetLibrary->SetFontDirectoryName( fontDirectory ); for(UINT ii=0; ii<mMeshCount; ii++) { // get the right material number ('material0', 'material1', 'material2', etc) materialValueName = _L("material"); snprintf(pNumber, 4, "%d", ii); // _itoa(ii, pNumber, 4, 10); materialValueName.append(s2ws(pNumber)); materialName = pBlock->GetValueByName(materialValueName)->ValueAsString(); shadowMaterialName = pBlock->GetValueByName(_L("shadowCast") + materialValueName)->ValueAsString(); bool isSkinned = pBlock->GetValueByName(_L("skeleton")) != &CPUTConfigEntry::sNullConfigValue; if( shadowMaterialName.length() == 0 ) { if(!isSkinned) { shadowMaterialName = _L("%shadowCast"); } else { shadowMaterialName = _L("%shadowCastSkinned"); } } // Get/load material for this mesh UINT totalNameCount = numSystemMaterials + NUM_GLOBAL_SYSTEM_MATERIALS; cString *pFinalSystemNames = new cString[totalNameCount]; // Copy "global" system materials to caller-supplied list for( int jj=0; jj<numSystemMaterials; jj++ ) { pFinalSystemNames[jj] = pSystemMaterialNames[jj]; } pFinalSystemNames[totalNameCount + CPUT_MATERIAL_INDEX_SHADOW_CAST] = shadowMaterialName; // pFinalSystemNames[totalNameCount + CPUT_MATERIAL_INDEX_BOUNDING_BOX] = _L("%BoundingBox"); int finalNumSystemMaterials = numSystemMaterials + NUM_GLOBAL_SYSTEM_MATERIALS; CPUTMaterial *pMaterial = pAssetLibrary->GetMaterial(materialName, false, this, ii, NULL, finalNumSystemMaterials, pFinalSystemNames); ASSERT( pMaterial, _L("Couldn't find material.") ); delete []pFinalSystemNames; mpLayoutCount[ii] = pMaterial->GetMaterialEffectCount(); SetMaterial(ii, pMaterial); // Release the extra refcount we're holding from the GetMaterial operation earlier // now the asset library, and this model have the only refcounts on that material pMaterial->Release(); // Create two ID3D11InputLayout objects, one for each material. // mpMesh[ii]->BindVertexShaderLayout( mpMaterial[ii], mpShadowCastMaterial); // mpShadowCastMaterial->Release() } return result; } // Set the material associated with this mesh and create/re-use a //----------------------------------------------------------------------------- void CPUTModelOGL::SetMaterial(UINT ii, CPUTMaterial *pMaterial) { CPUTModel::SetMaterial(ii, pMaterial); // Can't bind the layout if we haven't loaded the mesh yet. CPUTMeshOGL *pMesh = (CPUTMeshOGL*)mpMesh[ii]; // D3D11_INPUT_ELEMENT_DESC *pDesc = pMesh->GetLayoutDescription(); // if( pDesc ) { // pMesh->BindVertexShaderLayout(pMaterial, mpMaterial[ii]); } } #ifdef SUPPORT_DRAWING_BOUNDING_BOXES //----------------------------------------------------------------------------- void CPUTModelOGL::DrawBoundingBox(CPUTRenderParameters &renderParams) { UpdateShaderConstants(renderParams); UINT index = mpSubMaterialCount[0] + CPUT_MATERIAL_INDEX_BOUNDING_BOX; CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)(mpMaterial[0][index]); pMaterial->SetRenderStates(renderParams); ((CPUTMeshOGL*)mpBoundingBoxMesh)->Draw(renderParams, mpInputLayout[0][index]); } // Note that we only need one of these. We don't need to re-create it for every model. //----------------------------------------------------------------------------- void CPUTModelDX11::CreateBoundingBoxMesh() { CPUTResult result = CPUT_SUCCESS; float3 pVertices[8] = { float3( 1.0f, 1.0f, 1.0f ), // 0 float3( 1.0f, 1.0f, -1.0f ), // 1 float3( -1.0f, 1.0f, 1.0f ), // 2 float3( -1.0f, 1.0f, -1.0f ), // 3 float3( 1.0f, -1.0f, 1.0f ), // 4 float3( 1.0f, -1.0f, -1.0f ), // 5 float3( -1.0f, -1.0f, 1.0f ), // 6 float3( -1.0f, -1.0f, -1.0f ) // 7 }; USHORT pIndices[24] = { 0,1, 1,3, 3,2, 2,0, // Top 4,5, 5,7, 7,6, 6,4, // Bottom 0,4, 1,5, 2,6, 3,7 // Verticals }; CPUTVertexElementDesc pVertexElements[] = { { CPUT_VERTEX_ELEMENT_POSITON, tFLOAT, 12, 0 }, }; CPUTMesh *pMesh = mpBoundingBoxMesh = new CPUTMeshDX11(); pMesh->SetMeshTopology(CPUT_TOPOLOGY_INDEXED_LINE_LIST); CPUTBufferElementInfo vertexElementInfo; vertexElementInfo.mpSemanticName = "POSITION"; vertexElementInfo.mSemanticIndex = 0; vertexElementInfo.mElementType = CPUT_F32; vertexElementInfo.mElementComponentCount = 3; vertexElementInfo.mElementSizeInBytes = 12; vertexElementInfo.mOffset = 0; CPUTBufferElementInfo indexDataInfo; indexDataInfo.mElementType = CPUT_U16; indexDataInfo.mElementComponentCount = 1; indexDataInfo.mElementSizeInBytes = sizeof(UINT16); indexDataInfo.mOffset = 0; indexDataInfo.mSemanticIndex = 0; indexDataInfo.mpSemanticName = NULL; result = pMesh->CreateNativeResources( this, -1, 1, &vertexElementInfo, 8, // vertexCount pVertices, &indexDataInfo, 24, // indexCount pIndices ); ASSERT( CPUTSUCCESS(result), _L("Failed building bounding box mesh") ); cString modelSuffix = ptoc(this); UINT index = mpSubMaterialCount[0] + CPUT_MATERIAL_INDEX_BOUNDING_BOX; CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)(mpMaterial[0][index]); ((CPUTMeshOGL*)pMesh)->BindVertexShaderLayout( pMaterial, &mpInputLayout[0][index] ); } #endif
15,458
4,846
#include "Framework.h" Ninja::Ninja(UINT instanceID) : instanceID(instanceID), state(IDLE) { collider = new SphereCollider(); collider->tag = "NinjaCollider"; collider->Load(); hpBar = new ProgressBar("Textures/UI/hp_bar.png", "Textures/UI/hp_bar_BG.png"); //hpBar->scale *= 0.1f; } Ninja::~Ninja() { delete collider; delete hpBar; } void Ninja::Update() { SetLeftHand(); SetHpBar(); //Trace(); Move(); collider->UpdateWorld(); } void Ninja::Render() { if (!ninja->isActive) return; float radius = ((SphereCollider*)collider)->Radius(); if (!FRUSTUM->ContainSphere(collider->GlobalPos(), radius)) return; collider->Render(); } void Ninja::PostRender() { if (!ninja->isActive) return; float radius = ((SphereCollider*)collider)->Radius(); if (!FRUSTUM->ContainSphere(collider->GlobalPos(), radius)) return; hpBar->Render(); } void Ninja::GUIRender() { collider->GUIRender(); } void Ninja::Move() { if (terrain) ninja->position.y = terrain->GetHeight(ninja->position); } void Ninja::Hit() { collider->isActive = false; hp -= 30.0f; hpBar->SetValue(hp); if (hp > 0) SetClip(HIT); else SetClip(DYING); } void Ninja::SetEvent() { instancing->AddEvent(instanceID, HIT, 0.8f, bind(&Ninja::EndHit, this)); } void Ninja::Trace() { if (!collider->isActive) return; if (!target) return; Vector3 dir = target->position - ninja->position; Vector3 cross = Vector3::Cross(dir, ninja->Forward()); if (cross.y > 0.01f) ninja->rotation.y += DELTA; else if (cross.y < -0.01f) ninja->rotation.y -= DELTA; ninja->position -= ninja->Forward() * DELTA; SetClip(RUN); } void Ninja::EndHit() { SetClip(IDLE); collider->isActive = true; } void Ninja::EndDie() { ninja->isActive = false; } void Ninja::SetHpBar() { float distance = Distance(CAM->position, ninja->position); hpBar->scale.x = 10 / distance; hpBar->scale.y = 10 / distance; Vector3 barPos = ninja->position + Vector3(0, 5, 0); hpBar->position = CAM->WorldToScreenPoint(barPos); lerpHp = LERP(lerpHp, hp, lerpSpeed * DELTA); hpBar->SetLerpValue(lerpHp); hpBar->Update(); } void Ninja::SetLeftHand() { leftHand = instancing->GetTransformByNode(instanceID, 11) * ninja->GetWorld(); } void Ninja::SetMotions() { //ReadClip("Idle"); //ReadClip("Run"); //ReadClip("Attack"); ////ReadClip("Hit"); // 1. BreakPoint here, Start Debugging, go to ReadClip() //ReadClip("Hit", 0, true); //ReadClip("Dying"); // //clips[HIT]->SetEvent(0.8f, bind(&Ninja::EndHit, this)); //clips[DYING]->SetEvent(0.9f, bind(&Ninja::EndDie, this)); } void Ninja::SetClip(AnimState state) { if (this->state != state) { this->state = state; instancing->PlayClip(instanceID, state); } }
2,697
1,167
/* * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * BSD 3-Clause license. See the accompanying LICENSE file for details. */ #include <BayesFilters/GaussianMixture.h> using namespace bfl; using namespace Eigen; GaussianMixture::GaussianMixture() noexcept: GaussianMixture(1, 1, 0, false) { } GaussianMixture::GaussianMixture(const std::size_t components, const std::size_t dim) noexcept : GaussianMixture(components, dim, 0, false) { } GaussianMixture::GaussianMixture ( const std::size_t components, const std::size_t dim_linear, const std::size_t dim_circular, const bool use_quaternion ) noexcept : components(components), use_quaternion(use_quaternion), dim_circular_component(use_quaternion ? 4 : 1), dim(dim_linear + dim_circular * dim_circular_component), dim_linear(dim_linear), dim_circular(dim_circular), dim_noise(0), dim_covariance(use_quaternion ? dim_linear + dim_circular * (dim_circular_component - 1) : dim), mean_(dim, components), covariance_(dim_covariance, dim_covariance * components), weight_(components) { for (int i = 0; i < this->components; ++i) weight_(i) = 1.0 / this->components; /* Note: When using use_quaternion == false, the hypothesis is that there are dim_circular independent states each belonging to the manifold S1 (i.e. dim_circular angles). In this implementation they are treated as belonging to R^(dim_circular). Hence, the size of the covariance matrix is dim_covariance x (dim_covariance * components) where dim_covariance = dim. When using use_quaternion == true, instead the hypothesis is that there are dim_circular quaternions in the state, each belonging to the manifold S3. In this case, dim_circular_component = 4, since they are represented using 4 numbers. However, the covariance is represented using rotation vectors in R^3 that belong to the tangent space of the quaternion manifold. Hence, the size of the covariance matrix is dim_covariance x (dim_covariance * components) where dim_covariance = dim_linear + dim_circular * 3. */ } void GaussianMixture::resize(const std::size_t components, const std::size_t dim_linear, const std::size_t dim_circular) { std::size_t new_dim = dim_linear + dim_circular * dim_circular_component; std::size_t new_dim_covariance = use_quaternion ? dim_linear + dim_circular * (dim_circular_component - 1) : new_dim; if ((this->dim_linear == dim_linear) && (this->dim_circular == dim_circular) && (this->components == components)) return; else if ((this->dim == new_dim) && (this->components != components)) { mean_.conservativeResize(NoChange, components); covariance_.conservativeResize(NoChange, dim_covariance * components); weight_.conservativeResize(components); } else { // In any other case, it does not make sense to do conservative resize // since either old data is truncated or new data is incomplete mean_.resize(new_dim, components); covariance_.resize(new_dim_covariance, new_dim_covariance * components); weight_.resize(components); } this->components = components; this->dim = new_dim; this->dim_covariance = new_dim_covariance; this->dim_linear = dim_linear; this->dim_circular = dim_circular; } Ref<MatrixXd> GaussianMixture::mean() { return mean_; } Ref<VectorXd> GaussianMixture::mean(const std::size_t i) { return mean_.col(i); } double& GaussianMixture::mean(const std::size_t i, const std::size_t j) { return mean_(j, i); } const Ref<const MatrixXd> GaussianMixture::mean() const { return mean_; } const Ref<const VectorXd> GaussianMixture::mean(const std::size_t i) const { return mean_.col(i); } const double& GaussianMixture::mean(const std::size_t i, const std::size_t j) const { return mean_(j, i); } Ref<MatrixXd> GaussianMixture::covariance() { return covariance_; } Ref<MatrixXd> GaussianMixture::covariance(const std::size_t i) { return covariance_.middleCols(this->dim_covariance * i, this->dim_covariance); } double& GaussianMixture::covariance(const std::size_t i, const std::size_t j, const std::size_t k) { return covariance_(j, (this->dim_covariance * i) + k); } const Ref<const MatrixXd> GaussianMixture::covariance() const { return covariance_; } const Ref<const MatrixXd> GaussianMixture::covariance(const std::size_t i) const { return covariance_.middleCols(this->dim_covariance * i, this->dim_covariance); } const double& GaussianMixture::covariance(const std::size_t i, const std::size_t j, const std::size_t k) const { return covariance_(j, (this->dim_covariance * i) + k); } Ref<VectorXd> GaussianMixture::weight() { return weight_; } double& GaussianMixture::weight(const std::size_t i) { return weight_(i); } const Ref<const VectorXd> GaussianMixture::weight() const { return weight_; } const double& GaussianMixture::weight(const std::size_t i) const { return weight_(i); } bool GaussianMixture::augmentWithNoise(const Eigen::Ref<const Eigen::MatrixXd>& noise_covariance_matrix) { /* Augment each state with a noise component having zero mean and given covariance matrix. */ /* Check that covariance matrix is square. */ if (noise_covariance_matrix.rows() != noise_covariance_matrix.cols()) return false; dim_noise = noise_covariance_matrix.rows(); dim += dim_noise; dim_covariance += dim_noise; /* Add zero mean noise to each mean. */ mean_.conservativeResize(dim, NoChange); mean_.bottomRows(dim_noise) = MatrixXd::Zero(dim_noise, components); /* Resize covariance matrix. */ covariance_.conservativeResizeLike(MatrixXd::Zero(dim_covariance, dim_covariance * components)); /* Move old covariance matrices from right to left to avoid aliasing. Note that the covariance matrix of the 0-th coomponent, i.e. in the top-left corner of the matrix covariance_, is already in the correct place. */ std::size_t dim_old = use_quaternion ? dim_linear + dim_circular * (dim_circular_component - 1) : dim_linear + dim_circular; for (std::size_t i = 0; i < (components - 1); i++) { std::size_t i_index = components - 1 - i; Ref<MatrixXd> new_block = covariance_.block(0, i_index * dim_covariance, dim_old, dim_old); Ref<MatrixXd> old_block = covariance_.block(0, i_index * dim_old, dim_old, dim_old); /* Swap columns from to right to left to avoid aliasing. */ for (std::size_t j = 0; j < dim_old; j++) { std::size_t j_index = dim_old - 1 - j; new_block.col(j_index).swap(old_block.col(j_index)); } } for (std::size_t i = 0; i < components; i++) { /* Copy the noise covariance matrix in the bottom-right block of each covariance matrix. */ covariance_.block(dim_old, i * dim_covariance + dim_old, dim_noise, dim_noise) = noise_covariance_matrix; /* Clean part of the matrix that should be zero. */ covariance_.block(0, i * dim_covariance + dim_old, dim_old, dim_noise) = MatrixXd::Zero(dim_old, dim_noise); /* The part in covariance_.block(dim_old, i * dim_covariance, dim_noise, dim_old) was set to 0 when doing covariance_.conservativeResizeLike(MatrixXd::Zero(dim_covariance, dim_covariance * components)); since it is appended in order to expand the matrix. */ } return true; }
7,678
2,585
#include "Worker.h" #include "adios2/helper/adiosLog.h" #include "adios2/helper/adiosXMLUtil.h" #include <pugixml.hpp> namespace adios2 { namespace query { void XmlWorker::ParseMe() { auto lf_FileContents = [&](const std::string &configXML) -> std::string { std::ifstream fileStream(configXML); if (!fileStream) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseMe", "file " + configXML + " not found"); } std::ostringstream fileSS; fileSS << fileStream.rdbuf(); fileStream.close(); if (fileSS.str().empty()) { helper::Throw<std::invalid_argument>("Toolkit", "query::XmlWorker", "ParseMe", "config xml file is empty"); } return fileSS.str(); }; // local function lf_FileContents const std::string fileContents = lf_FileContents(m_QueryFile); const std::unique_ptr<pugi::xml_document> document = adios2::helper::XMLDocument(fileContents, "in Query XMLWorker"); const std::unique_ptr<pugi::xml_node> config = adios2::helper::XMLNode( "adios-query", *document, "in adios-query", true); const pugi::xml_node ioNode = config->child("io"); ParseIONode(ioNode); } // Parse() void XmlWorker::ParseIONode(const pugi::xml_node &ioNode) { #ifdef PARSE_IO const std::unique_ptr<pugi::xml_attribute> ioName = adios2::helper::XMLAttribute("name", ioNode, "in query"); const std::unique_ptr<pugi::xml_attribute> fileName = adios2::helper::XMLAttribute("file", ioNode, "in query"); // must be unique per io const std::unique_ptr<pugi::xml_node> &engineNode = adios2::helper::XMLNode("engine", ioNode, "in query", false, true); m_IO = &(m_Adios2.DeclareIO(ioName->value())); if (engineNode) { const std::unique_ptr<pugi::xml_attribute> type = adios2::query::XmlUtil::XMLAttribute("type", engineNode, "in query"); m_IO->SetEngine(type->value()); const adios2::Params parameters = helper::GetParameters(engineNode, "in query"); m_IO->SetParameters(parameters); } else { m_IO->SetEngine("BPFile"); } // adios2::Engine reader = currIO.Open(fileName.value(), // adios2::Mode::Read, m_Comm); m_SourceReader = &(m_IO->Open(fileName.value(), adios2::Mode::Read, m_Comm)); #else const std::unique_ptr<pugi::xml_attribute> ioName = adios2::helper::XMLAttribute("name", ioNode, "in query"); if (m_SourceReader->m_IO.m_Name.compare(ioName->value()) != 0) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseIONode", "invalid query io. Expecting io name = " + m_SourceReader->m_IO.m_Name + " found:" + ioName->value()); } #endif std::map<std::string, QueryBase *> subqueries; adios2::Box<adios2::Dims> ref; for (const pugi::xml_node &qTagNode : ioNode.children("tag")) { const std::unique_ptr<pugi::xml_attribute> name = adios2::helper::XMLAttribute("name", qTagNode, "in query"); const pugi::xml_node &variable = qTagNode.child("var"); QueryVar *q = ParseVarNode(variable, m_SourceReader->m_IO, *m_SourceReader); if (!q) continue; if (ref.first.size() == 0) { ref = q->m_Selection; } else if (!q->IsCompatible(ref)) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseIONode", "impactible query found on var:" + q->GetVarName()); } subqueries[name->value()] = q; } const pugi::xml_node &qNode = ioNode.child("query"); if (qNode == nullptr) { const pugi::xml_node &variable = ioNode.child("var"); m_Query = ParseVarNode(variable, m_SourceReader->m_IO, *m_SourceReader); } else { const std::unique_ptr<pugi::xml_attribute> op = adios2::helper::XMLAttribute("op", qNode, "in query"); QueryComposite *q = new QueryComposite(adios2::query::strToRelation(op->value())); for (const pugi::xml_node &sub : qNode.children()) { q->AddNode(subqueries[sub.name()]); } m_Query = q; } } // parse_io_node // node is the variable node QueryVar *XmlWorker::ParseVarNode(const pugi::xml_node &node, adios2::core::IO &currentIO, adios2::core::Engine &reader) { const std::string variableName = std::string( adios2::helper::XMLAttribute("name", node, "in query")->value()); // const std::string varType = currentIO.VariableType(variableName); const DataType varType = currentIO.InquireVariableType(variableName); if (varType == DataType::None) { helper::Log("Query", "XmlWorker", "ParseVarNode", "No such variable: " + variableName, helper::LogMode::ERROR); helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseVarNode", "variable: " + variableName + " not found"); } #define declare_type(T) \ if (varType == helper::GetDataType<T>()) \ { \ core::Variable<T> *var = currentIO.InquireVariable<T>(variableName); \ if (var) \ { \ QueryVar *q = new QueryVar(variableName); \ adios2::Dims zero(var->Shape().size(), 0); \ adios2::Dims shape = var->Shape(); \ q->SetSelection(zero, shape); \ ConstructQuery(*q, node); \ return q; \ } \ } ADIOS2_FOREACH_ATTRIBUTE_PRIMITIVE_STDTYPE_1ARG(declare_type) #undef declare_type return nullptr; } // parse_var_node void XmlWorker::ConstructTree(RangeTree &host, const pugi::xml_node &node) { std::string relationStr = adios2::helper::XMLAttribute("value", node, "in query")->value(); host.SetRelation(adios2::query::strToRelation(relationStr)); for (const pugi::xml_node &rangeNode : node.children("range")) { std::string valStr = adios2::helper::XMLAttribute("value", rangeNode, "in query") ->value(); std::string opStr = adios2::helper::XMLAttribute("compare", rangeNode, "in query") ->value(); host.AddLeaf(adios2::query::strToQueryOp(opStr), valStr); } for (const pugi::xml_node &opNode : node.children("op")) { adios2::query::RangeTree subNode; ConstructTree(subNode, opNode); host.AddNode(subNode); } } void XmlWorker::ConstructQuery(QueryVar &simpleQ, const pugi::xml_node &node) { // QueryVar* simpleQ = new QueryVar(variableName); pugi::xml_node bbNode = node.child("boundingbox"); if (bbNode) { std::string startStr = adios2::helper::XMLAttribute("start", bbNode, "in query")->value(); std::string countStr = adios2::helper::XMLAttribute("count", bbNode, "in query")->value(); adios2::Dims start = split(startStr, ','); adios2::Dims count = split(countStr, ','); if (start.size() != count.size()) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ConstructQuery", "dim of startcount does match in the bounding box definition"); } // simpleQ.setSelection(box.first, box.second); adios2::Dims shape = simpleQ.m_Selection.second; // set at the creation for default simpleQ.SetSelection(start, count); if (!simpleQ.IsSelectionValid(shape)) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ConstructQuery", "invalid selections for selection of var: " + simpleQ.GetVarName()); } } #ifdef NEVER // don't know whether this is useful. pugi::xml_node tsNode = node.child("tstep"); if (tsNode) { std::string startStr = adios2::helper::XMLAttribute("start", tsNode, "in query").value(); std::string countStr = adios2::helper::XMLAttribute("count", tsNode, "in query").value(); if ((startStr.size() > 0) && (countStr.size() > 0)) { std::stringstream ss(startStr), cc(countStr); ss >> simpleQ.m_TimestepStart; cc >> simpleQ.m_TimestepCount; } } #endif pugi::xml_node relationNode = node.child("op"); ConstructTree(simpleQ.m_RangeTree, relationNode); } } // namespace query } // namespace adios2
9,466
2,843
// // Created by liudiyang1998 on 13.04.21. // #ifndef FACTORY_FACTORY_H #define FACTORY_FACTORY_H #include "LeiFeng.h" class Factory { public: virtual LeiFeng* createLeiFeng()=0; }; #endif //FACTORY_FACTORY_H
218
109
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #include "chrono/physics/ChNodeXYZ.h" namespace chrono { ChNodeXYZ::ChNodeXYZ() : pos(VNULL), pos_dt(VNULL), pos_dtdt(VNULL) {} ChNodeXYZ::ChNodeXYZ(const ChVector<>& initial_pos) : pos(initial_pos), pos_dt(VNULL), pos_dtdt(VNULL) {} ChNodeXYZ::ChNodeXYZ(const ChNodeXYZ& other) : ChNodeBase(other) { pos = other.pos; pos_dt = other.pos_dt; pos_dtdt = other.pos_dtdt; } ChNodeXYZ& ChNodeXYZ::operator=(const ChNodeXYZ& other) { if (&other == this) return *this; ChNodeBase::operator=(other); pos = other.pos; pos_dt = other.pos_dt; pos_dtdt = other.pos_dtdt; return *this; } void ChNodeXYZ::LoadableGetStateBlock_x(int block_offset, ChState& mD) { mD.segment(block_offset, 3) = pos.eigen(); } void ChNodeXYZ::LoadableGetStateBlock_w(int block_offset, ChStateDelta& mD) { mD.segment(block_offset, 3) = pos_dt.eigen(); } void ChNodeXYZ::LoadableStateIncrement(const unsigned int off_x, ChState& x_new, const ChState& x, const unsigned int off_v, const ChStateDelta& Dv) { NodeIntStateIncrement(off_x, x_new, x, off_v, Dv); } void ChNodeXYZ::LoadableGetVariables(std::vector<ChVariables*>& mvars) { mvars.push_back(&Variables()); }; void ChNodeXYZ::ComputeNF( const double U, // x coordinate of application point in absolute space const double V, // y coordinate of application point in absolute space const double W, // z coordinate of application point in absolute space ChVectorDynamic<>& Qi, // Return result of N'*F here, maybe with offset block_offset double& detJ, // Return det[J] here const ChVectorDynamic<>& F, // Input F vector, size is 3, it is Force x,y,z in absolute coords. ChVectorDynamic<>* state_x, // if != 0, update state (pos. part) to this, then evaluate Q ChVectorDynamic<>* state_w // if != 0, update state (speed part) to this, then evaluate Q ) { // ChVector<> abs_pos(U,V,W); not needed, nodes has no torque. Assuming load is applied to node center ChVector<> absF(F.segment(0, 3)); Qi.segment(0, 3) = absF.eigen(); detJ = 1; // not needed because not used in quadrature. } void ChNodeXYZ::ArchiveOUT(ChArchiveOut& marchive) { // version number marchive.VersionWrite<ChNodeXYZ>(); // serialize parent class ChNodeBase::ArchiveOUT(marchive); // serialize all member data: marchive << CHNVP(pos); marchive << CHNVP(pos_dt); marchive << CHNVP(pos_dtdt); } /// Method to allow de serialization of transient data from archives. void ChNodeXYZ::ArchiveIN(ChArchiveIn& marchive) { // version number /*int version =*/marchive.VersionRead<ChNodeXYZ>(); // deserialize parent class: ChNodeBase::ArchiveIN(marchive); // deserialize all member data: marchive >> CHNVP(pos); marchive >> CHNVP(pos_dt); marchive >> CHNVP(pos_dtdt); } } // end namespace chrono
3,686
1,185
// Copyright 2016 Jonathan Buchanan. // This file is part of Sunglasses, which is licensed under the MIT License. // See LICENSE.md for details. #include <sunglasses/Scripting/LuaPrimitives.h> namespace sunglasses { namespace Scripting { template<> int getFromStack(lua_State *l, int index) { return lua_tointeger(l, index); } template<> double getFromStack(lua_State *l, int index) { return lua_tonumber(l, index); } template<> float getFromStack(lua_State *l, int index) { return (float)lua_tonumber(l, index); } template<> bool getFromStack(lua_State *l, int index) { return lua_toboolean(l, index); } template<> const char * getFromStack(lua_State *l, int index) { return lua_tostring(l, index); } template<> std::string getFromStack(lua_State *l, int index) { return std::string(lua_tostring(l, index)); } template<> void pushToStack(lua_State *l, int value) { lua_pushinteger(l, value); } template<> void pushToStack(lua_State *l, double value) { lua_pushnumber(l, value); } template<> void pushToStack(lua_State *l, float value) { lua_pushnumber(l, (double)value); } template<> void pushToStack(lua_State *l, bool value) { lua_pushboolean(l, value); } template<> void pushToStack(lua_State *l, const char *value) { lua_pushstring(l, value); } template<> void pushToStack(lua_State *l, std::string value) { lua_pushstring(l, value.c_str()); } } } // namespace
1,572
535
/* 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/core/tfrt/utils/error_util.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tfrt/support/error_util.h" #include "tensorflow/core/platform/status.h" namespace tfrt { namespace { TEST(ErrorUtilTest, AllSupportedErrorConversion){ #define ERROR_TYPE(TFRT_ERROR, TF_ERROR) \ { \ tensorflow::Status status(tensorflow::error::TF_ERROR, "error_test"); \ EXPECT_EQ(ConvertTfErrorCodeToTfrtErrorCode(status), \ tfrt::ErrorCode::TFRT_ERROR); \ } #include "tensorflow/core/tfrt/utils/error_type.def" // NOLINT } TEST(ErrorUtilTest, UnsupportedErrorConversion) { tensorflow::Status status(tensorflow::error::UNAUTHENTICATED, "error_test"); EXPECT_EQ(ConvertTfErrorCodeToTfrtErrorCode(status), tfrt::ErrorCode::kUnknown); } } // namespace } // namespace tfrt
1,649
491
#include <cstdio> #include <iostream> #include <sstream> #include <string> #include <cmath> #include <algorithm> #include <vector> #include <map> #include <queue> #include <set> #define X first #define Y second #define pb push_back #define ii pair<int,int> #define ll long long #define N 128 inline int MIN(int a,int b){return (a>b)?b:a;} inline int MAX(int a,int b){return (a<b)?b:a;} inline int ABS(int a){return (a>0)?a:-a;} using namespace std; int tt,n; int mat[N][N]; int row[N][N]; int col[N][N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>tt; for(int t=0;t<tt;++t) { cin>>n; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) cin>>mat[i][j]; for(int i=1;i<=n;++i) row[i][0]=col[0][i]=0; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) row[i][j]=row[i][j-1]+mat[i][j]; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) col[i][j]=col[i-1][j]+mat[i][j]; int ans=-0x7fffffff; int total = 0; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) total+=mat[i][j]; for(int i=1;i<=n;++i) { for(int j=1;j<=n;++j) { int sum3=0; for(int k=j;k<=n;++k) { sum3+=col[n][k]-col[0][k]; int sum1=0; int sum2=0; for(int l=i;l<=n;++l) { sum1+=row[l][k]-row[l][j-1]; sum2+=row[l][n]-row[l][0]; ans = MAX(sum1,ans); if(n!=k || j!=1) { ans = MAX(sum2-sum1,ans); } if(n!=l || i!=1) { ans = MAX(sum3-sum1,ans); } if((n!=k || j!=1) && (n!=l || i!=1)) { ans=MAX(total-sum3-sum2+sum1,ans); } } } } } cout<<ans<<"\n"; } return 0; }
1,616
975
//---------------------------------Spheral++----------------------------------// // VoronoiRedistributeNodes // // This algorithm uses the Voronoi tessellation to decide how to domain // decompose our points. The idea is to relax a set of generator points into // the SPH node distribution -- the generators are attracted to the SPH points // repelled by one and other. These generator points then become the seeds to // draw the Voronoi tessellation about, each cell of which then represents a // computational domain. // // Created by JMO, Fri Jan 15 09:56:56 PST 2010 //----------------------------------------------------------------------------// #ifndef VoronoiRedistributeNodes_HH #define VoronoiRedistributeNodes_HH #include "RedistributeNodes.hh" #include "Utilities/KeyTraits.hh" #include <vector> #include <map> #ifdef USE_MPI #include <mpi.h> #endif namespace Spheral { template<typename Dimension> class DataBase; template<typename Dimension> class NodeList; template<typename Dimension> class Boundary; template<typename Dimension> class VoronoiRedistributeNodes: public RedistributeNodes<Dimension> { public: //--------------------------- Public Interface ---------------------------// typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef KeyTraits::Key Key; // Constructors VoronoiRedistributeNodes(const double dummy, const bool workBalance, const bool balanceGenerators, const double tolerance, const unsigned maxIterations); // Destructor virtual ~VoronoiRedistributeNodes(); // Given a Spheral++ data base of NodeLists, repartition it among the processors. // This is the method required of all descendent classes. virtual void redistributeNodes(DataBase<Dimension>& dataBase, std::vector<Boundary<Dimension>*> boundaries = std::vector<Boundary<Dimension>*>()) override; // Given the set of DomainNodes with their domain assignments, compute the // (work weighted) domain centroids. void computeCentroids(const std::vector<DomainNode<Dimension> >& nodes, std::vector<Vector>& generators) const; // Assign the nodes to the given generator positions, simultaneously computing the total // generator work load. void assignNodesToGenerators(const std::vector<Vector>& generators, const std::vector<int>& generatorFlags, std::vector<double>& generatorWork, std::vector<DomainNode<Dimension> >& nodes, double& minWork, double& maxWork, unsigned& minNodes, unsigned& maxNodes) const; // Look for any generator that has too much work, and unassign it's most // distant nodes. void cullGeneratorNodesByWork(const std::vector<Vector>& generators, const std::vector<double>& generatorWork, const double targetWork, std::vector<int>& generatorFlags, std::vector<DomainNode<Dimension> >& nodes) const; // Find the adjacent generators in the Voronoi diagram. std::vector<size_t> findNeighborGenerators(const size_t igen, const std::vector<Vector>& generators) const; // Flag for whether we should compute the work per node or strictly balance by // node count. bool workBalance() const; void workBalance(bool val); // Should we try to work balance between generators? // node count. bool balanceGenerators() const; void balanceGenerators(bool val); // The tolerance we're using to check for convergence of the generators. double tolerance() const; void tolerance(double val); // The maximum number of iterations to try and converge the generator positions. unsigned maxIterations() const; void maxIterations(unsigned val); private: //--------------------------- Private Interface ---------------------------// bool mWorkBalance, mBalanceGenerators; double mTolerance; unsigned mMaxIterations; // No copy or assignment operations. VoronoiRedistributeNodes(const VoronoiRedistributeNodes& nodes); VoronoiRedistributeNodes& operator=(const VoronoiRedistributeNodes& rhs); }; } #else // Forward declare the VoronoiRedistributeNodes class. namespace Spheral { template<typename Dimension> class VoronoiRedistributeNodes; } #endif
4,773
1,223
#pragma once #include <cstdlib> #include <cstring> #include "toy/Math.hpp" namespace toy{ namespace memory{ // The memory size of Allocator01 always base of 2. template<typename T> class Allocator01 { public: Allocator01() { ; } ~Allocator01() { free(); } Allocator01(const Allocator01 &other) { copy_mykind(const_cast<Allocator01&>(other)); } Allocator01 operator = (const Allocator01 &other) { copy_mykind(const_cast<Allocator01&>(other)); return *this; } T* allocate(std::size_t n) { (void)n; } void deallocate(T* p, std::size_t n) { (void)n; (void)p; } private: bool copy(void *p,size_t s) { size(s); std::memcpy(_data,p,s); return 1; } void free() { if(_data) { std::free(_data); _data = nullptr; _size = 0; _trueSize = 0; } } // Allocate memory for user. bool size(size_t s) { _size = s; if ( s>_trueSize ) { size_t new_size = ::toy::math::Exp1<size_t>(s); if ( _data==nullptr ) { _data = std::malloc(new_size); } else { _data = std::realloc(_data,new_size); } _trueSize = new_size; } return 1; } // Allocate memory for user, and release the memory unused. bool fitSize(size_t s) { _size = s; size_t new_size = ::toy::math::Exp1<size_t>(s); if ( new_size>_trueSize ) { if(_data==nullptr) { _data = std::malloc(new_size); } else { _data = std::realloc(_data,new_size); } _trueSize = new_size; } else if ( new_size<_trueSize ) { _data = std::realloc(_data,new_size); _trueSize = new_size; } return 1; } void* data() const { return _data; } size_t size() const { return _size; } void* _data = nullptr; std::size_t _size = 0; std::size_t _trueSize = 0; inline void copy_mykind(Allocator01 &other) { free(); _size = other._size; _trueSize = other._trueSize; _data = std::malloc(_trueSize); std::memcpy(_data,other._data,_size); } }; }//namespace memory }//namespace toy
2,118
1,108
#include "random.hpp" #include <assert.h> namespace Util{ Random::Random(uint32_t _seed) { m_state[0] = 0xaffeaffe ^ _seed; m_state[1] = 0xf9b2a750 ^ (_seed * 0x804c8a24 + 0x68f699be); m_state[2] = 0x485eac66 ^ (_seed * 0x0fe56638 + 0xc917c8ce); m_state[3] = 0xcbd02714 ^ (_seed * 0x57571dae + 0xce2b3bd1); // Warmup Xorshift128(); Xorshift128(); Xorshift128(); Xorshift128(); } // ********************************************************************* // float Random::uniform(float _min, float _max) { double scale = (_max - _min) / 0xffffffff; return float(_min + scale * Xorshift128()); } // ********************************************************************* // int32_t Random::uniform(int32_t _min, int32_t _max) { uint32_t interval = uint32_t(_max - _min + 1); assert(interval != 0 && "Do not use integer maximum bounds!"); uint32_t value = Xorshift128(); return _min + value % interval; } // ********************************************************************* // Math::ArgVec<float, 2> Random::vector() { // Math::ArgVec<float, 2> vec; return Math::AVec2(uniform(-1.f,1.f), uniform(-1.f, 1.f)); } // ********************************************************************* // uint32_t Random::Xorshift128() { uint32_t tmp = m_state[0] ^ (m_state[0] << 11); m_state[0] = m_state[1]; m_state[1] = m_state[2]; m_state[2] = m_state[3]; m_state[3] ^= (m_state[3] >> 19) ^ tmp ^ (tmp >> 8); return m_state[3]; } }
1,488
665
#include "hcpch.h" #include "LevelManager.h" namespace Hercules { LevelData levelData; const void Hercules::LevelManager::OpenLevel(const char* levelPath, std::string projectPath) { HC_STAT("Opening {0}", levelPath); levelData.matColors.clear(); levelData.matShinies.clear(); SceneManager::GetEntites().clear(); SceneManager::GetTransformComponentList().clear(); SceneManager::GetLightComponentList().clear(); SceneManager::GetDemoComponentList().clear(); SceneManager::GetMeshComponentList().clear(); SceneManager::GetDirectionalLightList().clear(); SceneManager::GetPointLightList().clear(); SceneManager::GetSpotLightList().clear(); SceneManager::GetMaterialComponentList().clear(); SceneManager::GetTextureList().clear(); std::string line; std::ifstream levelFile(levelPath); int lineNR = 1; unsigned int id = 1; std::string delimiter = "#"; std::string colon = ":"; std::string pos = "P"; std::string rot = "R"; std::string scale = "S"; std::string color = "C"; std::string tex = "T"; std::string shiny = "H"; std::string mesh = "V"; std::string mat = "M"; //Read materials HC_CORE_STAT("Loading materials..."); for (auto& i : std::filesystem::directory_iterator(projectPath + "Assets/Materials")) { std::string path = i.path().string(); std::ifstream material(path); std::string name = ""; bool currentType = 0; while (std::getline(material, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); currentType = std::stoi(line); } else if (line.find(tex) != std::string::npos) { line.erase(0, line.find(tex) + tex.length()); name = i.path().filename().string().substr(0, i.path().filename().string().find(".")); std::string path = projectPath + line; SceneManager::NewTexture(name, path.c_str(), currentType); } else if (line.find(color) != std::string::npos) { if (line.substr(0, 1) == color) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); levelData.matColors.insert(std::pair<std::string, glm::vec3> (name, glm::vec3(std::stof(r), std::stof(g), std::stof(b)))); } } else if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); levelData.matShinies.insert(std::pair<std::string, float>(name, std::stof(line))); } } } } HC_CORE_SUCCESS("Materials loaded"); //Read level file HC_CORE_STAT("Loading {0}...", levelPath); while (std::getline(levelFile, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); std::string name = line.substr(0, line.find(colon)); line.erase(0, line.find(colon) + colon.length()); id = std::stoi(line.substr(0, line.find(colon))); SceneManager::NewEntity(name); } else if (line.find(pos) != std::string::npos) { if (line.substr(0, 1) == pos) { //Position line.erase(0, line.find(pos) + pos.length()); std::string px = line.substr(0, line.find("x")); line.erase(0, line.find("x") + pos.length()); std::string py = line.substr(0, line.find("y")); line.erase(0, line.find("y") + pos.length()); std::string pz = line.substr(0, line.find("z")); //Scale line.erase(0, line.find(scale) + scale.length()); std::string sx = line.substr(0, line.find("x")); line.erase(0, line.find("x") + scale.length()); std::string sy = line.substr(0, line.find("y")); line.erase(0, line.find("y") + scale.length()); std::string sz = line.substr(0, line.find("z")); //Rotation line.erase(0, line.find(rot) + rot.length()); std::string rx = line.substr(0, line.find("x")); line.erase(0, line.find("x") + rot.length()); std::string ry = line.substr(0, line.find("y")); line.erase(0, line.find("y") + rot.length()); std::string rz = line.substr(0, line.find("z")); SceneManager::NewComponent(TransformComponent(glm::vec3(std::stof(px), std::stof(py), std::stof(pz)), glm::vec3(std::stof(sx), std::stof(sy), std::stof(sz)), glm::vec3(std::stof(rx), std::stof(ry), std::stof(rz))), SceneManager::GetEntites().size()); } } else if (line.find("DL") != std::string::npos) { SceneManager::NewComponent(DirectionalLight(), id); } else if (line.find("T") != std::string::npos) { SceneManager::NewComponent(DemoComponent(), id); } if (line.find(mesh) != std::string::npos) { if (line.substr(0, 1) == mesh) { line.erase(0, line.find(mesh) + mesh.length()); SceneManager::NewComponent(MeshComponent(projectPath + line), id); } } if (line.find(mat) != std::string::npos) { if (line.substr(0, 1) == mat) { line.erase(0, line.find(mat) + mat.length()); std::string m = line.substr(0, line.find(mat)); SceneManager::NewComponent(MaterialComponent( SceneManager::GetTexture(m.c_str()), *GetColor(m)), id); SceneManager::GetMaterialComponent(id)->SetName(m); } } if (line.find(color) != std::string::npos) { if (line.substr(0, 1) == color) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); SceneManager::GetMaterialComponent(id)->SetColor(glm::vec3( std::stof(r), std::stof(g), std::stof(b))); } } if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); SceneManager::GetMaterialComponent(id)->SetShininess(std::stof(line)); } } } levelFile.close(); HC_CORE_SUCCESS("{0} loaded", levelPath); //ProcessMaterials(levelPath); } void LevelManager::ProcessMaterials(const char* levelPath) { std::ifstream levelFile(levelPath); std::string line; std::string mat = "M"; std::string delimiter = "#"; std::string colon = ":"; std::string color = "C"; std::string shiny = "H"; unsigned int id = 0; while (std::getline(levelFile, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); line.erase(0, line.find(colon) + colon.length()); id = std::stoi(line.substr(0, line.find(colon))); } else if (line.find(mat) != std::string::npos) { if (line.substr(0, 1) == mat) { line.erase(0, line.find(mat) + mat.length()); std::string m = line.substr(0, line.find(mat)); SceneManager::NewComponent(MaterialComponent( SceneManager::GetTexture(m.c_str()), *GetColor(m)), id); SceneManager::GetMaterialComponent(id)->SetName(m); } } else if (line.find(color) != std::string::npos) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); SceneManager::GetMaterialComponent(id)->SetColor(glm::vec3( std::stof(r), std::stof(g), std::stof(b))); } else if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); SceneManager::GetMaterialComponent(id)->SetShininess(std::stof(line)); } } } } //Saving level const void LevelManager::WriteLevel(const char* levelPath, std::string projectPath) { std::fstream file_out; file_out.open(levelPath, std::ios::out); if (!file_out.is_open()) { HC_CORE_ERROR("Failed to open level"); } else { for (auto &i : SceneManager::GetEntites()) { TransformComponent t = *SceneManager::GetTransformComponent(i.first); //Every entity will have a transform file_out << "\n#" << i.second << ":" << i.first << std::endl; file_out << "P" << t.GetPos().x << "x" << t.GetPos().y << "y" << t.GetPos().z << "z" << "S" << t.GetScale().x << "x" << t.GetScale().y << "y" << t.GetScale().z << "z" << "R" << t.GetRotation().x << "x" << t.GetRotation().y << "y" << t.GetRotation().z << "z" << std::endl; if (SceneManager::HasDirectionalLight(i.first)) file_out << "DL" << std::endl; if (SceneManager::HasTestComponent(i.first)) file_out << "T" << std::endl; if (SceneManager::HasMaterialComponent(i.first)) { file_out << "M" << SceneManager::GetMaterialComponent(i.first)->GetName() << std::endl; file_out << "H" << SceneManager::GetMaterialComponent(i.first)->GetShininess() << std::endl; file_out << "C" << SceneManager::GetMaterialComponent(i.first)->GetColor().x << "r" << SceneManager::GetMaterialComponent(i.first)->GetColor().y << "g" << SceneManager::GetMaterialComponent(i.first)->GetColor().z << "b" << std::endl; } if (SceneManager::HasMeshComponent(i.first)) { std::string relativePath = SceneManager::GetMeshComponent(i.first)->GetPath(); std::string absolutePath = relativePath.erase(0, relativePath.find(projectPath) + projectPath.length()); HC_CORE_INFO(absolutePath); file_out << "V" << absolutePath << std::endl; } } HC_CORE_SUCCESS("{0} Saved succesfully!", levelPath); } file_out.close(); } const void LevelManager::NewLevel(std::string levelName) { std::string path = "Levels/" + levelName + ".hclvl"; std::ofstream file_out(path); HC_CORE_SUCCESS("New Level: {0}", path); } glm::vec3* LevelManager::GetColor(std::string name) { for (auto& i : levelData.matColors) { if (i.first == name) { return &i.second; } } } float* LevelManager::GetShininess(std::string name) { for (auto& i : levelData.matShinies) { if (i.first == name) { return &i.second; } } } }
10,502
4,625
/* * Copyright 2011 Hewlett-Packard Development Company, L.P. 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 Hewlett-Packard 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 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "InitWebCoreQt.h" #include "NotImplemented.h" #include "PlatformStrategiesQt.h" #include "ScriptController.h" #include "SecurityPolicy.h" #if USE(QTKIT) #include "WebSystemInterface.h" #endif #include "qwebelement_p.h" #include <runtime/InitializeThreading.h> #include <wtf/MainThread.h> namespace WebCore { void initializeWebCoreQt() { static bool initialized = false; if (initialized) return; WebCore::initializeLoggingChannelsIfNecessary(); ScriptController::initializeThreading(); WTF::initializeMainThread(); WebCore::SecurityPolicy::setLocalLoadPolicy(WebCore::SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData); PlatformStrategiesQt::initialize(); QtWebElementRuntime::initialize(); #if USE(QTKIT) InitWebCoreSystemInterface(); #endif initialized = true; } }
2,460
828
#include "stdafx.h" #include "util/fixes.h" #include <obj.h> #include <temple_functions.h> #include "gamesystems/timeevents.h" #include <particles.h> #include <gamesystems/gamesystems.h> #include <gamesystems/map/sector.h> #include <gamesystems/particlesystems.h> /* This is the fix for bug #104, which causes particle systems to be duplicated when a diff file for a sector is loaded alongside the sector. ToEE first reads the light from the original sector @ 0x101063C3, apparently to get it's position. Then it reads the light from the diff file @ 0x10106452, *without* freeing the first light. This means the memory of the first light leaks (miniscule) and the particle systems created in the load function will also leak (major issue). The correct solution would be to a) free the light and b) not even create the particle systems in the first load function. This fix will simply free the light and kill the particle systems in the load-light-from-diff function as a quick fix. */ struct TioFile; // Fix for duplicate particle systems static class SectorLoadLightFix : TempleFix { public: void apply() override; private: static int ReadLight(TioFile* file, SectorLight** lightOut); static int ReadLightFromDiff(TioFile* file, SectorLight** lightOut); static int (*OrgReadLightFromDiff)(TioFile*, SectorLight**); static int (*OrgReadLight)(TioFile*, SectorLight**); } sectorCacheFix; int (*SectorLoadLightFix::OrgReadLightFromDiff)(TioFile*, SectorLight**); int (*SectorLoadLightFix::OrgReadLight)(TioFile*, SectorLight**); void SectorLoadLightFix::apply() { OrgReadLightFromDiff = replaceFunction(0x100A8050, ReadLightFromDiff); OrgReadLight = replaceFunction(0x100A6890, ReadLight); } int SectorLoadLightFix::ReadLight(TioFile* file, SectorLight** lightOut) { auto &particles = gameSystems->GetParticleSys(); SectorLight light; if (tio_fread(&light, 0x40, 1u, file) != 1) return 0; auto lightPos = light.position.ToInches3D(light.offsetZ); SectorLight *realLight; if (light.flags & 0x10) { realLight = (SectorLight *)malloc(0x48u); memcpy(realLight, &light, 0x40); if (tio_fread(&realLight->partSys, 8u, 1u, file) != 1) return 0; if (realLight->partSys.hashCode) { realLight->partSys.handle = particles.CreateAt(realLight->partSys.hashCode, lightPos); } else { realLight->partSys.handle = 0; } } else if (light.flags & 0x40) { realLight = (SectorLight *)malloc(0xB0u); memcpy(realLight, &light, 0x40); if (tio_fread(&realLight->partSys, 8u, 1u, file) != 1) return 0; if (tio_fread(&realLight->light2, 0x24u, 1u, file) != 1) return 0; // reset the handles so whatever the on-disk sector may say, the particle systems are not running realLight->partSys.handle = 0; realLight->light2.partSys.handle = 0; static auto& sIsNight = temple::GetRef<BOOL>(0x10B5DC80); SectorLightPartSys *partSys; if (sIsNight) { partSys = &realLight->light2.partSys; } else { partSys = &realLight->partSys; } if (partSys->hashCode) { partSys->handle = particles.CreateAt(partSys->hashCode, lightPos); } } else { realLight = (SectorLight *)malloc(0x40u); memcpy(realLight, &light, 0x40); } *lightOut = realLight; return 1; } int SectorLoadLightFix::ReadLightFromDiff(TioFile* file, SectorLight** lightOut) { auto& particles = gameSystems->GetParticleSys(); /* ToEE would let the light read from the original sector file leak, so we take care of it here and destroy the light and the particle systems that might have been created. */ auto lightOrg = *lightOut; if (lightOrg) { if (lightOrg->flags & 0x50) { auto partSys1 = lightOrg->partSys; if (partSys1.handle) { particles.Remove(partSys1.handle); } } if (lightOrg->flags & 0x40) { auto partSys2 = lightOrg->light2.partSys; if (partSys2.handle) { particles.Remove(partSys2.handle); } } free(lightOrg); } return ReadLight(file, lightOut); }
3,949
1,566
// File implement/oglplus/enums/object_type_names.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/object_type.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // 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 // namespace enums { OGLPLUS_LIB_FUNC StrCRef ValueName_( ObjectType*, GLenum value ) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVN_OBJECTTYPE) #define OGLPLUS_IMPL_EVN_OBJECTTYPE { switch(value) { #if defined GL_BUFFER case GL_BUFFER: return StrCRef("BUFFER"); #endif #if defined GL_FRAMEBUFFER case GL_FRAMEBUFFER: return StrCRef("FRAMEBUFFER"); #endif #if defined GL_PROGRAM_PIPELINE case GL_PROGRAM_PIPELINE: return StrCRef("PROGRAM_PIPELINE"); #endif #if defined GL_PROGRAM case GL_PROGRAM: return StrCRef("PROGRAM"); #endif #if defined GL_QUERY case GL_QUERY: return StrCRef("QUERY"); #endif #if defined GL_RENDERBUFFER case GL_RENDERBUFFER: return StrCRef("RENDERBUFFER"); #endif #if defined GL_SAMPLER case GL_SAMPLER: return StrCRef("SAMPLER"); #endif #if defined GL_SHADER case GL_SHADER: return StrCRef("SHADER"); #endif #if defined GL_TEXTURE case GL_TEXTURE: return StrCRef("TEXTURE"); #endif #if defined GL_TRANSFORM_FEEDBACK case GL_TRANSFORM_FEEDBACK: return StrCRef("TRANSFORM_FEEDBACK"); #endif #if defined GL_VERTEX_ARRAY case GL_VERTEX_ARRAY: return StrCRef("VERTEX_ARRAY"); #endif #if defined GL_NONE case GL_NONE: return StrCRef("NONE"); #endif default:; } OGLPLUS_FAKE_USE(value); return StrCRef(); } #else ; #endif } // namespace enums
1,761
722
#include <parser.hpp> #include <anton/optional.hpp> #include <anton/string7_stream.hpp> #include <anton/string7_view.hpp> // TODO: When matching keywords, ensure that the keyword is followed by non-identifier character (Find a cleaner way). // TODO: Figure out a way to match operators that use overlapping symbols (+ and +=) in a clean way. // TODO: const types. // TODO: add constructors (currently function call which will break if we use an array type). namespace vush { using namespace anton::literals; // keywords static constexpr anton::String7_View kw_if = u8"if"; static constexpr anton::String7_View kw_else = u8"else"; static constexpr anton::String7_View kw_switch = u8"switch"; static constexpr anton::String7_View kw_case = u8"case"; static constexpr anton::String7_View kw_default = u8"default"; static constexpr anton::String7_View kw_for = u8"for"; static constexpr anton::String7_View kw_while = u8"while"; static constexpr anton::String7_View kw_do = u8"do"; static constexpr anton::String7_View kw_return = u8"return"; static constexpr anton::String7_View kw_break = u8"break"; static constexpr anton::String7_View kw_continue = u8"continue"; static constexpr anton::String7_View kw_discard = u8"discard"; static constexpr anton::String7_View kw_true = u8"true"; static constexpr anton::String7_View kw_false = u8"false"; static constexpr anton::String7_View kw_from = u8"from"; static constexpr anton::String7_View kw_struct = u8"struct"; static constexpr anton::String7_View kw_import = u8"import"; static constexpr anton::String7_View kw_const = u8"const"; static constexpr anton::String7_View kw_settings = u8"settings"; static constexpr anton::String7_View kw_reinterpret = u8"reinterpret"; static constexpr anton::String7_View kw_invariant = u8"invariant"; static constexpr anton::String7_View kw_smooth = u8"smooth"; static constexpr anton::String7_View kw_flat = u8"flat"; static constexpr anton::String7_View kw_noperspective = u8"noperspective"; // attributes static constexpr anton::String7_View attrib_workgroup = u8"workgroup"; // stages static constexpr anton::String7_View stage_vertex = u8"vertex"; static constexpr anton::String7_View stage_fragment = u8"fragment"; static constexpr anton::String7_View stage_compute = u8"compute"; // separators and operators static constexpr anton::String7_View token_brace_open = u8"{"; static constexpr anton::String7_View token_brace_close = u8"}"; static constexpr anton::String7_View token_bracket_open = u8"["; static constexpr anton::String7_View token_bracket_close = u8"]"; static constexpr anton::String7_View token_paren_open = u8"("; static constexpr anton::String7_View token_paren_close = u8")"; static constexpr anton::String7_View token_angle_open = u8"<"; static constexpr anton::String7_View token_angle_close = u8">"; static constexpr anton::String7_View token_semicolon = u8";"; static constexpr anton::String7_View token_colon = u8":"; static constexpr anton::String7_View token_scope_resolution = u8"::"; static constexpr anton::String7_View token_arrow = u8"=>"; static constexpr anton::String7_View token_comma = u8","; // static constexpr anton::String7_View token_question = u8"?"; static constexpr anton::String7_View token_dot = u8"."; static constexpr anton::String7_View token_double_quote = u8"\""; static constexpr anton::String7_View token_plus = u8"+"; static constexpr anton::String7_View token_minus = u8"-"; static constexpr anton::String7_View token_multiply = u8"*"; static constexpr anton::String7_View token_divide = u8"/"; static constexpr anton::String7_View token_remainder = u8"%"; static constexpr anton::String7_View token_logic_and = u8"&&"; static constexpr anton::String7_View token_bit_and = u8"&"; static constexpr anton::String7_View token_logic_or = u8"||"; static constexpr anton::String7_View token_logic_xor = u8"^^"; static constexpr anton::String7_View token_bit_or = u8"|"; static constexpr anton::String7_View token_bit_xor = u8"^"; static constexpr anton::String7_View token_logic_not = u8"!"; static constexpr anton::String7_View token_bit_not = u8"~"; static constexpr anton::String7_View token_bit_lshift = u8"<<"; static constexpr anton::String7_View token_bit_rshift = u8">>"; static constexpr anton::String7_View token_equal = u8"=="; static constexpr anton::String7_View token_not_equal = u8"!="; static constexpr anton::String7_View token_less = u8"<"; static constexpr anton::String7_View token_greater = u8">"; static constexpr anton::String7_View token_less_equal = u8"<="; static constexpr anton::String7_View token_greater_equal = u8">="; static constexpr anton::String7_View token_assign = u8"="; static constexpr anton::String7_View token_increment = u8"++"; static constexpr anton::String7_View token_decrement = u8"--"; static constexpr anton::String7_View token_compound_plus = u8"+="; static constexpr anton::String7_View token_compound_minus = u8"-="; static constexpr anton::String7_View token_compound_multiply = u8"*="; static constexpr anton::String7_View token_compound_divide = u8"/="; static constexpr anton::String7_View token_compound_remainder = u8"%="; static constexpr anton::String7_View token_compound_bit_and = u8"&="; static constexpr anton::String7_View token_compound_bit_or = u8"|="; static constexpr anton::String7_View token_compound_bit_xor = u8"^="; static constexpr anton::String7_View token_compound_bit_lshift = u8"<<="; static constexpr anton::String7_View token_compound_bit_rshift = u8">>="; [[nodiscard]] static bool is_whitespace(char32 c) { return (c <= 32) | (c == 127); } [[nodiscard]] static bool is_binary_digit(char32 c) { return c == 48 || c == 49; } [[nodiscard]] static bool is_hexadecimal_digit(char32 c) { return (c >= 48 && c <= 57) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102); } [[nodiscard]] static bool is_octal_digit(char32 c) { return c >= 48 && c <= 55; } [[nodiscard]] static bool is_digit(char32 c) { return c >= 48 && c <= 57; } [[nodiscard]] static bool is_alpha(char32 c) { return (c >= 97 && c < 123) || (c >= 65 && c < 91); } [[nodiscard]] static bool is_first_identifier_character(char32 c) { return c == '_' || is_alpha(c); } [[nodiscard]] static bool is_identifier_character(char32 c) { return c == '_' || is_digit(c) || is_alpha(c); } [[nodiscard]] static bool is_keyword(anton::String_View string) { static constexpr anton::String7_View keywords[] = { kw_if, kw_else, kw_switch, kw_case, kw_default, kw_for, kw_while, kw_do, kw_return, kw_break, kw_continue, kw_discard, kw_true, kw_false, kw_from, kw_struct, kw_import, kw_const, kw_settings, kw_reinterpret, }; anton::String7_View string7{string.bytes_begin(), string.bytes_end()}; constexpr i64 array_size = sizeof(keywords) / sizeof(anton::String7_View); for(anton::String7_View const *i = keywords, *end = keywords + array_size; i != end; ++i) { if(*i == string7) { return true; } } return false; } class Lexer_State { public: i64 stream_offset; i64 line; i64 column; }; constexpr char8 eof_char8 = (char8)EOF; constexpr char32 eof_char32 = (char32)EOF; // TODO: Place this comment somewhere // The source string is ASCII only, so String7 will be the exact same size as String, // but String7 will avoid all Unicode function calls and thus accelerate parsing. class Lexer { public: Lexer(anton::String_View source): _begin(source.bytes_begin()), _end(source.bytes_end()), _current(source.bytes_begin()) {} bool match(anton::String7_View const string, bool const must_not_be_followed_by_identifier_char = false) { Lexer_State const state_backup = get_current_state(); for(char8 c: string) { if(_current != _end && *_current == c) { ++_current; ++_column; } else { restore_state(state_backup); return false; } } if(must_not_be_followed_by_identifier_char) { char32 const c = peek_next(); if(is_identifier_character(c)) { restore_state(state_backup); return false; } else { return true; } } else { return true; } } bool match_identifier(anton::String& out) { ignore_whitespace_and_comments(); if(_current != _end && !is_first_identifier_character(*_current)) { return false; } char8 const* identifier_end = _current + 1; while(identifier_end != _end && is_identifier_character(*identifier_end)) { ++identifier_end; } out += anton::String_View{_current, identifier_end}; _column += identifier_end - _current; _current = identifier_end; return true; } bool match_eof() { ignore_whitespace_and_comments(); return _current == _end || *_current == eof_char8; } void ignore_whitespace_and_comments() { while(true) { while(_current != _end && is_whitespace(*_current)) { if(*_current == '\n') { _line += 1; _column = 1; } else { ++_column; } ++_current; } if(_current != _end && *_current == '/' && _current + 1 != _end) { char32 const next_char = *(_current + 1); if(next_char == U'/') { for(; _current != _end && *_current != '\n'; ++_current) {} // The loop stops at the newline. Skip the newline. _current += 1; _line += 1; _column = 1; continue; } else if(next_char == U'*') { _current += 2; _column += 2; for(char32 c1 = get_next(), c2 = peek_next(); c1 != U'*' || c2 != U'/'; c1 = get_next(), c2 = peek_next()) {} get_next(); continue; } else { // Not a comment. End skipping. break; } } break; } } Lexer_State get_current_state() { ignore_whitespace_and_comments(); return {_current - _begin, _line, _column}; } Lexer_State get_current_state_no_skip() { return {_current - _begin, _line, _column}; } void restore_state(Lexer_State const state) { _current = _begin + state.stream_offset; _line = state.line; _column = state.column; } char32 get_next() { if(_current != _end) { char32 const c = *_current; ++_current; if(c == '\n') { _line += 1; _column = 1; } else { _column += 1; } return c; } else { return eof_char32; } } char32 peek_next() { if(_current != _end) { return *_current; } else { return eof_char32; } } void unget() { if(_current != _begin) { --_current; } } private: char8 const* _begin; char8 const* _end; char8 const* _current; i64 _line = 1; i64 _column = 1; }; class Parser { public: Parser(anton::String_View source_code, anton::String_View source_name): _source_name(source_name), _lexer(source_code) {} anton::Expected<Declaration_List, Parse_Error> build_ast() { Declaration_List ast; while(!_lexer.match_eof()) { if(Owning_Ptr declaration = try_declaration()) { ast.emplace_back(ANTON_MOV(declaration)); } else { return {anton::expected_error, _last_error}; } } return {anton::expected_value, ANTON_MOV(ast)}; } anton::Expected<Declaration_List, Parse_Error> parse_builtin_functions() { Declaration_List builtin_functions; while(!_lexer.match_eof()) { if(Owning_Ptr fn = try_function_declaration()) { fn->builtin = true; fn->source_info.line = 1; fn->source_info.end_line = 1; builtin_functions.emplace_back(ANTON_MOV(fn)); } else { return {anton::expected_error, _last_error}; } } return {anton::expected_value, ANTON_MOV(builtin_functions)}; } private: anton::String_View _source_name; Lexer _lexer; Parse_Error _last_error; void set_error(anton::String_View const message, Lexer_State const& state) { if(state.stream_offset >= _last_error.stream_offset) { _last_error.message = message; _last_error.line = state.line; _last_error.column = state.column; _last_error.stream_offset = state.stream_offset; } } void set_error(anton::String_View const message) { Lexer_State const state = _lexer.get_current_state_no_skip(); if(state.stream_offset >= _last_error.stream_offset) { _last_error.message = message; _last_error.line = state.line; _last_error.column = state.column; _last_error.stream_offset = state.stream_offset; } } Source_Info src_info(Lexer_State const& start, Lexer_State const& end) { return Source_Info{_source_name, start.line, start.column, start.stream_offset, end.line, end.column, end.stream_offset}; } Owning_Ptr<Declaration> try_declaration() { if(Owning_Ptr declaration_if = try_declaration_if()) { return declaration_if; } if(Owning_Ptr import_declaration = try_import_declaration()) { return import_declaration; } if(Owning_Ptr settings_declaration = try_settings_declaration()) { return settings_declaration; } if(Owning_Ptr struct_declaration = try_struct_declaration()) { return struct_declaration; } if(Owning_Ptr pass_stage = try_pass_stage_declaration()) { return pass_stage; } if(Owning_Ptr function_declaration = try_function_declaration()) { return function_declaration; } if(Owning_Ptr variable_declaration = try_variable_declaration()) { return variable_declaration; } if(Owning_Ptr constant = try_constant_declaration()) { return constant; } set_error(u8"expected declaration"); return nullptr; } Owning_Ptr<Declaration_If> try_declaration_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Declaration_List true_declarations; while(!_lexer.match(token_brace_close)) { if(_lexer.match_eof()) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return nullptr; } if(Owning_Ptr declaration = try_declaration()) { true_declarations.emplace_back(ANTON_MOV(declaration)); } else { return nullptr; } } Declaration_List false_declarations; if(_lexer.match(kw_else, true)) { if(Owning_Ptr if_declaration = try_declaration_if()) { false_declarations.emplace_back(ANTON_MOV(if_declaration)); } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } while(!_lexer.match(token_brace_close)) { if(Owning_Ptr declaration = try_declaration()) { false_declarations.emplace_back(ANTON_MOV(declaration)); } else { _lexer.restore_state(state_backup); return nullptr; } } } } return Owning_Ptr{ new Declaration_If(ANTON_MOV(condition), ANTON_MOV(true_declarations), ANTON_MOV(false_declarations), src_info(state_backup, state_backup))}; } Owning_Ptr<Import_Declaration> try_import_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_import, true)) { set_error(u8"expected 'import'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr string = try_string_literal()) { return Owning_Ptr{new Import_Declaration(ANTON_MOV(string), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } Owning_Ptr<Variable_Declaration> try_variable_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after variable declaration"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Variable_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Constant_Declaration> try_constant_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_const)) { set_error(u8"expected 'const'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_type = try_type(); if(!var_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after constant declaration"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Constant_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Struct_Member> try_struct_member() { Lexer_State const state_backup = _lexer.get_current_state(); bool has_invariant = false; bool has_interpolation = false; Interpolation interpolation = Interpolation::none; while(true) { if(_lexer.match(kw_invariant, true)) { if(has_invariant) { set_error(u8"multiple invariance qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } has_invariant = true; continue; } if(_lexer.match(kw_smooth, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::smooth; has_interpolation = true; continue; } if(_lexer.match(kw_flat, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::flat; has_interpolation = true; continue; } if(_lexer.match(kw_noperspective, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::noperspective; has_interpolation = true; continue; } break; } Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected member name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Struct_Member(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), interpolation, has_invariant, src)}; } Owning_Ptr<Struct_Declaration> try_struct_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_struct, true)) { set_error(u8"expected 'struct'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr struct_name = try_identifier(); if(!struct_name) { set_error(u8"expected struct name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Struct_Member>> members; while(!_lexer.match(token_brace_close)) { if(Owning_Ptr decl = try_struct_member()) { members.emplace_back(ANTON_MOV(decl)); } else { _lexer.restore_state(state_backup); return nullptr; } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Struct_Declaration(ANTON_MOV(struct_name), ANTON_MOV(members), src)}; } Owning_Ptr<Settings_Declaration> try_settings_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); auto match_string = [this, &state_backup]() -> anton::Optional<anton::String> { _lexer.ignore_whitespace_and_comments(); anton::String string; while(true) { char32 next_char = _lexer.peek_next(); if(next_char == eof_char32) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return anton::null_optional; } else if(is_whitespace(next_char) || next_char == U':' || next_char == U'}' || next_char == U'{') { return {ANTON_MOV(string)}; } else { string += next_char; _lexer.get_next(); } } }; auto match_nested_settings = [this, &state_backup, &match_string](auto match_nested_settings, anton::Array<Setting_Key_Value>& settings, anton::String const& setting_name) -> bool { while(true) { if(_lexer.match(token_brace_close)) { return true; } auto key_name = match_string(); if(!key_name) { _lexer.restore_state(state_backup); return false; } if(key_name.value().size_bytes() == 0) { set_error(u8"expected name"); _lexer.restore_state(state_backup); return false; } if(!_lexer.match(token_colon)) { set_error(u8"expected ':'"); _lexer.restore_state(state_backup); return false; } anton::String setting_key = setting_name; if(setting_key.size_bytes() > 0) { setting_key += u8"_"; } setting_key += key_name.value(); if(_lexer.match(token_brace_open)) { if(!match_nested_settings(match_nested_settings, settings, setting_key)) { _lexer.restore_state(state_backup); return false; } } else { auto value = match_string(); if(!value) { _lexer.restore_state(state_backup); return false; } if(value.value().size_bytes() == 0) { set_error(u8"expected value string after ':'"); _lexer.restore_state(state_backup); return false; } settings.emplace_back(Setting_Key_Value{ANTON_MOV(setting_key), ANTON_MOV(value.value())}); } } }; if(!_lexer.match(kw_settings, true)) { set_error(u8"expected 'settings'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr pass_name = try_identifier(); if(!pass_name) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr settings_declaration{new Settings_Declaration(ANTON_MOV(pass_name), src_info(state_backup, state_backup))}; if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(!match_nested_settings(match_nested_settings, settings_declaration->settings, anton::String{})) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); settings_declaration->source_info = src; return settings_declaration; } Owning_Ptr<Attribute> try_attribute() { Lexer_State const state_backup = _lexer.get_current_state(); // workgroup attribute if(_lexer.match(attrib_workgroup, true)) { if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr x = try_integer_literal(); if(!x) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Integer_Literal> y; Owning_Ptr<Integer_Literal> z; if(_lexer.match(token_comma)) { y = try_integer_literal(); if(!y) { _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_comma)) { z = try_integer_literal(); if(!z) { _lexer.restore_state(state_backup); return nullptr; } } } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Workgroup_Attribute(ANTON_MOV(x), ANTON_MOV(y), ANTON_MOV(z), src)}; } // TODO: Add a diagnostic for unrecognized attributes set_error(u8"expected identifier"); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Attribute_List> try_attribute_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_bracket_open)) { set_error(u8"expected '['"); _lexer.restore_state(state_backup); return anton::null_optional; } if(_lexer.match(token_bracket_close)) { set_error(u8"empty attribute list (TODO: PROVIDE A PROPER DIAGNOSTIC MESSAGE WITH EXACT LOCATION AND CODE SNIPPET)"); _lexer.restore_state(state_backup); return anton::null_optional; } Attribute_List attributes; while(true) { Owning_Ptr attribute = try_attribute(); if(!attribute) { _lexer.restore_state(state_backup); return anton::null_optional; } attributes.emplace_back(ANTON_MOV(attribute)); if(!_lexer.match(token_comma)) { break; } } if(!_lexer.match(token_bracket_close)) { _lexer.restore_state(state_backup); return anton::null_optional; } return ANTON_MOV(attributes); } Owning_Ptr<Image_Layout_Qualifier> try_image_layout_qualifier() { Image_Layout_Type qualifiers[] = {Image_Layout_Type::rgba32f, Image_Layout_Type::rgba16f, Image_Layout_Type::rg32f, Image_Layout_Type::rg16f, Image_Layout_Type::r11f_g11f_b10f, Image_Layout_Type::r32f, Image_Layout_Type::r16f, Image_Layout_Type::rgba16, Image_Layout_Type::rgb10_a2, Image_Layout_Type::rgba8, Image_Layout_Type::rg16, Image_Layout_Type::rg8, Image_Layout_Type::r16, Image_Layout_Type::r8, Image_Layout_Type::rgba16_snorm, Image_Layout_Type::rgba8_snorm, Image_Layout_Type::rg16_snorm, Image_Layout_Type::rg8_snorm, Image_Layout_Type::r16_snorm, Image_Layout_Type::r8_snorm, Image_Layout_Type::rgba32i, Image_Layout_Type::rgba16i, Image_Layout_Type::rgba8i, Image_Layout_Type::rg32i, Image_Layout_Type::rg16i, Image_Layout_Type::rg8i, Image_Layout_Type::r32i, Image_Layout_Type::r16i, Image_Layout_Type::r8i, Image_Layout_Type::rgba32ui, Image_Layout_Type::rgba16ui, Image_Layout_Type::rgb10_a2ui, Image_Layout_Type::rgba8ui, Image_Layout_Type::rg32ui, Image_Layout_Type::rg16ui, Image_Layout_Type::rg8ui, Image_Layout_Type::r32ui, Image_Layout_Type::r16ui, Image_Layout_Type::r8ui}; Lexer_State const state_backup = _lexer.get_current_state(); constexpr i64 array_size = sizeof(qualifiers) / sizeof(Image_Layout_Type); for(i64 i = 0; i < array_size; ++i) { anton::String_View const string{stringify(qualifiers[i])}; anton::String7_View const string7{string.bytes_begin(), string.bytes_end()}; if(_lexer.match(string7, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Image_Layout_Qualifier(qualifiers[i], src)}; } } return nullptr; } Owning_Ptr<Pass_Stage_Declaration> try_pass_stage_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); // Parse the attribute lists. We allow many attribute lists // to be present on a stage declaration. We merge the lists into // a single attribute array. Attribute_List attributes; while(true) { anton::Optional<Attribute_List> attributes_result = try_attribute_list(); if(!attributes_result) { break; } for(auto& attribute: attributes_result.value()) { attributes.emplace_back(ANTON_MOV(attribute)); } } Owning_Ptr return_type = try_type(); if(!return_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr pass = try_identifier(); if(!pass) { set_error(u8"expected pass name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_scope_resolution)) { set_error(u8"expected '::' after pass name"); _lexer.restore_state(state_backup); return nullptr; } static constexpr anton::String7_View stage_types_strings[] = {stage_vertex, stage_fragment, stage_compute}; static constexpr Stage_Type stage_types[] = {Stage_Type::vertex, Stage_Type::fragment, Stage_Type::compute}; Stage_Type stage_type; { bool found = false; for(i64 i = 0; i < 3; ++i) { if(_lexer.match(stage_types_strings[i], true)) { stage_type = stage_types[i]; found = true; break; } } if(!found) { set_error(u8"expected stage type"); _lexer.restore_state(state_backup); return nullptr; } } anton::Optional<Parameter_List> parameter_list = try_function_param_list(); if(!parameter_list) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Pass_Stage_Declaration(ANTON_MOV(attributes), ANTON_MOV(return_type), ANTON_MOV(pass), stage_type, ANTON_MOV(parameter_list.value()), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Function_Declaration> try_function_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); // Parse the attribute lists. We allow many attribute lists // to be present on a function declaration. We merge the lists // into a single attribute array. Attribute_List attributes; while(true) { anton::Optional<Attribute_List> attributes_result = try_attribute_list(); if(!attributes_result) { break; } for(auto& attribute: attributes_result.value()) { attributes.emplace_back(ANTON_MOV(attribute)); } } Owning_Ptr return_type = try_type(); if(!return_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr name = try_identifier(); if(!name) { set_error(u8"expected function name"); _lexer.restore_state(state_backup); return nullptr; } auto param_list = try_function_param_list(); if(!param_list) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Declaration(ANTON_MOV(attributes), ANTON_MOV(return_type), ANTON_MOV(name), ANTON_MOV(param_list.value()), ANTON_MOV(statements.value()), src)}; } anton::Optional<Parameter_List> try_function_param_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return anton::null_optional; } if(_lexer.match(token_paren_close)) { return Parameter_List{}; } Parameter_List param_list; // Match parameters do { Owning_Ptr param = try_function_parameter(); if(param) { param_list.emplace_back(ANTON_MOV(param)); } else { _lexer.restore_state(state_backup); return anton::null_optional; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')' after function parameter list"); _lexer.restore_state(state_backup); return anton::null_optional; } return ANTON_MOV(param_list); } Owning_Ptr<Function_Parameter_Node> try_function_parameter() { Lexer_State const state_backup = _lexer.get_current_state(); if(Owning_Ptr param_if = try_function_param_if()) { return param_if; } Owning_Ptr image_layout = try_image_layout_qualifier(); Owning_Ptr parameter_type = try_type(); if(!parameter_type) { set_error(u8"expected parameter type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr identifier = try_identifier(); if(!identifier) { set_error(u8"expected parameter name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Identifier> source; if(_lexer.match(kw_from, true)) { source = try_identifier(); if(!source) { set_error(u8"expected parameter source after 'from'"); _lexer.restore_state(state_backup); return nullptr; } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Parameter(ANTON_MOV(identifier), ANTON_MOV(parameter_type), ANTON_MOV(source), ANTON_MOV(image_layout), src)}; } Owning_Ptr<Function_Param_If> try_function_param_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr true_param = try_function_parameter(); if(!true_param) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(kw_else, true)) { if(Owning_Ptr param_if = try_function_param_if()) { return Owning_Ptr{ new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), ANTON_MOV(param_if), src_info(state_backup, state_backup))}; } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr false_param = try_function_parameter(); if(!false_param) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}'"); _lexer.restore_state(state_backup); return nullptr; } return Owning_Ptr{ new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), ANTON_MOV(false_param), src_info(state_backup, state_backup))}; } } else { return Owning_Ptr{new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), nullptr, src_info(state_backup, state_backup))}; } } // try_empty_statament // Match empty statement ';'. // bool try_empty_statement() { return _lexer.match(token_semicolon); } Owning_Ptr<Statement> try_statement() { if(Owning_Ptr block_statement = try_block_statement()) { return block_statement; } if(Owning_Ptr if_statement = try_if_statement()) { return if_statement; } if(Owning_Ptr switch_statement = try_switch_statement()) { return switch_statement; } if(Owning_Ptr for_statement = try_for_statement()) { return for_statement; } if(Owning_Ptr while_statement = try_while_statement()) { return while_statement; } if(Owning_Ptr do_while_statement = try_do_while_statement()) { return do_while_statement; } if(Owning_Ptr return_statement = try_return_statement()) { return return_statement; } if(Owning_Ptr break_statement = try_break_statement()) { return break_statement; } if(Owning_Ptr continue_statement = try_continue_statement()) { return continue_statement; } if(Owning_Ptr discard_statement = try_discard_statement()) { return discard_statement; } if(Owning_Ptr decl = try_variable_declaration()) { Source_Info const src = decl->source_info; Owning_Ptr decl_stmt{new Declaration_Statement(ANTON_MOV(decl), src)}; return decl_stmt; } if(Owning_Ptr decl = try_constant_declaration()) { Source_Info const src = decl->source_info; Owning_Ptr decl_stmt{new Declaration_Statement(ANTON_MOV(decl), src)}; return decl_stmt; } if(Owning_Ptr expr_stmt = try_expression_statement()) { return expr_stmt; } set_error(u8"expected a statement"); return nullptr; } // try_braced_statement_list // Match '{' statements '}' anton::Optional<Statement_List> try_braced_statement_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return anton::null_optional; } Statement_List body; while(true) { if(_lexer.match(token_brace_close)) { return {ANTON_MOV(body)}; } if(try_empty_statement()) { continue; } Owning_Ptr<Statement> statement = try_statement(); if(statement) { body.emplace_back(ANTON_MOV(statement)); continue; } _lexer.restore_state(state_backup); return anton::null_optional; } } Owning_Ptr<Type> try_type() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String type_name; if(!_lexer.match_identifier(type_name)) { set_error(u8"expected type identifier"); return nullptr; } if(is_keyword(type_name)) { anton::String msg = u8"expected type name, got '" + type_name + "' instead"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Type> base_type; if(anton::Optional<Builtin_GLSL_Type> res = enumify_builtin_glsl_type(type_name); res) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); base_type = Owning_Ptr{new Builtin_Type(res.value(), src)}; } else { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); base_type = Owning_Ptr{new User_Defined_Type(ANTON_MOV(type_name), src)}; } if(!_lexer.match(token_bracket_open)) { return base_type; } else { Owning_Ptr array_size = try_integer_literal(); if(!_lexer.match(token_bracket_close)) { set_error(u8"expected ']'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); // We don't support nested array types (yet), so we don't continue checking for brackets. return Owning_Ptr{new Array_Type(ANTON_MOV(base_type), ANTON_MOV(array_size), src)}; } } Owning_Ptr<Block_Statement> try_block_statement() { Lexer_State const state_backup = _lexer.get_current_state(); anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Block_Statement(ANTON_MOV(statements.value()), src)}; } Owning_Ptr<If_Statement> try_if_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> true_statements = try_braced_statement_list(); if(!true_statements) { _lexer.restore_state(state_backup); return nullptr; } Statement_List false_statements; if(_lexer.match(kw_else, true)) { if(Owning_Ptr if_statement = try_if_statement()) { false_statements.emplace_back(ANTON_MOV(if_statement)); } else { anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } false_statements = ANTON_MOV(statements.value()); } } return Owning_Ptr{ new If_Statement(ANTON_MOV(condition), ANTON_MOV(true_statements.value()), ANTON_MOV(false_statements), src_info(state_backup, state_backup))}; } Owning_Ptr<Switch_Statement> try_switch_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_switch, true)) { set_error(u8"expected 'switch'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr match_expression = try_expression(); if(!match_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Case_Statement>> cases; while(true) { Lexer_State const case_state = _lexer.get_current_state(); if(_lexer.match(token_brace_close)) { break; } Expression_List labels; do { Lexer_State const label_state = _lexer.get_current_state(); if(_lexer.match(kw_default, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(label_state, end_state); labels.emplace_back(Owning_Ptr{new Default_Expression(src)}); } else if(Owning_Ptr literal = try_integer_literal()) { labels.emplace_back(ANTON_MOV(literal)); } else { _lexer.restore_state(state_backup); return nullptr; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_arrow)) { set_error(u8"expected '=>'"_sv); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(case_state, end_state); Owning_Ptr case_statement = Owning_Ptr{new Case_Statement(ANTON_MOV(labels), ANTON_MOV(statements.value()), src)}; cases.emplace_back(ANTON_MOV(case_statement)); } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Switch_Statement(ANTON_MOV(match_expression), ANTON_MOV(cases), src)}; } Owning_Ptr<For_Statement> try_for_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_for, true)) { set_error("expected 'for'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_paren_open)) { set_error("unexpected '(' after 'for'"); _lexer.restore_state(state_backup); return nullptr; } // Match variable Owning_Ptr<Variable_Declaration> variable_declaration; if(!_lexer.match(token_semicolon)) { Lexer_State const var_decl_state = _lexer.get_current_state(); Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error("expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error("expected ';' in 'for' statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(var_decl_state, end_state); variable_declaration = Owning_Ptr{new Variable_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Expression> condition; if(!_lexer.match(token_semicolon)) { condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' in 'for' statement"); _lexer.restore_state(state_backup); return nullptr; } } Owning_Ptr post_expression = try_expression(); anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{ new For_Statement(ANTON_MOV(variable_declaration), ANTON_MOV(condition), ANTON_MOV(post_expression), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<While_Statement> try_while_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_while, true)) { set_error("expected 'while'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new While_Statement(ANTON_MOV(condition), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Do_While_Statement> try_do_while_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_do, true)) { set_error("expected 'do'"); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(kw_while, true)) { set_error("expected 'while'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' after do-while statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Do_While_Statement(ANTON_MOV(condition), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Return_Statement> try_return_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_return, true)) { set_error("expected 'return'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr return_expression = try_expression(); if(!_lexer.match(token_semicolon)) { set_error("expected ';' after return statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Return_Statement(ANTON_MOV(return_expression), src)}; } Owning_Ptr<Break_Statement> try_break_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_break, true)) { set_error(u8"expected 'break'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after break statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Break_Statement(src)}; } Owning_Ptr<Continue_Statement> try_continue_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_continue, true)) { set_error(u8"expected 'continue'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after continue statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Continue_Statement(src)}; } Owning_Ptr<Discard_Statement> try_discard_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_discard, true)) { set_error(u8"expected 'discard'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after discard statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Discard_Statement(src)}; } Owning_Ptr<Expression_Statement> try_expression_statement() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr expression = try_expression(); if(!expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' at the end of statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_Statement(ANTON_MOV(expression), src)}; } Owning_Ptr<Expression> try_expression() { return try_assignment_expression(); } Owning_Ptr<Expression> try_assignment_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr lhs = try_binary_expression(); if(!lhs) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const op_state = _lexer.get_current_state(); Arithmetic_Assignment_Type type; bool is_direct = false; if(_lexer.match(token_assign)) { is_direct = true; } else if(_lexer.match(token_compound_plus)) { type = Arithmetic_Assignment_Type::plus; } else if(_lexer.match(token_compound_minus)) { type = Arithmetic_Assignment_Type::minus; } else if(_lexer.match(token_compound_multiply)) { type = Arithmetic_Assignment_Type::multiply; } else if(_lexer.match(token_compound_divide)) { type = Arithmetic_Assignment_Type::divide; } else if(_lexer.match(token_compound_remainder)) { type = Arithmetic_Assignment_Type::remainder; } else if(_lexer.match(token_compound_bit_lshift)) { type = Arithmetic_Assignment_Type::lshift; } else if(_lexer.match(token_compound_bit_rshift)) { type = Arithmetic_Assignment_Type::rshift; } else if(_lexer.match(token_compound_bit_and)) { type = Arithmetic_Assignment_Type::bit_and; } else if(_lexer.match(token_compound_bit_or)) { type = Arithmetic_Assignment_Type::bit_or; } else if(_lexer.match(token_compound_bit_xor)) { type = Arithmetic_Assignment_Type::bit_xor; } else { return lhs; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr rhs = try_assignment_expression(); if(!rhs) { _lexer.restore_state(state_backup); return nullptr; } if(is_direct) { return Owning_Ptr{new Assignment_Expression(ANTON_MOV(lhs), ANTON_MOV(rhs), src)}; } else { return Owning_Ptr{new Arithmetic_Assignment_Expression(type, ANTON_MOV(lhs), ANTON_MOV(rhs), src)}; } } // Owning_Ptr<Expression> try_elvis_expression() { // Lexer_State const state_backup = _lexer.get_current_state(); // Owning_Ptr cond = try_logic_or_expr(); // if(!cond) { // _lexer.restore_state(state_backup); // return nullptr; // } // if(!_lexer.match(token_question)) { // return cond; // } // // TODO: is using try_expression here correct? // Owning_Ptr true_expression = try_expression(); // if(!true_expression) { // _lexer.restore_state(state_backup); // return nullptr; // } // if(!_lexer.match(token_colon)) { // set_error(u8"expected ':'"); // _lexer.restore_state(state_backup); // return nullptr; // } // Owning_Ptr false_expression = try_expression(); // if(!false_expression) { // _lexer.restore_state(state_backup); // return nullptr; // } // Lexer_State const end_state = _lexer.get_current_state_no_skip(); // Source_Info const src = src_info(state_backup, end_state); // return Owning_Ptr{new Elvis_Expression(ANTON_MOV(cond), ANTON_MOV(true_expression), ANTON_MOV(false_expression), src)}; // } Owning_Ptr<Expression> try_binary_expression() { auto insert_node = [](Owning_Ptr<Expression> root, Owning_Ptr<Binary_Expression> node) -> Owning_Ptr<Expression> { auto get_precedence = [](Binary_Expression& expression) -> i32 { switch(expression.type) { case Binary_Expression_Type::logic_or: return 11; case Binary_Expression_Type::logic_xor: return 10; case Binary_Expression_Type::logic_and: return 9; case Binary_Expression_Type::equal: return 5; case Binary_Expression_Type::unequal: return 5; case Binary_Expression_Type::greater_than: return 4; case Binary_Expression_Type::less_than: return 4; case Binary_Expression_Type::greater_equal: return 4; case Binary_Expression_Type::less_equal: return 4; case Binary_Expression_Type::bit_or: return 8; case Binary_Expression_Type::bit_xor: return 7; case Binary_Expression_Type::bit_and: return 6; case Binary_Expression_Type::lshift: return 3; case Binary_Expression_Type::rshift: return 3; case Binary_Expression_Type::add: return 2; case Binary_Expression_Type::sub: return 2; case Binary_Expression_Type::mul: return 1; case Binary_Expression_Type::div: return 1; case Binary_Expression_Type::mod: return 1; } }; i32 const node_precedence = get_precedence(*node); Owning_Ptr<Expression>* insertion_node = &root; while(true) { if((**insertion_node).node_type != AST_Node_Type::binary_expression) { break; } Binary_Expression& expression = static_cast<Binary_Expression&>(**insertion_node); i32 const expression_precedence = get_precedence(expression); if(expression_precedence < node_precedence) { // Precedence is smaller insertion_node = &expression.rhs; } else { break; } } node->lhs = ANTON_MOV(*insertion_node); *insertion_node = ANTON_MOV(node); return root; }; Owning_Ptr<Expression> root = try_unary_expression(); if(!root) { return nullptr; } while(true) { Lexer_State const op_state = _lexer.get_current_state(); if(_lexer.match(token_compound_bit_and) || _lexer.match(token_compound_bit_or) || _lexer.match(token_compound_bit_xor) || _lexer.match(token_compound_bit_lshift) || _lexer.match(token_compound_bit_rshift) || _lexer.match(token_compound_remainder) || _lexer.match(token_compound_divide) || _lexer.match(token_compound_multiply) || _lexer.match(token_compound_plus) || _lexer.match(token_compound_minus)) { _lexer.restore_state(op_state); return root; } if(_lexer.match(token_logic_or)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_or, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_logic_xor)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_xor, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_logic_and)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_and, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_or)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_or, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_xor)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_xor, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_and)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_and, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_lshift)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::lshift, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_rshift)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::rshift, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_not_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::unequal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_less_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::less_equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_greater_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::greater_equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_greater)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::greater_than, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_less)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::less_than, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_plus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::add, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_minus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::sub, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_multiply)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::mul, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_divide)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::div, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_remainder)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::mod, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else { break; } } return root; } Owning_Ptr<Expression> try_unary_expression() { Lexer_State const state_backup = _lexer.get_current_state(); if(_lexer.match(token_increment)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Prefix_Increment_Expression(ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_decrement)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Prefix_Decrement_Expression(ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_plus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::plus, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_minus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::minus, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_logic_not)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::logic_not, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_bit_not)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::bit_not, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else { return try_postfix_expression(); } } Owning_Ptr<Expression> try_postfix_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr primary_expr = try_primary_expression(); if(!primary_expr) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> expr = ANTON_MOV(primary_expr); while(true) { if(_lexer.match(token_dot)) { if(Owning_Ptr member_name = try_identifier()) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Member_Access_Expression(ANTON_MOV(expr), ANTON_MOV(member_name), src)}; } else { set_error(u8"expected member name"); _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_bracket_open)) { Owning_Ptr index = try_expression(); if(!index) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_bracket_close)) { set_error(u8"expected ']'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Array_Access_Expression(ANTON_MOV(expr), ANTON_MOV(index), src)}; } else if(_lexer.match(token_increment)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Postfix_Increment_Expression(ANTON_MOV(expr), src)}; } else if(_lexer.match(token_decrement)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Postfix_Decrement_Expression(ANTON_MOV(expr), src)}; } else { break; } } return expr; } Owning_Ptr<Expression> try_primary_expression() { if(Owning_Ptr parenthesised_expression = try_paren_expr()) { return parenthesised_expression; } if(Owning_Ptr expr = try_reinterpret_expr()) { return expr; } if(Owning_Ptr expression_if = try_expression_if()) { return expression_if; } if(Owning_Ptr float_literal = try_float_literal()) { return float_literal; } if(Owning_Ptr integer_literal = try_integer_literal()) { return integer_literal; } if(Owning_Ptr bool_literal = try_bool_literal()) { return bool_literal; } if(Owning_Ptr function_call = try_function_call_expression()) { return function_call; } if(Owning_Ptr identifier_expression = try_identifier_expression()) { return identifier_expression; } return nullptr; } Owning_Ptr<Parenthesised_Expression> try_paren_expr() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr paren_expression = try_expression(); if(!paren_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Parenthesised_Expression(ANTON_MOV(paren_expression), src)}; } Owning_Ptr<Reinterpret_Expression> try_reinterpret_expr() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_reinterpret, true)) { set_error(u8"expected 'reinterpret'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_angle_open)) { set_error(u8"expected '<'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr target_type = try_type(); if(!target_type) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_angle_close)) { set_error(u8"expected '>'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr source = try_expression(); if(!source) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_comma)) { set_error(u8"expected ','"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr index = try_expression(); if(!index) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Reinterpret_Expression{ANTON_MOV(target_type), ANTON_MOV(source), ANTON_MOV(index), src}}; } Owning_Ptr<Expression_If> try_expression_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_brace_close)) { set_error(u8"expected an expression before '}'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr true_expression = try_expression(); if(!true_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}' after expression"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(kw_else, true)) { set_error(u8"expected an 'else' branch"); _lexer.restore_state(state_backup); return nullptr; } if(Owning_Ptr expression_if = try_expression_if()) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_If(ANTON_MOV(condition), ANTON_MOV(true_expression), ANTON_MOV(expression_if), src)}; } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_brace_close)) { set_error(u8"expected an expression before '}'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr false_expression = try_expression(); if(!false_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}' after expression"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_If(ANTON_MOV(condition), ANTON_MOV(true_expression), ANTON_MOV(false_expression), src)}; } } Owning_Ptr<Function_Call_Expression> try_function_call_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr identifier = try_identifier(); if(!identifier) { set_error(u8"expected function name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_open)) { set_error(u8"expected '(' after function name"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Expression>> arguments; if(_lexer.match(token_paren_close)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Call_Expression(ANTON_MOV(identifier), ANTON_MOV(arguments), src)}; } do { if(Owning_Ptr expression = try_expression()) { arguments.emplace_back(ANTON_MOV(expression)); } else { _lexer.restore_state(state_backup); return nullptr; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Call_Expression(ANTON_MOV(identifier), ANTON_MOV(arguments), src)}; } Owning_Ptr<Float_Literal> try_float_literal() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String number; if(char32 const next_char = _lexer.peek_next(); next_char == '-' || next_char == U'+') { number += next_char; _lexer.get_next(); } i64 pre_point_digits = 0; for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++pre_point_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } // A decimal number must not have leading 0 except when the number is 0 if(number.size_bytes() > 1 && number.data()[0] == '0') { _lexer.restore_state(state_backup); return nullptr; } if(pre_point_digits == 0) { number += '0'; } bool has_period = false; i64 post_point_digits = 0; if(_lexer.peek_next() == '.') { has_period = true; number += '.'; _lexer.get_next(); for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++post_point_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } if(post_point_digits == 0) { number += '0'; } } if(pre_point_digits == 0 && post_point_digits == 0) { set_error(u8"not a floating point constant", state_backup); _lexer.restore_state(state_backup); return nullptr; } bool has_e = false; if(char32 const e = _lexer.peek_next(); e == U'e' || e == U'E') { has_e = true; number += 'E'; _lexer.get_next(); if(char32 const sign = _lexer.peek_next(); sign == '-' || sign == U'+') { number += sign; _lexer.get_next(); } i64 e_digits = 0; for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++e_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } if(e_digits == 0) { set_error("exponent has no digits"); _lexer.restore_state(state_backup); return nullptr; } } if(!has_e && !has_period) { set_error(u8"not a floating point constant", state_backup); _lexer.restore_state(state_backup); return nullptr; } Float_Literal_Type type = Float_Literal_Type::f32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"d" || suffix == u8"D") { type = Float_Literal_Type::f64; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on floating point literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Float_Literal(ANTON_MOV(number), type, src)}; } Owning_Ptr<Integer_Literal> try_integer_literal() { // Section 4.1.3 of The OpenGL Shading Language 4.60.7 states that integer literals are never negative. // Instead the leading '-' is always interpreted as a unary minus operator. We follow the same convention. Lexer_State const state_backup = _lexer.get_current_state(); // Binary literal bool const has_bin_prefix = _lexer.match(u8"0b") || _lexer.match(u8"0B"); if(has_bin_prefix) { anton::String out; while(is_binary_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } if(char32 const next = _lexer.peek_next(); is_digit(next)) { set_error(u8"invalid digit '" + anton::String::from_utf32(&next, 4) + u8"' in binary integer literal"); _lexer.restore_state(state_backup); return nullptr; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::bin, src}}; } // Octal literal bool const has_oct_prefix = _lexer.match(u8"0o") || _lexer.match(u8"0O"); if(has_oct_prefix) { anton::String out; while(is_octal_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } if(char32 const next = _lexer.peek_next(); is_digit(next)) { set_error(u8"invalid digit '" + anton::String::from_utf32(&next, 4) + u8"' in octal integer literal"); _lexer.restore_state(state_backup); return nullptr; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::oct, src}}; } // Hexadecimal literal bool const has_hex_prefix = _lexer.match(u8"0x") || _lexer.match(u8"0X"); if(has_hex_prefix) { anton::String out; while(is_hexadecimal_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::hex, src}}; } // Decimal literal anton::String out; if(char32 const next = _lexer.peek_next(); !is_digit(next)) { set_error(u8"expected integer literal"); _lexer.restore_state(state_backup); return nullptr; } while(is_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + "' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::dec, src}}; } Owning_Ptr<Bool_Literal> try_bool_literal() { Lexer_State const state_backup = _lexer.get_current_state(); if(_lexer.match(kw_true, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Bool_Literal(true, src)}; } else if(_lexer.match(kw_false, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Bool_Literal(false, src)}; } else { set_error("expected bool literal"); return nullptr; } } Owning_Ptr<String_Literal> try_string_literal() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_double_quote)) { set_error(u8"expected \""); return nullptr; } anton::String string; while(true) { char32 next_char = _lexer.peek_next(); if(next_char == U'\n') { // We disallow newlines inside string literals set_error(u8"newlines are not allowed in string literals"); _lexer.restore_state(state_backup); return nullptr; } else if(next_char == eof_char32) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return nullptr; } else if(next_char == U'\\') { string += _lexer.get_next(); string += _lexer.get_next(); } else if(next_char == U'\"') { _lexer.get_next(); break; } else { string += next_char; _lexer.get_next(); } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new String_Literal(ANTON_MOV(string), src)}; } Owning_Ptr<Identifier> try_identifier() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String identifier; if(!_lexer.match_identifier(identifier)) { set_error(u8"expected an identifier"); _lexer.restore_state(state_backup); return nullptr; } if(is_keyword(identifier)) { anton::String msg = u8"keyword '" + identifier + "' may not be used as identifier"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Identifier(ANTON_MOV(identifier), src)}; } Owning_Ptr<Identifier_Expression> try_identifier_expression() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String identifier; if(!_lexer.match_identifier(identifier)) { set_error(u8"expected an identifier"); _lexer.restore_state(state_backup); return nullptr; } if(is_keyword(identifier)) { anton::String msg = u8"keyword '" + identifier + "' may not be used as identifier"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Identifier_Expression(ANTON_MOV(identifier), src)}; } }; anton::Expected<Declaration_List, Parse_Error> parse_source(anton::String_View const source_name, anton::String_View const source_code) { Parser parser(source_code, source_name); anton::Expected<Declaration_List, Parse_Error> ast = parser.build_ast(); return ast; } anton::Expected<Declaration_List, Parse_Error> parse_builtin_functions(anton::String_View const source_name, anton::String_View const source_code) { Parser parser(source_code, source_name); anton::Expected<Declaration_List, Parse_Error> ast = parser.parse_builtin_functions(); return ast; } } // namespace vush
118,110
33,620
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int N = 30007; struct Node { int p, v, s; Node* ch[2]; Node(int v):v(v) {p = rand(); ch[0] = ch[1] = NULL; s = 1;} int cmp(int x) const { if (x == v) return -1; return x < v ? 0 : 1; } void Maintain() { s = 1; if (ch[0]) s += ch[0] -> s; if (ch[1]) s += ch[1] -> s; } }; Node* Root; int i, v, a[N]; void Rotate(Node* &o, int d) { Node* k = o -> ch[d ^ 1]; o -> ch[d ^ 1] = k -> ch[d]; k -> ch[d] = o; o -> Maintain(); k -> Maintain(); o = k; } void Insert(Node* &o) { if (o == NULL) {o = new Node(v); o -> Maintain(); return;} int d = o -> cmp(v); Insert(o -> ch[d]); if (o -> ch[d] -> p > o -> p) Rotate(o, d ^ 1); o -> Maintain(); } void Remove(Node* &o) { int d = o -> cmp(v); if (d == -1) { if (o -> ch[0] == NULL) o = o -> ch[1]; else if (o -> ch[1] == NULL) o = o -> ch[0]; else { int d2 = o -> ch[0] -> p > o -> ch[1] -> p ? 1 : 0; Rotate(o, d2); Remove(o -> ch[d2]); } } else Remove(o -> ch[d]); if (o) o -> Maintain(); } bool Find(Node* o) { int d; while (o) { d = o -> cmp(v); if (d == -1) return true; o = o -> ch[d]; } return false; } int Kth(Node* o, int k) { if (o == NULL || k <= 0 || k > o -> s) return 0; int s = o -> ch[0] == NULL ? 0 : o -> ch[0] -> s; if (s + 1 == k) return o -> v; else if (k <= s) return Kth(o -> ch[0], k); else return Kth(o -> ch[1], k - s - 1); } int main() { int n, m, q, s = 0; srand(time(NULL)); ios::sync_with_stdio(false); cin >> n >> q; for (int j = 1; j <= n; ++j) cin >> a[j]; i = 0; while (q--) { cin >> m; while (s < m) {v = a[++s]; Insert(Root);} cout << Kth(Root, ++i) << endl; } return 0; }
1,719
897
#include "account_model.h" #include <fstream> #include <tuple> std::string account_model::accounts_file_location_; sf::String account_model::current_user_internal_representation_; sf::String account_model::current_user_screen_name_; using namespace std; bool account_model::init() { current_user_internal_representation_ = ""; current_user_screen_name_ = ""; accounts_file_location_ = "Data\\accounts.txt"; return true; } void account_model::add_account(sf::String internal_and_account_and_password) { const string temp_sf_to_std = internal_and_account_and_password + "\n"; ofstream output_file(accounts_file_location_, std::ios_base::app | std::ios_base::out); output_file << temp_sf_to_std; } bool account_model::get_account(sf::String account_name, sf::String& account_password, sf::String& internal_representation) { ifstream ifs(accounts_file_location_); string line; string username = ""; string password = ""; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. if (username == account_name) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. account_password = line.substr(pos2 + 1); // password is after the second pipe. return true; } } } } return false; } sf::String account_model::get_screen_name_from_internal(sf::String internal) { ifstream ifs(accounts_file_location_); string line; string internal_representation = ""; string username = ""; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. if (internal_representation == internal) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. return username; } } } } return username; } // Returns " " if username not found. sf::String account_model::get_internal_from_screen_name(sf::String username) { ifstream ifs(accounts_file_location_); string line; string internal_representation = ""; string username_2 = ""; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { username_2 = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. if (username_2 == username) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. return internal_representation; } } } } return " "; } sf::String account_model::get_next_internal_value() { int highest_internal = 0; ifstream ifs(accounts_file_location_); string line; while (getline(ifs, line)) { string internal = ""; const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { internal = line.substr(0, pos); // internal representation is before the first pipe. if (highest_internal < stoi(internal)) { highest_internal = stoi(internal); } } } } return to_string(highest_internal + 1); } int account_model::get_nb_of_accounts() { auto nb_of_accounts = 0; ifstream ifs(accounts_file_location_); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { nb_of_accounts++; } } } return nb_of_accounts; } std::vector<sf::String> account_model::get_accounts() { std::vector<sf::String> accounts; ifstream ifs(accounts_file_location_); string line; while (getline(ifs, line)) { string username = ""; string internal = ""; const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. accounts.push_back(username); } } } return accounts; } void account_model::delete_account(sf::String internal) { sf::String internal_representation = ""; ifstream ifs(accounts_file_location_); ofstream temp("Data\\temp.txt"); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { if(internal_representation != internal) { temp << line << endl; } } } } ifs.close(); temp.close(); if(remove(accounts_file_location_.c_str()) == 0) { rename("Data\\temp.txt", accounts_file_location_.c_str()); } else { remove("Data\\temp.txt"); } } void account_model::modify_account_password(sf::String internal, sf::String new_password) { sf::String internal_representation = ""; sf::String username = ""; ifstream ifs(accounts_file_location_); ofstream temp("Data\\temp.txt"); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { if (internal_representation == internal) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. const std::string new_line = internal + "|" + username + "|" + new_password; temp << new_line << endl; } else { temp << line << endl; } } } } ifs.close(); temp.close(); if (remove(accounts_file_location_.c_str()) == 0) { rename("Data\\temp.txt", accounts_file_location_.c_str()); } else { remove("Data\\temp.txt"); } } void account_model::modify_account_username(sf::String internal, sf::String new_screen_name) { sf::String internal_representation = ""; sf::String password = ""; ifstream ifs(accounts_file_location_); ofstream temp("Data\\temp.txt"); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { if (internal_representation == internal) { password = line.substr(pos2 + 1); // password is after the second pipe. const std::string new_line = internal + "|" + new_screen_name + "|" + password; temp << new_line << endl; } else { temp << line << endl; } } } } ifs.close(); temp.close(); if (remove(accounts_file_location_.c_str()) == 0) { rename("Data\\temp.txt", accounts_file_location_.c_str()); } else { remove("Data\\temp.txt"); } } sf::String account_model::get_current_user_screen_name() { return current_user_screen_name_; } sf::String account_model::get_current_user_internal_representation() { return current_user_internal_representation_; } void account_model::set_current_user(sf::String current_user_screen_name, sf::String current_user_internal_representation) { current_user_screen_name_ = current_user_screen_name; current_user_internal_representation_ = current_user_internal_representation; } void account_model::log_out_current_user() { current_user_screen_name_ = ""; current_user_internal_representation_ = ""; }
8,730
3,208
#include <algorithm> #include <QDebug> #include "Sound_Queue.h" Sound_Queue::Sound_Queue() : buffer(0), audio(0){ } Sound_Queue::~Sound_Queue() { if (audio) { delete audio; } } const char* Sound_Queue::start(long sample_rate, int chan_count) { QAudioFormat as; as.setSampleType(QAudioFormat::SignedInt); as.setSampleSize(16); as.setCodec("audio/pcm"); as.setSampleRate((int)sample_rate); as.setChannelCount(chan_count); QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice()); if (audio == 0) { if (!info.isFormatSupported(as)) { qDebug() << "The requested format is not supported: " << as; qDebug() << "The nearest format is: " << info.nearestFormat(as); qDebug() << "And the prefferred format is: " << info.preferredFormat(); return "format not supported"; } else { audio = new QAudioOutput(as, this); buffer.start(); audio->start(&buffer); buffer.setSamplePeriod(audio->periodSize() / sizeof (sample_t)); } } qDebug() << "Preferred audio format: " << info.preferredFormat(); qDebug() << "The requested format is: " << as; qDebug() << "Audio Buffer Size:" << audio->bufferSize(); qDebug() << "Audio Period Size:" << audio->periodSize(); return NULL; } void Sound_Queue::restart() { if (audio) { audio->reset(); } } void Sound_Queue::stop() { if (audio) { audio->stop(); } } void Sound_Queue::write(const sample_t *in, long count) { buffer.write_samples(in, count); }
1,483
540
#include <QApplication> #include <QMessageBox> #include <QMainWindow> #include "Kernel_type.h" #include "Scene_surface_mesh_item.h" #include "Scene_polylines_item.h" #include <CGAL/Three/Polyhedron_demo_plugin_helper.h> #include <CGAL/Three/Polyhedron_demo_plugin_interface.h> #include <CGAL/Polygon_mesh_processing/stitch_borders.h> #include <CGAL/boost/graph/split_graph_into_polylines.h> #include <CGAL/boost/graph/helpers.h> #include <boost/graph/filtered_graph.hpp> using namespace CGAL::Three; class Polyhedron_demo_polyhedron_stitching_plugin : public QObject, public Polyhedron_demo_plugin_helper { Q_OBJECT Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface) Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0" FILE "polyhedron_stitching_plugin.json") QAction* actionDetectBorders; QAction* actionStitchBorders; QAction* actionStitchByCC; public: QList<QAction*> actions() const { return QList<QAction*>() << actionDetectBorders << actionStitchBorders << actionStitchByCC; } void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* /* m */) { scene = scene_interface; actionDetectBorders= new QAction(tr("Detect Boundaries"), mainWindow); actionDetectBorders->setObjectName("actionDetectBorders"); actionDetectBorders->setProperty("subMenuName", "Polygon Mesh Processing"); actionStitchBorders= new QAction(tr("Stitch Duplicated Boundaries"), mainWindow); actionStitchBorders->setObjectName("actionStitchBorders"); actionStitchBorders->setProperty("subMenuName", "Polygon Mesh Processing/Repair"); actionStitchByCC= new QAction(tr("Stitch Borders Per Connected Components"), mainWindow); actionStitchByCC->setObjectName("actionStitchByCC"); actionStitchByCC->setProperty("subMenuName", "Polygon Mesh Processing/Repair"); autoConnectActions(); } bool applicable(QAction*) const { Q_FOREACH(int index, scene->selectionIndices()) { if ( qobject_cast<Scene_surface_mesh_item*>(scene->item(index)) ) return true; } return false; } template <typename Item> void on_actionDetectBorders_triggered(Scene_interface::Item_id index); template <typename Item> void on_actionStitchBorders_triggered(Scene_interface::Item_id index); template <typename Item> void on_actionStitchByCC_triggered(Scene_interface::Item_id index); public Q_SLOTS: void on_actionDetectBorders_triggered(); void on_actionStitchBorders_triggered(); void on_actionStitchByCC_triggered(); }; // end Polyhedron_demo_polyhedron_stitching_plugin template <typename Item> void Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered(Scene_interface::Item_id index) { typedef typename Item::Face_graph FaceGraph; Item* item = qobject_cast<Item*>(scene->item(index)); if(item) { Scene_polylines_item* new_item = new Scene_polylines_item(); FaceGraph* pMesh = item->polyhedron(); normalize_border(*pMesh); for(auto ed : edges(*pMesh)) { if(pMesh->is_border(ed)) { new_item->polylines.push_back(Scene_polylines_item::Polyline()); new_item->polylines.back().push_back(pMesh->point(pMesh->source(pMesh->halfedge(ed)))); new_item->polylines.back().push_back(pMesh->point(pMesh->target(pMesh->halfedge(ed)))); } } if (new_item->polylines.empty()) { delete new_item; } else { new_item->setName(tr("Boundary of %1").arg(item->name())); new_item->setColor(Qt::red); scene->addItem(new_item); new_item->invalidateOpenGLBuffers(); } } } void Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered() { Q_FOREACH(int index, scene->selectionIndices()){ on_actionDetectBorders_triggered<Scene_surface_mesh_item>(index); } } template <typename Item> void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered(Scene_interface::Item_id index) { Item* item = qobject_cast<Item*>(scene->item(index)); if(item){ typename Item::Face_graph* pMesh = item->polyhedron(); CGAL::Polygon_mesh_processing::stitch_borders(*pMesh); item->invalidateOpenGLBuffers(); scene->itemChanged(item); } } void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered() { Q_FOREACH(int index, scene->selectionIndices()){ on_actionStitchBorders_triggered<Scene_surface_mesh_item>(index); } } template <typename Item> void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchByCC_triggered(Scene_interface::Item_id index) { Item* item = qobject_cast<Item*>(scene->item(index)); if(!item) return; CGAL::Polygon_mesh_processing::stitch_borders(*item->polyhedron(), CGAL::parameters::apply_per_connected_component(true)); item->invalidateOpenGLBuffers(); scene->itemChanged(item); } void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchByCC_triggered() { Q_FOREACH(int index, scene->selectionIndices()){ on_actionStitchByCC_triggered<Scene_surface_mesh_item>(index); } } #include "Polyhedron_stitching_plugin.moc"
5,283
1,837
// 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 "components/ntp_tiles/json_unsafe_parser.h" #include "base/bind.h" #include "base/callback.h" #include "base/json/json_parser.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" namespace ntp_tiles { void JsonUnsafeParser::Parse(const std::string& unsafe_json, const SuccessCallback& success_callback, const ErrorCallback& error_callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( [](const std::string& unsafe_json, const SuccessCallback& success_callback, const ErrorCallback& error_callback) { std::string error_msg; int error_line, error_column; std::unique_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( unsafe_json, base::JSON_ALLOW_TRAILING_COMMAS, nullptr, &error_msg, &error_line, &error_column); if (value) { success_callback.Run(std::move(value)); } else { error_callback.Run(base::StringPrintf( "%s (%d:%d)", error_msg.c_str(), error_line, error_column)); } }, unsafe_json, success_callback, error_callback)); } } // namespace ntp_tiles
1,545
453
/** * @file main.cpp * @author Andrew SASSOYE */ #include <iostream> #include <algorithm> #include <functional> #include "../resources/utilscpp.hpp" #include "../src/sign.hpp" #include "../resources/data_fraction.h" #include "fraction_constexpr.hpp" using namespace std; using namespace g54327; const size_t N_FRACTIONS = 50; void exe2(); void exe6(); void exe89(); static void printFraction(std::string, const std::vector<Fraction> &); static void printFraction(std::string, const std::vector<const Fraction *> &); static void printFraction(std::string, const std::vector<std::reference_wrapper<Fraction>> &); int main() { utils::exercise("Exercice 8.2", exe2); utils::exercise("Exercice 8.6 + 8.7", exe6); utils::exercise("Exercice 8.8 + 8.9", exe89); } void exe2() { cout << "cout << Sign::PLUS => " << Sign::PLUS << endl; cout << "cout << Sign::MINUS => " << Sign::MINUS << endl; cout << "cout << Sign::ZERO => " << Sign::ZERO << endl; } void exe6() { auto v = nvs::data_signed(N_FRACTIONS); std::vector<Fraction> fractions{N_FRACTIONS}; size_t errors{}; for (auto tuple : v) { try { fractions.emplace_back( Fraction{ std::get<0>(tuple), std::get<1>(tuple) }); } catch (std::invalid_argument &e) { ++errors; } } cout << "error_count: " << errors << endl << "fractions.size(): " << fractions.size() << endl << endl; printFraction("fractions content: ", fractions); std::vector<const Fraction *> fractions_ptr{fractions.size()}; std::generate(fractions_ptr.begin(), fractions_ptr.end(), [&fractions]() -> const Fraction * { static int i = 0; return &fractions[i++]; } ); printFraction("before sorting (pointer): ", fractions_ptr); std::sort( fractions_ptr.begin(), fractions_ptr.end(), [](const Fraction *f1, const Fraction *f2) { return *f1 < *f2; }); printFraction("after sorting (pointer): ", fractions_ptr); } void exe89() { auto v = nvs::data_unsigned(N_FRACTIONS); std::vector<Fraction> fractions{N_FRACTIONS}; size_t errors{}; for (auto tuple : v) { try { fractions.emplace_back( Fraction{ g54327::sign(std::get<0>(tuple)), std::get<1>(tuple), std::get<2>(tuple) }); } catch (std::invalid_argument &e) { ++errors; } } cout << "error_count: " << errors << endl << "fractions.size(): " << fractions.size() << endl << endl; printFraction("fractions content: ", fractions); std::vector<std::reference_wrapper<Fraction>> rw{fractions.begin(), fractions.end()}; printFraction("before sorting (reference wrapper): ", rw); std::sort(rw.begin(), rw.end(), std::less<>()); printFraction("after sorting (reference wrapper): ", rw); } void printFraction(std::string description, const vector<Fraction> &fractions) { int i = 1; cout << description.data() << endl; for (const auto &fraction : fractions) { cout << fraction << (i++ % 16 == 0 ? "\n" : " "); } cout << endl << endl; } void printFraction(std::string description, const vector<const Fraction *> &fractions) { int i = 1; cout << description.data() << endl; for (const auto fraction : fractions) { cout << *fraction << (i++ % 16 == 0 ? "\n" : " "); } cout << endl << endl; } void printFraction(std::string description, const vector<std::reference_wrapper<Fraction>> &fractions) { int i = 1; cout << description.data() << endl; for (const auto &fraction : fractions) { cout << fraction << (i++ % 16 == 0 ? "\n" : " "); } cout << endl << endl; }
3,703
1,312
#include "Component.h" C3_NAMESPACE_BEGIN CBaseComponent::CBaseComponent() { RefCount = 0; } void CBaseComponent::AddRef() { RefCount++; } void CBaseComponent::Release() { auto count = RefCount--; if (count == 0) delete this; } TypeId CBaseComponent::RealType() { return GetTypeId<IComponent>(); } bool CBaseComponent::IsType(TypeId id) { if (id == GetTypeId<IComponent>()) return true; return false; } bool CBaseComponent::QueryInterface(TypeId iid, void **outPtr) { bool success = false; if (iid == GetTypeId<IComponent>()) { success = true; *outPtr = static_cast<IComponent*>(this); } return success; } CMovable::CMovable() { } CMovable::~CMovable() { } C3_NAMESPACE_END
703
285
// Boost.Geometry Index // // Pairs intended to be used internally in nodes. // // Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland. // // 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) #ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP #include <boost/move/move.hpp> namespace boost { namespace geometry { namespace index { namespace detail { namespace rtree { template <typename First, typename Pointer> class ptr_pair { public: typedef First first_type; typedef Pointer second_type; ptr_pair(First const& f, Pointer s) : first(f), second(s) {} //ptr_pair(ptr_pair const& p) : first(p.first), second(p.second) {} //ptr_pair & operator=(ptr_pair const& p) { first = p.first; second = p.second; return *this; } first_type first; second_type second; }; template <typename First, typename Pointer> inline ptr_pair<First, Pointer> make_ptr_pair(First const& f, Pointer s) { return ptr_pair<First, Pointer>(f, s); } // TODO: It this will be used, rename it to unique_ptr_pair and possibly use unique_ptr. template <typename First, typename Pointer> class exclusive_ptr_pair { BOOST_MOVABLE_BUT_NOT_COPYABLE(exclusive_ptr_pair) public: typedef First first_type; typedef Pointer second_type; exclusive_ptr_pair(First const& f, Pointer s) : first(f), second(s) {} // INFO - members aren't really moved! exclusive_ptr_pair(BOOST_RV_REF(exclusive_ptr_pair) p) : first(p.first), second(p.second) { p.second = 0; } exclusive_ptr_pair & operator=(BOOST_RV_REF(exclusive_ptr_pair) p) { first = p.first; second = p.second; p.second = 0; return *this; } first_type first; second_type second; }; template <typename First, typename Pointer> inline exclusive_ptr_pair<First, Pointer> make_exclusive_ptr_pair(First const& f, Pointer s) { return exclusive_ptr_pair<First, Pointer>(f, s); } }} // namespace detail::rtree }}} // namespace boost::geometry::index #endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP
2,191
788
#include <stdint.h> #include "../Level.h" #include "../Game.h" #include "../Log.h" #include "../MathUtil.h" //#define SPIRAL_OFFSET_FIX //Fixes the radius offset to scale properly static const uint8_t FlipAngleTable[] = { 0x00,0x00, 0x01,0x01,0x16,0x16,0x16,0x16,0x2C,0x2C, 0x2C,0x2C,0x42,0x42,0x42,0x42,0x58,0x58, 0x58,0x58,0x6E,0x6E,0x6E,0x6E,0x84,0x84, 0x84,0x84,0x9A,0x9A,0x9A,0x9A,0xB0,0xB0, 0xB0,0xB0,0xC6,0xC6,0xC6,0xC6,0xDC,0xDC, 0xDC,0xDC,0xF2,0xF2,0xF2,0xF2,0x01,0x01, 0x00,0x00, }; static const int8_t CosineTable[] = { 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30, 30, 30, 29, 29, 29, 29, 29, 28, 28, 28, 28, 27, 27, 27, 27, 26, 26, 26, 25, 25, 25, 24, 24, 24, 23, 23, 22, 22, 21, 21, 20, 20, 19, 18, 18, 17, 16, 16, 15, 14, 14, 13, 12, 12, 11, 10, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 2, 2, 1, 0, -1, -2, -2, -3, -4, -4, -5, -6, -7, -7, -8, -9, -9,-10,-10, -11,-11,-12,-12,-13,-14,-14,-15, -15,-16,-16,-17,-17,-18,-18,-19, -19,-19,-20,-21,-21,-22,-22,-23, -23,-24,-24,-25,-25,-26,-26,-27, -27,-28,-28,-28,-29,-29,-30,-30, -30,-31,-31,-31,-32,-32,-32,-33, -33,-33,-33,-34,-34,-34,-35,-35, -35,-35,-35,-35,-35,-35,-36,-36, -36,-36,-36,-36,-36,-36,-36,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-36,-36,-36,-36, -36,-36,-36,-35,-35,-35,-35,-35, -35,-35,-35,-34,-34,-34,-33,-33, -33,-33,-32,-32,-32,-31,-31,-31, -30,-30,-30,-29,-29,-28,-28,-28, -27,-27,-26,-26,-25,-25,-24,-24, -23,-23,-22,-22,-21,-21,-20,-19, -19,-18,-18,-17,-16,-16,-15,-14, -14,-13,-12,-11,-11,-10, -9, -8, -7, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 10, 11, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, }; void ObjSpiral(OBJECT *object) //Also MTZ cylinder { //Set our routine based off of our subtype if (object->routine == 0) { object->routine = (object->subtype < 0x80) ? 1 : 2; object->widthPixels = 208; } switch (object->routine) { case 1: //EHZ Spiral { for (size_t i = 0; i < gLevel->playerList.size(); i++) { //Get the player PLAYER *player = gLevel->playerList[i]; if (object->playerContact[i].standing == false) //Not already on the spiral { if (player->status.inAir) //Don't run on corkscrew if in mid-air continue; //Check if we're at the sides of the spiral if (!player->status.shouldNotFall) //If not standing on an object (already on a spiral) { //Check if we're at the sides of the spiral int16_t xOff = player->x.pos - object->x.pos; if (player->xVel >= 0) //Moving in from the left { if (xOff < -0xD0 || xOff > -0xC0) continue; } else //Moving in from the right { if (xOff < 0xC0 || xOff > 0xD0) continue; } } else { //Check if we're at the sides of the spiral int16_t xOff = player->x.pos - object->x.pos; if (player->xVel >= 0) //Moving in from the left { if (xOff < -0xC0 || xOff > -0xB0) continue; } else //Moving in from the right { if (xOff < 0xB0 || xOff > 0xC0) continue; } } //Check if we're near the bottom and not already on an object controlling us int16_t yOff = player->y.pos - object->y.pos - 0x10; if (yOff < 0 || yOff >= 0x30 || player->objectControl.disableOurMovement) continue; //Set the player to run on the spiral player->AttachToObject(object, i); } else { //Running on the corkscrew if (!(abs(player->inertia) < 0x600 || player->status.inAir)) //If not slowed down or jumped off { int16_t xOff = player->x.pos - object->x.pos + 0xD0; if (xOff >= 0 && xOff < 0x1A0) //If still on the spiral { //Move across the spiral if (player->status.shouldNotFall) //If still running on the spiral { //Set our Y-position int8_t cosine = CosineTable[xOff]; #ifndef SPIRAL_OFFSET_FIX int16_t yOff = player->yRadius - 19; #else int16_t yOff = ((player->yRadius - 19) * cosine) / (cosine < 0 ? 37 : 32); #endif player->y.pos = (object->y.pos + cosine) - yOff; //Set our flip angle player->flipAngle = FlipAngleTable[(xOff / 8) & 0x3F]; } continue; } } //Fall off player->status.shouldNotFall = false; object->playerContact[i].standing = false; player->flipsRemaining = false; player->flipSpeed = 4; } } break; } case 2: //MTZ Cylinder { //None break; } } object->UnloadOffscreen(object->x.pos); }
5,273
3,494
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #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 LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; int n, p[3001], v[3001], m, cnt; void visit(int cur){ if(v[cur]) return; v[cur] = 1; visit(p[cur]); return; } int main(){ sd(n); for(int i = 1; i <= n; i++){ sd(p[i]); } sd(m); for(int i = 1; i <= n; i++){ if(!v[i]){ visit(i); cnt++; } } memset(v, 0, sizeof v); m = n - m; // tr(cnt); printf("%d\n", abs(m-cnt)); if(m < cnt){ visit(1); for(int i = 2; i <= n and cnt > m; i++){ if(!v[i]){ visit(i); printf("%d %d ", 1, i); cnt--; } } } else if(m > cnt){ for(int i = 1; i <= n and m > cnt; i++){ vector<int> pos(n+1, -1); int cur = 0; for(int j = p[i]; j != i; j = p[j]) pos[j] = cur++; pos[i] = cur; cur = 0; for(int j = i+1; j <= n and m > cnt; j++){ if(pos[j] >= cur){ printf("%d %d ", i, j); m--; cur = pos[j]+1; swap(p[i], p[j]); } } } } return 0; }
1,731
937
#include "MemoryCheck.h" #include <iostream> #ifdef WINDOWS #include <stdlib.h> #include <crtdbg.h> void prepareMemoryCheck() { _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); } void printMemoryUsage() { std::cout << "====================\n"; _CrtMemState state; _CrtMemCheckpoint(&state); _CrtMemDumpStatistics(&state); std::cout << "====================\n"; } void endMemoryDump() { auto leak_found = _CrtDumpMemoryLeaks(); if (!leak_found) std::puts("No memory leaks found in this application!"); } #else static std::size_t CURRENT_MEMORY_USAGE = 0; void* operator new(std::size_t size) { if (void* ptr = malloc(size)) { CURRENT_MEMORY_USAGE += size; return ptr; } throw std::bad_alloc{}; } void operator delete(void* ptr, std::size_t size) { CURRENT_MEMORY_USAGE -= size; std::free(ptr); } void prepareMemoryCheck() { CURRENT_MEMORY_USAGE = 0; } void printMemoryUsage() { std::cout << "Currently " << CURRENT_MEMORY_USAGE << " bytes allocated to the program\n"; } void endMemoryDump() { std::cout << "Memory usage at the end: " << CURRENT_MEMORY_USAGE << " bytes. "; if (CURRENT_MEMORY_USAGE > 0) std::cout << "WARNING: Not all memory was deallocated."; std::cout << std::endl; } #endif
1,495
620
/* * Copyright (c) 2016 - present 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 <vector> namespace iterator_access { struct X { int id; }; int possible_npe(std::vector<X> in) { int* x = nullptr; for (auto iter = in.begin(); iter != in.end(); ++iter) { if (iter->id >= 0 && iter->id <= 0) { return *x; } } return 1; } int impossible_npe(std::vector<X> in) { int* x = nullptr; for (auto iter = in.begin(); iter != in.end(); ++iter) { if (iter->id > 0 && iter->id <= 0) { return *x; } } return 1; } }
786
287
/* * source code: hp_rechner.cpp * author: Lukas Eder * date: 28.12.2017 * * Descr.: * Grundlegende Rechnungen von Addition, Subtraktion, Multiplikation und Division nach dem HP-Rechner-Model. */ #include "hpFunktionen.h" #include <iostream> using namespace std; // Hauptprogramm int main() { // Variablen double resultat = 0.0, input1 = 0.0, input2 = 0.0; char menu = ' ', rep = ' '; // Titel cout << "***** HP-RECHNER *****\n" << endl; do { menu = menue(menu); // Input durch user if (rep == 'c') { input1 = resultat; } else { cout << "\nVariable 1:" << endl; cin >> input1; } cout << "Variable 2:" << endl; cin >> input2; // Berechnungen switch (menu) { case '+': resultat = addition(input1, input2); break; case '-': resultat = subtraktion(input1, input2); break; case '*': resultat = multiplikation(input1, input2); break; case '/': resultat = division(input1, input2); break; default: cout << "ERROR!" << endl; break; } // Output cout << "\n" << input1 << " " << menu << " " << input2 << " = " << resultat << endl; //Programmrepetition cout << "\n" << "y\tNeue Rechnung\n" << "c\tmit altem Resultat fortfahren\n" << "q\tBeenden\n\n" <<"Ihre Wahl:" << endl; cin >> rep; } while (rep != 'q'); cout << "\nWiedersehen!" << endl; }
1,436
648
//============================================================================== /* Grid heating test case for electros in 2D This deck is made for quickly testing code changes by testing the grid heating rate. It initializes a 2D box of electrons with periodic boundary conditions and lets it evolve for for 0.5 picoseconds. The electrons are started very hot in an approximately linear heating regime. Ions are excluded for speed. This is not a test of the correctness of the physics in the code, i.e., it does not compare to an analytic physical result and asess if the code gives an answer close to that. Instead, it tests (more specifically, gridHeatingTestElec.py tests) if the code output has changed appreciably from a reference. This deck is very heavily modified from a short pulse deck origionally written by Brian J. Albright, 2005. Written by Scott V. Luedtke, XCP-6, August 15, 2019 */ //============================================================================== //#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #define CATCH_CONFIG_RUNNER // We will provide a custom main #include "catch.hpp" // TODO: this import may ultimately be a bad idea, but it lets you paste an input deck in... #include "deck/wrapper.h" begin_globals { int energies_interval; // how frequently to dump energies }; begin_diagnostics { //if ( step()%1==0 ) sim_log("Time step: "<<step()); # define should_dump(x) \ (global->x##_interval>0 && remainder(step(),global->x##_interval)==0) if ( step()==0 ) { if ( rank()==0 ) { dump_mkdir("heating_rundata"); } // if } // energy in various fields/particles if( should_dump(energies) ) { dump_energies( "heating_rundata/energies", step() ==0 ? 0 : 1 ); } //if } begin_initialization { // do not change parameters in this block: double elementary_charge = 4.8032e-10; // stat coulomb double elementary_charge2 = elementary_charge * elementary_charge; double speed_of_light = 2.99792458e10; // cm/sec double m_e = 9.1094e-28; // g double k_boltz = 1.6022e-12; // ergs/eV double mec2 = m_e*speed_of_light*speed_of_light/k_boltz; double eps0 = 1; double cfl_req = 0.98; // How close to Courant should we try to run double damp = 0.0; // Level of radiation damping double n_e_over_n_crit = 1e2; // n_e/n_crit in solid slab double vacuum_wavelength = 1e3 *1e-7; // used for normalization double delta = (vacuum_wavelength/(2.0*M_PI))/sqrt(n_e_over_n_crit); // c/wpe double nx = 10; double ny = 10; double nz = 1; double box_size_x = nx*0.5*delta;// microns double box_size_y = ny*0.5*delta;// microns double box_size_z = nz*0.5*delta;// microns int load_particles = 1; // Flag to turn off particle load for testing wave launch. William Daughton. //???????????????????????????????????????????????????????????????????? double nppc = 64 ; // Average number of macro particles/cell of each species double t_e = 20e4; // electron temp, eV double uthe = sqrt(t_e/mec2); // vthe/c double n_e = speed_of_light*speed_of_light*m_e/(4.0*M_PI*elementary_charge2*delta*delta); // n_e is used for emax only double debye = uthe*delta; //?????????????????????????????????????????????????????????????????????????? int topology_x = nproc(); int topology_y = 1; int topology_z = 1; double cell_size_t = box_size_y/(debye*ny); // in debye double cell_size_tz= box_size_z/(debye*nz); double cell_size_l = box_size_x/(debye*nx); double hy = debye*cell_size_t/delta; double hz = debye*cell_size_tz/delta; double hx = debye*cell_size_l/delta; double Lx = nx*hx; // in c/wpe double Ly = ny*hy; double Lz = nz*hz; double particles_alloc = nppc*ny*nz*nx; double dt = cfl_req*courant_length(Lx, Ly, Lz, nx, ny, nz); double dt_courant = dt; double t_stop = 500. * 1e-15*speed_of_light/delta;// runtime in 1/omega_pe // Diagnostics intervals. int energies_interval = 100; global->energies_interval = energies_interval; double omega_0 = sqrt(1.0/n_e_over_n_crit); // w0/wpe double delta_0 = delta*sqrt(n_e_over_n_crit); // c/w0 double Ne = nppc*nx*ny*nz; // Number of macro electrons in box Ne = trunc_granular(Ne, nproc()); // Make Ne divisible by number of processors double Npe = Lx*Ly*Lz; // Number of physical electrons in box, wpe = 1 double qe = -Npe/Ne; // Charge per macro electron // Print stuff that I need for plotters and such, and with enough sig figs! // Be very careful modifying this. Plotters depend on explicit locations of // some of these numbers. Generally speaking, add lines at the end only. if(rank() == 0){ FILE * out; out = fopen("heating_params.txt", "w"); fprintf(out, "# Parameter file used for plotters.\n"); fprintf(out, "%.14e Time step (dt), code units\n", dt); fprintf(out, "%.14e Laser wavelength, SI\n", vacuum_wavelength*1e-2); fprintf(out, "%.14e Ratio of electron to critical density\n", n_e_over_n_crit); fprintf(out, "%d Number of cells in x\n", int(nx)); fprintf(out, "%d Number of cells in y\n", int(ny)); fprintf(out, "%d Number of cells in z\n", int(nz)); fprintf(out, "%.14e Box size x, microns\n", box_size_x*1e4); fprintf(out, "%.14e Box size y, microns\n", box_size_y*1e4); fprintf(out, "%.14e Box size z, microns\n", box_size_z*1e4); fclose(out); } // PRINT SIMULATION PARAMETERS sim_log("***** Simulation parameters *****"); sim_log("* Processors: "<<nproc()); sim_log("* dt_courant"<<dt_courant); sim_log("* delta/dx,delta/dz = "<<1.0/hx<<" "<<1.0/hz); sim_log("* Time step, max time, nsteps = "<<dt<<" "<<t_stop<<" "<<int(t_stop/(dt))); sim_log("* Debye length,cell size_l,cell size_t,delta,delta_0 = "<<debye<<" "<<cell_size_l<<" "<<cell_size_t<<" "<<delta<<" "<<delta_0); sim_log("* Lx, Ly, Lz = "<<Lx<<" "<<Ly<<" "<<Lz); sim_log("* nx, ny, nz = "<<nx<<" "<<ny<<" "<<nz); sim_log("* Charge/macro electron = "<<qe); sim_log("* particles_alloc = "<<particles_alloc); sim_log("* Average particles/processor: "<<Ne/nproc()); sim_log("* Average particles/cell: "<<nppc); sim_log("* Omega_0, Omega_pe: "<<(omega_0)<<" "<<1); sim_log("* Plasma density, ne/nc: "<<n_e<<" "<<n_e_over_n_crit); sim_log("* T_e,m_e: "<<t_e<<" "<<1); sim_log("* Radiation damping: "<<damp); sim_log("* Fraction of courant limit: "<<cfl_req); sim_log("* vthe/c: "<<uthe); sim_log("* energies_interval: "<<energies_interval); sim_log("*********************************"); // SETUP HIGH-LEVEL SIMULATION PARMETERS // FIXME : proper normalization in these units for: xfocus, ycenter, zcenter, waist sim_log("Setting up high-level simulation parameters. "); num_step = int(t_stop/(dt)); status_interval = 20000; //???????????????????????????????????????????????????????????????????????????????? sync_shared_interval = status_interval/10; clean_div_e_interval = status_interval/10; clean_div_b_interval = status_interval/10; verbose = 0; // SETUP THE GRID sim_log("Setting up computational grid."); grid->dx = hx; grid->dy = hy; grid->dz = hz; grid->dt = dt; grid->cvac = 1; grid->eps0 = eps0; // Partition a periodic box among the processors sliced uniformly in z: define_periodic_grid( 0, -0.5*Ly, -0.5*Lz, // Low corner Lx, 0.5*Ly, 0.5*Lz, // High corner nx, ny, nz, // Resolution topology_x, topology_y, topology_z); // Topology sim_log("Setting up electrons. "); //??????????????????????????????????????????????????????????????????????? // How oversized should the particle buffers be in case of non-uniform plasma? // The left and right ranks are half filled, and the middle will get to 1.5x // filled. An over_alloc_fac between .5 and 1.5 should drop if not // dynamically resizing. double over_alloc_fac = 1.3; double max_local_np_e = over_alloc_fac*particles_alloc/nproc(); double max_local_nm_e = max_local_np_e / 1.; species_t * electron = define_species("electron", -1, 1, max_local_np_e, max_local_nm_e, 0, 1); // SETUP THE MATERIALS sim_log("Setting up materials. "); define_material( "vacuum", 1 ); define_field_array( NULL, damp ); // LOAD PARTICLES // Load particles using rejection method (p. 290 Num. Recipes in C 2ed, Press et al.) if ( load_particles!=0 ) { sim_log( "Loading particles" ); seed_entropy( 2995471 ); // Kevin said it should be this way // Fast load of particles double xmin = grid->x0; double xmax = (grid->x0+grid->nx*grid->dx); double ymin = grid->y0; double ymax = (grid->y0+grid->ny*grid->dy); double zmin = grid->z0; double zmax = (grid->z0+grid->nz*grid->dz); repeat( (Ne)/(topology_x*topology_y*topology_z) ) { double x = uniform( rng(0), xmin, xmax ); double y = uniform( rng(0), ymin, ymax ); double z = uniform( rng(0), zmin, zmax ); // Rejection method, based on user-defined density function // Simplified for the uniform plasma used in this test if ( uniform( rng(0), 0, 1 ) < 1. ) { inject_particle( electron, x, y, z, normal( rng(0), 0, uthe ), normal( rng(0), 0, uthe ), normal( rng(0), 0, uthe ), fabs(qe), 0, 0 ); } } } // if load_particles } TEST_CASE( "Check if Weibel gives correct energy (within tol)", "[energy]" ) { // Init and run sim vpic_simulation simulation = vpic_simulation(); // TODO: We should do this in a safer manner simulation.initialize( 0, NULL ); while( simulation.advance() ); simulation.finalize(); } begin_particle_injection { // No particle injection for this simulation } begin_current_injection { // No current injection for this simulation } begin_field_injection { // No field injection for this simulation } begin_particle_collisions{ // No collisions for this simulation } // Manually implement catch main int main( int argc, char* argv[] ) { // Setup boot_services( &argc, &argv ); int result = Catch::Session().run( argc, argv ); // clean-up... halt_services(); return result; }
11,486
4,152
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cloudwf/model/SetUpgradeImgByModelRequest.h> using AlibabaCloud::Cloudwf::Model::SetUpgradeImgByModelRequest; SetUpgradeImgByModelRequest::SetUpgradeImgByModelRequest() : RpcServiceRequest("cloudwf", "2017-03-28", "SetUpgradeImgByModel") { setMethod(HttpRequest::Method::Post); } SetUpgradeImgByModelRequest::~SetUpgradeImgByModelRequest() {} std::string SetUpgradeImgByModelRequest::getImgVersion()const { return imgVersion_; } void SetUpgradeImgByModelRequest::setImgVersion(const std::string& imgVersion) { imgVersion_ = imgVersion; setParameter("ImgVersion", imgVersion); } long SetUpgradeImgByModelRequest::getApModelId()const { return apModelId_; } void SetUpgradeImgByModelRequest::setApModelId(long apModelId) { apModelId_ = apModelId; setParameter("ApModelId", std::to_string(apModelId)); } std::string SetUpgradeImgByModelRequest::getAccessKeyId()const { return accessKeyId_; } void SetUpgradeImgByModelRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string SetUpgradeImgByModelRequest::getImgAddr()const { return imgAddr_; } void SetUpgradeImgByModelRequest::setImgAddr(const std::string& imgAddr) { imgAddr_ = imgAddr; setParameter("ImgAddr", imgAddr); } std::string SetUpgradeImgByModelRequest::getComment()const { return comment_; } void SetUpgradeImgByModelRequest::setComment(const std::string& comment) { comment_ = comment; setParameter("Comment", comment); }
2,204
734
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (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. // ------------------------------------------------------------------------ #ifdef ARMA_USE_LAPACK //! \namespace lapack namespace for LAPACK functions namespace lapack { template<typename eT> inline void getrf(blas_int* m, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetrf)(m, n, (T*)a, lda, ipiv, info); } } template<typename eT> inline void getri(blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } } template<typename eT> inline void trtri(char* uplo, char* diag, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrtri)(uplo, diag, n, (T*)a, lda, info); } } template<typename eT> inline void geev(char* jobvl, char* jobvr, blas_int* N, eT* a, blas_int* lda, eT* wr, eT* wi, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgeev)(jobvl, jobvr, N, (T*)a, lda, (T*)wr, (T*)wi, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgeev)(jobvl, jobvr, N, (T*)a, lda, (T*)wr, (T*)wi, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } } template<typename eT> inline void cx_geev(char* jobvl, char* jobvr, blas_int* N, eT* a, blas_int* lda, eT* w, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgeev)(jobvl, jobvr, N, (cx_T*)a, lda, (cx_T*)w, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgeev)(jobvl, jobvr, N, (cx_T*)a, lda, (cx_T*)w, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void syev(char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, eT* w, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssyev)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsyev)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, info); } } template<typename eT> inline void syevd(char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, eT* w, eT* work, blas_int* lwork, blas_int* iwork, blas_int* liwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssyevd)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, iwork, liwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsyevd)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, iwork, liwork, info); } } template<typename eT> inline void heev ( char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, typename eT::value_type* w, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cheev)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zheev)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void heevd ( char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, typename eT::value_type* w, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* lrwork, blas_int* iwork, blas_int* liwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cheevd)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, lrwork, iwork, liwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zheevd)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, lrwork, iwork, liwork, info); } } template<typename eT> inline void ggev ( char* jobvl, char* jobvr, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* alphar, eT* alphai, eT* beta, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sggev)(jobvl, jobvr, n, (T*)a, lda, (T*)b, ldb, (T*)alphar, (T*)alphai, (T*)beta, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dggev)(jobvl, jobvr, n, (T*)a, lda, (T*)b, ldb, (T*)alphar, (T*)alphai, (T*)beta, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } } template<typename eT> inline void cx_ggev ( char* jobvl, char* jobvr, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* alpha, eT* beta, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cggev)(jobvl, jobvr, n, (cx_T*)a, lda, (cx_T*)b, ldb, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zggev)(jobvl, jobvr, n, (cx_T*)a, lda, (cx_T*)b, ldb, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void potrf(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_spotrf)(uplo, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dpotrf)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cpotrf)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zpotrf)(uplo, n, (T*)a, lda, info); } } template<typename eT> inline void potri(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_spotri)(uplo, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dpotri)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cpotri)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zpotri)(uplo, n, (T*)a, lda, info); } } template<typename eT> inline void geqrf(blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void orgqr(blas_int* m, blas_int* n, blas_int* k, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sorgqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dorgqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void ungqr(blas_int* m, blas_int* n, blas_int* k, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; arma_fortran(arma_cungqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; arma_fortran(arma_zungqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void gesvd ( char* jobu, char* jobvt, blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* s, eT* u, blas_int* ldu, eT* vt, blas_int* ldvt, eT* work, blas_int* lwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesvd)(jobu, jobvt, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesvd)(jobu, jobvt, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, info); } } template<typename T> inline void cx_gesvd ( char* jobu, char* jobvt, blas_int* m, blas_int* n, std::complex<T>* a, blas_int* lda, T* s, std::complex<T>* u, blas_int* ldu, std::complex<T>* vt, blas_int* ldvt, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; arma_fortran(arma_cgesvd) ( jobu, jobvt, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, info ); } else if(is_double<T>::value) { typedef double bT; arma_fortran(arma_zgesvd) ( jobu, jobvt, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, info ); } } template<typename eT> inline void gesdd ( char* jobz, blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* s, eT* u, blas_int* ldu, eT* vt, blas_int* ldvt, eT* work, blas_int* lwork, blas_int* iwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesdd)(jobz, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesdd)(jobz, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, iwork, info); } } template<typename T> inline void cx_gesdd ( char* jobz, blas_int* m, blas_int* n, std::complex<T>* a, blas_int* lda, T* s, std::complex<T>* u, blas_int* ldu, std::complex<T>* vt, blas_int* ldvt, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* iwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; arma_fortran(arma_cgesdd) ( jobz, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, iwork, info ); } else if(is_double<T>::value) { typedef double bT; arma_fortran(arma_zgesdd) ( jobz, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, iwork, info ); } } template<typename eT> inline void gesv(blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void gesvx(char* fact, char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* af, blas_int* ldaf, blas_int* ipiv, char* equed, eT* r, eT* c, eT* b, blas_int* ldb, eT* x, blas_int* ldx, eT* rcond, eT* ferr, eT* berr, eT* work, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesvx)(fact, trans, n, nrhs, (T*)a, lda, (T*)af, ldaf, ipiv, equed, (T*)r, (T*)c, (T*)b, ldb, (T*)x, ldx, (T*)rcond, (T*)ferr, (T*)berr, (T*)work, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesvx)(fact, trans, n, nrhs, (T*)a, lda, (T*)af, ldaf, ipiv, equed, (T*)r, (T*)c, (T*)b, ldb, (T*)x, ldx, (T*)rcond, (T*)ferr, (T*)berr, (T*)work, iwork, info); } } template<typename T, typename eT> inline void cx_gesvx(char* fact, char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* af, blas_int* ldaf, blas_int* ipiv, char* equed, T* r, T* c, eT* b, blas_int* ldb, eT* x, blas_int* ldx, T* rcond, T* ferr, T* berr, eT* work, T* rwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> cx_T; arma_fortran(arma_cgesvx)(fact, trans, n, nrhs, (cx_T*)a, lda, (cx_T*)af, ldaf, ipiv, equed, (pod_T*)r, (pod_T*)c, (cx_T*)b, ldb, (cx_T*)x, ldx, (pod_T*)rcond, (pod_T*)ferr, (pod_T*)berr, (cx_T*)work, (pod_T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> cx_T; arma_fortran(arma_zgesvx)(fact, trans, n, nrhs, (cx_T*)a, lda, (cx_T*)af, ldaf, ipiv, equed, (pod_T*)r, (pod_T*)c, (cx_T*)b, ldb, (cx_T*)x, ldx, (pod_T*)rcond, (pod_T*)ferr, (pod_T*)berr, (cx_T*)work, (pod_T*)rwork, info); } } template<typename eT> inline void gels(char* trans, blas_int* m, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } } template<typename eT> inline void gelsd(blas_int* m, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* S, eT* rcond, blas_int* rank, eT* work, blas_int* lwork, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgelsd)(m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)S, (T*)rcond, rank, (T*)work, lwork, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgelsd)(m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)S, (T*)rcond, rank, (T*)work, lwork, iwork, info); } } template<typename T> inline void cx_gelsd(blas_int* m, blas_int* n, blas_int* nrhs, std::complex<T>* a, blas_int* lda, std::complex<T>* b, blas_int* ldb, T* S, T* rcond, blas_int* rank, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* iwork, blas_int* info) { typedef typename std::complex<T> eT; arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> cx_T; arma_fortran(arma_cgelsd)(m, n, nrhs, (cx_T*)a, lda, (cx_T*)b, ldb, (pod_T*)S, (pod_T*)rcond, rank, (cx_T*)work, lwork, (pod_T*)rwork, iwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> cx_T; arma_fortran(arma_zgelsd)(m, n, nrhs, (cx_T*)a, lda, (cx_T*)b, ldb, (pod_T*)S, (pod_T*)rcond, rank, (cx_T*)work, lwork, (pod_T*)rwork, iwork, info); } } template<typename eT> inline void trtrs(char* uplo, char* trans, char* diag, blas_int* n, blas_int* nrhs, const eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } } template<typename eT> inline void gees(char* jobvs, char* sort, void* select, blas_int* n, eT* a, blas_int* lda, blas_int* sdim, eT* wr, eT* wi, eT* vs, blas_int* ldvs, eT* work, blas_int* lwork, blas_int* bwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgees)(jobvs, sort, select, n, (T*)a, lda, sdim, (T*)wr, (T*)wi, (T*)vs, ldvs, (T*)work, lwork, bwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgees)(jobvs, sort, select, n, (T*)a, lda, sdim, (T*)wr, (T*)wi, (T*)vs, ldvs, (T*)work, lwork, bwork, info); } } template<typename T> inline void cx_gees(char* jobvs, char* sort, void* select, blas_int* n, std::complex<T>* a, blas_int* lda, blas_int* sdim, std::complex<T>* w, std::complex<T>* vs, blas_int* ldvs, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* bwork, blas_int* info) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; typedef std::complex<bT> cT; arma_fortran(arma_cgees)(jobvs, sort, select, n, (cT*)a, lda, sdim, (cT*)w, (cT*)vs, ldvs, (cT*)work, lwork, (bT*)rwork, bwork, info); } else if(is_double<T>::value) { typedef double bT; typedef std::complex<bT> cT; arma_fortran(arma_zgees)(jobvs, sort, select, n, (cT*)a, lda, sdim, (cT*)w, (cT*)vs, ldvs, (cT*)work, lwork, (bT*)rwork, bwork, info); } } template<typename eT> inline void trsyl(char* transa, char* transb, blas_int* isgn, blas_int* m, blas_int* n, const eT* a, blas_int* lda, const eT* b, blas_int* ldb, eT* c, blas_int* ldc, eT* scale, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (T*)scale, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (T*)scale, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (float*)scale, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (double*)scale, info); } } template<typename eT> inline void sytrf(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } } template<typename eT> inline void sytri(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } } template<typename eT> inline void gges ( char* jobvsl, char* jobvsr, char* sort, void* selctg, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* sdim, eT* alphar, eT* alphai, eT* beta, eT* vsl, blas_int* ldvsl, eT* vsr, blas_int* ldvsr, eT* work, blas_int* lwork, eT* bwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgges)(jobvsl, jobvsr, sort, selctg, n, (T*)a, lda, (T*)b, ldb, sdim, (T*)alphar, (T*)alphai, (T*)beta, (T*)vsl, ldvsl, (T*)vsr, ldvsr, (T*)work, lwork, (T*)bwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgges)(jobvsl, jobvsr, sort, selctg, n, (T*)a, lda, (T*)b, ldb, sdim, (T*)alphar, (T*)alphai, (T*)beta, (T*)vsl, ldvsl, (T*)vsr, ldvsr, (T*)work, lwork, (T*)bwork, info); } } template<typename eT> inline void cx_gges ( char* jobvsl, char* jobvsr, char* sort, void* selctg, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* sdim, eT* alpha, eT* beta, eT* vsl, blas_int* ldvsl, eT* vsr, blas_int* ldvsr, eT* work, blas_int* lwork, typename eT::value_type* rwork, typename eT::value_type* bwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgges)(jobvsl, jobvsr, sort, selctg, n, (cx_T*)a, lda, (cx_T*)b, ldb, sdim, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vsl, ldvsl, (cx_T*)vsr, ldvsr, (cx_T*)work, lwork, (T*)rwork, (T*)bwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgges)(jobvsl, jobvsr, sort, selctg, n, (cx_T*)a, lda, (cx_T*)b, ldb, sdim, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vsl, ldvsl, (cx_T*)vsr, ldvsr, (cx_T*)work, lwork, (T*)rwork, (T*)bwork, info); } } template<typename eT> inline typename get_pod_type<eT>::result lange(char* norm, blas_int* m, blas_int* n, eT* a, blas_int* lda, typename get_pod_type<eT>::result* work) { arma_type_check(( is_supported_blas_type<eT>::value == false )); typedef typename get_pod_type<eT>::result out_T; if(is_float<eT>::value) { typedef float pod_T; typedef float T; return out_T( arma_fortran(arma_slange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_double<eT>::value) { typedef double pod_T; typedef double T; return out_T( arma_fortran(arma_dlange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> T; return out_T( arma_fortran(arma_clange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> T; return out_T( arma_fortran(arma_zlange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } } template<typename eT> inline void gecon(char* norm, blas_int* n, eT* a, blas_int* lda, eT* anorm, eT* rcond, eT* work, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgecon)(norm, n, (T*)a, lda, (T*)anorm, (T*)rcond, (T*)work, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgecon)(norm, n, (T*)a, lda, (T*)anorm, (T*)rcond, (T*)work, iwork, info); } } template<typename T> inline void cx_gecon(char* norm, blas_int* n, std::complex<T>* a, blas_int* lda, T* anorm, T* rcond, std::complex<T>* work, T* rwork, blas_int* info) { typedef typename std::complex<T> eT; arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgecon)(norm, n, (cx_T*)a, lda, (pod_T*)anorm, (pod_T*)rcond, (cx_T*)work, (pod_T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgecon)(norm, n, (cx_T*)a, lda, (pod_T*)anorm, (pod_T*)rcond, (cx_T*)work, (pod_T*)rwork, info); } } inline blas_int laenv(blas_int* ispec, char* name, char* opts, blas_int* n1, blas_int* n2, blas_int* n3, blas_int* n4) { return arma_fortran(arma_ilaenv)(ispec, name, opts, n1, n2, n3, n4); } template<typename eT> inline void sytrs(char* uplo, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void getrs(char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void lahqr(blas_int* wantt, blas_int* wantz, blas_int* n, blas_int* ilo, blas_int* ihi, eT* h, blas_int* ldh, eT* wr, eT* wi, blas_int* iloz, blas_int* ihiz, eT* z, blas_int* ldz, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_slahqr)(wantt, wantz, n, ilo, ihi, (T*)h, ldh, (T*)wr, (T*)wi, iloz, ihiz, (T*)z, ldz, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dlahqr)(wantt, wantz, n, ilo, ihi, (T*)h, ldh, (T*)wr, (T*)wi, iloz, ihiz, (T*)z, ldz, info); } } template<typename eT> inline void stedc(char* compz, blas_int* n, eT* d, eT* e, eT* z, blas_int* ldz, eT* work, blas_int* lwork, blas_int* iwork, blas_int* liwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sstedc)(compz, n, (T*)d, (T*)e, (T*)z, ldz, (T*)work, lwork, iwork, liwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dstedc)(compz, n, (T*)d, (T*)e, (T*)z, ldz, (T*)work, lwork, iwork, liwork, info); } } template<typename eT> inline void trevc(char* side, char* howmny, blas_int* select, blas_int* n, eT* t, blas_int* ldt, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, blas_int* mm, blas_int* m, eT* work, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strevc)(side, howmny, select, n, (T*)t, ldt, (T*)vl, ldvl, (T*)vr, ldvr, mm, m, (T*)work, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrevc)(side, howmny, select, n, (T*)t, ldt, (T*)vl, ldvl, (T*)vr, ldvr, mm, m, (T*)work, info); } } template<typename eT> inline void larnv(blas_int* idist, blas_int* iseed, blas_int* n, eT* x) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_slarnv)(idist, iseed, n, (T*)x); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dlarnv)(idist, iseed, n, (T*)x); } } } #endif
38,320
16,797
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * 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. * * * * ========================================================================= */ //============================================================================= // // CLASS RuleInterfaceT // //============================================================================= #ifndef OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH #define OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH //== INCLUDES ================================================================= #include <string> #include <OpenMesh/Tools/Subdivider/Adaptive/Composite/CompositeTraits.hh> //== NAMESPACE ================================================================ namespace OpenMesh { // BEGIN_NS_OPENMESH namespace Subdivider { // BEGIN_NS_SUBDIVIDER namespace Adaptive { // BEGIN_NS_ADAPTIVE //== FORWARDS ================================================================= template <typename M> class CompositeT; template <typename M> class RuleInterfaceT; //== CLASS DEFINITION ========================================================= // ---------------------------------------------------------------------------- /** Handle template for adaptive composite subdividion rules * \internal * * Use typed handle of a rule, e.g. Tvv3<MyMesh>::Handle. */ template < typename R > struct RuleHandleT : public BaseHandle { explicit RuleHandleT(int _idx=-1) : BaseHandle(_idx) {} typedef R Rule; operator bool() const { return is_valid(); } }; /** Defines the method type() (RuleInterfaceT::type()) and the * typedefs Self and Handle. */ #define COMPOSITE_RULE( classname, mesh_type ) \ protected:\ friend class CompositeT<mesh_type>; \ public: \ const char *type() const override { return #classname; } \ typedef classname<mesh_type> Self; \ typedef RuleHandleT< Self > Handle // ---------------------------------------------------------------------------- /** Base class for adaptive composite subdivision rules * \see class CompositeT */ template <typename M> class RuleInterfaceT { public: typedef M Mesh; typedef RuleInterfaceT<M> Self; typedef RuleHandleT< Self > Rule; typedef typename M::Scalar scalar_t; protected: /// Default constructor RuleInterfaceT(Mesh& _mesh) : mesh_(_mesh),prev_rule_(nullptr),subdiv_rule_(nullptr),subdiv_type_(0),number_(0),n_rules_(0) {}; public: /// Destructor virtual ~RuleInterfaceT() {}; /// Returns the name of the rule. /// Use define COMPOSITE_RULE to overload this function in a derived class. virtual const char *type() const = 0; public: /// \name Raise item //@{ /// Raise item to target state \c _target_state. virtual void raise(typename M::FaceHandle& _fh, state_t _target_state) { if (mesh_.data(_fh).state() < _target_state) { update(_fh, _target_state); mesh_.data(_fh).inc_state(); } } virtual void raise(typename M::EdgeHandle& _eh, state_t _target_state) { if (mesh_.data(_eh).state() < _target_state) { update(_eh, _target_state); mesh_.data(_eh).inc_state(); } } virtual void raise(typename M::VertexHandle& _vh, state_t _target_state) { if (mesh_.data(_vh).state() < _target_state) { update(_vh, _target_state); mesh_.data(_vh).inc_state(); } } //@} void update(typename M::FaceHandle& _fh, state_t _target_state) { typename M::FaceHandle opp_fh; while (mesh_.data(_fh).state() < _target_state - 1) { prev_rule()->raise(_fh, _target_state - 1); } // Don't use unflipped / unfinal faces!!! if (subdiv_type() == 3) { if (mesh_.face_handle(mesh_.opposite_halfedge_handle(mesh_.halfedge_handle(_fh))).is_valid()) { while (!mesh_.data(_fh).final()) { opp_fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(mesh_.halfedge_handle(_fh))); assert (mesh_.data(_fh).state() >= mesh_.data(opp_fh).state()); // different states: raise other face if (mesh_.data(_fh).state() > mesh_.data(opp_fh).state()){ // raise opposite face prev_rule()->raise(opp_fh, _target_state - 1); } else { // equal states // flip edge // typename M::EdgeHandle eh(mesh_.edge_handle(mesh_.halfedge_handle(_fh))); // if (mesh_.is_flip_ok(eh)) { // std::cout << "Flipping Edge...\n"; // mesh_.flip(eh); // mesh_.data(_fh).set_final(); // mesh_.data(opp_fh).set_final(); // } // else { // std::cout << "Flip not okay.\n"; // } } } } else { // mesh_.data(_fh).set_final(); } // std::cout << "Raising Face to Level " // << _target_state // << " with " // << type() // << ".\n"; } assert( subdiv_type() != 4 || mesh_.data(_fh).final() || _target_state%n_rules() == (subdiv_rule()->number() + 1)%n_rules() ); typename M::FaceEdgeIter fe_it; typename M::FaceVertexIter fv_it; typename M::EdgeHandle eh; typename M::VertexHandle vh; std::vector<typename M::FaceHandle> face_vector; face_vector.clear(); if (_target_state > 1) { for (fe_it = mesh_.fe_iter(_fh); fe_it.is_valid(); ++fe_it) { eh = *fe_it; prev_rule()->raise(eh, _target_state - 1); } for (fv_it = mesh_.fv_iter(_fh); fv_it.is_valid(); ++fv_it) { vh = *fv_it; prev_rule()->raise(vh, _target_state - 1); } } } void update(typename M::EdgeHandle& _eh, state_t _target_state) { state_t state(mesh_.data(_eh).state()); // raise edge to correct state if (state + 1 < _target_state && _target_state > 0) { prev_rule()->raise(_eh, _target_state - 1); } typename M::VertexHandle vh; typename M::FaceHandle fh; if (_target_state > 1) { vh = mesh_.to_vertex_handle(mesh_.halfedge_handle(_eh, 0)); prev_rule()->raise(vh, _target_state - 1); vh = mesh_.to_vertex_handle(mesh_.halfedge_handle(_eh, 1)); prev_rule()->raise(vh, _target_state - 1); fh = mesh_.face_handle(mesh_.halfedge_handle(_eh, 0)); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); fh = mesh_.face_handle(mesh_.halfedge_handle(_eh, 1)); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); } } void update(typename M::VertexHandle& _vh, state_t _target_state) { state_t state(mesh_.data(_vh).state()); // raise vertex to correct state if (state + 1 < _target_state) { prev_rule()->raise(_vh, _target_state - 1); } std::vector<typename M::HalfedgeHandle> halfedge_vector; halfedge_vector.clear(); typename M::VertexOHalfedgeIter voh_it; typename M::EdgeHandle eh; typename M::FaceHandle fh; if (_target_state > 1) { for (voh_it = mesh_.voh_iter(_vh); voh_it.is_valid(); ++voh_it) { halfedge_vector.push_back(*voh_it); } while ( !halfedge_vector.empty() ) { eh = mesh_.edge_handle(halfedge_vector.back()); halfedge_vector.pop_back(); prev_rule()->raise(eh, _target_state - 1); } for (voh_it = mesh_.voh_iter(_vh); voh_it.is_valid(); ++voh_it) { halfedge_vector.push_back(*voh_it); } while ( !halfedge_vector.empty() ) { fh = mesh_.face_handle(halfedge_vector.back()); halfedge_vector.pop_back(); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); } } } public: /// Type of split operation, if it is a topological operator int subdiv_type() const { return subdiv_type_; } /// Position in rule sequence int number() const { return number_; } /// \name Parameterization of rule //@{ /// Set coefficient - ignored by non-parameterized rules. virtual void set_coeff( scalar_t _coeff ) { coeff_ = _coeff; } /// Get coefficient - ignored by non-parameterized rules. scalar_t coeff() const { return coeff_; } //@} protected: void set_prev_rule(Self*& _p) { prev_rule_ = _p; } Self* prev_rule() { return prev_rule_; } void set_subdiv_rule(Self*& _n) { subdiv_rule_ = _n; } Self* subdiv_rule() const { return subdiv_rule_; } void set_number(int _n) { number_ = _n; } void set_n_rules(int _n) { n_rules_ = _n; } int n_rules() const { return n_rules_; } void set_subdiv_type(int _n) { assert(_n == 3 || _n == 4); subdiv_type_ = _n; } friend class CompositeT<M>; protected: Mesh& mesh_; private: Self* prev_rule_; Self* subdiv_rule_; int subdiv_type_; int number_; int n_rules_; scalar_t coeff_; private: // Noncopyable RuleInterfaceT(const RuleInterfaceT&); RuleInterfaceT& operator=(const RuleInterfaceT&); }; //============================================================================= } // END_NS_ADAPTIVE } // END_NS_SUBDIVIDER } // END_NS_OPENMESH //============================================================================= #endif // OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH defined //=============================================================================
12,250
3,993
#pragma once namespace Zion { class Log { public: static void Open(const char *filename); static void Close(); static void Write(const char *format, ...); }; };
217
57
/* * Copyright (c) 2007, Laminar Research. * * 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. * */ /** OBJ7 exporter for AC3D **/ /* ANDY SEZ ABOUT MATERIALS: There's: Prototype int ac_palette_get_new_material_index(ACMaterialTemplate *m) if this material exists then return it's index otherwise, allocate a new one, copy the contents from m and return it's index This calls: Prototype Boolean material_compare(ACMaterial *m, ACMaterialTemplate *m2) That checks each part of the material. So- you'll get a whole new material if there's the slightest difference. If you only need RGB, use: Prototype long rgb_to_index(long rgbcol) This only checks the rgb of existing materials - not all the other attributes. */ #include "TclStubs.h" #include "ac_plugin.h" #include "Undoable.h" #ifdef Boolean #undef Boolean #endif #include "obj8_import.h" #include "ac_utils.h" #include "XObjDefs.h" #include "XObjReadWrite.h" #include "ObjConvert.h" #include "obj_model.h" #include "obj_anim.h" #include "obj_panel.h" #include <list> using std::list; // Set this to 1 and each change in culling or flat/smooth shading pops another object. #define OBJ_FOR_ALL_ATTRS 0 /*************************************************************************************************** * OBJ8 IMPORT AND EXPORT ***************************************************************************************************/ ACObject * do_obj8_load(char *filename) { ACObject * group_obj = NULL; ACObject * lod_obj = NULL; ACObject * stuff_obj = NULL; list<ACObject *> anim_obj; char * tex_full_name = NULL; int tex_id = -1; char * panel_full_name = NULL; int panel_id = -1; // char anim_cmd[1024]; string anim_dat; // char * anim_old_cmd; // Point3 key1, key2; int i; material_template_t current_material; current_material.rgb.r = 1.0; current_material.rgb.g = 1.0; current_material.rgb.b = 1.0; current_material.ambient.r = 0.2; current_material.ambient.g = 0.2; current_material.ambient.b = 0.2; current_material.specular.r = 0.0; current_material.specular.g = 0.0; current_material.specular.b = 0.0; current_material.emissive.r = 0.0; current_material.emissive.g = 0.0; current_material.emissive.b = 0.0; current_material.shininess = 128; current_material.transparency = 0.0; int default_material = ac_palette_get_new_material_index(&current_material); Point3 p3; char strbuf[256]; // obj8.lods.clear(); XObj8 obj8; if (!XObj8Read(filename, obj8)) { XObj obj7; if (!XObjRead(filename, obj7)) return NULL; Obj7ToObj8(obj7, obj8); } set_std_panel(); for (int n = 0; n < obj8.regions.size(); ++n) { add_sub_panel(obj8.regions[n].left,obj8.regions[n].bottom,obj8.regions[n].right,obj8.regions[n].top); } group_obj = new_object(OBJECT_GROUP); string fname(filename); string::size_type p = fname.find_last_of("\\/"); string justName = (p == fname.npos) ? fname : fname.substr(p+1); string justPath = fname.substr(0,p+1); string::size_type p2 = obj8.texture.find_last_of("\\/:"); string texName = (p2 == obj8.texture.npos) ? obj8.texture : obj8.texture.substr(p2+1); if (texName.size() > 4) texName.erase(texName.size()-4); string texPath; if(p2 != obj8.texture.npos) texPath = obj8.texture.substr(0,p2+1); string texNameBmp = texName + ".bmp"; string texNamePng = texName + ".png"; string texNameDds = texName + ".dds"; string texNamePvr = texName + ".pvr"; string texPathBmp = texPath + texNameBmp; string texPathPng = texPath + texNamePng; string texPathDds = texPath + texNameDds; string texPathPvr = texPath + texNamePvr; const char * panel_names[] = { "cockpit_3d/-PANELS-/Panel_Preview.png", "cockpit_3d/-PANELS-/Panel.png", "cockpit_3d/-PANELS-/Panel_Airliner.png", "cockpit_3d/-PANELS-/Panel_Fighter.png", "cockpit_3d/-PANELS-/Panel_Glider.png", "cockpit_3d/-PANELS-/Panel_Helo.png", "cockpit_3d/-PANELS-/Panel_Autogyro.png", "cockpit_3d/-PANELS-/Panel_General_IFR.png", "cockpit_3d/-PANELS-/Panel_Autogyro_Twin.png", "cockpit_3d/-PANELS-/Panel_Fighter_IFR.png", "cockpit/-PANELS-/Panel_Preview.png", "cockpit/-PANELS-/Panel.png", "cockpit/-PANELS-/Panel_Airliner.png", "cockpit/-PANELS-/Panel_Fighter.png", "cockpit/-PANELS-/Panel_Glider.png", "cockpit/-PANELS-/Panel_Helo.png", "cockpit/-PANELS-/Panel_Autogyro.png", "cockpit/-PANELS-/Panel_General_IFR.png", "cockpit/-PANELS-/Panel_Autogyro_Twin.png", "cockpit/-PANELS-/Panel_Fighter_IFR.png", 0 }; bool has_cockpit_cmd = false; bool has_cockpit_reg = false; for(vector<XObjLOD8>::iterator lod = obj8.lods.begin(); lod != obj8.lods.end(); ++lod) for(vector<XObjCmd8>::iterator cmd = lod->cmds.begin(); cmd != lod->cmds.end(); ++cmd) { if (cmd->cmd == attr_Tex_Cockpit) has_cockpit_cmd = true; if (cmd->cmd == attr_Tex_Cockpit_Subregion) has_cockpit_reg = true; } object_set_name(group_obj,(char *) justName.c_str()); if (!texName.empty()) { if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNamePvr.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNamePng.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNameBmp.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNameDds.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathPvr.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathPng.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathBmp.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathDds.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); } if (has_cockpit_cmd || has_cockpit_reg) { printf("Trying cockpit textures.\n"); int n = 0; while(panel_id == -1 && panel_names[n]) { panel_full_name = search_texture(filename, (char*)panel_names[n]); if(panel_full_name) panel_id = add_new_texture_opt(panel_full_name, (char*)panel_names[n]); ++n; } if(panel_id == -1 && has_cockpit_reg) { message_dialog((char*)"Warning: I was unable to find a panel texture to load, but you are using panel regions. Your texure coordinates may be incorrect after import."); } } for(vector<XObjLOD8>::iterator lod = obj8.lods.begin(); lod != obj8.lods.end(); ++lod) { lod_obj = new_object(OBJECT_GROUP); if (lod->lod_far != 0.0) sprintf(strbuf, "LOD %f/%f",lod->lod_near, lod->lod_far); else strcpy(strbuf, "Default LOD"); object_set_name(lod_obj, strbuf); if (lod->lod_far != 0.0) { OBJ_set_LOD_near(lod_obj, lod->lod_near); OBJ_set_LOD_far (lod_obj, lod->lod_far ); } object_add_child(group_obj, lod_obj); bool shade_flat = false; bool two_side = false; int panel_tex = tex_id; int last_reg = -1; float s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; float no_blend = -1.0; string hard_poly; int deck = 0; float offset = 0; string light_level; float light_v1 = 0.0f, light_v2 = 1.0f; int draw_disable = 0; int wall = 0; int manip_type = manip_none; string manip_dref1, manip_dref2, manip_cursor, manip_tooltip; float manip_wheel = 0.0; float manip_drag_axis[3]; float manip_v1_min; float manip_v1_max; float manip_v2_min; float manip_v2_max; map<int, Vertex *> vmap; for(vector<XObjCmd8>::iterator cmd = lod->cmds.begin(); cmd != lod->cmds.end(); ++cmd) { switch(cmd->cmd) { case obj8_Tris: case obj8_Lines: if (stuff_obj == NULL) { stuff_obj = new_object(OBJECT_NORMAL); vmap.clear(); if (panel_tex != -1)object_texture_set(stuff_obj, panel_tex); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), stuff_obj); OBJ_set_poly_os(stuff_obj, offset); OBJ_set_blend(stuff_obj, no_blend); OBJ_set_hard(stuff_obj, hard_poly.c_str()); OBJ_set_deck(stuff_obj,deck); if(light_level.empty()) OBJ_set_mod_lit(stuff_obj,0); else { OBJ_set_mod_lit(stuff_obj,1); OBJ_set_lit_dataref(stuff_obj,light_level.c_str()); OBJ_set_lit_v1(stuff_obj, light_v1); OBJ_set_lit_v2(stuff_obj, light_v2); } OBJ_set_wall(stuff_obj,wall); OBJ_set_draw_disable(stuff_obj,draw_disable); OBJ_set_manip_type(stuff_obj,manip_type); switch(manip_type) { case manip_axis: case manip_axis_pix: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dz(stuff_obj,manip_drag_axis[2]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_axis_2d: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_v2_min(stuff_obj,manip_v2_min); OBJ_set_manip_v2_max(stuff_obj,manip_v2_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_command: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_command_axis: OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dz(stuff_obj,manip_drag_axis[2]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_noop: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_dref_push: case manip_dref_toggle: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_dref_radio: OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_dref_delta: case manip_dref_wrap: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_v2_min(stuff_obj,manip_v2_min); OBJ_set_manip_v2_max(stuff_obj,manip_v2_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_command_knob: case manip_command_switch_ud: case manip_command_switch_lr: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_dref_knob: case manip_dref_switch_ud: case manip_dref_switch_lr: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); break; } sprintf(strbuf, "POLY_OS=%d HARD=%s BLEND=%s", (int) offset, hard_poly.c_str(), no_blend >= 0.0 ? "no":"yes"); object_set_name(stuff_obj, strbuf); } if (cmd->cmd == obj8_Tris) { int total_verts = 0; vector<Vertex *> verts; for (i = 0; i < cmd->idx_count; ++i) { map<int,Vertex *>::iterator idx_iter = vmap.find(obj8.indices[cmd->idx_offset + i]); if(idx_iter != vmap.end()) { verts.push_back(idx_iter->second); } else { ++total_verts; float * dat = obj8.geo_tri.get(obj8.indices[cmd->idx_offset + i]); p3.x = dat[0]; p3.y = dat[1]; p3.z = dat[2]; verts.push_back(object_add_new_vertex_head(stuff_obj, &p3)); vmap.insert(map<int,Vertex*>::value_type(obj8.indices[cmd->idx_offset + i],verts.back())); } } Surface * s = NULL; for (i = 0; i < cmd->idx_count; ++i) { if ((i % 3) == 0) { s = new_surface(); surface_set_type(s, SURFACE_POLYGON); surface_set_twosided(s, two_side); surface_set_shading(s, !shade_flat); object_add_surface_head(stuff_obj, s); int our_material = ac_palette_get_new_material_index(&current_material); surface_set_col(s, our_material); if (our_material != default_material) OBJ_set_use_materials(stuff_obj, 1); } float * dat = obj8.geo_tri.get(obj8.indices[cmd->idx_offset + i]); surface_add_vertex_head(s, verts[i], dat[6] * s_mul + s_add, dat[7] * t_mul + t_add); } } else { vector<Vertex *> verts; int i; for (i = 0; i < cmd->idx_count; ++i) { float * dat = obj8.geo_lines.get(obj8.indices[cmd->idx_offset + i]); p3.x = dat[0]; p3.y = dat[1]; p3.z = dat[2]; verts.push_back(object_add_new_vertex_head(stuff_obj, &p3)); } Surface * s = NULL; for (i = 0; i < cmd->idx_count; ++i) { float * dat = obj8.geo_lines.get(obj8.indices[cmd->idx_offset + i]); if ((i % 2) == 0) { s = new_surface(); surface_set_rgb_long(s, rgb_floats_to_long(dat[3], dat[4], dat[5])); surface_set_type(s, SURFACE_LINE); surface_set_twosided(s, two_side); surface_set_shading(s, !shade_flat); object_add_surface_head(stuff_obj, s); } surface_add_vertex_head(s, verts[i], 0.0, 0.0); } } break; case attr_Tex_Normal: if (panel_tex != tex_id) stuff_obj = NULL; panel_tex = tex_id; last_reg = -1; s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; manip_type = manip_none; break; case attr_Tex_Cockpit: if (panel_tex != panel_id) stuff_obj = NULL; panel_tex = panel_id; last_reg = -1; s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; manip_type = manip_panel; break; case attr_Tex_Cockpit_Subregion: if (panel_tex != panel_id) stuff_obj = NULL; if(last_reg != (int) cmd->params[0]) stuff_obj = NULL; panel_tex = panel_id; last_reg = (int) cmd->params[0]; manip_type = manip_panel; panel_get_import_scaling(panel_id,last_reg,&s_mul,&t_mul,&s_add,&t_add); break; case attr_No_Blend: if (!no_blend != cmd->params[0]) stuff_obj = NULL; no_blend = cmd->params[0]; break; case attr_Blend: if (no_blend != -1.0) stuff_obj = NULL; no_blend = -1.0; break; case attr_Hard: if (hard_poly != cmd->name) stuff_obj = NULL; if(deck == 1) stuff_obj = NULL; hard_poly = cmd->name; deck = 0; break; case attr_Hard_Deck: if (hard_poly != cmd->name) stuff_obj = NULL; if(deck == 0) stuff_obj = NULL; hard_poly = cmd->name; deck = 1; break; case attr_No_Hard: if (!hard_poly.empty()) stuff_obj = NULL; hard_poly.clear(); deck = 0; break; case attr_Offset: if (offset != cmd->params[0]) stuff_obj = NULL; offset = cmd->params[0]; break; case attr_Shade_Flat: #if OBJ_FOR_ALL_ATTRS if (!shade_flat) stuff_obj = NULL; #endif shade_flat = true; break; case attr_Shade_Smooth: #if OBJ_FOR_ALL_ATTRS if (shade_flat) stuff_obj = NULL; #endif shade_flat = false; break; case attr_Cull: #if OBJ_FOR_ALL_ATTRS if (two_side) stuff_obj = NULL; #endif two_side = false; break; case attr_NoCull: #if OBJ_FOR_ALL_ATTRS if (!two_side) stuff_obj = NULL; #endif two_side = true; break; case attr_Solid_Wall: if(!wall) stuff_obj = NULL; wall = 1; break; case attr_No_Solid_Wall: if(wall) stuff_obj = NULL; wall = 0; break; case attr_Draw_Disable: if(!draw_disable) stuff_obj = NULL; draw_disable = 1; break; case attr_Draw_Enable: if(draw_disable) stuff_obj = NULL; draw_disable = 0; break; case attr_Light_Level: if(light_level != cmd->name) stuff_obj = NULL; if(light_v1 != cmd->params[0]) stuff_obj = NULL; if(light_v2 != cmd->params[1]) stuff_obj = NULL; light_v1 = cmd->params[0]; light_v2 = cmd->params[1]; light_level = cmd->name; break; case attr_Light_Level_Reset: if(!light_level.empty()) stuff_obj = NULL; light_v1 = 0.0f; light_v2 = 1.0f; light_level.clear(); break; case attr_Layer_Group: OBJ_set_layer_group(group_obj, cmd->name.c_str()); OBJ_set_layer_group_offset(group_obj, cmd->params[0]); break; case attr_Manip_Drag_Axis: stuff_obj = NULL; manip_type = manip_axis; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Drag_2d: stuff_obj = NULL; manip_type = manip_axis_2d; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Command: stuff_obj = NULL; manip_type = manip_command; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Axis: stuff_obj = NULL; manip_type = manip_command_axis; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; break; case attr_Manip_Noop: stuff_obj = NULL; manip_type = manip_noop; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Push: stuff_obj = NULL; manip_type = manip_dref_push; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Radio: stuff_obj = NULL; manip_type = manip_dref_radio; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Toggle: stuff_obj = NULL; manip_type = manip_dref_toggle; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Delta: stuff_obj = NULL; manip_type = manip_dref_delta; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Wrap: stuff_obj = NULL; manip_type = manip_dref_wrap; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Drag_Axis_Pix: stuff_obj = NULL; manip_type = manip_axis_pix; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Command_Knob: stuff_obj = NULL; manip_type = manip_command_knob; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Switch_Up_Down: stuff_obj = NULL; manip_type = manip_command_switch_ud; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Switch_Left_Right: stuff_obj = NULL; manip_type = manip_command_switch_lr; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Axis_Knob: stuff_obj = NULL; manip_type = manip_dref_knob; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Axis_Switch_Up_Down: stuff_obj = NULL; manip_type = manip_dref_switch_ud; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Axis_Switch_Left_Right: stuff_obj = NULL; manip_type = manip_dref_switch_lr; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case anim_Begin: { stuff_obj = NULL; ACObject * parent = anim_obj.empty() ? lod_obj : anim_obj.back(); anim_obj.push_back(new_object(OBJECT_GROUP)); object_add_child(parent, anim_obj.back()); object_set_name(anim_obj.back(), (char*)"ANIMATION"); OBJ_set_animation_group(anim_obj.back(),1); } break; case anim_End: stuff_obj = NULL; anim_obj.pop_back(); break; case anim_Translate: { stuff_obj = NULL; int root = 0; if (obj8.animation[cmd->idx_offset].keyframes[root].v[0] != 0.0 || obj8.animation[cmd->idx_offset].keyframes[root].v[1] != 0.0 || obj8.animation[cmd->idx_offset].keyframes[root].v[2] != 0.0) anim_add_static(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes[root].v, obj8.animation[cmd->idx_offset].dataref.c_str(), "static translate"); if (obj8.animation[cmd->idx_offset].keyframes.size() > 2 || (obj8.animation[cmd->idx_offset].keyframes.size() == 2 && ( obj8.animation[cmd->idx_offset].keyframes[0].v[0] != obj8.animation[cmd->idx_offset].keyframes[1].v[0] || obj8.animation[cmd->idx_offset].keyframes[0].v[1] != obj8.animation[cmd->idx_offset].keyframes[1].v[1] || obj8.animation[cmd->idx_offset].keyframes[0].v[2] != obj8.animation[cmd->idx_offset].keyframes[1].v[2]))) anim_add_translate(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "translate", obj8.animation[cmd->idx_offset].loop); } break; case anim_Rotate: { stuff_obj = NULL; float center[3] = { 0.0, 0.0, 0.0 }; anim_add_rotate(anim_obj.back(), 0, center, obj8.animation[cmd->idx_offset].axis, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "rotate", obj8.animation[cmd->idx_offset].loop); } break; case anim_Show: stuff_obj = NULL; anim_add_show(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "show"); break; case anim_Hide: stuff_obj = NULL; anim_add_hide(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "show"); break; case obj8_Lights: for (i = 0; i < cmd->idx_count; ++i) { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; float * dat = obj8.geo_lights.get(cmd->idx_offset + i); pt_ac3.x = dat[0]; pt_ac3.y = dat[1]; pt_ac3.z = dat[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); sprintf(strbuf, "RGB (%f,%f,%f)", dat[3], dat[4], dat[5]); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, strbuf); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_red(light, dat[3]); OBJ_set_light_green(light, dat[4]); OBJ_set_light_blue(light, dat[5]); OBJ_set_light_named(light, "rgb"); } break; case obj8_LightNamed: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*) cmd->name.c_str()); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_named(light, cmd->name.c_str()); } break; case obj8_LightCustom: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_named(light, "custom"); OBJ_set_light_dataref(light, cmd->name.c_str()); OBJ_set_light_red (light,cmd->params[3]); OBJ_set_light_green (light,cmd->params[4]); OBJ_set_light_blue (light,cmd->params[5]); OBJ_set_light_alpha (light,cmd->params[6]); OBJ_set_light_size (light,cmd->params[7]); OBJ_set_light_s1 (light,cmd->params[8]); OBJ_set_light_t1 (light,cmd->params[9]); OBJ_set_light_s2 (light,cmd->params[10]); OBJ_set_light_t2 (light,cmd->params[11]); } break; case obj_Smoke_Black: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*)"Black Smoke"); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_smoke_size(light, cmd->params[3]); OBJ_set_light_named(light, "black smoke"); } break; case obj_Smoke_White: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*)"White Smoke"); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_smoke_size(light, cmd->params[3]); OBJ_set_light_named(light, "white smoke"); } break; case attr_Ambient_RGB: break; case attr_Diffuse_RGB: current_material.rgb.r = cmd->params[0]; current_material.rgb.g = cmd->params[1]; current_material.rgb.b = cmd->params[2]; break; case attr_Emission_RGB: current_material.emissive.r = cmd->params[0]; current_material.emissive.g = cmd->params[1]; current_material.emissive.b = cmd->params[2]; break; case attr_Specular_RGB: break; case attr_Shiny_Rat: current_material.specular.r = cmd->params[0]; current_material.specular.g = cmd->params[0]; current_material.specular.b = cmd->params[0]; break; case attr_Reset: current_material.rgb.r = 1.0; current_material.rgb.g = 1.0; current_material.rgb.b = 1.0; current_material.specular.r = 0.0; current_material.specular.g = 0.0; current_material.specular.b = 0.0; current_material.emissive.r = 0.0; current_material.emissive.g = 0.0; current_material.emissive.b = 0.0; break; } } } object_calc_normals_force(group_obj); bake_static_transitions(group_obj); purge_datarefs(); gather_datarefs(group_obj); sync_datarefs(); return group_obj; }
34,710
17,083
#include <TestSupport.h> #include <Core/SpawningKit/Handshake/Prepare.h> #include <Core/SpawningKit/Handshake/Perform.h> #include <LoggingKit/Context.h> #include <SystemTools/UserDatabase.h> #include <boost/bind/bind.hpp> #include <cstdio> #include <IOTools/IOUtils.h> using namespace std; using namespace Passenger; using namespace Passenger::SpawningKit; namespace tut { struct Core_SpawningKit_HandshakePerformTest: public TestBase { WrapperRegistry::Registry wrapperRegistry; SpawningKit::Context::Schema schema; SpawningKit::Context context; SpawningKit::Config config; boost::shared_ptr<HandshakeSession> session; pid_t pid; Pipe stdoutAndErr; HandshakePerform::DebugSupport *debugSupport; AtomicInt counter; FileDescriptor server; Core_SpawningKit_HandshakePerformTest() : context(schema), pid(getpid()), debugSupport(NULL) { wrapperRegistry.finalize(); context.resourceLocator = resourceLocator; context.wrapperRegistry = &wrapperRegistry; context.integrationMode = "standalone"; context.spawnDir = getSystemTempDir(); config.appGroupName = "appgroup"; config.appRoot = "/tmp/myapp"; config.startCommand = "echo hi"; config.startupFile = "/tmp/myapp/app.py"; config.appType = "wsgi"; config.spawnMethod = "direct"; config.bindAddress = "127.0.0.1"; config.user = lookupSystemUsernameByUid(getuid()); config.group = lookupSystemGroupnameByGid(getgid()); config.internStrings(); } ~Core_SpawningKit_HandshakePerformTest() { Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["level"] = DEFAULT_LOG_LEVEL_NAME; config["app_output_log_level"] = DEFAULT_APP_OUTPUT_LOG_LEVEL_NAME; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } } void init(JourneyType type) { vector<StaticString> errors; ensure("Config is valid", config.validate(errors)); context.finalize(); session = boost::make_shared<HandshakeSession>(context, config, type); session->journey.setStepInProgress(SPAWNING_KIT_PREPARATION); HandshakePrepare(*session).execute().finalize(); session->journey.setStepInProgress(SPAWNING_KIT_HANDSHAKE_PERFORM); session->journey.setStepInProgress(SUBPROCESS_BEFORE_FIRST_EXEC); } void execute() { HandshakePerform performer(*session, pid, FileDescriptor(), stdoutAndErr.first); performer.debugSupport = debugSupport; performer.execute(); counter++; } static Json::Value createGoodPropertiesJson() { Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; socket["accept_http_requests"] = true; doc["sockets"].append(socket); return doc; } void signalFinish() { writeFile(session->responseDir + "/finish", "1"); } void signalFinishWithError() { writeFile(session->responseDir + "/finish", "0"); } }; struct FreePortDebugSupport: public HandshakePerform::DebugSupport { Core_SpawningKit_HandshakePerformTest *test; HandshakeSession *session; AtomicInt expectedStartPort; virtual void beginWaitUntilSpawningFinished() { expectedStartPort = session->expectedStartPort; test->counter++; } }; struct CrashingDebugSupport: public HandshakePerform::DebugSupport { virtual void beginWaitUntilSpawningFinished() { throw RuntimeException("oh no!"); } }; DEFINE_TEST_GROUP_WITH_LIMIT(Core_SpawningKit_HandshakePerformTest, 80); /***** General logic *****/ TEST_METHOD(1) { set_test_name("If the app is generic, it finishes when the app is pingable"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.genericApp = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); } TEST_METHOD(2) { set_test_name("If findFreePort is true, it finishes when the app is pingable"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.findFreePort = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); } TEST_METHOD(3) { set_test_name("It finishes when the app has sent the finish signal"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); SHOULD_NEVER_HAPPEN(100, result = counter > 0; ); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); signalFinish(); EVENTUALLY(1, result = counter == 1; ); } TEST_METHOD(10) { set_test_name("It raises an error if the process exits prematurely"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(StaticString(e.what()), "The application process exited prematurely."); } } TEST_METHOD(11) { set_test_name("It raises an error if the procedure took too long"); config.startTimeoutMsec = 50; init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child usleep(1000000); _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(StaticString(e.what()), "A timeout occurred while spawning an application process."); } } TEST_METHOD(15) { set_test_name("In the event of an error, it sets the SPAWNING_KIT_HANDSHAKE_PERFORM step to the errored state"); CrashingDebugSupport debugSupport; this->debugSupport = &debugSupport; init(SPAWN_DIRECTLY); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &) { ensure_equals(session->journey.getFirstFailedStep(), SPAWNING_KIT_HANDSHAKE_PERFORM); } } TEST_METHOD(16) { set_test_name("In the event of an error, the exception contains journey state information from the response directory"); CrashingDebugSupport debugSupport; this->debugSupport = &debugSupport; init(SPAWN_DIRECTLY); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_ERRORED"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &) { ensure_equals(session->journey.getStepInfo(SUBPROCESS_LISTEN).state, STEP_ERRORED); } } TEST_METHOD(17) { set_test_name("In the event of an error, the exception contains subprocess stdout and stderr data"); Pipe p = createPipe(__FILE__, __LINE__); CrashingDebugSupport debugSupport; init(SPAWN_DIRECTLY); HandshakePerform performer(*session, pid, FileDescriptor(), p.first); performer.debugSupport = &debugSupport; Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["app_output_log_level"] = "debug"; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } writeExact(p.second, "hi\n"); try { performer.execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getStdoutAndErrData(), "hi\n"); } } TEST_METHOD(18) { set_test_name("In the event of an error caused by the subprocess, the exception contains messages from" " the subprocess as dumped in the response directory"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/error/summary", "the summary"); createFile(session->responseDir + "/error/problem_description.txt", "the <problem>"); createFile(session->responseDir + "/error/advanced_problem_details", "the advanced problem details"); createFile(session->responseDir + "/error/solution_description.html", "the <b>solution</b>"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "the summary"); ensure_equals(e.getProblemDescriptionHTML(), "the &lt;problem&gt;"); ensure_equals(e.getAdvancedProblemDetails(), "the advanced problem details"); ensure_equals(e.getSolutionDescriptionHTML(), "the <b>solution</b>"); } } TEST_METHOD(19) { set_test_name("In the event of success, it loads the journey state information from the response directory"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->journey.getStepInfo(SUBPROCESS_LISTEN).state, STEP_PERFORMED); } TEST_METHOD(20) { // Limited test of whether the code mitigates symlink attacks. set_test_name("It does not read from symlinks"); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties-real.json", createGoodPropertiesJson().toStyledString()); symlink("properties-real.json", (session->responseDir + "/properties.json").c_str()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "Cannot open 'properties.json'")); } } /***** Success response handling *****/ TEST_METHOD(30) { set_test_name("The result object contains basic information such as FDs and time"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->result.pid, pid); ensure(session->result.spawnStartTime != 0); ensure(session->result.spawnEndTime >= session->result.spawnStartTime); ensure(session->result.spawnStartTimeMonotonic != 0); ensure(session->result.spawnEndTimeMonotonic >= session->result.spawnStartTimeMonotonic); } TEST_METHOD(31) { set_test_name("The result object contains sockets specified in properties.json"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:3000"); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, 1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(32) { set_test_name("If the app is generic, it automatically registers the free port as a request-handling socket"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.genericApp = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:" + toString(session->expectedStartPort)); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, -1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(33) { set_test_name("If findFreePort is true, it automatically registers the free port as a request-handling socket"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.findFreePort = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:" + toString(session->expectedStartPort)); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, -1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(34) { set_test_name("It raises an error if we expected the subprocess to create a properties.json," " but the file does not conform to the required format"); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties.json", "{ \"sockets\": {} }"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "'sockets' must be an array")); } } TEST_METHOD(35) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one request-handling socket in properties.json, yet the file does" " not specify any"); Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; doc["sockets"].append(socket); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "the application did not report any sockets to receive requests on")); } } TEST_METHOD(36) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one request-handling socket in properties.json, yet properties.json" " does not exist"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "sockets are not supplied")); } } TEST_METHOD(37) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one preloader command socket in properties.json, yet the file does" " not specify any"); Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; doc["sockets"].append(socket); init(START_PRELOADER); createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "the application did not report any sockets to receive preloader commands on")); } } TEST_METHOD(38) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one preloader command socket in properties.json, yet properties.json" " does not exist"); init(START_PRELOADER); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "sockets are not supplied")); } } TEST_METHOD(39) { set_test_name("It raises an error if properties.json specifies a Unix domain socket" " that is not located in the apps.s subdir of the instance directory"); TempDir tmpDir("tmp.instance"); context.instanceDir = absolutizePath("tmp.instance"); init(SPAWN_DIRECTLY); Json::Value doc = createGoodPropertiesJson(); doc["sockets"][0]["address"] = "unix:/foo"; createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "must be an absolute path to a file in")); } } TEST_METHOD(40) { set_test_name("It raises an error if properties.json specifies a Unix domain socket" " that is not owned by the app"); if (geteuid() != 0) { return; } TempDir tmpDir("tmp.instance"); mkdir("tmp.instance/apps.s", 0700); string socketPath = absolutizePath("tmp.instance/apps.s/foo.sock"); init(SPAWN_DIRECTLY); Json::Value doc = createGoodPropertiesJson(); doc["sockets"][0]["address"] = "unix:" + socketPath; createFile(session->responseDir + "/properties.json", doc.toStyledString()); safelyClose(createUnixServer(socketPath)); chown(socketPath.c_str(), 1, 1); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure("(1)", containsSubstring(e.getSummary(), "must be owned by user")); } } /***** Error response handling *****/ TEST_METHOD(50) { set_test_name("It raises an error if the application responded with an error"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "The web application aborted with an error during startup."); } } TEST_METHOD(51) { set_test_name("The exception contains error messages provided by the application"); init(SPAWN_DIRECTLY); writeFile(session->workDir->getPath() + "/response/error/summary", "the summary"); writeFile(session->workDir->getPath() + "/response/error/problem_description.html", "the problem description"); writeFile(session->workDir->getPath() + "/response/error/solution_description.html", "the solution description"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "the summary"); ensure_equals(e.getProblemDescriptionHTML(), "the problem description"); ensure_equals(e.getSolutionDescriptionHTML(), "the solution description"); } } TEST_METHOD(52) { set_test_name("The exception describes which steps in the journey had failed"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); } catch (const SpawnException &e) { ensure_equals(e.getJourney().getFirstFailedStep(), SUBPROCESS_BEFORE_FIRST_EXEC); } } TEST_METHOD(53) { set_test_name("The exception contains the subprocess' output"); Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["app_output_log_level"] = "debug"; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } init(SPAWN_DIRECTLY); stdoutAndErr = createPipe(__FILE__, __LINE__); writeExact(stdoutAndErr.second, "oh no"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getStdoutAndErrData(), "oh no"); } } TEST_METHOD(54) { set_test_name("The exception contains the subprocess' environment variables dump"); init(SPAWN_DIRECTLY); writeFile(session->workDir->getPath() + "/envdump/envvars", "the env dump"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSubprocessEnvvars(), "the env dump"); } } TEST_METHOD(55) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is a subprocess journey step in the IN_PROGRESS state," " then we set that latter step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/steps/subprocess_before_first_exec/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/subprocess_before_first_exec/duration", "1"); createFile(session->responseDir + "/steps/subprocess_spawn_env_setupper_before_shell/state", "STEP_IN_PROGRESS"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_ERRORED); ensure_equals("SUBPROCESS_OS_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_NOT_STARTED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(56) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and no subprocess journey steps are in the PERFORMED state," " then we set the first subprocess journey step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_ERRORED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(57) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and some but not all subprocess journey steps are in the PERFORMED state," " then we set the step that comes right after the last PERFORMED step," " to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/steps/subprocess_before_first_exec/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/subprocess_before_first_exec/duration", "1"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_ERRORED); ensure_equals("SUBPROCESS_OS_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_NOT_STARTED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(58) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and all subprocess journey steps are in the PERFORMED state," " then we set the last subprocess step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } JourneyStep firstStep = getFirstSubprocessJourneyStep(); JourneyStep lastStep = getLastSubprocessJourneyStep(); JourneyStep step; for (step = firstStep; step < lastStep; step = JourneyStep((int) step + 1)) { if (!session->journey.hasStep(step)) { continue; } createFile(session->responseDir + "/steps/" + journeyStepToStringLowerCase(step) + "/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/" + journeyStepToStringLowerCase(step) + "/duration", "1"); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_OS_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_APP_LOAD_OR_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_APP_LOAD_OR_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_APP_LOAD_OR_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_APP_LOAD_OR_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_LISTEN is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_LISTEN).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_FINISH is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_FINISH).state, STEP_ERRORED); } } }
28,436
10,990
/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * \file main.cxx * * An application which acts as an openlcb hub with the GC protocol. * * @author Balazs Racz * @date 3 Aug 2013 */ #include <emscripten.h> #include <emscripten/bind.h> #include <emscripten/val.h> #include <memory> #include "os/os.h" #include "utils/constants.hxx" #include "utils/Hub.hxx" #include "utils/GridConnectHub.hxx" #include "utils/GcTcpHub.hxx" #include "utils/JSTcpHub.hxx" #include "utils/JSTcpClient.hxx" #include "utils/FileUtils.hxx" #include "executor/Executor.hxx" #include "executor/Service.hxx" #include "openlcb/SimpleStack.hxx" #include "openlcb/SimpleNodeInfoMockUserFile.hxx" namespace openlcb { extern const SimpleNodeStaticValues SNIP_STATIC_DATA = { 4, "OpenMRN", "CDI test server", "node.js", "1.00"}; } openlcb::MockSNIPUserFile snip_user_file( "Default user name", "Default user description"); const char *const openlcb::SNIP_DYNAMIC_FILENAME = openlcb::MockSNIPUserFile::snip_user_file_path; const uint64_t node_id_base = 0x050101011800ULL; uint64_t node_id = node_id_base | 0xF3; OVERRIDE_CONST(gc_generate_newlines, 1); int port = -1; int upstream_port = 12021; const char *upstream_host = nullptr; const char *cdi_file = nullptr; namespace openlcb { /// This symbol contains the embedded text of the CDI xml file. const char CDI_DATA[128*1024] = {0,}; } void usage(const char *e) { fprintf(stderr, "Usage: %s [-p port] [-u hub_host [-q hub_port]] [-n id] -x cdi_file\n\n", e); fprintf(stderr, "\n\nArguments:\n"); fprintf(stderr, "\t-c filename is the filename for the CDI (xml text).\n"); fprintf(stderr, "\t-p port Opens a TCP server on this port and listens for clients connecting with a GridConnect protocol (like a hub).\n"); /* fprintf(stderr, "\t-d device is a path to a physical device doing " "serial-CAN or USB-CAN. If specified, opens device and " "adds it to the hub.\n");*/ fprintf(stderr, "\t-u upstream_host is the host name for a TCP GridConnect " "hub. If specified, this program will connect to that hub for the CAN-bus.\n"); fprintf(stderr, "\t-q upstream_port is the port number for the upstream hub.\n"); fprintf(stderr, "\t-n id sets the lowest 8 bits of the node id. Valid values: 0..255. Default: 243.\n"); exit(1); } void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hp:u:q:x:n:")) >= 0) { switch (opt) { case 'h': usage(argv[0]); break; /* case 'd': device_path = optarg; break;*/ case 'p': port = atoi(optarg); break; case 'u': upstream_host = optarg; break; case 'q': upstream_port = atoi(optarg); break; case 'n': node_id = node_id_base + atoi(optarg); break; case 'x': cdi_file = optarg; break; default: fprintf(stderr, "Unknown option %c\n", opt); usage(argv[0]); } } if (!cdi_file) { fprintf(stderr, "cdi_file is not specified\n"); usage(argv[0]); } string contents = read_file_to_string(cdi_file); if (contents.size() + 1 <= sizeof(openlcb::CDI_DATA)) { memcpy((char*)openlcb::CDI_DATA, contents.c_str(), contents.size() + 1); } else { DIE("CDI file too large."); } } /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { parse_args(argc, argv); openlcb::SimpleCanStack stack(node_id); const size_t configlen = 16*1024; uint8_t* cdispace = new uint8_t[configlen]; memset(cdispace, 0, configlen); openlcb::ReadWriteMemoryBlock ramblock(cdispace, configlen); stack.memory_config_handler()->registry()->insert(nullptr, openlcb::MemoryConfigDefs::SPACE_CONFIG, &ramblock); GcPacketPrinter packet_printer(stack.can_hub(), false); std::unique_ptr<JSTcpHub> hub; if (port > 0) { hub.reset(new JSTcpHub(stack.can_hub(), port)); } std::unique_ptr<JSTcpClient> client; if (upstream_host) { client.reset(new JSTcpClient(stack.can_hub(), upstream_host, upstream_port)); } /* int dev_fd = 0; while (1) { if (device_path && !dev_fd) { dev_fd = ::open(device_path, O_RDWR); if (dev_fd > 0) { // Sets up the terminal in raw mode. Otherwise linux might echo // characters coming in from the device and that will make // packets go back to where they came from. HASSERT(!tcflush(dev_fd, TCIOFLUSH)); struct termios settings; HASSERT(!tcgetattr(dev_fd, &settings)); cfmakeraw(&settings); HASSERT(!tcsetattr(dev_fd, TCSANOW, &settings)); LOG(INFO, "Opened device %s.\n", device_path); create_gc_port_for_can_hub(&can_hub0, dev_fd); } else { LOG(ERROR, "Failed to open device %s: %s\n", device_path, strerror(errno)); } } sleep(1); }*/ stack.loop_executor(); return 0; }
7,019
2,402
#include <iostream> class MyClass { public: MyClass() { std::cout << "Constructor called!" << std::endl; } ~MyClass() { std::cout << "Destructor called!" << std::endl; } }; int main() { MyClass myClass; std::cout << "Function body!" << std::endl; return 0; }
335
105
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/identity/identity_mint_queue.h" #include <vector> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using extensions::IdentityMintRequestQueue; namespace { class MockRequest : public extensions::IdentityMintRequestQueue::Request { public: MOCK_METHOD1(StartMintToken, void(IdentityMintRequestQueue::MintType)); }; } // namespace TEST(IdentityMintQueueTest, SerialRequests) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; MockRequest request2; EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request2); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request2); } TEST(IdentityMintQueueTest, InteractiveType) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); } TEST(IdentityMintQueueTest, ParallelRequests) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; MockRequest request2; MockRequest request3; EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request2); queue.RequestStart(type, extension_id, std::set<std::string>(), &request3); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); EXPECT_CALL(request3, StartMintToken(type)).Times(1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request2); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request3); } TEST(IdentityMintQueueTest, ParallelRequestsFromTwoExtensions) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id1("ext_id_1"); std::string extension_id2("ext_id_2"); MockRequest request1; MockRequest request2; EXPECT_CALL(request1, StartMintToken(type)).Times(1); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id1, std::set<std::string>(), &request1); queue.RequestStart(type, extension_id2, std::set<std::string>(), &request2); queue.RequestComplete(type, extension_id1, std::set<std::string>(), &request1); queue.RequestComplete(type, extension_id2, std::set<std::string>(), &request2); } TEST(IdentityMintQueueTest, ParallelRequestsForDifferentScopes) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; MockRequest request2; std::set<std::string> scopes1; std::set<std::string> scopes2; scopes1.insert("a"); scopes1.insert("b"); scopes2.insert("a"); EXPECT_CALL(request1, StartMintToken(type)).Times(1); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, scopes1, &request1); queue.RequestStart(type, extension_id, scopes2, &request2); queue.RequestComplete(type, extension_id, scopes1, &request1); queue.RequestComplete(type, extension_id, scopes2, &request2); } TEST(IdentityMintQueueTest, KeyComparisons) { std::string extension_id1("ext_id_1"); std::string extension_id2("ext_id_2"); std::set<std::string> scopes1; std::set<std::string> scopes2; std::set<std::string> scopes3; scopes1.insert("a"); scopes1.insert("b"); scopes2.insert("a"); std::vector<std::string> ids; ids.push_back(extension_id1); ids.push_back(extension_id2); std::vector<std::set<std::string> > scopesets; scopesets.push_back(scopes1); scopesets.push_back(scopes2); scopesets.push_back(scopes3); std::vector<IdentityMintRequestQueue::RequestKey> keys; typedef std::vector< IdentityMintRequestQueue::RequestKey>::const_iterator RequestKeyIterator; std::vector<std::string>::const_iterator id_it; std::vector<std::set<std::string> >::const_iterator scope_it; for (id_it = ids.begin(); id_it != ids.end(); ++id_it) { for (scope_it = scopesets.begin(); scope_it != scopesets.end(); ++scope_it) { keys.push_back(IdentityMintRequestQueue::RequestKey( IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE, *id_it, *scope_it)); keys.push_back(IdentityMintRequestQueue::RequestKey( IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE, *id_it, *scope_it)); } } // keys should not be less than themselves for (RequestKeyIterator it = keys.begin(); it != keys.end(); ++it) { EXPECT_FALSE(*it < *it); } // keys should not equal different keys for (RequestKeyIterator it1 = keys.begin(); it1 != keys.end(); ++it1) { RequestKeyIterator it2 = it1; for (++it2; it2 != keys.end(); ++it2) { EXPECT_TRUE(*it1 < *it2 || *it2 < *it1); EXPECT_FALSE(*it1 < *it2 && *it2 < *it1); } } } TEST(IdentityMintQueueTest, Empty) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; EXPECT_TRUE(queue.empty(type, extension_id, std::set<std::string>())); EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); EXPECT_FALSE(queue.empty(type, extension_id, std::set<std::string>())); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); EXPECT_TRUE(queue.empty(type, extension_id, std::set<std::string>())); }
6,713
2,327
#include "matrix.h" #include <iostream> Matrix::~Matrix() { for (size_t i = 0; i < cols; i++) delete[] arr[i]; delete[] arr; } Matrix& Matrix::operator *= (int k) { for (size_t i = 0; i < cols; i++) for (size_t j = 0; j < rows; j++) arr[i][j] *= k; return *this; } bool Matrix::operator == (const Matrix &m) { if (rows != m.rows || cols != m.cols) return false; for (size_t i = 0; i < cols; i++) for (size_t j = 0; j < rows; j++) if (arr[i][j] != m.arr[i][j]) return false; return true; } bool Matrix::operator != (const Matrix &m) { return !(*this == m); } Row Matrix::operator[](size_t j) { if (j >= cols) throw std::out_of_range(""); return Row(arr[j], rows); } const Row Matrix::operator[](size_t j) const { if (j >= cols) throw std::out_of_range(""); return Row(arr[j], rows); } int& Row::operator [](size_t i) { if (i >= rows) throw std::out_of_range(""); return row[i]; } const int& Row::operator [](size_t i) const { if (i >= rows) throw std::out_of_range(""); return row[i]; }
1,106
436
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "AnimGraphRuntimePrivatePCH.h" #include "BoneControllers/AnimNode_ObserveBone.h" #include "AnimationRuntime.h" ///////////////////////////////////////////////////// // FAnimNode_ObserveBone FAnimNode_ObserveBone::FAnimNode_ObserveBone() : DisplaySpace(BCS_ComponentSpace) , bRelativeToRefPose(false) , Translation(FVector::ZeroVector) , Rotation(FRotator::ZeroRotator) , Scale(FVector(1.0f)) { } void FAnimNode_ObserveBone::GatherDebugData(FNodeDebugData& DebugData) { const FString DebugLine = FString::Printf(TEXT("(Bone: %s has T(%s), R(%s), S(%s))"), *BoneToObserve.BoneName.ToString(), *Translation.ToString(), *Rotation.Euler().ToString(), *Scale.ToString()); DebugData.AddDebugItem(DebugLine); ComponentPose.GatherDebugData(DebugData); } void FAnimNode_ObserveBone::EvaluateBoneTransforms(USkeletalMeshComponent* SkelComp, FCSPose<FCompactPose>& MeshBases, TArray<FBoneTransform>& OutBoneTransforms) { const FBoneContainer BoneContainer = MeshBases.GetPose().GetBoneContainer(); const FCompactPoseBoneIndex BoneIndex = BoneToObserve.GetCompactPoseIndex(BoneContainer); FTransform BoneTM = MeshBases.GetComponentSpaceTransform(BoneIndex); // Convert to the specific display space if necessary FAnimationRuntime::ConvertCSTransformToBoneSpace(SkelComp, MeshBases, BoneTM, BoneIndex, DisplaySpace); // Convert to be relative to the ref pose if necessary if (bRelativeToRefPose) { const FTransform& SourceOrigRef = BoneContainer.GetRefPoseArray()[BoneToObserve.BoneIndex]; BoneTM = BoneTM.GetRelativeTransform(SourceOrigRef); } // Cache off the values for display Translation = BoneTM.GetTranslation(); Rotation = BoneTM.GetRotation().Rotator(); Scale = BoneTM.GetScale3D(); } bool FAnimNode_ObserveBone::IsValidToEvaluate(const USkeleton* Skeleton, const FBoneContainer& RequiredBones) { return (BoneToObserve.IsValid(RequiredBones)); } void FAnimNode_ObserveBone::InitializeBoneReferences(const FBoneContainer& RequiredBones) { BoneToObserve.Initialize(RequiredBones); }
2,086
734
/* 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 RelationTypes.hpp \brief enum of the available types and subtypes for relations, plugin names ... */ /*! \file RelationTypes.hpp Include files related to the different types of relations */ #ifndef RelationTypes_hpp #define RelationTypes_hpp #include "FirstOrderNonLinearR.hpp" #include "FirstOrderType1R.hpp" #include "FirstOrderType2R.hpp" #include "FirstOrderLinearR.hpp" #include "FirstOrderLinearTIR.hpp" #include "LagrangianLinearTIR.hpp" #include "LagrangianScleronomousR.hpp" #include "LagrangianRheonomousR.hpp" #include "LagrangianCompliantR.hpp" #include "LagrangianCompliantLinearTIR.hpp" #endif
1,317
414
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). #include "table/block_based/partitioned_filter_block.h" #include <utility> #include "file/file_util.h" #include "monitoring/perf_context_imp.h" #include "port/malloc.h" #include "port/port.h" #include "rocksdb/filter_policy.h" #include "table/block_based/block.h" #include "table/block_based/block_based_table_reader.h" #include "util/coding.h" namespace ROCKSDB_NAMESPACE { PartitionedFilterBlockBuilder::PartitionedFilterBlockBuilder( const SliceTransform* _prefix_extractor, bool whole_key_filtering, FilterBitsBuilder* filter_bits_builder, int index_block_restart_interval, const bool use_value_delta_encoding, PartitionedIndexBuilder* const p_index_builder, const uint32_t partition_size) : FullFilterBlockBuilder(_prefix_extractor, whole_key_filtering, filter_bits_builder), index_on_filter_block_builder_(index_block_restart_interval, true /*use_delta_encoding*/, use_value_delta_encoding), index_on_filter_block_builder_without_seq_(index_block_restart_interval, true /*use_delta_encoding*/, use_value_delta_encoding), p_index_builder_(p_index_builder), keys_added_to_partition_(0) { keys_per_partition_ = filter_bits_builder_->CalculateNumEntry(partition_size); if (keys_per_partition_ < 1) { // partition_size (minus buffer, ~10%) might be smaller than minimum // filter size, sometimes based on cache line size. Try to find that // minimum size without CalculateSpace (not necessarily available). uint32_t larger = std::max(partition_size + 4, uint32_t{16}); for (;;) { keys_per_partition_ = filter_bits_builder_->CalculateNumEntry(larger); if (keys_per_partition_ >= 1) { break; } larger += larger / 4; if (larger > 100000) { // might be a broken implementation. substitute something reasonable: // 1 key / byte. keys_per_partition_ = partition_size; break; } } } } PartitionedFilterBlockBuilder::~PartitionedFilterBlockBuilder() {} void PartitionedFilterBlockBuilder::MaybeCutAFilterBlock( const Slice* next_key) { // Use == to send the request only once if (keys_added_to_partition_ == keys_per_partition_) { // Currently only index builder is in charge of cutting a partition. We keep // requesting until it is granted. p_index_builder_->RequestPartitionCut(); } if (!p_index_builder_->ShouldCutFilterBlock()) { return; } filter_gc.push_back(std::unique_ptr<const char[]>(nullptr)); // Add the prefix of the next key before finishing the partition. This hack, // fixes a bug with format_verison=3 where seeking for the prefix would lead // us to the previous partition. const bool add_prefix = next_key && prefix_extractor() && prefix_extractor()->InDomain(*next_key); if (add_prefix) { FullFilterBlockBuilder::AddPrefix(*next_key); } Slice filter = filter_bits_builder_->Finish(&filter_gc.back()); std::string& index_key = p_index_builder_->GetPartitionKey(); filters.push_back({index_key, filter}); keys_added_to_partition_ = 0; Reset(); } void PartitionedFilterBlockBuilder::Add(const Slice& key) { MaybeCutAFilterBlock(&key); FullFilterBlockBuilder::Add(key); } void PartitionedFilterBlockBuilder::AddKey(const Slice& key) { FullFilterBlockBuilder::AddKey(key); keys_added_to_partition_++; } Slice PartitionedFilterBlockBuilder::Finish( const BlockHandle& last_partition_block_handle, Status* status) { if (finishing_filters == true) { // Record the handle of the last written filter block in the index FilterEntry& last_entry = filters.front(); std::string handle_encoding; last_partition_block_handle.EncodeTo(&handle_encoding); std::string handle_delta_encoding; PutVarsignedint64( &handle_delta_encoding, last_partition_block_handle.size() - last_encoded_handle_.size()); last_encoded_handle_ = last_partition_block_handle; const Slice handle_delta_encoding_slice(handle_delta_encoding); index_on_filter_block_builder_.Add(last_entry.key, handle_encoding, &handle_delta_encoding_slice); if (!p_index_builder_->seperator_is_key_plus_seq()) { index_on_filter_block_builder_without_seq_.Add( ExtractUserKey(last_entry.key), handle_encoding, &handle_delta_encoding_slice); } filters.pop_front(); } else { MaybeCutAFilterBlock(nullptr); } // If there is no filter partition left, then return the index on filter // partitions if (UNLIKELY(filters.empty())) { *status = Status::OK(); if (finishing_filters) { if (p_index_builder_->seperator_is_key_plus_seq()) { return index_on_filter_block_builder_.Finish(); } else { return index_on_filter_block_builder_without_seq_.Finish(); } } else { // This is the rare case where no key was added to the filter return Slice(); } } else { // Return the next filter partition in line and set Incomplete() status to // indicate we expect more calls to Finish *status = Status::Incomplete(); finishing_filters = true; return filters.front().filter; } } PartitionedFilterBlockReader::PartitionedFilterBlockReader( const BlockBasedTable* t, CachableEntry<Block>&& filter_block) : FilterBlockReaderCommon(t, std::move(filter_block)) {} std::unique_ptr<FilterBlockReader> PartitionedFilterBlockReader::Create( const BlockBasedTable* table, const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer, bool use_cache, bool prefetch, bool pin, BlockCacheLookupContext* lookup_context) { assert(table); assert(table->get_rep()); assert(!pin || prefetch); CachableEntry<Block> filter_block; if (prefetch || !use_cache) { const Status s = ReadFilterBlock(table, prefetch_buffer, ro, use_cache, nullptr /* get_context */, lookup_context, &filter_block); if (!s.ok()) { IGNORE_STATUS_IF_ERROR(s); return std::unique_ptr<FilterBlockReader>(); } if (use_cache && !pin) { filter_block.Reset(); } } return std::unique_ptr<FilterBlockReader>( new PartitionedFilterBlockReader(table, std::move(filter_block))); } bool PartitionedFilterBlockReader::KeyMayMatch( const Slice& key, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, const Slice* const const_ikey_ptr, GetContext* get_context, BlockCacheLookupContext* lookup_context) { assert(const_ikey_ptr != nullptr); assert(block_offset == kNotValid); if (!whole_key_filtering()) { return true; } return MayMatch(key, prefix_extractor, block_offset, no_io, const_ikey_ptr, get_context, lookup_context, &FullFilterBlockReader::KeyMayMatch); } void PartitionedFilterBlockReader::KeysMayMatch( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, BlockCacheLookupContext* lookup_context) { assert(block_offset == kNotValid); if (!whole_key_filtering()) { return; // Any/all may match } MayMatch(range, prefix_extractor, block_offset, no_io, lookup_context, &FullFilterBlockReader::KeysMayMatch); } bool PartitionedFilterBlockReader::PrefixMayMatch( const Slice& prefix, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, const Slice* const const_ikey_ptr, GetContext* get_context, BlockCacheLookupContext* lookup_context) { assert(const_ikey_ptr != nullptr); assert(block_offset == kNotValid); if (!table_prefix_extractor() && !prefix_extractor) { return true; } return MayMatch(prefix, prefix_extractor, block_offset, no_io, const_ikey_ptr, get_context, lookup_context, &FullFilterBlockReader::PrefixMayMatch); } void PartitionedFilterBlockReader::PrefixesMayMatch( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, BlockCacheLookupContext* lookup_context) { assert(block_offset == kNotValid); if (!table_prefix_extractor() && !prefix_extractor) { return; // Any/all may match } MayMatch(range, prefix_extractor, block_offset, no_io, lookup_context, &FullFilterBlockReader::PrefixesMayMatch); } BlockHandle PartitionedFilterBlockReader::GetFilterPartitionHandle( const CachableEntry<Block>& filter_block, const Slice& entry) const { IndexBlockIter iter; const InternalKeyComparator* const comparator = internal_comparator(); Statistics* kNullStats = nullptr; filter_block.GetValue()->NewIndexIterator( comparator->user_comparator(), table()->get_rep()->get_global_seqno(BlockType::kFilter), &iter, kNullStats, true /* total_order_seek */, false /* have_first_key */, index_key_includes_seq(), index_value_is_full()); iter.Seek(entry); if (UNLIKELY(!iter.Valid())) { // entry is larger than all the keys. However its prefix might still be // present in the last partition. If this is called by PrefixMayMatch this // is necessary for correct behavior. Otherwise it is unnecessary but safe. // Assuming this is an unlikely case for full key search, the performance // overhead should be negligible. iter.SeekToLast(); } assert(iter.Valid()); BlockHandle fltr_blk_handle = iter.value().handle; return fltr_blk_handle; } Status PartitionedFilterBlockReader::GetFilterPartitionBlock( FilePrefetchBuffer* prefetch_buffer, const BlockHandle& fltr_blk_handle, bool no_io, GetContext* get_context, BlockCacheLookupContext* lookup_context, CachableEntry<ParsedFullFilterBlock>* filter_block) const { assert(table()); assert(filter_block); assert(filter_block->IsEmpty()); if (!filter_map_.empty()) { auto iter = filter_map_.find(fltr_blk_handle.offset()); // This is a possible scenario since block cache might not have had space // for the partition if (iter != filter_map_.end()) { filter_block->SetUnownedValue(iter->second.GetValue()); return Status::OK(); } } ReadOptions read_options; if (no_io) { read_options.read_tier = kBlockCacheTier; } const Status s = table()->RetrieveBlock(prefetch_buffer, read_options, fltr_blk_handle, UncompressionDict::GetEmptyDict(), filter_block, BlockType::kFilter, get_context, lookup_context, /* for_compaction */ false, /* use_cache */ true); return s; } bool PartitionedFilterBlockReader::MayMatch( const Slice& slice, const SliceTransform* prefix_extractor, uint64_t block_offset, bool no_io, const Slice* const_ikey_ptr, GetContext* get_context, BlockCacheLookupContext* lookup_context, FilterFunction filter_function) const { CachableEntry<Block> filter_block; Status s = GetOrReadFilterBlock(no_io, get_context, lookup_context, &filter_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return true; } if (UNLIKELY(filter_block.GetValue()->size() == 0)) { return true; } auto filter_handle = GetFilterPartitionHandle(filter_block, *const_ikey_ptr); if (UNLIKELY(filter_handle.size() == 0)) { // key is out of range return false; } CachableEntry<ParsedFullFilterBlock> filter_partition_block; s = GetFilterPartitionBlock(nullptr /* prefetch_buffer */, filter_handle, no_io, get_context, lookup_context, &filter_partition_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return true; } FullFilterBlockReader filter_partition(table(), std::move(filter_partition_block)); return (filter_partition.*filter_function)( slice, prefix_extractor, block_offset, no_io, const_ikey_ptr, get_context, lookup_context); } void PartitionedFilterBlockReader::MayMatch( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, bool no_io, BlockCacheLookupContext* lookup_context, FilterManyFunction filter_function) const { CachableEntry<Block> filter_block; Status s = GetOrReadFilterBlock(no_io, range->begin()->get_context, lookup_context, &filter_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return; // Any/all may match } if (UNLIKELY(filter_block.GetValue()->size() == 0)) { return; // Any/all may match } auto start_iter_same_handle = range->begin(); BlockHandle prev_filter_handle = BlockHandle::NullBlockHandle(); // For all keys mapping to same partition (must be adjacent in sorted order) // share block cache lookup and use full filter multiget on the partition // filter. for (auto iter = start_iter_same_handle; iter != range->end(); ++iter) { // TODO: re-use one top-level index iterator BlockHandle this_filter_handle = GetFilterPartitionHandle(filter_block, iter->ikey); if (!prev_filter_handle.IsNull() && this_filter_handle != prev_filter_handle) { MultiGetRange subrange(*range, start_iter_same_handle, iter); MayMatchPartition(&subrange, prefix_extractor, block_offset, prev_filter_handle, no_io, lookup_context, filter_function); range->AddSkipsFrom(subrange); start_iter_same_handle = iter; } if (UNLIKELY(this_filter_handle.size() == 0)) { // key is out of range // Not reachable with current behavior of GetFilterPartitionHandle assert(false); range->SkipKey(iter); prev_filter_handle = BlockHandle::NullBlockHandle(); } else { prev_filter_handle = this_filter_handle; } } if (!prev_filter_handle.IsNull()) { MultiGetRange subrange(*range, start_iter_same_handle, range->end()); MayMatchPartition(&subrange, prefix_extractor, block_offset, prev_filter_handle, no_io, lookup_context, filter_function); range->AddSkipsFrom(subrange); } } void PartitionedFilterBlockReader::MayMatchPartition( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, BlockHandle filter_handle, bool no_io, BlockCacheLookupContext* lookup_context, FilterManyFunction filter_function) const { CachableEntry<ParsedFullFilterBlock> filter_partition_block; Status s = GetFilterPartitionBlock( nullptr /* prefetch_buffer */, filter_handle, no_io, range->begin()->get_context, lookup_context, &filter_partition_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return; // Any/all may match } FullFilterBlockReader filter_partition(table(), std::move(filter_partition_block)); (filter_partition.*filter_function)(range, prefix_extractor, block_offset, no_io, lookup_context); } size_t PartitionedFilterBlockReader::ApproximateMemoryUsage() const { size_t usage = ApproximateFilterBlockMemoryUsage(); #ifdef ROCKSDB_MALLOC_USABLE_SIZE usage += malloc_usable_size(const_cast<PartitionedFilterBlockReader*>(this)); #else usage += sizeof(*this); #endif // ROCKSDB_MALLOC_USABLE_SIZE return usage; // TODO(myabandeh): better estimation for filter_map_ size } // TODO(myabandeh): merge this with the same function in IndexReader void PartitionedFilterBlockReader::CacheDependencies(const ReadOptions& ro, bool pin) { assert(table()); const BlockBasedTable::Rep* const rep = table()->get_rep(); assert(rep); BlockCacheLookupContext lookup_context{TableReaderCaller::kPrefetch}; CachableEntry<Block> filter_block; Status s = GetOrReadFilterBlock(false /* no_io */, nullptr /* get_context */, &lookup_context, &filter_block); if (!s.ok()) { ROCKS_LOG_WARN(rep->ioptions.info_log, "Error retrieving top-level filter block while trying to " "cache filter partitions: %s", s.ToString().c_str()); IGNORE_STATUS_IF_ERROR(s); return; } // Before read partitions, prefetch them to avoid lots of IOs assert(filter_block.GetValue()); IndexBlockIter biter; const InternalKeyComparator* const comparator = internal_comparator(); Statistics* kNullStats = nullptr; filter_block.GetValue()->NewIndexIterator( comparator->user_comparator(), rep->get_global_seqno(BlockType::kFilter), &biter, kNullStats, true /* total_order_seek */, false /* have_first_key */, index_key_includes_seq(), index_value_is_full()); // Index partitions are assumed to be consecuitive. Prefetch them all. // Read the first block offset biter.SeekToFirst(); BlockHandle handle = biter.value().handle; uint64_t prefetch_off = handle.offset(); // Read the last block's offset biter.SeekToLast(); handle = biter.value().handle; uint64_t last_off = handle.offset() + handle.size() + kBlockTrailerSize; uint64_t prefetch_len = last_off - prefetch_off; std::unique_ptr<FilePrefetchBuffer> prefetch_buffer; prefetch_buffer.reset(new FilePrefetchBuffer()); IOOptions opts; s = PrepareIOFromReadOptions(ro, rep->file->env(), opts); if (s.ok()) { s = prefetch_buffer->Prefetch(opts, rep->file.get(), prefetch_off, static_cast<size_t>(prefetch_len)); } // After prefetch, read the partitions one by one for (biter.SeekToFirst(); biter.Valid(); biter.Next()) { handle = biter.value().handle; CachableEntry<ParsedFullFilterBlock> block; // TODO: Support counter batch update for partitioned index and // filter blocks s = table()->MaybeReadBlockAndLoadToCache( prefetch_buffer.get(), ro, handle, UncompressionDict::GetEmptyDict(), &block, BlockType::kFilter, nullptr /* get_context */, &lookup_context, nullptr /* contents */); assert(s.ok() || block.GetValue() == nullptr); if (s.ok() && block.GetValue() != nullptr) { if (block.IsCached()) { if (pin) { filter_map_[handle.offset()] = std::move(block); } } } IGNORE_STATUS_IF_ERROR(s); } } const InternalKeyComparator* PartitionedFilterBlockReader::internal_comparator() const { assert(table()); assert(table()->get_rep()); return &table()->get_rep()->internal_comparator; } bool PartitionedFilterBlockReader::index_key_includes_seq() const { assert(table()); assert(table()->get_rep()); return table()->get_rep()->index_key_includes_seq; } bool PartitionedFilterBlockReader::index_value_is_full() const { assert(table()); assert(table()->get_rep()); return table()->get_rep()->index_value_is_full; } } // namespace ROCKSDB_NAMESPACE
19,392
5,963
/* D. Up the Strip */ // https://codeforces.com/contest/1561/problem/D1 // Date: Aug/24/2021 18:29 (00:54:05) // Runtime: 6000 ms // Memory: 29160 KB // Verdict: TLE #include <iostream> #include <string.h> using namespace std; int n, m; int memo[4000010]; int count(int x) { if (memo[x] != -1) return memo[x]; if (x == 1) return 1; long long ans = 0; for (int y = 1; y <= x - 1; y++) ans = (ans + count(x - y)) % m; for (int z = 2; z <= x; z++) ans = (ans + count(x / z)) % m; return memo[x] = ans; } int main() { cin >> n >> m; memset(memo, -1, sizeof memo); cout << count(n); }
626
301
/********************************************************************** * Copyright (c) 2008-2014, 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 PROJECT_CONCRETEOBJECTRECORDS_HPP #define PROJECT_CONCRETEOBJECTRECORDS_HPP // utilities #include <project/AttributeRecord.hpp> #include <project/CloudSessionRecord.hpp> #include <project/CloudSettingsRecord.hpp> #include <project/FileReferenceRecord.hpp> #include <project/TagRecord.hpp> #include <project/UrlRecord.hpp> #include <project/URLSearchPathRecord.hpp> #include <project/VagrantSessionRecord.hpp> #include <project/VagrantSettingsRecord.hpp> // runmanager #include <project/WorkflowRecord.hpp> // ruleset #include <project/OSArgumentRecord.hpp> // analysis #include <project/AnalysisRecord.hpp> #include <project/DataPointRecord.hpp> #include <project/DataPointValueRecord.hpp> #include <project/DDACEAlgorithmRecord.hpp> #include <project/DesignOfExperimentsRecord.hpp> #include <project/FSUDaceAlgorithmRecord.hpp> #include <project/LinearFunctionRecord.hpp> #include <project/MeasureGroupRecord.hpp> #include <project/NullMeasureRecord.hpp> #include <project/OptimizationDataPointRecord.hpp> #include <project/OptimizationProblemRecord.hpp> #include <project/OutputAttributeVariableRecord.hpp> #include <project/ParameterStudyAlgorithmRecord.hpp> #include <project/ProblemRecord.hpp> #include <project/PSUADEDaceAlgorithmRecord.hpp> #include <project/RubyContinuousVariableRecord.hpp> #include <project/RubyMeasureRecord.hpp> #include <project/SamplingAlgorithmRecord.hpp> #include <project/SequentialSearchRecord.hpp> // utilities #include <project/AttributeRecord_Impl.hpp> #include <project/CloudSessionRecord_Impl.hpp> #include <project/CloudSettingsRecord_Impl.hpp> #include <project/FileReferenceRecord_Impl.hpp> #include <project/TagRecord_Impl.hpp> #include <project/UrlRecord_Impl.hpp> #include <project/URLSearchPathRecord_Impl.hpp> #include <project/VagrantSessionRecord_Impl.hpp> #include <project/VagrantSettingsRecord_Impl.hpp> // runmanager #include <project/WorkflowRecord_Impl.hpp> // ruleset #include <project/OSArgumentRecord_Impl.hpp> // analysis #include <project/AnalysisRecord_Impl.hpp> #include <project/DataPointRecord_Impl.hpp> #include <project/DataPointValueRecord_Impl.hpp> #include <project/DDACEAlgorithmRecord_Impl.hpp> #include <project/DesignOfExperimentsRecord_Impl.hpp> #include <project/FSUDaceAlgorithmRecord_Impl.hpp> #include <project/LinearFunctionRecord_Impl.hpp> #include <project/MeasureGroupRecord_Impl.hpp> #include <project/NullMeasureRecord_Impl.hpp> #include <project/OptimizationDataPointRecord_Impl.hpp> #include <project/OptimizationProblemRecord_Impl.hpp> #include <project/OutputAttributeVariableRecord_Impl.hpp> #include <project/ParameterStudyAlgorithmRecord_Impl.hpp> #include <project/ProblemRecord_Impl.hpp> #include <project/PSUADEDaceAlgorithmRecord_Impl.hpp> #include <project/RubyContinuousVariableRecord_Impl.hpp> #include <project/RubyMeasureRecord_Impl.hpp> #include <project/SamplingAlgorithmRecord_Impl.hpp> #include <project/SequentialSearchRecord_Impl.hpp> #endif // PROJECT_CONCRETEOBJECTRECORDS_HPP
4,090
1,259
#ifndef _FUNCTION_HPP #define _FUNCTION_HPP #include <SDL2/SDL.h> #include <string> #include "block.hpp" void gameover(const std::string &message); block *XYtoArr(int x, int y); void dfs(block *it); block *mouseToArr(int _x, int _y); void setball(); void init(); inline void clock(const unsigned int frames_per_second); void my_time_update(bool); #endif
357
136
#include<iostream> #define MAX_SIZE 5 int sort(int arr[MAX_SIZE], int key) { int pos = 0; for(int i=0;i<MAX_SIZE;i++) { if(arr[i]==key) return(i); } return (-1); } int main() { int list[MAX_SIZE]; int ele; std::cout<<"Enter Array: "; for(int i = 0; i<MAX_SIZE;i++){ std::cin>>list[i]; } std::cout<<"\n\nEnter element to search: "; std::cin>>ele; int pos = sort(list,ele); if (pos==-1) std::cout<<"\nElement not found."; else std::cout<<"\nElement found at position "<<pos+1; return 0; }
612
244
/** MIT License Copyright (c) 2018 Vasilyev Daniil **/ #include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") template<typename T> using v = vector<T>; #define int long long typedef string str; typedef vector<int> vint; #define rep(a, l, r) for(int a = (l); a < (r); a++) #define pb push_back #define sz(a) ((int) a.size()) const long long inf = 4611686018427387903; //2^62 - 1 #if 0 //FileIO const string fileName = ""; ifstream fin ((fileName == "" ? "input.txt" : fileName + ".in" )); ofstream fout((fileName == "" ? "output.txt" : fileName + ".out")); #define get fin>> #define put fout<< #else #define get cin>> #define put cout<< #endif #define eol put endl void read() {} template<typename Arg,typename... Args> void read (Arg& arg,Args&... args){get (arg) ;read(args...) ;} void print(){} template<typename Arg,typename... Args> void print(Arg arg,Args... args){put (arg)<<" ";print(args...);} void debug(){eol;} template<typename Arg,typename... Args> void debug(Arg arg,Args... args){put (arg)<<" ";debug(args...);} int getInt(){int a; get a; return a;} //code goes here const int mod = 1e9 + 7; int solve(str r) { if (sz(r) == 1) return r[0] - '0' + 1; int ans = 0; str dd = "9"; while (sz(dd) + 1 < sz(r)) dd += "9"; ans += solve(dd); int n = sz(r); int dp[n][10]; rep(i, 0, n) { int prob1 = (i ? r[i - 1] - '0' : -1); if (prob1 > r[i] - '0') break; rep(j, 0, 10) { dp[i][j] = 0; if (r[i] - '0' < j || (i + 1 < n && r[i] - '0' == j) || (i == 0 && j == 0)) continue; if (prob1 <= j) dp[i][j] = 1; } rep(p, i + 1, n) rep(j, 0, 10) { dp[p][j] = 0; rep(k, 0, j + 1) dp[p][j] = (dp[p][j] + dp[p - 1][k]) % mod; } rep(j, 0, 10) ans = (ans + dp[n - 1][j]) % mod; } return ans; } int good(str a) { char pr = '0'; for (char i : a) if (i >= pr) pr = i; else return 0; return 1; } void run() { str a, b; read(a, b); put (solve(b) - solve(a) + good(a) + mod) % mod; } int32_t main() {srand(time(0)); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); put fixed; put setprecision(15); run(); return 0;}
2,480
1,029
/** ** Copyright (c) 2011 Illumina, Inc. ** ** ** This software is covered by the "Illumina Non-Commercial Use Software ** and Source Code License Agreement" and any user of this software or ** source file is bound by the terms therein (see accompanying file ** Illumina_Non-Commercial_Use_Software_and_Source_Code_License_Agreement.pdf) ** ** This file is part of the BEETL software package. ** ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone ** Lightweight BWT Construction for Very Large String Collections. ** Proceedings of CPM 2011, pp.219-231 ** **/ #ifndef DEFINED_ALPHABET_HH #define DEFINED_ALPHABET_HH #include "Config.hh" #include "Types.hh" // Convention is that first char is the string terminator char and // is lexicographically less than the rest #ifdef USE_STANDARD_LEXICOGRAPHIC_ORDER static const char alphabet[] = "$ACGNTZ"; static const int whichPileInverse[] = { '$', 'A', 'C', 'G', 'N', 'T', 'Z' }; #else static const char alphabet[] = "$ACGTN"; static const int whichPileInverse[] = { '$', 'A', 'C', 'G', 'T', 'N', 'Z' }; #endif // Type able to contain symbols of the alphabet (in biologic case 6 ($,A,C,G,N,T)) typedef uchar AlphabetSymbol; //static const int alphabetSize(strlen(alphabet)); enum { alphabetSize = 7 }; // Next is a character that should not be in the alphabet // because it gets used as a marker in a couple of places in the code static const char notInAlphabet( 'Z' ); // One of the characters has special status: marks end of a string static const char terminatorChar( '$' ); // One of the characters has special status: 'don't know' character static const char dontKnowChar( 'N' ); const int nv( -1 ); #ifdef USE_STANDARD_LEXICOGRAPHIC_ORDER // encoding is ($,A,C,G,N,T)=(0,1,2,3,4,5) //static const char baseNames [] = "ACGNT"; static const int whichPile[] = { nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 0, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, /* next is 'A' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 4, nv, /* next is 'P' */ nv, nv, nv, nv, 5, nv, nv, nv, nv, nv, 6, nv, nv, nv, nv, nv, // added Z for Huffman nv, /* next is 'a' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 4, nv, /* next is 'p' */ nv, nv, nv, nv, 5, nv, nv, nv, nv, nv, 6, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv }; #else // encoding is ($,A,C,G,T,N)=(0,1,2,3,4,5) //static const char baseNames [] = "ACGTN"; static const int whichPile[] = { nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 0, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, /* next is 'A' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 5, nv, /* next is 'P' */ nv, nv, nv, nv, 4, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, /* next is 'a' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 5, nv, /* next is 'p' */ nv, nv, nv, nv, 4, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv }; #endif // Used by BackTracker classes typedef bool AlphabetFlag[alphabetSize]; #endif
4,424
2,417
#pragma once #include <bits/stdc++.h> using namespace std; // Tropical matrix operations (max plus or min plus) template <typename T> struct tmat { using vec = vector<T>; using unit_type = T; static constexpr T inf = numeric_limits<T>::lowest() / 2; static const T add(const T& a, const T& b) { return max(a, b); } static const T mul(const T& a, const T& b) { return a + b; } int n, m; T* data = nullptr; tmat() : n(0), m(0) {} tmat(int n, int m, const T& v = inf) { assign(n, m, v); } tmat(const tmat& o) : n(o.n), m(o.m), data(new T[n * m]) { copy(o.data, o.data + n * m, data); } tmat(tmat&& o) : tmat() { *this = move(o); } tmat& operator=(const tmat& o) { return *this = tmat(o); } tmat& operator=(tmat&& o) noexcept { using std::swap; swap(n, o.n), swap(m, o.m), swap(data, o.data); return *this; } ~tmat() { delete[] data; } bool operator==(const tmat& o) const { return n == o.n && m == o.m && equal(data, data + n * m, o.data); } bool operator!=(const tmat& o) const { return !(*this == o); } void assign(int n, int m, const T& v) { this->n = n, this->m = m, delete[] data, data = new T[n * m]; std::fill(data, data + n * m, v); } array<int, 2> size() const { return {n, m}; } T* operator[](int x) const { return data + x * m; } T& operator[](array<int, 2> xy) const { return data + (xy[0] * m + xy[1]); } template <typename U> static tmat from(const vector<vector<U>>& vals) { int n = vals.size(), m = n ? vals[0].size() : 0; tmat a(n, m); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = vals[i][j]; return a; } template <typename O = T> friend auto tovec(const tmat& a) { vector<vector<O>> m(a.n, vector<T>(a.m)); for (int i = 0; i < a.n; i++) for (int j = 0; j < a.m; j++) m[i][j] = a[i][j]; return m; } static tmat identity(int n) { tmat a(n, n, inf); for (int i = 0; i < n; i++) a[i][i] = 0; return a; } friend tmat transpose(const tmat& a) { tmat b(a.m, a.n); for (int i = 0; i < a.m; i++) for (int j = 0; j < a.n; j++) b[i][j] = a[j][i]; return b; } friend tmat& operator+=(tmat& a, const tmat& b) { assert(a.size() == b.size() && "Different matrix dimensions"); for (int i = 0, s = a.n * a.m; i < s; i++) a[i] = add(a[i], b[i]); return a; } friend tmat operator*(const tmat& a, const tmat& b) { assert(a.m == b.n && "Invalid proper matrix multiplication"); tmat c(a.n, b.m, inf); for (int i = 0; i < a.n; i++) for (int k = 0; k < a.m; k++) for (int j = 0; j < b.m; j++) c[i][j] = add(c[i][j], mul(a[i][k], b[k][j])); return c; } friend vec operator*(const tmat& a, const vec& b) { assert(a.m == int(b.size()) && "Invalid matrix/vector multiplication"); vec c(a.n, inf); for (int i = 0; i < a.n; i++) for (int j = 0; j < a.m; j++) c[i] = add(c[i], mul(a[i][j], b[j])); return c; } friend tmat operator^(tmat a, int64_t e) { assert(a.n == a.m && "Matrix exp operand is not square"); tmat c = tmat::identity(a.n); while (e > 0) { if (e & 1) c = c * a; if (e >>= 1) a = a * a; } return c; } friend tmat operator+(tmat a, const tmat& b) { return a += b; } tmat operator*=(const tmat& b) { return *this = *this * b; } tmat operator^=(int64_t e) { return *this = *this ^ e; } friend string to_string(const tmat& a) { vector<vector<string>> cell(a.n, vector<string>(a.m)); vector<size_t> w(a.m); for (int i = 0; i < a.n; i++) { for (int j = 0; j < a.m; j++) { using std::to_string; if constexpr (std::is_same<T, string>::value) { cell[i][j] = a[i][j]; } else { cell[i][j] = to_string(a[i][j]); } w[j] = max(w[j], cell[i][j].size()); } } string s; for (int i = 0; i < a.n; i++) { for (int j = 0; j < a.m; j++) { s += string(w[j] + 1 - cell[i][j].size(), ' '); s += cell[i][j]; } s += '\n'; } return s; } friend ostream& operator<<(ostream& out, const tmat& a) { return out << to_string(a); } friend istream& operator>>(istream& in, tmat& a) { for (int i = 0; i < a.n * a.m; i++) in >> a.data[i]; return in; } };
4,899
1,886
#include <glapi.h> #include <device.h> #include <config.h> #include <window.h> #include <GLFW/glfw3.h> #include <GL/gl.h> namespace engine { namespace gfx { Device::Device(Window& wnd): m_log("GFX_DEVICE"), m_window(wnd) { } bool Device::init() { m_log.debug("init"); if (!glapi::init()) { OGL_CHECK_ERRORS(); return false; } glClearColor(0.1f, 0.1f, 0.25f, 1.0f); glClearDepth(1.0f); glDisable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return OGL_CHECK_ERRORS(); } void Device::swapBuffers() { glFinish(); glfwSwapBuffers(m_window.handle()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); OGL_CHECK_ERRORS(); } void Device::onResize(const int width, const int height) { glViewport(0, 0, width, height); OGL_CHECK_ERRORS(); for (auto cb: m_resizeCallbacks) { cb(width, height); } } void Device::registerOnResizeCallback(ResizeCb cb) { m_resizeCallbacks.push_back(cb); } void Device::getFramebufferSize(int* width, int* height) { glfwGetFramebufferSize(m_window.handle(), width, height); } } //gfx } //engine
1,234
522
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*===================================================================== ** ** Source: test2.c ** ** Purpose: Tests that APCs are not executed if a thread never enters an ** alertable state after they are queued. ** ** **===================================================================*/ #include <palsuite.h> const int ChildThreadSleepTime = 2000; const int InterruptTime = 1000; DWORD ChildThread; BOOL InAPC; /* synchronization events */ static HANDLE hSyncEvent1 = NULL; static HANDLE hSyncEvent2 = NULL; /* thread result because we have no GetExitCodeThread() API */ static BOOL bThreadResult = FAIL; VOID PALAPI APCFunc(ULONG_PTR dwParam) { InAPC = TRUE; } DWORD PALAPI SleeperProc(LPVOID lpParameter) { DWORD ret; /* signal the main thread that we're ready to proceed */ if( ! SetEvent( hSyncEvent1 ) ) { Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() ); bThreadResult = FAIL; goto done; } /* wait for notification from the main thread */ ret = WaitForSingleObject( hSyncEvent2, 20000 ); if( ret != WAIT_OBJECT_0 ) { Trace( "ERROR:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); bThreadResult = FAIL; goto done; } /* call our sleep function */ Sleep( ChildThreadSleepTime ); /* success if we reach here */ bThreadResult = PASS; done: /* signal the main thread that we're finished */ if( ! SetEvent( hSyncEvent1 ) ) { Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() ); bThreadResult = FAIL; } /* return success or failure */ return bThreadResult; } int __cdecl main (int argc, char **argv) { /* local variables */ HANDLE hThread = 0; int ret; BOOL bResult = FAIL; /* initialize the PAL */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } InAPC = FALSE; /* create a pair of synchronization events to coordinate our threads */ hSyncEvent1 = CreateEvent( NULL, FALSE, FALSE, NULL ); if( hSyncEvent1 == NULL ) { Trace( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() ); goto cleanup; } hSyncEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL ); if( hSyncEvent2 == NULL ) { Trace( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() ); goto cleanup; } /* create a child thread */ hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)SleeperProc, 0, 0, &ChildThread); if (hThread == NULL) { Trace( "ERROR:%lu:CreateThread() call failed\n", GetLastError()); goto cleanup; } /* wait on our synchronization event to ensure the thread is running */ ret = WaitForSingleObject( hSyncEvent1, 20000 ); if( ret != WAIT_OBJECT_0 ) { Trace( "ERROR:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); goto cleanup; } /* queue a user APC on the child thread */ ret = QueueUserAPC(APCFunc, hThread, 0); if (ret == 0) { Trace( "ERROR:%lu:QueueUserAPC() call failed\n", GetLastError()); goto cleanup; } /* signal the child thread to continue */ if( ! SetEvent( hSyncEvent2 ) ) { Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() ); goto cleanup; } /* wait on our synchronization event to ensure the other thread is done */ ret = WaitForSingleObject( hSyncEvent1, 20000 ); if( ret != WAIT_OBJECT_0 ) { Trace( "ERROR:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); goto cleanup; } /* check that the thread executed successfully */ if( bThreadResult == FAIL ) { goto cleanup; } /* check whether the APC function was executed */ if( InAPC ) { Trace( "FAIL:APC function was executed but shouldn't have been\n" ); goto cleanup; } /* success if we reach here */ bResult = PASS; cleanup: /* wait for the other thread to finish */ if( hThread != NULL ) { ret = WaitForSingleObject( hThread, INFINITE ); if (ret == WAIT_FAILED) { Trace( "ERROR:%lu:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); bResult = FAIL; } } /* close our synchronization handles */ if( hSyncEvent1 != NULL ) { if( ! CloseHandle( hSyncEvent1 ) ) { Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() ); bResult = FAIL; } } if( hSyncEvent2 != NULL ) { if( ! CloseHandle( hSyncEvent2 ) ) { Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() ); bResult = FAIL; } } if( bResult == FAIL ) { Fail( "test failed\n" ); } /* terminate the PAL */ PAL_Terminate(); /* return success */ return PASS; }
5,496
1,728
#include "globals.h" #include "flags.h" #include "writer.h" #include "fluxmap.h" #include "decoders/decoders.h" #include "encoders/encoders.h" #include "sector.h" #include "proto.h" #include "fluxsink/fluxsink.h" #include "fluxsource/fluxsource.h" #include "arch/brother/brother.h" #include "arch/ibm/ibm.h" #include "imagereader/imagereader.h" #include "fluxengine.h" #include "fmt/format.h" #include <google/protobuf/text_format.h> #include <fstream> static FlagGroup flags; static StringFlag sourceImage( { "--input", "-i" }, "source image to read from", "", [](const auto& value) { ImageReader::updateConfigForFilename(config.mutable_image_reader(), value); }); static StringFlag destFlux( { "--dest", "-d" }, "flux destination to write to", "", [](const auto& value) { FluxSink::updateConfigForFilename(config.mutable_flux_sink(), value); FluxSource::updateConfigForFilename(config.mutable_flux_source(), value); }); static StringFlag destCylinders( { "--cylinders", "-c" }, "cylinders to write to", "", [](const auto& value) { setRange(config.mutable_cylinders(), value); }); static StringFlag destHeads( { "--heads", "-h" }, "heads to write to", "", [](const auto& value) { setRange(config.mutable_heads(), value); }); int mainWrite(int argc, const char* argv[]) { if (argc == 1) showProfiles("write", formats); flags.parseFlagsWithConfigFiles(argc, argv, formats); std::unique_ptr<ImageReader> reader(ImageReader::create(config.image_reader())); std::unique_ptr<AbstractEncoder> encoder(AbstractEncoder::create(config.encoder())); std::unique_ptr<FluxSink> fluxSink(FluxSink::create(config.flux_sink())); std::unique_ptr<AbstractDecoder> decoder; if (config.has_decoder()) decoder = AbstractDecoder::create(config.decoder()); std::unique_ptr<FluxSource> fluxSource; if (config.has_flux_source() && config.flux_source().has_drive()) fluxSource = FluxSource::create(config.flux_source()); writeDiskCommand(*reader, *encoder, *fluxSink, decoder.get(), fluxSource.get()); return 0; }
2,057
791
#include "li_wire.h" #include <QDebug> #include "../layout_def.h" #include "li_layer.h" namespace open_edi { namespace gui { LI_Wire::LI_Wire(ScaleFactor* scale_factor) : LI_Base(scale_factor) { item_ = new LGI_Wire; item_->setLiBase(this); pen_.setColor(QColor(0xff, 0, 0, 0xff)); brush_ = QBrush(QColor(0xff, 0, 0, 0xff), Qt::Dense5Pattern); type_ = ObjType::kWire; name_ = kLiWireName; visible_ = true; setZ(0); } LI_Wire::~LI_Wire() { } LGI_Wire* LI_Wire::getGraphicItem() { return item_; } void LI_Wire::draw(QPainter* painter) { painter->setPen(pen_); painter->setBrush(brush_); LI_Base::draw(painter); } void LI_Wire::drawWires(open_edi::db::Wire& wire) { auto layer = dynamic_cast<LI_Layer*>(li_mgr_->getLayerByName(wire.getLayer()->getName())); if (!layer->isVisible()) { return; } QPainter painter(layer->getGraphicItem()->getMap()); pen_.setColor(layer->getColor()); brush_.setColor(layer->getColor()); auto box = __translateDbBoxToQtBox(wire.getBBox()); painter.setBrush(brush_); painter.setPen(pen_); __fillBox(&painter, brush_, box); __drawBox(&painter, box); } void LI_Wire::drawWires(open_edi::db::Wire* wire) { // auto layer = dynamic_cast<LI_Layer*>(li_mgr_->getLayerByName(wire->getLayer()->getName())); // if (!layer->isVisible()) { // return; // } // layer->obj_vectors_.push_back(wire); } bool LI_Wire::isMainLI() { return false; } void LI_Wire::setZ(int z) { z_ = z + (int)(LayerZ::kBase); item_->setZValue(z_); } // namespace gui void LI_Wire::preDraw() { auto net_v = li_mgr_->getLiByName(kLiNetName)->isVisible(); // if (!net_v) { // return; // } // if (!visible_) { // return; // } refreshBoundSize(); refreshItemMap(); std::vector<open_edi::db::Object*> result; open_edi::db::fetchDB(selected_area_, &result); auto factor = *scale_factor_; // printf("COMPONENTS %d ;\n", num_components); setOffset(-selected_area_.getLLX(), -selected_area_.getLLY()); open_edi::db::Wire* wire; QPainter painter; for (auto obj : result) { auto obj_type = obj->getObjectType(); if (open_edi::db::ObjectType::kObjectTypeWire == obj_type) { wire = static_cast<open_edi::db::Wire*>(obj); // drawWires(*wire); drawWires(wire); } if (open_edi::db::ObjectType::kObjectTypeVia == obj_type) { qDebug() << "via"; } } } } // namespace gui } // namespace open_edi
2,594
1,001
#ifndef COCO_COMBIX_COMBINATORS_CHOICE_HPP_ #define COCO_COMBIX_COMBINATORS_CHOICE_HPP_ #include <type_traits> #include <utility> #include <coco/combix/error.hpp> #include <coco/combix/parser_traits.hpp> namespace coco { namespace combix { template <typename... P> struct choice_parser; template <typename P> struct choice_parser<P> { choice_parser(P const& p) : p(p) {} template <typename Stream> parse_result<parse_result_of_t<P, Stream>, Stream> parse(Stream& s) const { return coco::combix::parse(p, s); } template <typename Stream> void add_error(parse_error<Stream>& err) const { p.add_error(err); } private: P p; }; template <typename Head, typename... Tail> struct choice_parser<Head, Tail...> : choice_parser<Tail...> { using base_type = choice_parser<Tail...>; choice_parser(Head const& h, Tail const&... tail) : choice_parser<Tail...>(tail...), p(h) {} template <typename Stream> typename std::enable_if< std::is_same<parse_result_of_t<Head, Stream>, parse_result_of_t<base_type, Stream>>::value, parse_result<parse_result_of_t<Head, Stream>, Stream>>::type parse(Stream& s) const { auto res = coco::combix::parse(p, s); if (res) { return res; } else if (res.unwrap_error().consumed()) { return res.unwrap_error(); } auto tail_res = base_type::parse(s); if (tail_res) { return tail_res; } res.unwrap_error().merge(std::move(tail_res.unwrap_error())); return res.unwrap_error(); } template <typename Stream> void add_error(parse_error<Stream>& err) const { p.add_error(err); base_type::add_error(err); } private: Head p; }; template <typename... Args> choice_parser<std::decay_t<Args>...> choice(Args&&... args) { return choice_parser<std::decay_t<Args>...>(std::forward<Args>(args)...); } } // namespace combix } // namespace coco #endif
2,151
723
#ifndef STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP #define STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP #include <stan/math/torsten/dsolve/pk_vars.hpp> #include <stan/math/torsten/return_type.hpp> #include <boost/math/tools/promotion.hpp> #include <Eigen/Dense> #include <numeric> #include <string> #include <vector> namespace torsten { /* * Raw events record in the form of NONMEN, except that * for the population input @c len consisting of data record * length for each individual. * @tparam T0 type of scalar for time of events. * @tparam T1 type of scalar for amount at each event. * @tparam T2 type of scalar for rate at each event. * @tparam T3 type of scalar for inter-dose inteveral at each event. * @tparam T4 type of scalars for the model parameters. * @tparam T5 type of scalars for the bio-variability parameters. * @tparam T6 type of scalars for the model tlag parameters. */ template <typename T0, typename T1, typename T2, typename T3, typename T4_container, typename T5, typename T6> struct NONMENEventsRecord { using T4 = typename stan::math::value_type<T4_container>::type; using T_scalar = typename torsten::return_t<T0, T1, T2, T3, T4, T5, T6>::type; using T_time = typename torsten::return_t<T0, T1, T3, T6, T2>::type; using T_rate = typename torsten::return_t<T2, T5>::type; using T_amt = typename torsten::return_t<T1, T5>::type; using T_par = T4; using T_par_rate = T2; using T_par_ii = T3; private: const std::vector<int> len_1_; public: const int nev; const int ncmt; std::vector<int> begin_; const std::vector<int>& len_; const int total_num_event_times; const std::vector<T0>& time_; const std::vector<T1>& amt_; const std::vector<T2>& rate_; const std::vector<T3>& ii_; const std::vector<int>& evid_; const std::vector<int>& cmt_; const std::vector<int>& addl_; const std::vector<int>& ss_; const std::vector<T4_container>& pMatrix_; const std::vector<std::vector<T5> >& biovar_; const std::vector<std::vector<T6> >& tlag_; /* * Constructor using population data with parameter give as * matrix, such as in linear ODE models * @param[in] n number of compartments in model * @param[in] len record length for each individual. * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] biovar bioavailability * @param[in] tlag lag time */ template <typename T0_, typename T1_, typename T2_, typename T3_, typename T4_container_, typename T5_, typename T6_> NONMENEventsRecord(int n, const std::vector<int>& len, const std::vector<T0_>& time, const std::vector<T1_>& amt, const std::vector<T2_>& rate, const std::vector<T3_>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<T4_container_>& pMatrix, const std::vector<std::vector<T5_> >& biovar, const std::vector<std::vector<T6_> >& tlag) : len_1_(), nev(time.size()), ncmt(n), begin_(len.size()), len_(len), total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)), time_ (time ), amt_ (amt ), rate_ (rate ), ii_ (ii ), evid_ (evid ), cmt_ (cmt ), addl_ (addl ), ss_ (ss ), pMatrix_(pMatrix), biovar_ (biovar ), tlag_ (tlag ) { begin_[0] = 0; std::partial_sum(len.begin(), len.end() - 1, begin_.begin() + 1); } /* * Constructor using individual data with parameter give as * matrix, such as in linear ODE models * @param[in] n number of compartments in model * @param[in] len record length for each individual. * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] biovar bioavailability * @param[in] tlag lag time */ template <typename T0_, typename T1_, typename T2_, typename T3_, typename T4_container_, typename T5_, typename T6_> NONMENEventsRecord(int n, const std::vector<T0_>& time, const std::vector<T1_>& amt, const std::vector<T2_>& rate, const std::vector<T3_>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<T4_container_>& pMatrix, const std::vector<std::vector<T5_> >& biovar, const std::vector<std::vector<T6_> >& tlag) : len_1_(1, time.size()), nev(time.size()), ncmt(n), begin_{0}, len_(len_1_), total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)), time_ (time ), amt_ (amt ), rate_ (rate ), ii_ (ii ), evid_ (evid ), cmt_ (cmt ), addl_ (addl ), ss_ (ss ), pMatrix_(pMatrix), biovar_ (biovar ), tlag_ (tlag ) {} /* * begin of the parameters for individual @c id * in @c pMatrix. It is assumed that all the paramter are * either constant or time dependent. */ int begin_param(int id) const { return pMatrix_.size() == len_.size() ? id : begin_[id]; } /* * length of the parameters for individual @c id * in @c pMatrix. It is assumed that all the paramter are * either constant or time dependent. */ int len_param(int id) const { return pMatrix_.size() == len_.size() ? 1 : len_[id]; } int begin_biovar(int id) const { return biovar_.size() == len_.size() ? id : begin_[id]; } int len_biovar(int id) const { return biovar_.size() == len_.size() ? 1 : len_[id]; } int begin_tlag(int id) const { return tlag_.size() == len_.size() ? id : begin_[id]; } int len_tlag(int id) const { return tlag_.size() == len_.size() ? 1 : len_[id]; } inline bool has_ss_dosing() const { return has_ss_dosing(0); } /* * check the exisitence of steady state dosing events */ inline bool has_ss_dosing(int id) const { bool res = false; int begin = begin_[id]; int end = size_t(id + 1) == len_.size() ? time_.size() : begin_[id + 1]; for (int i = begin; i < end; ++i) { if ((evid_[i] == 1 || evid_[i] == 4) && ss_[i] != 0) { res = true; break; } } return res; } /* * check for the exisitence of lag time */ bool has_lag(int id) const { using stan::math::value_of; return std::any_of(tlag_.begin() + begin_tlag(id), tlag_.begin() + begin_tlag(id) + len_tlag(id), [](const std::vector<T6>& v) { return std::any_of(v.begin(), v.end(), [](const T6& x) { return std::abs(value_of(x)) > 1.E-10; }); }); } /* * check for the exisitence of lag time */ bool has_lag() const { return has_lag(0); } inline int parameter_size() const { return pMatrix_[0].size(); } inline int num_event_times(int id) const { return len_.at(id); } inline int num_event_times() const { return len_.at(0); } inline int num_subjects() const { return len_.size(); } }; } #endif
8,593
3,025
// ============================================================================ // Copyright (c) 2017-2019, by Vitaly Grigoriev, <Vit.link420@gmail.com>. // This file is part of ProtocolAnalyzer open source project under MIT License. // ============================================================================ #ifndef PROTOCOL_ANALYZER_PARSER_HPP #define PROTOCOL_ANALYZER_PARSER_HPP #include <vector> #include <string_view> namespace analyzer::framework::parser { /** * @class PortsParser Parser.hpp "include/framework/Parser.hpp" * @brief Class that parses the range of ports. */ class PortsParser { private: /** * @brief Variable that contains the current value of range. */ uint16_t rangeState = 0; /** * @brief Variable that contains the last value of range. */ uint16_t rangeEnd = 0; /** * @brief Vector of strings that contains the split values on input. */ std::vector<std::string_view> inputStates = { }; public: /** * @brief Default constructor of PortsParser class. */ PortsParser(void) = default; /** * @brief Default destructor of PortsParser class. */ ~PortsParser(void) = default; PortsParser (PortsParser &&) = delete; PortsParser (const PortsParser &) = delete; PortsParser & operator= (PortsParser &&) = delete; PortsParser & operator= (const PortsParser &) = delete; /** * @brief Static variable that indicates the end of parsing or error. */ static const uint16_t end = 0; /** * @brief Constructor of PortParser class. * @param [in] ports - The sequence of ports listed through a separator. * @param [in] delimiter - The separator. Default: ','. * * @note For example: 80,1-5,433,25-36,90. */ explicit PortsParser (std::string_view /*ports*/, char /*delimiter*/ = ',') noexcept; /** * @brief Method that sets internal state of port parser. * @param [in] ports - The sequence of ports listed through a separator. * @param [in] delimiter - The separator. Default: ','. */ void SetPorts (std::string_view /*ports*/, char /*delimiter*/ = ',') noexcept; /** * @brief Method that gets next port value in input range. * @return Port number or PortsParser::end value if port enumeration is complete or an error occurred. * * @note The program MUST check the return value for PortsParser::end value. */ uint16_t GetNextPort(void) noexcept; }; } // namespace parser. #endif // PROTOCOL_ANALYZER_PARSER_HPP
2,793
804
// // Distributions.cpp // MNN // // Created by MNN on 2019/11/28. // Copyright © 2018, Alibaba Group Holding Limited // #include "Distributions.hpp" #include <cmath> namespace MNN { namespace Train { void Distributions::uniform(const int count, const float min, const float max, float *r, std::mt19937 gen) { std::uniform_real_distribution<float> dis(min, std::nextafter(max, std::numeric_limits<float>::max())); for (int i = 0; i < count; i++) { r[i] = dis(gen); } } void Distributions::gaussian(const int count, const float mu, const float sigma, float *r, std::mt19937 gen) { std::normal_distribution<float> dis(mu, sigma); for (int i = 0; i < count; i++) { r[i] = dis(gen); } } } // namespace Train } // namespace MNN
772
288
// // Construction de VBO // #include "vbobuild.hh" #include "sys/msys.h" #include "sys/msys_debug.h" #include "cube.hh" namespace VBO { // ========================================================================= // Versions pour les hommes, où il faut gérer les indices // Version de base, avec position et taille unsigned int addCubeToChunk(vertex * dest, const vector3f &p, float size, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = dest[count]; dst.p = dst.p * size + p; ++count; } return count; } // Version de base, avec position et couleur unsigned int addCubeToChunk(vertex * dest, const vector3f &p, const vector3f &color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = dest[count]; dst.p += p; dst.r = color.x; dst.g = color.y; dst.b = color.z; ++count; } return count; } // Version de base, avec position et couleur par face unsigned int addCubeToChunk(vertex * dest, const vector3f &p, const vector3f & x1Color, const vector3f & x2Color, const vector3f & y1Color, const vector3f & y2Color, const vector3f & z1Color, const vector3f & z2Color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = dest[count]; dst.p += p; if (i < 4) { dst.r = x1Color.x; dst.g = x1Color.y; dst.b = x1Color.z; } else if (i < 8) { dst.r = x2Color.x; dst.g = x2Color.y; dst.b = x2Color.z; } else if (i < 12) { dst.r = y1Color.x; dst.g = y1Color.y; dst.b = y1Color.z; } else if (i < 16) { dst.r = y2Color.x; dst.g = y2Color.y; dst.b = y2Color.z; } else if (i < 20) { dst.r = z1Color.x; dst.g = z1Color.y; dst.b = z1Color.z; } else { dst.r = z2Color.x; dst.g = z2Color.y; dst.b = z2Color.z; } ++count; } return count; } // Version avec matrice unsigned int addCubeToChunk(vertex * dest, const matrix4 & transform, const vector3f &color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = transformedVertex(transform, dest[count]); dst.r = color.x; dst.g = color.y; dst.b = color.z; ++count; } return count; } // ========================================================================= // Versions équivalentes, à base de tableau void addCube(Array<vertex> &vbo, const vector3f & pos, float size, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { // FIXME : l'assert n'est plus bonne depuis qu'on peut retirer des faces IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, pos, size, x1face, x2face, y1face, y2face, z1face, z2face); } void addCube(Array<vertex> &vbo, const vector3f & pos, const vector3f & color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { // FIXME : l'assert n'est plus bonne depuis qu'on peut retirer des faces IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, pos, color, x1face, x2face, y1face, y2face, z1face, z2face); } void addCube(Array<vertex> &vbo, const vector3f & pos, const vector3f & x1Color, const vector3f & x2Color, const vector3f & y1Color, const vector3f & y2Color, const vector3f & z1Color, const vector3f & z2Color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { // FIXME : l'assert n'est plus bonne depuis qu'on peut retirer des faces IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, pos, x1Color, x2Color, y1Color, y2Color, z1Color, z2Color, x1face, x2face, y1face, y2face, z1face, z2face); } void addCube(Array<vertex> & vbo, const matrix4 & transform, const vector3f & color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, transform, color, x1face, x2face, y1face, y2face, z1face, z2face); } // ========================================================================= // Version last minute VBO service // Si on veut reutiliser le code, attention a la couleur aleatoire. :) void addElements(Array<vertex> & vbo, const Node * tree, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { const Renderable * renderables = tree->visiblePart(); for (int i = 0; i < tree->numberOfRenderables(); ++i) { const Renderable & renderable = renderables[i]; const vector3f color(msys_frand(), 1., 1.); // // FIXME : c'est un mesh qu'on veut ajouter !! // addCube(vbo, tree->localTransform(), color, x1face, x2face, y1face, y2face, z1face, z2face); } const Node * const * children = tree->children(); for (int i = 0; i < tree->numberOfChildren(); ++i) { addElements(vbo, children[i], x1face, x2face, y1face, y2face, z1face, z2face); } } }
7,422
3,162
// MIT License // // Copyright (c) 2020 ADCIRC Development Group // // 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. // // Author: Zach Cobell // Contact: zcobell@thewaterinstitute.org // #include "Preprocessor.h" #include <numeric> #include <utility> #include "Constants.h" #include "Logging.h" #include "Vortex.h" using namespace Gahm; Preprocessor::Preprocessor(Atcf *atcf) : m_data(atcf) {} int Preprocessor::run() { if (m_data->format() == Atcf::ASWIP) { Logging::warning( "You have elected to recompute parameters previously input into the " "code. Input will be overwritten."); } int ierr = 0; ierr = this->calculateOverlandTranslationVelocity(); ierr += this->generateMissingPressureData(); ierr += this->calculateRadii(); ierr += this->computeParameters(); return ierr; } /** * Compute the U/V translational velocities on sphere * @param d1 Previous AtcfLine object * @param d2 Current AtcfLine object * @param[out] uv u-speed * @param[out] vv v-speed * @param[out] uuvv uv-speed * @return error code */ int Preprocessor::uvTrans(const AtcfLine &d1, const AtcfLine &d2, double &uv, double &vv, double &uuvv) { const auto dxdy = Constants::sphericalDx(d1.lon(), d1.lat(), d2.lon(), d2.lat()); const double dt = static_cast<double>(d2.datetime().toSeconds() - d1.datetime().toSeconds()); uv = std::abs(std::get<0>(dxdy) / dt); if (d2.lon() - d1.lon() <= 0.0) uv *= -1.0; vv = std::abs(std::get<1>(dxdy) / dt); if (d2.lat() - d1.lat() <= 0.0) vv *= -1.0; uuvv = std::get<2>(dxdy) / dt; return 0; } /** * Compute the translation velocities for all records in the storm * @return error code */ int Preprocessor::calculateOverlandTranslationVelocity() { for (auto it = m_data->data()->begin() + 1; it != m_data->data()->end(); ++it) { auto r1 = *(it - 1); auto r2 = *(it); double u, v, uv; int ierr = Preprocessor::uvTrans(r1, r2, u, v, uv); if (ierr != 0) { gahm_throw_exception("Error calculating UVTrans"); } if (uv * Units::convert(Units::MetersPerSecond, Units::Knot) < 1.0) { uv = 1.0 * Units::convert(Units::Knot, Units::MetersPerSecond); it->setStormDirection((it - 1)->stormDirection()); } else { double dir = std::atan2(u, v); if (dir < 0.0) dir += Constants::twopi(); it->setStormDirection(dir * Units::convert(Units::Radian, Units::Degree)); } it->setStormTranslationVelocities(u, v, uv); it->setStormSpeed(uv); } m_data->data()->begin()->setStormDirection( (m_data->data()->begin() + 1)->stormDirection()); m_data->data()->begin()->setStormSpeed( (m_data->data()->begin() + 1)->stormSpeed()); auto v = (m_data->data()->begin() + 1)->stormTranslationVelocities(); m_data->data()->begin()->setStormTranslationVelocities( std::get<0>(v), std::get<1>(v), std::get<2>(v)); return 0; } /** * Sets the isotach to have all radii at rmax * @param[inout] radii array of radii in each quadrant * @param[inout] quadFlag flag specifying if the quadrant has data * @param[in] rmax radius to isotach * @param[in] record record number * @param[in] isotach isotach number */ void Preprocessor::setAllRadiiToRmax(CircularArray<double, 4> &radii, CircularArray<bool, 4> &quadFlag, const double rmax, const size_t record, const size_t isotach) { std::fill(quadFlag.begin(), quadFlag.end(), 1); std::fill(radii.begin(), radii.end(), rmax); m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "No isotachs reported. Assuming a constant " "radius (RMAX). Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Sets the radii to half of the sum of the nonzero radii * @param[inout] radii array of radii in each quadrant * @param[in] radiisum sum of available radii * @param[in] record record number * @param[in] isotach isotach number */ void Preprocessor::setMissingRadiiToHalfNonzeroRadii( CircularArray<double, 4> &radii, const double radiisum, const size_t record, const size_t isotach) { Logging::debug("RADII:HALF:: " + std::to_string(radiisum) + " " + std::to_string(radiisum * 0.5)); for (auto i = 0; i < radii.size(); ++i) { if (radii.at(i) == 0.0) radii.set(i, radiisum * 0.5); } m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "One isotach reported. Missing radii are half " "the nonzero radius. Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Sets the missing radii to half of the average of the two specified radii * @param radii array of radii in each quadrant * @param radiisum sum of available radii * @param record record number * @param isotach isotach number */ void Preprocessor::setMissingRadiiToHalfOfAverageSpecifiedRadii( CircularArray<double, 4> &radii, const double radiisum, size_t record, size_t isotach) { Logging::debug( "RADII:HALFAVERAGE:: " + std::to_string(radiisum * Units::convert(Units::Kilometer, Units::NauticalMile)) + " " + std::to_string(radiisum * 0.25 * Units::convert(Units::Kilometer, Units::NauticalMile))); for (auto i = 0; i < radii.size(); ++i) { if (radii.at(i) == 0.0) radii.set(i, radiisum * 0.25); } m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "Two isotachs reported. Missing radii are half " "the average of the nonzero radii, Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Sets the radii to the average of the specified adjacent radii * @param radii array of radii for this isotach * @param lookup_radii radii specified in extended space * @param record record number * @param isotach isotach number */ void Preprocessor::setMissingRadiiToAverageOfAdjacentRadii( CircularArray<double, 4> &radii, size_t record, size_t isotach) { for (long j = 0; j < static_cast<long>(radii.size()); ++j) { if (radii.at(j) == 0.0) { Logging::debug("RADII:AVGADJACENT: " + std::to_string(radii.at(j - 1)) + ", " + std::to_string(radii.at(j + 1)) + ", " + std::to_string((radii.at(j - 1) + radii.at(j + 1)) * 0.5)); radii.set(j, (radii.at(j - 1) + radii.at(j + 1)) * 0.5); } } m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "Three isotachs reported. Missing radius is half " "the nonzero radius on either side. Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Computes the isotach radii values when they are not fully specified by the * Atcf file * @return */ int Preprocessor::calculateRadii() { Logging::debug("Beginning to compute missing radii"); for (auto ait = m_data->data()->begin(); ait != m_data->data()->end(); ++ait) { for (size_t i = 0; i < ait->nIsotach(); ++i) { const double radiisum = std::accumulate(ait->isotach(i).isotachRadius().begin(), ait->isotach(i).isotachRadius().end(), 0.0); ait->isotach(i).generateQuadFlag(); const unsigned int numNonzero = Preprocessor::countNonzeroIsotachs(ait, i); Logging::debug("NumNonzero Isotachs: " + std::to_string(numNonzero) + " " + std::to_string(ait->isotach(i).quadFlag().at(0)) + " " + std::to_string(ait->isotach(i).quadFlag().at(1)) + " " + std::to_string(ait->isotach(i).quadFlag().at(2)) + " " + std::to_string(ait->isotach(i).quadFlag().at(3))); const size_t record = ait - m_data->data()->begin(); switch (numNonzero) { case 0: this->setAllRadiiToRmax(ait->isotach(i).isotachRadius(), ait->isotach(i).quadFlag(), ait->radiusMaxWinds(), record, i); break; case 1: this->setMissingRadiiToHalfNonzeroRadii( ait->isotach(i).isotachRadius(), radiisum, record, i); break; case 2: this->setMissingRadiiToHalfOfAverageSpecifiedRadii( ait->isotach(i).isotachRadius(), radiisum, record, i); break; case 3: this->setMissingRadiiToAverageOfAdjacentRadii( ait->isotach(i).isotachRadius(), record, i); break; case 4: //...No missing radii break; default: gahm_throw_exception("Number of radii specified is not applicable"); break; } } } return 0; } unsigned Preprocessor::countNonzeroIsotachs( const std::vector<AtcfLine>::iterator &ait, size_t i) { unsigned numNonzero = 0; for (auto j = 0; j < 4; ++j) { if (ait->isotach(i).quadFlag().at(j)) { numNonzero++; } } return numNonzero; } /** * Computes any missing pressure values in the specified Atcf data using the * specified method * @param[in] method method to use for hurricane pressure * @return error code */ int Preprocessor::generateMissingPressureData( const HurricanePressure::PressureMethod &method) { HurricanePressure hp(method); double vmax_global = 0.0; for (auto it = m_data->data()->begin(); it != m_data->data()->end(); ++it) { vmax_global = std::max(vmax_global, it->vmax()); if (it->centralPressure() <= 0.0) { if (it == m_data->data()->begin()) { it->setCentralPressure( HurricanePressure::computeInitialPressureEstimate(it->vmax())); m_data->assumptions()->add(generate_assumption( Assumption::MINOR, "Pressure data was assumed using initial " "pressure estimate method. Record " + std::to_string(it - m_data->data()->begin()))); } else { it->setCentralPressure(hp.computePressure( it->vmax(), vmax_global, (it - 1)->vmax(), (it - 1)->centralPressure(), it->lat(), it->uvTrans())); m_data->assumptions()->add(generate_assumption( Assumption::MINOR, "Pressure was computed as " + std::to_string(it->centralPressure()) + "mb using vmax=" + std::to_string(it->vmax()) + "m/s, vmax_global=" + std::to_string(vmax_global) + "m/s, previous_pressure=" + std::to_string((it - 1)->centralPressure()) + "mb, lat=" + std::to_string(it->lat()) + ", speed=" + std::to_string(it->uvTrans()) + "m/s, with method=" + HurricanePressure::pressureMethodString(hp.pressureMethod()) + " for record " + std::to_string(it - m_data->data()->begin()))); } } } return 0; } int Preprocessor::computeParameters() { size_t rec_counter = 0; for (auto &a : *(m_data->data())) { //...Compute the global parameters for this period in the storm const auto stormMotion = Preprocessor::computeStormMotion(a.stormSpeed(), a.stormDirection()); a.setVmaxBl(Preprocessor::computeVMaxBL(a.vmax(), stormMotion.uv)); a.setHollandB(Constants::calcHollandB(a.vmaxBl(), a.centralPressure(), Constants::backgroundPressure())); for (size_t i = 0; i < a.nIsotach(); ++i) { rec_counter++; //...Check if the isotach is zero const double vr = a.isotach(i).windSpeed() == 0.0 ? a.vmax() : a.isotach(i).windSpeed(); //...Compute the inward rotation angles const std::array<double, 4> quadRotateAngle = Preprocessor::computeQuadRotateAngle(a, i); //...Initialize the flag that checks for violations in vmax vs vmaxbl std::array<bool, 4> vmwBLflag = {false, false, false, false}; //...Fill the holland b and phi in all quadrants for this isotach a.isotach(i).hollandB().fill(a.hollandB()); a.isotach(i).phi().fill(1.0); //...Converge inward rotation angle Preprocessor::convergeInwardRotationAngle(rec_counter, i, a, stormMotion, vr, quadRotateAngle, vmwBLflag); } } return 0; } void Preprocessor::convergeInwardRotationAngle( size_t rec_counter, size_t i, AtcfLine &a, const Preprocessor::StormMotion &stormMotion, const double vr, const std::array<double, 4> &quadRotateAngle, std::array<bool, 4> &vmwBLflag) const { const size_t nquadrotat = i == 0 ? 300 : 1; // const size_t nquadrotat = 1; for (auto j = 0; j < nquadrotat; ++j) { Preprocessor::computeQuadrantVrLoop(j, quadRotateAngle, vmwBLflag, a.vmaxBl(), vr, stormMotion, a.isotach(i)); Preprocessor::recomputeQuadrantVrLoop(j, quadRotateAngle, vmwBLflag, a.vmaxBl(), vr, a.stormDirection(), stormMotion, a.isotach(i)); //...Create a new vortex object and compute the radius to max wind // in each quadrant of the storm Vortex v(&a, rec_counter, i, m_data->assumptions_sharedptr()); v.computeRadiusToWind(); } } std::array<double, 4> Preprocessor::computeQuadRotateAngle(const AtcfLine &a, size_t i) { constexpr double initial_quadRotateAngle = 25.0 * Units::convert(Units::Degree, Units::Radian); std::array<double, 4> quadRotateAngle{ initial_quadRotateAngle, initial_quadRotateAngle, initial_quadRotateAngle, initial_quadRotateAngle}; if (i > 0) { for (auto j = 0; j < 4; ++j) { quadRotateAngle[j] = Constants::frictionAngle( a.isotach(i).isotachRadius().at(j), a.isotach(i).rmax().at(j)); } } return quadRotateAngle; } void Preprocessor::computeQuadrantVrLoop( const size_t quadrotindex, const std::array<double, 4> &quadRotateAngle, const std::array<bool, 4> &vmwBLflag, const double vmaxBL, const double vr, const StormMotion &stormMotion, Isotach &isotach) { for (auto k = 0; k < 4; ++k) { const double quadrantVectorAngle = Preprocessor::computeQuadrantVectorAngle(k, quadRotateAngle); if (quadrotindex == 0 || !vmwBLflag[k]) { const double qvr = Preprocessor::computeQuadrantVrValue( vmaxBL, quadrantVectorAngle, stormMotion, vr); isotach.quadrantVr().set(k, qvr); } } } double Preprocessor::computeQuadrantVrValue(const double vmaxBL, const double quadrantVectorAngles, const StormMotion &stormMotion, const double vr) { const double epsilonAngle = Preprocessor::computeEpsilonAngle( vmaxBL, quadrantVectorAngles, stormMotion); const double uvr = vr * std::cos(epsilonAngle); const double vvr = vr * std::sin(epsilonAngle); const double gamma = Preprocessor::computeGamma(uvr, vvr, vr, stormMotion, vmaxBL); constexpr double mps2kt = Units::convert(Units::MetersPerSecond, Units::Knot); const double qvr = std::sqrt(std::pow(uvr * mps2kt - gamma * stormMotion.u * mps2kt, 2.0) + std::pow(vvr * mps2kt - gamma * stormMotion.v * mps2kt, 2.0)) / Constants::windReduction(); return qvr * Units::convert(Units::Knot, Units::MetersPerSecond); } void Preprocessor::recomputeQuadrantVrLoop( const size_t quadrotindex, const std::array<double, 4> &quadRotateAngle, std::array<bool, 4> &vmwBLflag, const double vmaxBL, const double vr, const double stormDirection, const StormMotion &stormMotion, Isotach &isotach) { constexpr double deg2rad = Units::convert(Units::Degree, Units::Radian); for (auto k = 0; k < 4; ++k) { if (isotach.quadrantVr().at(k) > vmaxBL || vmwBLflag[k]) { if (quadrotindex == 1) vmwBLflag[k] = true; if (!isotach.isotachRadiusNullInInput().at(k)) { const double quadrantVectorAngle = Preprocessor::computeQuadrantVectorAngle(k, quadRotateAngle); double qvr = Preprocessor::computeQuadrantVrValue(quadrantVectorAngle, stormMotion, vr); qvr /= Constants::windReduction(); isotach.quadrantVr().set(k, qvr); isotach.vmaxBl().set(k, qvr); } else { isotach.vmaxBl().set(k, vmaxBL); const double uvr = vr * std::cos(stormDirection * deg2rad); const double vvr = vr * std::sin(stormDirection * deg2rad); const double gamma = Preprocessor::computeGamma(uvr, vvr, vr, stormMotion, vmaxBL); const double qvr2 = (vr - gamma * stormMotion.uv) / Constants::windReduction(); isotach.quadrantVr().set(k, qvr2); } } else { isotach.vmaxBl().set(k, vmaxBL); } } } double Preprocessor::computeQuadrantVrValue(const double quadrantVectorAngle, const StormMotion &stormMotion, const double vr) { constexpr double mps2kt = Units::convert(Units::MetersPerSecond, Units::Knot); const double qvr_1 = (stormMotion.u * mps2kt * std::cos(quadrantVectorAngle) + stormMotion.v * mps2kt * std::sin(quadrantVectorAngle)); const double qvr = (-2.0 * qvr_1 + std::sqrt(4.0 * std::pow(qvr_1, 2.0) - 4.0 * (std::pow(stormMotion.uv * mps2kt, 2.0) - std::pow(vr * mps2kt, 2.0)))) / 2.0; return qvr * Units::convert(Units::Knot, Units::MetersPerSecond); } double Preprocessor::computeGamma(const double uvr, const double vvr, const double vr, const StormMotion &stormMotion, const double vmaxBL) { constexpr double ms2kt = Units::convert(Units::MetersPerSecond, Units::Knot); const double g0 = (2.0 * uvr * ms2kt * stormMotion.u * ms2kt + 2.0 * vvr * ms2kt * stormMotion.v * ms2kt); const double g1 = std::pow(g0, 2.0); const double g2 = 4.0 * (std::pow(stormMotion.uv * ms2kt, 2.0) - std::pow(vmaxBL * ms2kt, 2.0) * Constants::windReduction() * Constants::windReduction()); const double g3 = std::pow(vr * ms2kt, 2.0); const double g4 = 2.0 * (std::pow(stormMotion.uv * ms2kt, 2.0) - std::pow(vmaxBL * ms2kt, 2.0) * Constants::windReduction() * Constants::windReduction()); double g = (g0 - std::sqrt(g1 - g2 * g3)) / g4; g = std::max(std::min(g, 1.0), 0.0); return g; } double Preprocessor::computeEpsilonAngle(const double velocity, const double quadrantVectorAngle, const StormMotion &stormMotion) { double e = Constants::twopi() + std::atan2(velocity * std::sin(quadrantVectorAngle) + stormMotion.v, velocity * std::cos(quadrantVectorAngle) + stormMotion.u); if (e > Constants::twopi()) e -= Constants::twopi(); return e; } Preprocessor::StormMotion Preprocessor::computeStormMotion( const double speed, const double direction) { double stormMotion = 1.5 * std::pow(speed * Units::convert(Units::MetersPerSecond, Units::Knot), 0.63) * Units::convert(Units::Knot, Units::MetersPerSecond); double stormMotionU = std::sin(direction * Units::convert(Units::Degree, Units::Radian)) * stormMotion; double stormMotionV = std::cos(direction * Units::convert(Units::Degree, Units::Radian)) * stormMotion; return {stormMotionU, stormMotionV, stormMotion}; } double Preprocessor::computeVMaxBL(const double vmax, const double stormMotion) { return (vmax - stormMotion) / Constants::windReduction(); } double Preprocessor::computeQuadrantVectorAngle( const size_t index, const std::array<double, 4> quadRotateAngle) { assert(index < 4); return Constants::quadrantAngle(index) + (Constants::halfpi() + quadRotateAngle[index]); }
21,402
7,267
#include "Python.h" #include "x11.h" #define DEBUG_ASSERT(cond) \ if(!(cond)) \ { \ fprintf(stderr, "Assert: %s | Function: %s\n", #cond, __FUNCTION__); \ assert(0); \ } static PyObject* x11_hash_wrapper(PyObject *self, PyObject *args) { char* input_data; int input_data_len; char hash_data[32]; char* p = (char*)hash_data; int hash_data_len = 32; DEBUG_ASSERT(args != NULL); PyArg_ParseTuple(args, "s#" , &input_data, &input_data_len); DEBUG_ASSERT(input_data != NULL); x11_hash(input_data, p, input_data_len); PyObject* resultObject = Py_BuildValue("s#", hash_data, hash_data_len); return resultObject; } static PyMethodDef x11_methods[] = { {"x11_hash", x11_hash_wrapper, METH_VARARGS, "x11_hash(input_data)"}, {NULL, NULL, 0, NULL} }; extern "C" { void initpyX11(void) { Py_InitModule("pyX11", x11_methods); } }
899
375
/* Copyright (c) 2020 Xavier Leclercq Released under the MIT License See https://github.com/Ishiko-cpp/Terminal/blob/master/LICENSE.txt */ #include "TerminalOutputTests.h" #include "Ishiko/Terminal/TerminalOutput.h" #include <Ishiko/Process/CurrentProcess.h> #include <boost/filesystem/operations.hpp> using namespace Ishiko::Terminal; using namespace Ishiko::Tests; TerminalOutputTests::TerminalOutputTests(const TestNumber& number, const TestEnvironment& environment) : TestSequence(number, "TerminalOutput tests", environment) { append<HeapAllocationErrorsTest>("Construction test 1", ConstructionTest1); append<FileComparisonTest>("write test 1", WriteTest1); append<FileComparisonTest>("write test 2", WriteTest2); append<FileComparisonTest>("write test 3", WriteTest3); append<FileComparisonTest>("write test 4", WriteTest4); } void TerminalOutputTests::ConstructionTest1(Test& test) { TerminalOutput output(stdout); ISHTF_PASS(); } void TerminalOutputTests::WriteTest1(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest1.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest1.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); output.write("text"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); } void TerminalOutputTests::WriteTest2(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest2.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest2.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); std::string text = "text"; output.write(text); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); } void TerminalOutputTests::WriteTest3(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest3.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest3.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); output.write("text", Ishiko::Color::eRed); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); } void TerminalOutputTests::WriteTest4(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest4.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest4.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); std::string text = "text"; output.write(text, Ishiko::Color::eRed); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); }
3,636
1,068
// xcharconv.h internal header // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception //~ #pragma once #ifndef _XCHARCONV_H #define _XCHARCONV_H //~ #include <yvals_core.h> //~ #if _STL_COMPILER_PREPROCESSOR //~ #include <cstdint> //~ #include <type_traits> //~ #include <xerrc.h> #if 0 //~#if !_HAS_CXX17 #error The contents of <charconv> are only available with C++17. (Also, you should not include this internal header.) #endif // !_HAS_CXX17 //~ #pragma pack(push, _CRT_PACKING) //~ #pragma warning(push, _STL_WARNING_LEVEL) //~ #pragma warning(disable : _STL_DISABLED_WARNINGS) //~ _STL_DISABLE_CLANG_WARNINGS //~ #pragma push_macro("new") //~ #undef new //~ _STD_BEGIN enum class chars_format { scientific = 0b001, fixed = 0b010, hex = 0b100, general = fixed | scientific, }; //~ _BITMASK_OPS(chars_format) struct to_chars_result { char* ptr; std::errc ec; #if 0 //~#if _HAS_CXX20 [[nodiscard]] friend bool operator==(const to_chars_result&, const to_chars_result&) = default; #endif // _HAS_CXX20 }; //~ _STD_END //~ #pragma pop_macro("new") //~ _STL_RESTORE_CLANG_WARNINGS //~ #pragma warning(pop) //~ #pragma pack(pop) //~ #endif // _STL_COMPILER_PREPROCESSOR #endif // _XCHARCONV_H
1,290
550
#ifdef NALL_STRING_INTERNAL_HPP namespace nall { template<bool Insensitive> bool chrequal(char x, char y) { if(Insensitive) return chrlower(x) == chrlower(y); return x == y; } template<bool Quoted, typename T> bool quoteskip(T*& p) { if(Quoted == false) return false; if(*p != '\'' && *p != '\"') return false; while(*p == '\'' || *p == '\"') { char x = *p++; while(*p && *p++ != x); } return true; } template<bool Quoted, typename T> bool quotecopy(char*& t, T*& p) { if(Quoted == false) return false; if(*p != '\'' && *p != '\"') return false; while(*p == '\'' || *p == '\"') { char x = *p++; *t++ = x; while(*p && *p != x) *t++ = *p++; *t++ = *p++; } return true; } } #endif
734
310
// // Button.cpp // // Created by Aleksey on 19.11.2020. // #include "Button.hpp" #include <2d/CCSprite.h> #include <2d/CCCamera.h> #include <base/CCDirector.h> #include <base/CCEventDispatcher.h> #include <base/CCEventListenerTouch.h> #include <base/CCEventCustom.h> using namespace custom_ui; Button* Button::create() { if (auto button = new (std::nothrow) Button) { button->autorelease(); return button; } return nullptr; } Button* Button::create(const std::string& normal, const std::string& pressed, const std::string& dragout) { if (auto button = Button::create()) return button->setNormalImage(normal)->setPressedImage(pressed)->setDragoutImage(dragout); return nullptr; } Button* Button::create(const std::string& normal, const std::string& pressed, const std::string& dragout, const buttonCallback& callback) { if (auto button = Button::create(normal, pressed, dragout)) return button->setPressedCallback(callback); return nullptr; } Button* Button::setNormalImage(const std::string& file) { if (auto sprite = cocos2d::Sprite::create(file)) { if (auto old = m_stateView.find(eButtonState::IDLE); old != m_stateView.end()) this->removeChild(old->second); m_stateView.insert_or_assign(eButtonState::IDLE, sprite); m_stateView.try_emplace(eButtonState::PRESSED, sprite); m_stateView.try_emplace(eButtonState::DRAGOUT, sprite); addChild(sprite); setExpandZone(getContentSize()); setSafeZone(getContentSize()); sprite->setVisible(true); sprite->setAnchorPoint({0.5f, 0.5f}); } return this; } Button* Button::setPressedImage(const std::string& file) { if (auto sprite = cocos2d::Sprite::create(file)) { if (auto old_idle = m_stateView.find(eButtonState::IDLE); old_idle != m_stateView.end()) { if (auto old = m_stateView.find(eButtonState::PRESSED); old != m_stateView.end()) { if (old->second != old_idle->second) this->removeChild(old->second); } } m_stateView.insert_or_assign(eButtonState::PRESSED, sprite); addChild(sprite); sprite->setVisible(false); sprite->setAnchorPoint({0.5f, 0.5f}); } return this; } Button* Button::setDragoutImage(const std::string& file) { if (auto sprite = cocos2d::Sprite::create(file)) { if (auto old_idle = m_stateView.find(eButtonState::IDLE); old_idle != m_stateView.end()) { if (auto old = m_stateView.find(eButtonState::DRAGOUT); old != m_stateView.end()) { if (old->second != old_idle->second) this->removeChild(old->second); } } m_stateView.insert_or_assign(eButtonState::DRAGOUT, sprite); addChild(sprite); sprite->setVisible(false); sprite->setAnchorPoint({0.5f, 0.5f}); } return this; } Button* Button::setPressedCallback(buttonCallback callback) { m_callback = callback; return this; } void Button::setSafeZone(cocos2d::Size zone) { auto content_size = getContentSize(); m_safeZone.width = content_size.width > zone.width ? content_size.width : zone.width; m_safeZone.height = content_size.height > zone.height ? content_size.height : zone.height; return this; } void Button::setExpandZone(cocos2d::Size zone) { auto content_size = getContentSize(); m_expandZone.width = content_size.width > zone.width ? content_size.width : zone.width; m_expandZone.height = content_size.height > zone.height ? content_size.height : zone.height; return this; } const cocos2d::Size& Button::getContentSize() const { if (auto it = m_stateView.find(eButtonState::IDLE); it != m_stateView.end()) return it->second->getContentSize(); return cocos2d::Node::getContentSize(); } cocos2d::Node* Button::getNormalNode() const { return getStateNode(eButtonState::IDLE); } cocos2d::Node* Button::getPressedNode() const { return getStateNode(eButtonState::PRESSED); } cocos2d::Node* Button::getDragoutNode() const { return getStateNode(eButtonState::DRAGOUT); } bool Button::isPressed() const { return m_currentState == eButtonState::PRESSED; } Button::Button() noexcept { setAnchorPoint({0.5f, 0.5f}); auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); auto listener = cocos2d::EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(Button::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(Button::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(Button::onTouchEnded, this); dispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void Button::sendEvent(ButtonEventData_t data) { cocos2d::EventCustom event(data.event_name); event.setUserData(&data); _eventDispatcher->dispatchEvent(&event); if (m_callback) m_callback(this); } void Button::setState(eButtonState next_state) { for (const auto& [state, node] : m_stateView) node->setVisible(state == next_state); m_currentState = next_state; } bool Button::touchTest(cocos2d::Rect rect, cocos2d::Point point) { return isScreenPointInRect(point, cocos2d::Camera::getVisitingCamera(), getWorldToNodeTransform(), rect, nullptr); } bool Button::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event) { auto touch_pos = touch->getLocation(); cocos2d::Rect base_rect{getNormalNode()->getPosition() - getContentSize() / 2.f, getContentSize()}; cocos2d::Rect expand_rect{getNormalNode()->getPosition() - m_expandZone / 2.f, m_expandZone}; if (touchTest(base_rect, touch_pos) || touchTest(expand_rect, touch_pos)) { setState(eButtonState::PRESSED); return true; } return false; } void Button::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event) { auto touch_pos = touch->getLocation(); cocos2d::Rect base_rect{getNormalNode()->getPosition() - getContentSize() / 2.f, getContentSize()}; cocos2d::Rect expand_rect{getNormalNode()->getPosition() - m_expandZone / 2.f, m_expandZone}; cocos2d::Rect safe_rect{getNormalNode()->getPosition() - m_safeZone / 2.f, m_safeZone}; if (touchTest(base_rect, touch_pos) || touchTest(expand_rect, touch_pos)) { if (m_currentState != eButtonState::PRESSED) setState(eButtonState::PRESSED); } else if (touchTest(safe_rect, touch_pos)) { if (m_currentState != eButtonState::DRAGOUT) setState(eButtonState::DRAGOUT); } else { setState(eButtonState::IDLE); } } void Button::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event) { if (isPressed()) sendEvent({this, press_event_name}); setState(eButtonState::IDLE); } cocos2d::Node* Button::getStateNode(eButtonState state) const { if (auto it = m_stateView.find(state); it != m_stateView.end()) return it->second; return nullptr; }
7,264
2,464
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "SpatialGDKEditorSettings.h" #include "Dom/JsonObject.h" #include "Internationalization/Regex.h" #include "ISettingsModule.h" #include "Misc/FileHelper.h" #include "Misc/MessageDialog.h" #include "Modules/ModuleManager.h" #include "Serialization/JsonReader.h" #include "Serialization/JsonSerializer.h" #include "Settings/LevelEditorPlaySettings.h" #include "Templates/SharedPointer.h" #include "SpatialConstants.h" #include "SpatialGDKSettings.h" USpatialGDKEditorSettings::USpatialGDKEditorSettings(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , bShowSpatialServiceButton(false) , bDeleteDynamicEntities(true) , bGenerateDefaultLaunchConfig(true) , bStopSpatialOnExit(false) , bAutoStartLocalDeployment(true) , PrimaryDeploymentRegionCode(ERegionCode::US) , SimulatedPlayerLaunchConfigPath(FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectDir() / TEXT("Plugins/UnrealGDK/SpatialGDK/Build/Programs/Improbable.Unreal.Scripts/WorkerCoordinator/SpatialConfig/cloud_launch_sim_player_deployment.json")))) , SimulatedPlayerDeploymentRegionCode(ERegionCode::US) { SpatialOSLaunchConfig.FilePath = GetSpatialOSLaunchConfig(); SpatialOSSnapshotFile = GetSpatialOSSnapshotFile(); ProjectName = GetProjectNameFromSpatial(); } void USpatialGDKEditorSettings::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent) { Super::PostEditChangeProperty(PropertyChangedEvent); // Use MemberProperty here so we report the correct member name for nested changes const FName Name = (PropertyChangedEvent.MemberProperty != nullptr) ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None; if (Name == GET_MEMBER_NAME_CHECKED(USpatialGDKEditorSettings, bDeleteDynamicEntities)) { ULevelEditorPlaySettings* PlayInSettings = GetMutableDefault<ULevelEditorPlaySettings>(); PlayInSettings->SetDeleteDynamicEntities(bDeleteDynamicEntities); PlayInSettings->PostEditChange(); PlayInSettings->SaveConfig(); } else if (Name == GET_MEMBER_NAME_CHECKED(USpatialGDKEditorSettings, LaunchConfigDesc)) { SetRuntimeWorkerTypes(); SetLevelEditorPlaySettingsWorkerTypes(); } } void USpatialGDKEditorSettings::PostInitProperties() { Super::PostInitProperties(); ULevelEditorPlaySettings* PlayInSettings = GetMutableDefault<ULevelEditorPlaySettings>(); PlayInSettings->SetDeleteDynamicEntities(bDeleteDynamicEntities); PlayInSettings->PostEditChange(); PlayInSettings->SaveConfig(); SetRuntimeWorkerTypes(); SetLevelEditorPlaySettingsWorkerTypes(); } void USpatialGDKEditorSettings::SetRuntimeWorkerTypes() { TSet<FName> WorkerTypes; for (const FWorkerTypeLaunchSection& WorkerLaunch : LaunchConfigDesc.ServerWorkers) { if (WorkerLaunch.WorkerTypeName != NAME_None) { WorkerTypes.Add(WorkerLaunch.WorkerTypeName); } } USpatialGDKSettings* RuntimeSettings = GetMutableDefault<USpatialGDKSettings>(); if (RuntimeSettings != nullptr) { RuntimeSettings->ServerWorkerTypes.Empty(WorkerTypes.Num()); RuntimeSettings->ServerWorkerTypes.Append(WorkerTypes); RuntimeSettings->PostEditChange(); RuntimeSettings->SaveConfig(CPF_Config, *RuntimeSettings->GetDefaultConfigFilename()); } } void USpatialGDKEditorSettings::SetLevelEditorPlaySettingsWorkerTypes() { ULevelEditorPlaySettings* PlayInSettings = GetMutableDefault<ULevelEditorPlaySettings>(); PlayInSettings->WorkerTypesToLaunch.Empty(LaunchConfigDesc.ServerWorkers.Num()); for (const FWorkerTypeLaunchSection& WorkerLaunch : LaunchConfigDesc.ServerWorkers) { PlayInSettings->WorkerTypesToLaunch.Add(WorkerLaunch.WorkerTypeName, WorkerLaunch.NumEditorInstances); } } FString USpatialGDKEditorSettings::GetProjectNameFromSpatial() const { FString FileContents; const FString SpatialOSFile = FSpatialGDKServicesModule::GetSpatialOSDirectory().Append(TEXT("/spatialos.json")); if (!FFileHelper::LoadFileToString(FileContents, *SpatialOSFile)) { return TEXT(""); } TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(FileContents); TSharedPtr<FJsonObject> JsonObject; if (FJsonSerializer::Deserialize(Reader, JsonObject)) { return JsonObject->GetStringField("name"); } return FString(); } bool USpatialGDKEditorSettings::IsAssemblyNameValid(const FString& Name) { const FRegexPattern AssemblyPatternRegex(SpatialConstants::AssemblyPattern); FRegexMatcher RegMatcher(AssemblyPatternRegex, Name); return RegMatcher.FindNext(); } bool USpatialGDKEditorSettings::IsProjectNameValid(const FString& Name) { const FRegexPattern ProjectPatternRegex(SpatialConstants::ProjectPattern); FRegexMatcher RegMatcher(ProjectPatternRegex, Name); return RegMatcher.FindNext(); } bool USpatialGDKEditorSettings::IsDeploymentNameValid(const FString& Name) { const FRegexPattern DeploymentPatternRegex(SpatialConstants::DeploymentPattern); FRegexMatcher RegMatcher(DeploymentPatternRegex, Name); return RegMatcher.FindNext(); } bool USpatialGDKEditorSettings::IsRegionCodeValid(const ERegionCode::Type RegionCode) { UEnum* pEnum = FindObject<UEnum>(ANY_PACKAGE, TEXT("ERegionCode"), true); return pEnum != nullptr && pEnum->IsValidEnumValue(RegionCode); } void USpatialGDKEditorSettings::SetPrimaryDeploymentName(const FString& Name) { PrimaryDeploymentName = Name; SaveConfig(); } void USpatialGDKEditorSettings::SetAssemblyName(const FString& Name) { AssemblyName = Name; SaveConfig(); } void USpatialGDKEditorSettings::SetProjectName(const FString& Name) { ProjectName = Name; SaveConfig(); } void USpatialGDKEditorSettings::SetPrimaryLaunchConfigPath(const FString& Path) { PrimaryLaunchConfigPath.FilePath = FPaths::ConvertRelativePathToFull(Path); SaveConfig(); } void USpatialGDKEditorSettings::SetSnapshotPath(const FString& Path) { SnapshotPath.FilePath = FPaths::ConvertRelativePathToFull(Path); SaveConfig(); } void USpatialGDKEditorSettings::SetPrimaryRegionCode(const ERegionCode::Type RegionCode) { PrimaryDeploymentRegionCode = RegionCode; } void USpatialGDKEditorSettings::SetSimulatedPlayerRegionCode(const ERegionCode::Type RegionCode) { SimulatedPlayerDeploymentRegionCode = RegionCode; } void USpatialGDKEditorSettings::SetSimulatedPlayersEnabledState(bool IsEnabled) { bSimulatedPlayersIsEnabled = IsEnabled; SaveConfig(); } void USpatialGDKEditorSettings::SetSimulatedPlayerDeploymentName(const FString& Name) { SimulatedPlayerDeploymentName = Name; SaveConfig(); } void USpatialGDKEditorSettings::SetNumberOfSimulatedPlayers(uint32 Number) { NumberOfSimulatedPlayers = Number; SaveConfig(); } bool USpatialGDKEditorSettings::IsDeploymentConfigurationValid() const { bool result = IsAssemblyNameValid(AssemblyName) && IsDeploymentNameValid(PrimaryDeploymentName) && IsProjectNameValid(ProjectName) && !SnapshotPath.FilePath.IsEmpty() && !PrimaryLaunchConfigPath.FilePath.IsEmpty() && IsRegionCodeValid(PrimaryDeploymentRegionCode); if (IsSimulatedPlayersEnabled()) { result = result && IsDeploymentNameValid(SimulatedPlayerDeploymentName) && !SimulatedPlayerLaunchConfigPath.IsEmpty() && IsRegionCodeValid(SimulatedPlayerDeploymentRegionCode); } return result; }
7,201
2,280
/* * This file is part of the MiniPython project, http://minipython.org/ * * The MIT License (MIT) * * Copyright (c) 2015-2017 Kevin Thomas * * 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 "microbit/microbitdal.h" extern "C" { #include "py/runtime.h" #include "microbit/modmicrobit.h" typedef struct _microbit_i2c_obj_t { mp_obj_base_t base; MiniPythonI2C *i2c; } microbit_i2c_obj_t; STATIC mp_obj_t microbit_i2c_init(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_freq, MP_ARG_INT, {.u_int = 100000} }, { MP_QSTR_sda, MP_ARG_OBJ, {.u_obj = mp_const_none } }, { MP_QSTR_scl, MP_ARG_OBJ, {.u_obj = mp_const_none } }, }; // parse args microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)pos_args[0]; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); PinName p_sda = I2C_SDA0; PinName p_scl = I2C_SCL0; if (args[1].u_obj != mp_const_none) { p_sda = (PinName)microbit_obj_get_pin_name(args[1].u_obj); } if (args[2].u_obj != mp_const_none) { p_scl = (PinName)microbit_obj_get_pin_name(args[2].u_obj); } self->i2c->set_pins(p_sda, p_scl); self->i2c->frequency(args[0].u_int); // Call underlying mbed i2c_reset to reconfigure the pins and reset the peripheral i2c_reset(self->i2c->get_i2c_obj()); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(microbit_i2c_init_obj, 1, microbit_i2c_init); // Probe the given I2C address with an empty write to see if a device responds with an ACK STATIC bool i2c_probe(i2c_t *obj, uint8_t address) { obj->i2c->ADDRESS = address; obj->i2c->SHORTS = 0; obj->i2c->TASKS_STARTTX = 1; obj->i2c->EVENTS_STOPPED = 0; obj->i2c->TASKS_STOP = 1; uint32_t timeout = 10000; while (!obj->i2c->EVENTS_STOPPED && timeout > 0) { --timeout; } bool ack = timeout > 0 && obj->i2c->ERRORSRC == 0; i2c_reset(obj); return ack; } STATIC mp_obj_t microbit_i2c_scan(mp_obj_t self_in) { microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)MP_OBJ_TO_PTR(self_in); i2c_t *obj = self->i2c->get_i2c_obj(); mp_obj_t list = mp_obj_new_list(0, NULL); // 7-bit addresses 0b0000xxx and 0b1111xxx are reserved for (int addr = 0x08; addr < 0x78; ++addr) { if (i2c_probe(obj, addr)) { mp_obj_list_append(list, MP_OBJ_NEW_SMALL_INT(addr)); } } return list; } MP_DEFINE_CONST_FUN_OBJ_1(microbit_i2c_scan_obj, microbit_i2c_scan); STATIC mp_obj_t microbit_i2c_read(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_n, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_repeat, MP_ARG_BOOL, {.u_bool = false} }, }; // parse args microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)pos_args[0]; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // do the I2C read vstr_t vstr; vstr_init_len(&vstr, args[1].u_int); int err = self->i2c->read(args[0].u_int << 1, vstr.buf, vstr.len, args[2].u_bool); if (err != MICROBIT_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "I2C read error %d", err)); } // return bytes object with read data return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } MP_DEFINE_CONST_FUN_OBJ_KW(microbit_i2c_read_obj, 1, microbit_i2c_read); STATIC mp_obj_t microbit_i2c_write(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_buf, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_repeat, MP_ARG_BOOL, {.u_bool = false} }, }; // parse args microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)pos_args[0]; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // do the I2C write mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1].u_obj, &bufinfo, MP_BUFFER_READ); int err = self->i2c->write(args[0].u_int << 1, (char*)bufinfo.buf, bufinfo.len, args[2].u_bool); if (err != MICROBIT_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "I2C write error %d", err)); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(microbit_i2c_write_obj, 1, microbit_i2c_write); STATIC const mp_map_elem_t microbit_i2c_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&microbit_i2c_init_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_scan), (mp_obj_t)&microbit_i2c_scan_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&microbit_i2c_read_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&microbit_i2c_write_obj }, }; STATIC MP_DEFINE_CONST_DICT(microbit_i2c_locals_dict, microbit_i2c_locals_dict_table); const mp_obj_type_t microbit_i2c_type = { { &mp_type_type }, .name = MP_QSTR_MicroBitI2C, .print = NULL, .make_new = NULL, .call = NULL, .unary_op = NULL, .binary_op = NULL, .attr = NULL, .subscr = NULL, .getiter = NULL, .iternext = NULL, .buffer_p = {NULL}, .protocol = NULL, .parent = NULL, .locals_dict = (mp_obj_dict_t*)&microbit_i2c_locals_dict, }; const microbit_i2c_obj_t microbit_i2c_obj = { {&microbit_i2c_type}, .i2c = &ubit_i2c, }; }
6,781
2,993
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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 any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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 <gtest/gtest.h> #include "ModelFixture.hpp" #include "../GroundHeatExchangerVertical.hpp" #include "../GroundHeatExchangerVertical_Impl.hpp" #include "../AirLoopHVAC.hpp" #include "../PlantLoop.hpp" #include "../Node.hpp" #include "../Node_Impl.hpp" #include "../AirLoopHVACZoneSplitter.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, GroundHeatExchangerVertical_DefaultConstructor) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_EXIT ( { Model model; GroundHeatExchangerVertical testObject = GroundHeatExchangerVertical(model); exit(0); } , ::testing::ExitedWithCode(0), "" ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_Connections) { Model m; GroundHeatExchangerVertical testObject(m); Node inletNode(m); Node outletNode(m); m.connect(inletNode,inletNode.outletPort(),testObject,testObject.inletPort()); m.connect(testObject,testObject.outletPort(),outletNode,outletNode.inletPort()); ASSERT_TRUE( testObject.inletModelObject() ); ASSERT_TRUE( testObject.outletModelObject() ); EXPECT_EQ( inletNode.handle(), testObject.inletModelObject()->handle() ); EXPECT_EQ( outletNode.handle(), testObject.outletModelObject()->handle() ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_addToNode) { Model m; GroundHeatExchangerVertical testObject(m); AirLoopHVAC airLoop(m); Node supplyOutletNode = airLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)2, airLoop.supplyComponents().size() ); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_FALSE(testObject.addToNode(inletNode)); EXPECT_EQ((unsigned)5, airLoop.demandComponents().size()); PlantLoop plantLoop(m); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_TRUE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)7, plantLoop.supplyComponents().size() ); Node demandOutletNode = plantLoop.demandOutletNode(); EXPECT_FALSE(testObject.addToNode(demandOutletNode)); EXPECT_EQ( (unsigned)5, plantLoop.demandComponents().size() ); GroundHeatExchangerVertical testObjectClone = testObject.clone(m).cast<GroundHeatExchangerVertical>(); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_TRUE(testObjectClone.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)9, plantLoop.supplyComponents().size() ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddRemoveSupplyBranchForComponent) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); EXPECT_TRUE(plantLoop.addSupplyBranchForComponent(testObject)); EXPECT_EQ((unsigned)7, plantLoop.supplyComponents().size()); EXPECT_NE((unsigned)9, plantLoop.supplyComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); EXPECT_TRUE(plantLoop.removeSupplyBranchWithComponent(testObject)); EXPECT_EQ((unsigned)5, plantLoop.supplyComponents().size()); EXPECT_NE((unsigned)7, plantLoop.supplyComponents().size()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddDemandBranchForComponent) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); EXPECT_FALSE(plantLoop.addDemandBranchForComponent(testObject)); EXPECT_EQ((unsigned)5, plantLoop.demandComponents().size()); EXPECT_NE((unsigned)7, plantLoop.demandComponents().size()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddToNodeTwoSameObjects) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); Node supplyOutletNode = plantLoop.supplyOutletNode(); testObject.addToNode(supplyOutletNode); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); } TEST_F(ModelFixture, GroundHeatExchangerVertical_Remove) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); Node supplyOutletNode = plantLoop.supplyOutletNode(); testObject.addToNode(supplyOutletNode); EXPECT_EQ((unsigned)7, plantLoop.supplyComponents().size()); testObject.remove(); EXPECT_EQ((unsigned)5, plantLoop.supplyComponents().size()); } //test cloning the object TEST_F(ModelFixture, GroundHeatExchangerVertical_Clone){ Model m; //make an object to clone, and edit some property to make sure the clone worked GroundHeatExchangerVertical testObject(m); testObject.setMaximumFlowRate(3.14); //clone into the same model GroundHeatExchangerVertical testObjectClone = testObject.clone(m).cast<GroundHeatExchangerVertical>(); EXPECT_EQ(3.14,testObjectClone.maximumFlowRate()); //clone into another model Model m2; GroundHeatExchangerVertical testObjectClone2 = testObject.clone(m2).cast<GroundHeatExchangerVertical>(); EXPECT_EQ(3.14,testObjectClone2.maximumFlowRate()); EXPECT_NE(testObjectClone2, testObjectClone); EXPECT_NE(testObjectClone2.handle(), testObjectClone.handle()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_GFunctions) { Model model; GroundHeatExchangerVertical testObject(model); std::vector< GFunction > gFunctions = testObject.gFunctions(); EXPECT_EQ(35, gFunctions.size()); testObject.removeAllGFunctions(); gFunctions = testObject.gFunctions(); EXPECT_EQ(0, gFunctions.size()); EXPECT_TRUE(testObject.addGFunction(1.0, 1.5)); gFunctions = testObject.gFunctions(); EXPECT_EQ(1, gFunctions.size()); testObject.addGFunction(2.0, 2.5); testObject.removeGFunction(0); gFunctions = testObject.gFunctions(); EXPECT_EQ(1, gFunctions.size()); EXPECT_DOUBLE_EQ(2.0, gFunctions[0].lnValue()); EXPECT_DOUBLE_EQ(2.5, gFunctions[0].gValue()); testObject.removeAllGFunctions(); for (int i=0; i<100; i++) { testObject.addGFunction(i, i + 0.5); } gFunctions = testObject.gFunctions(); EXPECT_EQ(100, gFunctions.size()); EXPECT_THROW(testObject.addGFunction(1.0, 1.5), openstudio::Exception); }
8,226
2,819
// pyUserLibrarymodule.cpp // This file is generated by Shroud nowrite-version. Do not edit. // 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 "pyUserLibrarymodule.hpp" #define PY_ARRAY_UNIQUE_SYMBOL SHROUD_USERLIBRARY_ARRAY_API #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include "numpy/arrayobject.h" // splicer begin include // splicer end include #ifdef __cplusplus #define SHROUD_UNUSED(param) #else #define SHROUD_UNUSED(param) param #endif #if PY_MAJOR_VERSION >= 3 #define PyInt_AsLong PyLong_AsLong #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyString_FromString PyUnicode_FromString #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #endif // splicer begin C_definition // splicer end C_definition PyObject *PP_error_obj; PyObject *PP_init_userlibrary_example_nested(void); PyObject *PP_init_userlibrary_example(void); // splicer begin additional_functions // splicer end additional_functions static PyMethodDef PP_methods[] = { {nullptr, (PyCFunction)nullptr, 0, nullptr} /* sentinel */ }; /* * inituserlibrary - Initialization function for the module * *must* be called inituserlibrary */ static char PP__doc__[] = "library documentation" ; struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct module_state _state; #endif #if PY_MAJOR_VERSION >= 3 static int userlibrary_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int userlibrary_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "userlibrary", /* m_name */ PP__doc__, /* m_doc */ sizeof(struct module_state), /* m_size */ PP_methods, /* m_methods */ nullptr, /* m_reload */ userlibrary_traverse, /* m_traverse */ userlibrary_clear, /* m_clear */ NULL /* m_free */ }; #define RETVAL m #define INITERROR return nullptr #else #define RETVAL #define INITERROR return #endif extern "C" PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_userlibrary(void) #else inituserlibrary(void) #endif { PyObject *m = nullptr; const char * error_name = "userlibrary.Error"; // splicer begin C_init_locals // splicer end C_init_locals /* Create the module and add the functions */ #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule4("userlibrary", PP_methods, PP__doc__, (PyObject*)nullptr,PYTHON_API_VERSION); #endif if (m == nullptr) return RETVAL; struct module_state *st = GETSTATE(m); import_array(); { PyObject *submodule = PP_init_userlibrary_example(); if (submodule == nullptr) INITERROR; Py_INCREF(submodule); PyModule_AddObject(m, (char *) "example", submodule); } PP_error_obj = PyErr_NewException((char *) error_name, nullptr, nullptr); if (PP_error_obj == nullptr) return RETVAL; st->error = PP_error_obj; PyModule_AddObject(m, "Error", st->error); // splicer begin C_init_body // splicer end C_init_body /* Check for errors */ if (PyErr_Occurred()) Py_FatalError("can't initialize module userlibrary"); return RETVAL; }
3,568
1,272
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2020 Joel E. Anderson * * 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 <stddef.h> #include <stumpless.h> #include <gtest/gtest.h> #include "test/helper/memory_counter.hpp" #define TEST_BUFFER_LENGTH 2048 NEW_MEMORY_COUNTER( add_message_leak ) namespace { TEST( AddMessageLeakTest, TypicalUse ) { struct stumpless_target *target; char buffer[TEST_BUFFER_LENGTH]; int i; int add_result; INIT_MEMORY_COUNTER( add_message_leak ); target = stumpless_open_buffer_target( "add-message-leak-testing", buffer, sizeof( buffer ) ); ASSERT_TRUE( target != NULL ); for( i = 0; i < 1000; i++ ) { add_result = stumpless_add_message( target, "temp message %d", i ); ASSERT_GE( add_result, 0 ); } stumpless_close_buffer_target( target ); stumpless_free_all( ); ASSERT_NO_LEAK( add_message_leak ); } }
1,529
529
/****************************************************************************** Author: Matthew Nolan OrangeMUD Codebase Date: January 2001 [Crossplatform] License: 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. Copyright 2000-2019 Matthew Nolan, All Rights Reserved ******************************************************************************/ #include "CommonTypes.h" #include "ObjectIndex.h" #include "ObjectProxy.h" ObjectProxy::ObjectProxy() : mObject(NULL) { } ObjectProxy::~ObjectProxy() { } bool ObjectProxy::IsCustom() { return mCustomObject.IsNull() ? false : true; } void ObjectProxy::Customize() { if(mCustomObject.Ptr()) return; APtr<ObjectData> nCustom(new ObjectData(GetIndex())); mCustomObject = nCustom.Detach(); mObject = mCustomObject; } void ObjectProxy::Revert() { mCustomObject.Dispose(); mObject = GetIndex()->GetFlyweight(); ASSERT(mObject); } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif const STRINGCW& ObjectProxy::Name() const { return mObject->mName; } const STRINGCW& ObjectProxy::PName() const { return mObject->mPName; } const STRINGCW& ObjectProxy::Keywords() const { return mObject->mKeywords; } const STRINGCW& ObjectProxy::ShortDesc() const { return mObject->mShortDesc; } const STRINGCW& ObjectProxy::PShortDesc() const { return mObject->mPShortDesc; } const STRINGCW& ObjectProxy::Description() const { return mObject->mDescription; } LONG ObjectProxy::Value(SHORT hIndex) const { return mObject->mValue[hIndex]; } LONG ObjectProxy::WearFlags() const { return GetIndex()->mWearFlags; } SHORT ObjectProxy::ItemType() const { return GetIndex()->mItemType; } float ObjectProxy::Weight() const { return mObject->mWeight; } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif STRINGCW& ObjectProxy::xName() { Customize(); return mObject->mName; } STRINGCW& ObjectProxy::xPName() { Customize(); return mObject->mPName; } STRINGCW& ObjectProxy::xKeywords() { Customize(); return mObject->mKeywords; } STRINGCW& ObjectProxy::xShortDesc() { Customize(); return mObject->mShortDesc; } STRINGCW& ObjectProxy::xPShortDesc() { Customize(); return mObject->mPShortDesc; } STRINGCW& ObjectProxy::xDescription() { Customize(); return mObject->mDescription; } LONG& ObjectProxy::xValue(SHORT hIndex) { Customize(); return mObject->mValue[hIndex]; } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif ObjectData::ObjectData(ObjectIndex* hLikeObj) { ASSERT(hLikeObj); mName = hLikeObj->mName; mPName = hLikeObj->mPName; mKeywords = hLikeObj->mKeywords; mShortDesc = hLikeObj->mShortDesc; mPShortDesc = hLikeObj->mPShortDesc; mDescription = hLikeObj->mDescription; mItemType = hLikeObj->mItemType; mLevel = hLikeObj->mLevel; mWeight = hLikeObj->mWeight; mMaterials = hLikeObj->mMaterials; mAntiFlags = hLikeObj->mAntiFlags; mObjectFlags = hLikeObj->mObjectFlags; mValue[0] = hLikeObj->mValue[0]; mValue[1] = hLikeObj->mValue[1]; mValue[2] = hLikeObj->mValue[2]; mValue[3] = hLikeObj->mValue[3]; mValue[4] = hLikeObj->mValue[4]; //Only exist in Customized Objects: mAge = 0; mOwner = ""; mTimer = 0; mEnchantment = 0; } ObjectData::~ObjectData() { }
5,295
1,662
#include "CExpressionPicker.h" #include <QHeaderView> #include <QMouseEvent> #include "CExpressionPickerDelegate.h" #include <QDebug> CExpressionPicker::CExpressionPicker(QWidget *parent) :QTableView(parent) ,mModel(new QStandardItemModel(this)) ,mPreView(new QLabel(this)) ,mShowPreView(false) ,mShowIconRect(true) ,mMaxColumnCount(12) ,mMaxRowCount(4) ,mMovie(new QMovie(this)) { this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->horizontalHeader()->setVisible(false); this->verticalHeader()->setVisible(false); this->horizontalHeader()->setDefaultSectionSize(33); this->verticalHeader()->setDefaultSectionSize(33); this->setEditTriggers(QTableView::NoEditTriggers); this->setSelectionMode(QTableView::SingleSelection); this->setShowGrid(false); this->setMouseTracking(true); this->setStyleSheet("QTableView{background-color:rgba(0,0,0,0);border:none;}"); this->setModel(mModel); connect(this, &CExpressionPicker::clicked, this, &CExpressionPicker::onClicked); //delegate CExpressionPickerDelegate* tdelegate = new CExpressionPickerDelegate; tdelegate->setParent(this); this->setItemDelegate(tdelegate); //pre viewer mPreView->setMouseTracking(true); mPreView->hide(); mPreView->resize(33*2,33*2); mPreView->setStyleSheet("background-color:white;"); mPreView->installEventFilter(this); mMovie->setScaledSize(mPreView->size()); mMovie->setCacheMode(QMovie::CacheAll); mPreView->setMovie(mMovie); } CExpressionPicker::~CExpressionPicker() { } void CExpressionPicker::setShowPreView(bool s) { mShowPreView = s; } bool CExpressionPicker::isShowPreView() { return mShowPreView; } void CExpressionPicker::setShowIconRect(bool s) { mShowIconRect = s; } bool CExpressionPicker::isShowIconRect() { return mShowIconRect; } void CExpressionPicker::setExpressionList(const CExpressionPicker::ExpressionList &li) { mExpressionList = li; mModel->clear(); int capacity = this->maxRowCount()*this->maxColumnCount(); int tSize = capacity <= li.count() ? capacity : li.count(); for(int i = 0; i < tSize; i++) { Expression exp = li[i]; QStandardItem* item = new QStandardItem("expression"); item->setData(exp.desc , ExpressionRole_Desc); item->setData(exp.fileName , ExpressionRole_FileName); item->setData(exp.groupid , ExpressionRole_GroupId); item->setData(exp.id , ExpressionRole_Id); item->setData(exp.shortcut , ExpressionRole_Shortcut); item->setData(exp.tooltip , ExpressionRole_Tooltip); item->setToolTip(exp.tooltip); int currentColumn = i % this->maxColumnCount(); int currentRow = i / this->maxColumnCount(); mModel->setItem(currentRow, currentColumn, item); } } CExpressionPicker::ExpressionList CExpressionPicker::expressionList() { return mExpressionList; } void CExpressionPicker::setMaxColumnCount(int n) { mMaxColumnCount = n; } void CExpressionPicker::setMaxRowCount(int n) { mMaxRowCount = n; } int CExpressionPicker::maxColumnCount() { return mMaxColumnCount; } int CExpressionPicker::maxRowCount() { return mMaxRowCount; } void CExpressionPicker::leaveEvent(QEvent *e) { QTableView::leaveEvent(e); mPreView->hide(); } void CExpressionPicker::mouseMoveEvent(QMouseEvent *e) { QTableView::mouseMoveEvent(e); if(!this->isShowPreView()) { mPreView->hide(); return; } //movie QModelIndex tindex = this->indexAt(e->pos()); if(!tindex.isValid() || !tindex.data(ExpressionRole_Id).isValid()) { mPreView->hide(); return; } if(e->x() <= mPreView->width()) { mPreView->move(this->width() - mPreView->width() - 1, 0 + 1); } else { mPreView->move(1,1); } mPreView->show(); QString filename = tindex.data(ExpressionRole_FileName).toString(); if(filename != mMovie->fileName()) { mMovie->stop(); mMovie->setFileName(filename); mMovie->start(); } } bool CExpressionPicker::eventFilter(QObject *obj, QEvent *e) { bool res = QTableView::eventFilter(obj,e); if (obj == nullptr || e == nullptr) { return res; } if(obj == mPreView) { if(e->type() == QEvent::MouseMove) { if(mPreView->pos() != QPoint(0,0)) { mPreView->move(0,0); } else { mPreView->move(this->width() - mPreView->width(), 0); } } if(e->type() == QEvent::Hide) { mMovie->stop(); } if(e->type() == QEvent::Show) { mMovie->start(); } } return res; } void CExpressionPicker::onClicked(const QModelIndex &index) { if(!index.isValid()) return; if(!index.data(ExpressionRole_Id).isValid()) return; Expression exp; exp.desc = index.data(ExpressionRole_Desc ).toString(); exp.fileName = index.data(ExpressionRole_FileName ).toString(); exp.groupid = index.data(ExpressionRole_GroupId ).toString(); exp.id = index.data(ExpressionRole_Id ).toString(); exp.shortcut = index.data(ExpressionRole_Shortcut ).toString(); exp.tooltip = index.data(ExpressionRole_Tooltip ).toString(); emit expressionClicked(exp); }
5,761
1,875
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "xsapi/contextual_search_service.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_CONTEXTUAL_SEARCH_CPP_BEGIN contextual_search_game_clip_uri_info::contextual_search_game_clip_uri_info() : m_fileSize(0), m_uriType(contextual_search_game_clip_uri_type::none) { } contextual_search_game_clip_uri_info::contextual_search_game_clip_uri_info( _In_ web::uri url, _In_ uint64_t fileSize, _In_ contextual_search_game_clip_uri_type uriType, _In_ utility::datetime expiration ) : m_url(std::move(url)), m_fileSize(fileSize), m_uriType(uriType), m_expiration(std::move(expiration)) { } contextual_search_game_clip_uri_type contextual_search_game_clip_uri_info::convert_string_to_clip_uri_type(_In_ const string_t& value) { if (utils::str_icmp(value, _T("Original")) == 0) { return contextual_search_game_clip_uri_type::original; } else if (utils::str_icmp(value, _T("Download")) == 0) { return contextual_search_game_clip_uri_type::download; } else if (utils::str_icmp(value, _T("Ahls")) == 0) { return contextual_search_game_clip_uri_type::http_live_streaming; } else if (utils::str_icmp(value, _T("SmoothStreaming")) == 0) { return contextual_search_game_clip_uri_type::smooth_streaming; } return contextual_search_game_clip_uri_type::none; } xbox_live_result<contextual_search_game_clip_uri_info> contextual_search_game_clip_uri_info::_Deserialize(_In_ const web::json::value& inputJson) { if (inputJson.is_null()) return xbox_live_result<contextual_search_game_clip_uri_info>(); std::error_code errc = xbox_live_error_code::no_error; contextual_search_game_clip_uri_info result( utils::extract_json_string(inputJson, _T("Uri"), errc, false), utils::extract_json_uint52(inputJson, _T("FileSize"), errc, false), convert_string_to_clip_uri_type(utils::extract_json_string(inputJson, _T("UriType"), errc, false)), utils::extract_json_time(inputJson, _T("Expiration"), errc, false) ); return xbox_live_result<contextual_search_game_clip_uri_info>(result, errc); } const web::uri& contextual_search_game_clip_uri_info::url() const { return m_url; } uint64_t contextual_search_game_clip_uri_info::file_size() const { return m_fileSize; } contextual_search_game_clip_uri_type contextual_search_game_clip_uri_info::uri_type() const { return m_uriType; } const utility::datetime& contextual_search_game_clip_uri_info::expiration() const { return m_expiration; } NAMESPACE_MICROSOFT_XBOX_SERVICES_CONTEXTUAL_SEARCH_CPP_END
2,777
1,030
#include "FSDWidgetBlueprintLibrary.h" #include "Templates/SubclassOf.h" class UObject; class UWidget; class UHorizontalBox; class UUserWidget; class UWidgetAnimation; class USizeBox; class UPanelWidget; class UTextBlock; class UImage; class UWindowWidget; class AFSDPlayerState; class UFSDCheatManager; class APlayerController; class UVerticalBox; class USpacer; class UTexture2D; class UHorizontalBoxSlot; class UVerticalBoxSlot; class UUniformGridPanel; class UUniformGridSlot; void UFSDWidgetBlueprintLibrary::ToggleAnimationLooping(UObject* WorldContext, UWidgetAnimation* InAnimation, FWidgetAnimationSettings InSettings, bool InLoop, bool& OutPlayingChanged, bool& OutIsPlaying) { } bool UFSDWidgetBlueprintLibrary::TextSmallerThan(const FText& Text1, const FText& Text2) { return false; } bool UFSDWidgetBlueprintLibrary::TextGreaterThan(const FText& Text1, const FText& Text2) { return false; } TArray<UWidget*> UFSDWidgetBlueprintLibrary::SortWidgetArray(const TArray<UWidget*>& InWidgets, const FFSDWidgetBlueprintLibraryInCompareFunction& InCompareFunction) { return TArray<UWidget*>(); } void UFSDWidgetBlueprintLibrary::SimpleBox(FPaintContext& Context, FVector2D Position, FVector2D Size, FLinearColor Tint) { } FTimerHandle UFSDWidgetBlueprintLibrary::SetTimerForNextTick(UObject* WorldContext, const FFSDWidgetBlueprintLibraryTimerDelegate& TimerDelegate) { return FTimerHandle{}; } void UFSDWidgetBlueprintLibrary::SetSizeBoxSettings(USizeBox*& InSizeBox, const FSizeBoxSettings& InSettings) { } void UFSDWidgetBlueprintLibrary::SetMousePosition(UObject* WorldContextObject, int32 X, int32 Y) { } void UFSDWidgetBlueprintLibrary::SetChildrenVisibility(UPanelWidget* Panel, ESlateVisibility Visibility, int32 StartIndex, TSubclassOf<UUserWidget> OptionalClassFilter) { } void UFSDWidgetBlueprintLibrary::ScrubAnimation(UObject* WorldContext, UWidgetAnimation* InAnimation, float Progress01) { } void UFSDWidgetBlueprintLibrary::ScaleTextBlockToHeight(UTextBlock* TextBlock, float TargetHeight, bool SetMinimimumWidth) { } void UFSDWidgetBlueprintLibrary::ScaleImageToHeight(UImage* Image, float TargetHeight) { } void UFSDWidgetBlueprintLibrary::PrintStrings(UObject* WorldContextObject, const TArray<FString>& InStrings, bool bPrintToScreen, bool bPrintToLog, FLinearColor TextColor, float Duration) { } FString UFSDWidgetBlueprintLibrary::MidIgnoringWhiteSpace(const FString& Source, int32 Index, int32 count) { return TEXT(""); } FVector2D UFSDWidgetBlueprintLibrary::MeasureTextSize(const FText& Text, const FSlateFontInfo& Font) { return FVector2D{}; } FVector2D UFSDWidgetBlueprintLibrary::MeasureTextBlockSize(const UTextBlock* TextBlock) { return FVector2D{}; } void UFSDWidgetBlueprintLibrary::Line(FPaintContext& Context, FVector2D Pos1, FVector2D Pos2, FLinearColor Tint) { } FLinearColor UFSDWidgetBlueprintLibrary::LerpColors(const TArray<FLinearColor>& Colors, bool Interpolate, float Progress01) { return FLinearColor{}; } int32 UFSDWidgetBlueprintLibrary::LengthIgnoringWhitespace(const FString& Source) { return 0; } bool UFSDWidgetBlueprintLibrary::IsWindowsPlatform(UObject* WorldContextObject) { return false; } bool UFSDWidgetBlueprintLibrary::IsWhiteSpaceAt(const FString& Source, int32 Index) { return false; } bool UFSDWidgetBlueprintLibrary::IsWhiteSpace(const FString& Source) { return false; } bool UFSDWidgetBlueprintLibrary::IsHUDVisible(UObject* WorldContextObject) { return false; } FString UFSDWidgetBlueprintLibrary::IntToRomanNumeral(int32 Value) { return TEXT(""); } bool UFSDWidgetBlueprintLibrary::HasAnyVisibleChildren(UPanelWidget* Panel, int32 StartIndex, TSubclassOf<UUserWidget> OptionalClassFilter) { return false; } FString UFSDWidgetBlueprintLibrary::GetShortTimeString(int32 TotalSeconds, bool BlinkDelimiter) { return TEXT(""); } UWindowWidget* UFSDWidgetBlueprintLibrary::GetParentWindowWidget(UUserWidget* InWidget) { return NULL; } UUserWidget* UFSDWidgetBlueprintLibrary::GetParentUserWidget(UUserWidget* InWidget) { return NULL; } AFSDPlayerState* UFSDWidgetBlueprintLibrary::GetOwningFSDPlayerState(UWidget* Target) { return NULL; } FText UFSDWidgetBlueprintLibrary::GetKeyName(const FKey& Key) { return FText::GetEmpty(); } float UFSDWidgetBlueprintLibrary::GetFontMaxHeight(const FSlateFontInfo& Font) { return 0.0f; } float UFSDWidgetBlueprintLibrary::GetFontBaseline(const FSlateFontInfo& Font) { return 0.0f; } UWidget* UFSDWidgetBlueprintLibrary::GetFocusedWidget(UObject* WorldContextObject, APlayerController* Controller) { return NULL; } UUserWidget* UFSDWidgetBlueprintLibrary::GetFocusableParentUserWidget(UUserWidget* InWidget) { return NULL; } FVector2D UFSDWidgetBlueprintLibrary::GetDrawSize(FPaintContext& InContext) { return FVector2D{}; } UFSDCheatManager* UFSDWidgetBlueprintLibrary::GetCheatManager(UObject* WorldContextObject) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::FindChildWidget(UPanelWidget*& ParentWidget, TSubclassOf<UUserWidget> WidgetClass, bool SearchChildren) { return NULL; } UVerticalBox* UFSDWidgetBlueprintLibrary::CreateVerticalBox(UObject* WorldContext) { return NULL; } UTextBlock* UFSDWidgetBlueprintLibrary::CreateTextBlock(UObject* WorldContext, FText Text, FSlateFontInfo Font, TEnumAsByte<ETextJustify::Type> Justification, FLinearColor Color, bool WrapText) { return NULL; } USpacer* UFSDWidgetBlueprintLibrary::CreateSpacer(UObject* WorldContext, FVector2D Size) { return NULL; } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildrenWithCallbackEx(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass, const FFSDWidgetBlueprintLibraryOnCreatedOrReused& OnCreatedOrReused, const FFSDWidgetBlueprintLibraryOnCollapsed& OnCollapsed) { return TArray<UUserWidget*>(); } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildrenWithCallback(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass, const FFSDWidgetBlueprintLibraryOnCreatedOrReused& OnCreatedOrReused) { return TArray<UUserWidget*>(); } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildren(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass) { return TArray<UUserWidget*>(); } UImage* UFSDWidgetBlueprintLibrary::CreateImageSized(UObject* WorldContext, UTexture2D* Texture, FLinearColor Tint, FVector2D Size) { return NULL; } UImage* UFSDWidgetBlueprintLibrary::CreateImage(UObject* WorldContext, UTexture2D* Texture, FLinearColor Tint, bool AutoSize) { return NULL; } UHorizontalBox* UFSDWidgetBlueprintLibrary::CreateHorizontalBox(UObject* WorldContext) { return NULL; } FText UFSDWidgetBlueprintLibrary::ClampTextLength(const FText& Text, int32 MaxLength, const FText& CutOffIndicator) { return FText::GetEmpty(); } void UFSDWidgetBlueprintLibrary::Box(FPaintContext& Context, FVector2D Position, FVector2D Size, const FSlateBrush& Brush, FLinearColor Tint) { } UWidget* UFSDWidgetBlueprintLibrary::AddWidgetToRow(UVerticalBox* VerticalBox, UWidget* Widget, int32 MaxWidgetsPerRow, float WidgetSpacing, float RowSpacing, UHorizontalBoxSlot*& OutSlot, UHorizontalBox*& OutRow) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToVerticalBoxEx(UVerticalBox* VerticalBox, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, float Size, FMargin Padding, UVerticalBoxSlot*& OutSlot, UVerticalBox*& OutVerticalBox) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToUniformGridEx(UUniformGridPanel* GridPanel, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, int32 Column, int32 Row, UUniformGridSlot*& OutSlot, UUniformGridPanel*& OutGridPanel) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToHorizontalBoxEx(UHorizontalBox* HorizontalBox, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, float Size, FMargin Padding, UHorizontalBoxSlot*& OutSlot, UHorizontalBox*& OutHorizontalBox) { return NULL; } UFSDWidgetBlueprintLibrary::UFSDWidgetBlueprintLibrary() { }
8,329
2,655
#include "AnimalThirdPersonControler.h" #include <OgreMath.h> #include "TerrainUtils.h" const float camDist = 900.f; AnimalThirdPersonControler::AnimalThirdPersonControler() : m_lookAround(false), m_camDistance(camDist), m_camAngularSpeed(0.0015f), m_camHeightOffset(0.f), m_pCamera(nullptr), m_pAnimal(nullptr), m_pTerrainGroup(nullptr) { } AnimalThirdPersonControler::~AnimalThirdPersonControler() { } void AnimalThirdPersonControler::attach(Animal* i_pAnimal, Ogre::Camera* i_pCamera, Ogre::TerrainGroup* i_pTerrainGroup) { m_pAnimal = i_pAnimal; m_pCamera = i_pCamera; m_pTerrainGroup = i_pTerrainGroup; m_camHeightOffset = i_pAnimal->m_heightOffset; if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; m_pAnimal->dropOnTerrain(*i_pTerrainGroup); // Position camera m_pCamera->setPosition(m_pAnimal->m_pNode->getPosition() - m_camDistance * m_pAnimal->m_pNode->getOrientation().xAxis()); m_pCamera->lookAt(m_pAnimal->m_pNode->getPosition() + m_pAnimal->m_cameraLookAtOffset); } void AnimalThirdPersonControler::detach() { m_pAnimal = nullptr; m_pCamera = nullptr; } void AnimalThirdPersonControler::alignAnimalToCamera(double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; // Find new orientation of avatar Ogre::Vector3 camY = m_pCamera->getDirection(); Ogre::Vector3 aniX = m_pAnimal->m_pNode->getOrientation().xAxis(); Ogre::Vector3 aniY = m_pAnimal->m_pNode->getOrientation().yAxis(); Ogre::Vector3 newAniX = camY.dotProduct(aniX) * aniX + camY.dotProduct(aniY) * aniY; if (newAniX.isZeroLength()) return; newAniX.normalise(); m_pAnimal->turn(newAniX, i_timeSinceLastFrame); } void AnimalThirdPersonControler::move(int i_frontDir, int i_sideDir, bool i_run, double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; if (!(i_frontDir == 0 && i_sideDir == 0)) { Ogre::Vector3 oldAniPos = m_pAnimal->m_pNode->getPosition(); m_pAnimal->moveOnTerrain(i_frontDir, i_sideDir, i_run, i_timeSinceLastFrame, *m_pTerrainGroup); Ogre::Vector3 newAniPos = m_pAnimal->m_pNode->getPosition(); // Update cammera Ogre::Vector3 newCamPos = m_pCamera->getPosition() + newAniPos - oldAniPos; Ogre::Vector3 newAvatarToCamera = newCamPos - m_pAnimal->m_pNode->getPosition(); if (newAvatarToCamera.length() != m_camDistance) newAvatarToCamera = newAvatarToCamera.normalisedCopy() * m_camDistance; // Collide with terrain m_collideCamWithTerrain(newAvatarToCamera); } if (!m_lookAround) alignAnimalToCamera(i_timeSinceLastFrame); } void AnimalThirdPersonControler::orient(int i_xRel, int i_yRel, double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; Ogre::Vector3 camPos = m_pCamera->getPosition(); Ogre::Radian angleX(i_xRel * -m_camAngularSpeed); Ogre::Radian angleY(i_yRel * -m_camAngularSpeed); Ogre::Vector3 avatarToCamera = m_pCamera->getPosition() - m_pAnimal->m_pNode->getPosition(); // restore lenght if (avatarToCamera.length() != m_camDistance) avatarToCamera = avatarToCamera.normalisedCopy() * m_camDistance; // Do not go to the poles Ogre::Radian latitude = m_pAnimal->m_pNode->getOrientation().zAxis().angleBetween(avatarToCamera); if (latitude < Ogre::Radian(Ogre::Math::DegreesToRadians(10.f)) && angleY < Ogre::Radian(0.f)) angleY = Ogre::Radian(0.f); else if (latitude > Ogre::Radian(Ogre::Math::DegreesToRadians(170.f)) && angleY > Ogre::Radian(0.f)) angleY = Ogre::Radian(0.f); Ogre::Quaternion orient = Ogre::Quaternion(angleY, m_pCamera->getOrientation().xAxis()) * Ogre::Quaternion(angleX, m_pCamera->getOrientation().yAxis()); Ogre::Vector3 newAvatarToCamera = orient * avatarToCamera; // Move camera closer if collides with terrain m_collideCamWithTerrain(newAvatarToCamera); } void AnimalThirdPersonControler::m_collideCamWithTerrain(const Ogre::Vector3& i_avatarToCamera) { // Move camera closer if collides with terrain Ogre::Vector3 colPos, newCamPos; if (rayToTerrain(m_pAnimal->m_pNode->getPosition(), i_avatarToCamera, *m_pTerrainGroup, colPos) && ((m_pAnimal->m_pNode->getPosition() - colPos).length() < m_camDistance + m_camHeightOffset)) { newCamPos = colPos - i_avatarToCamera.normalisedCopy() * m_camHeightOffset; } else { newCamPos = m_pAnimal->m_pNode->getPosition() + i_avatarToCamera; } m_pCamera->setPosition(newCamPos); m_pCamera->lookAt(m_pAnimal->m_pNode->getPosition() + m_pAnimal->m_cameraLookAtOffset); }
4,491
1,843
// // Created by kier on 2019-09-03. // #include "runtime/operator.h" #include "global/operator_factory.h" #include "backend/name.h" #include "core/tensor_builder.h" #include "runtime/stack.h" #include "kernels/cpu/operator_on_cpu.h" #include "backend/base/base_roi_align.h" #include "dragon/roi_align_op.h" /** * THis cpu implement was fork from Dragon, SeetaTech */ namespace ts { namespace cpu { class ROIAlign : public OperatorOnCPU<base::ROIAlign> { public: std::shared_ptr<dragon::ROIAlignOp<dragon::CPUContext>> m_dragon; void init() override { dragon::Workspace ws; m_dragon = std::make_shared<dragon::ROIAlignOp<dragon::CPUContext>>(this, &ws); } int run(Stack &stack) override { m_dragon->bind_outputs(1); m_dragon->bind_inputs(std::vector<Tensor>(stack.begin(), stack.end())); m_dragon->RunOnDevice(); stack.push(Tensor::Pack(m_dragon->outputs())); m_dragon->clean(); return 1; } std::vector<Tensor> roi_align( const std::vector<Tensor> &inputs, int pool_h, int pool_w, float spatial_scale, int sampling_ratio) override { TS_LOG_ERROR << "What a Terrible Failure!" << eject; return {}; } }; } } using namespace ts; using namespace cpu; TS_REGISTER_OPERATOR(ROIAlign, CPU, name::layer::roi_align())
1,537
504
#include "pathwatch.h" namespace pathwatch { PathWatcher::PathWatcher() { } void PathWatcher::watchInternal(fs::path, CallbackWrapper callbacks) { } PathWatcher::~PathWatcher() {} }
199
77
/* NOTE - eventually this file will be automatically updated using a Perl script that understand * the naming of test case files, functions, and namespaces. */ #include <time.h> /* for time() */ #include <stdlib.h> /* for srand() */ #include "std_testcase.h" #include "testcases.h" int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); globalArgc = argc; globalArgv = argv; #ifndef OMITGOOD /* Calling C good functions */ /* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_66_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_13_good();"); CWE675_Duplicate_Operations_on_Resource__open_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_21_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_44_good();"); CWE675_Duplicate_Operations_on_Resource__open_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_14_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_17_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_04_good();"); CWE675_Duplicate_Operations_on_Resource__open_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_10_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_64_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_16_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_11_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_34_good();"); CWE675_Duplicate_Operations_on_Resource__open_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_18_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_13_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_12_good();"); CWE675_Duplicate_Operations_on_Resource__open_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_53_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_65_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_21_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_04_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_68_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_12_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_31_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_45_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_45_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_14_good();"); CWE675_Duplicate_Operations_on_Resource__open_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_63_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_15_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_22_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_05_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_65_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_18_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_14_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_61_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_22_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_17_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_44_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_52_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_32_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_41_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_54_good();"); CWE675_Duplicate_Operations_on_Resource__open_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_05_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_41_good();"); CWE675_Duplicate_Operations_on_Resource__open_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_03_good();"); CWE675_Duplicate_Operations_on_Resource__open_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_53_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_05_good();"); CWE675_Duplicate_Operations_on_Resource__open_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_02_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_04_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_09_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_64_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_12_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_53_good();"); CWE675_Duplicate_Operations_on_Resource__open_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_01_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_10_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_54_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_09_good();"); CWE675_Duplicate_Operations_on_Resource__open_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_17_good();"); CWE675_Duplicate_Operations_on_Resource__open_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_63_good();"); CWE675_Duplicate_Operations_on_Resource__open_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_21_good();"); CWE675_Duplicate_Operations_on_Resource__open_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_61_good();"); CWE675_Duplicate_Operations_on_Resource__open_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_66_good();"); CWE675_Duplicate_Operations_on_Resource__open_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_07_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_11_good();"); CWE675_Duplicate_Operations_on_Resource__open_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_42_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_34_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_41_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_15_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_68_good();"); CWE675_Duplicate_Operations_on_Resource__open_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_02_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_06_good();"); CWE675_Duplicate_Operations_on_Resource__open_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_67_good();"); CWE675_Duplicate_Operations_on_Resource__open_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_32_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_54_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_67_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_03_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_61_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_42_good();"); CWE675_Duplicate_Operations_on_Resource__open_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_13_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_65_good();"); CWE675_Duplicate_Operations_on_Resource__open_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_16_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_01_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_34_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_11_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_51_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_16_good();"); CWE675_Duplicate_Operations_on_Resource__open_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_08_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_66_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_08_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_22_good();"); CWE675_Duplicate_Operations_on_Resource__open_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_44_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_52_good();"); CWE675_Duplicate_Operations_on_Resource__open_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_31_good();"); CWE675_Duplicate_Operations_on_Resource__open_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_64_good();"); CWE675_Duplicate_Operations_on_Resource__open_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_06_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_63_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_32_good();"); CWE675_Duplicate_Operations_on_Resource__open_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_06_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_07_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_52_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_67_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_07_good();"); CWE675_Duplicate_Operations_on_Resource__open_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_45_good();"); CWE675_Duplicate_Operations_on_Resource__open_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_03_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_02_good();"); CWE675_Duplicate_Operations_on_Resource__open_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_09_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_10_good();"); CWE675_Duplicate_Operations_on_Resource__open_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_08_good();"); CWE675_Duplicate_Operations_on_Resource__open_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_42_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_68_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_31_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_01_good();"); CWE675_Duplicate_Operations_on_Resource__open_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_18_good();"); CWE675_Duplicate_Operations_on_Resource__open_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_15_good();"); CWE675_Duplicate_Operations_on_Resource__open_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_51_good();"); CWE675_Duplicate_Operations_on_Resource__open_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_51_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_51_good(); /* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ good functions */ /* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_74::good();"); CWE675_Duplicate_Operations_on_Resource__open_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_62::good();"); CWE675_Duplicate_Operations_on_Resource__open_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_73::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::good();"); CWE675_Duplicate_Operations_on_Resource__open_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::good();"); CWE675_Duplicate_Operations_on_Resource__open_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_82::good();"); CWE675_Duplicate_Operations_on_Resource__open_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_73::good();"); CWE675_Duplicate_Operations_on_Resource__open_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_33::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_43::good();"); CWE675_Duplicate_Operations_on_Resource__open_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_74::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_81::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::good();"); CWE675_Duplicate_Operations_on_Resource__open_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_74::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_72::good();"); CWE675_Duplicate_Operations_on_Resource__open_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_62::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_33::good();"); CWE675_Duplicate_Operations_on_Resource__open_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_81::good();"); CWE675_Duplicate_Operations_on_Resource__open_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_62::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::good();"); CWE675_Duplicate_Operations_on_Resource__open_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_33::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_82::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_82::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_81::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_43::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_72::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_43::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_73::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_72::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::good(); /* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITGOOD */ #ifndef OMITBAD /* Calling C bad functions */ /* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_66_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_13_bad();"); CWE675_Duplicate_Operations_on_Resource__open_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_21_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_44_bad();"); CWE675_Duplicate_Operations_on_Resource__open_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_14_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_17_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_04_bad();"); CWE675_Duplicate_Operations_on_Resource__open_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_10_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_64_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_16_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_11_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_34_bad();"); CWE675_Duplicate_Operations_on_Resource__open_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_18_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_13_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_12_bad();"); CWE675_Duplicate_Operations_on_Resource__open_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_53_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_65_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_21_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_04_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_68_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_12_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_31_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_45_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_45_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_14_bad();"); CWE675_Duplicate_Operations_on_Resource__open_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_63_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_15_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_22_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_05_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_65_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_18_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_14_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_61_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_22_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_17_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_44_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_52_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_32_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_41_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_54_bad();"); CWE675_Duplicate_Operations_on_Resource__open_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_05_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_41_bad();"); CWE675_Duplicate_Operations_on_Resource__open_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_03_bad();"); CWE675_Duplicate_Operations_on_Resource__open_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_53_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_05_bad();"); CWE675_Duplicate_Operations_on_Resource__open_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_02_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_04_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_09_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_64_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_12_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_53_bad();"); CWE675_Duplicate_Operations_on_Resource__open_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_01_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_10_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_54_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_09_bad();"); CWE675_Duplicate_Operations_on_Resource__open_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_17_bad();"); CWE675_Duplicate_Operations_on_Resource__open_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_63_bad();"); CWE675_Duplicate_Operations_on_Resource__open_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_21_bad();"); CWE675_Duplicate_Operations_on_Resource__open_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_61_bad();"); CWE675_Duplicate_Operations_on_Resource__open_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_66_bad();"); CWE675_Duplicate_Operations_on_Resource__open_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_07_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_11_bad();"); CWE675_Duplicate_Operations_on_Resource__open_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_42_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_34_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_41_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_15_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_68_bad();"); CWE675_Duplicate_Operations_on_Resource__open_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_02_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_06_bad();"); CWE675_Duplicate_Operations_on_Resource__open_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_67_bad();"); CWE675_Duplicate_Operations_on_Resource__open_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_32_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_54_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_67_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_03_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_61_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_42_bad();"); CWE675_Duplicate_Operations_on_Resource__open_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_13_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_65_bad();"); CWE675_Duplicate_Operations_on_Resource__open_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_16_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_01_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_34_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_11_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_51_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_16_bad();"); CWE675_Duplicate_Operations_on_Resource__open_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_08_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_66_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_08_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_22_bad();"); CWE675_Duplicate_Operations_on_Resource__open_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_44_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_52_bad();"); CWE675_Duplicate_Operations_on_Resource__open_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_31_bad();"); CWE675_Duplicate_Operations_on_Resource__open_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_64_bad();"); CWE675_Duplicate_Operations_on_Resource__open_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_06_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_63_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_32_bad();"); CWE675_Duplicate_Operations_on_Resource__open_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_06_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_07_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_52_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_67_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_07_bad();"); CWE675_Duplicate_Operations_on_Resource__open_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_45_bad();"); CWE675_Duplicate_Operations_on_Resource__open_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_03_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_02_bad();"); CWE675_Duplicate_Operations_on_Resource__open_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_09_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_10_bad();"); CWE675_Duplicate_Operations_on_Resource__open_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_08_bad();"); CWE675_Duplicate_Operations_on_Resource__open_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_42_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_68_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_31_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_01_bad();"); CWE675_Duplicate_Operations_on_Resource__open_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_18_bad();"); CWE675_Duplicate_Operations_on_Resource__open_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_15_bad();"); CWE675_Duplicate_Operations_on_Resource__open_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_51_bad();"); CWE675_Duplicate_Operations_on_Resource__open_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_51_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_51_bad(); /* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ bad functions */ /* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_74::bad();"); CWE675_Duplicate_Operations_on_Resource__open_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_62::bad();"); CWE675_Duplicate_Operations_on_Resource__open_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_73::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::bad();"); CWE675_Duplicate_Operations_on_Resource__open_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::bad();"); CWE675_Duplicate_Operations_on_Resource__open_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_82::bad();"); CWE675_Duplicate_Operations_on_Resource__open_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_73::bad();"); CWE675_Duplicate_Operations_on_Resource__open_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_33::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_43::bad();"); CWE675_Duplicate_Operations_on_Resource__open_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_74::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_81::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::bad();"); CWE675_Duplicate_Operations_on_Resource__open_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_74::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_72::bad();"); CWE675_Duplicate_Operations_on_Resource__open_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_62::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_33::bad();"); CWE675_Duplicate_Operations_on_Resource__open_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_81::bad();"); CWE675_Duplicate_Operations_on_Resource__open_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_62::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::bad();"); CWE675_Duplicate_Operations_on_Resource__open_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_33::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_82::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_82::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_81::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_43::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_72::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_43::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_73::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_72::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::bad(); /* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITBAD */ return 0; }
59,189
25,310
/* * create_mask.cpp * * Author: * Siddharth Kherada <siddharthkherada27[at]gmail[dot]com> * * This tutorial demonstrates how to make mask image (black and white). * The program takes as input a source image and outputs its corresponding * mask image. */ #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace std; using namespace cv; Mat src, img1, mask, final; Point point; vector<Point> pts; int drag = 0; int var = 0; int flag = 0; void mouseHandler(int, int, int, int, void*); void mouseHandler(int event, int x, int y, int, void*) { if (event == EVENT_LBUTTONDOWN && !drag) { if (flag == 0) { if (var == 0) img1 = src.clone(); point = Point(x, y); circle(img1, point, 2, Scalar(0, 0, 255), -1, 8, 0); pts.push_back(point); var++; drag = 1; if (var > 1) line(img1,pts[var-2], point, Scalar(0, 0, 255), 2, 8, 0); imshow("Source", img1); } } if (event == EVENT_LBUTTONUP && drag) { imshow("Source", img1); drag = 0; } if (event == EVENT_RBUTTONDOWN) { flag = 1; img1 = src.clone(); if (var != 0) { polylines( img1, pts, 1, Scalar(0,0,0), 2, 8, 0); } imshow("Source", img1); } if (event == EVENT_RBUTTONUP) { flag = var; final = Mat::zeros(src.size(), CV_8UC3); mask = Mat::zeros(src.size(), CV_8UC1); vector<vector<Point> > vpts; vpts.push_back(pts); fillPoly(mask, vpts, Scalar(255, 255, 255), 8, 0); bitwise_and(src, src, final, mask); imshow("Mask", mask); imshow("Result", final); imshow("Source", img1); } if (event == EVENT_MBUTTONDOWN) { pts.clear(); var = 0; drag = 0; flag = 0; imshow("Source", src); } } int main(int argc, char **argv) { CommandLineParser parser(argc, argv, "{@input | lena.jpg | input image}"); parser.about("This program demonstrates using mouse events\n"); parser.printMessage(); cout << "\n\tleft mouse button - set a point to create mask shape\n" "\tright mouse button - create mask from points\n" "\tmiddle mouse button - reset\n"; String input_image = parser.get<String>("@input"); src = imread(samples::findFile(input_image)); if (src.empty()) { printf("Error opening image: %s\n", input_image.c_str()); return 0; } namedWindow("Source", WINDOW_AUTOSIZE); setMouseCallback("Source", mouseHandler, NULL); imshow("Source", src); waitKey(0); return 0; }
2,783
1,035
/****************************************************************************/ /* Copyright 2005-2006, Francis Russell */ /* */ /* 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 DESOLA_PROFILING_EQUALITY_CHECKING_VISITOR_HPP #define DESOLA_PROFILING_EQUALITY_CHECKING_VISITOR_HPP #include "Desola_profiling_fwd.hpp" #include <map> #include <cassert> #include <typeinfo> namespace desola { namespace detail { template<typename T_element> class PEqualityCheckingVisitor : public PExpressionNodeVisitor<T_element> { private: const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*> mappings; bool equal; template<typename T_node> void checkMatch(const T_node& left) { assert(mappings.find(&left) != mappings.end()); const PExpressionNode<T_element>& right = *(mappings.find(&left)->second); if (typeid(left) == typeid(right)) { const T_node& castedRight = static_cast<const T_node&>(right); equal = equal && left.isEqual(castedRight, mappings); } else { equal = false; } } public: PEqualityCheckingVisitor(const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*>& m) : mappings(m), equal(true) { } bool isEqual() const { return equal; } virtual void visit(PElementGet<vector, T_element>& e) { checkMatch(e); } virtual void visit(PElementGet<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PElementSet<vector, T_element>& e) { checkMatch(e); } virtual void visit(PElementSet<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<vector, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PMatrixMult<T_element>& e) { checkMatch(e); } virtual void visit(PMatrixVectorMult<T_element>& e) { checkMatch(e); } virtual void visit(PTransposeMatrixVectorMult<T_element>& e) { checkMatch(e); } virtual void visit(PVectorDot<T_element>& e) { checkMatch(e); } virtual void visit(PVectorCross<T_element>& e) { checkMatch(e); } virtual void visit(PVectorTwoNorm<T_element>& e) { checkMatch(e); } virtual void visit(PMatrixTranspose<T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<vector, T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<vector, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<vector, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PAbsolute<T_element>& e) { checkMatch(e); } virtual void visit(PSquareRoot<T_element>& e) { checkMatch(e); } }; } } #endif
4,469
1,479
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION * SPDX-License-Identifier: Apache-2.0 */ #include <assert.h> #include "buffersuballocator_vk.h" #include "debug_util_vk.h" #include "error_vk.h" namespace bgfx { ////////////////////////////////////////////////////////////////////////// void BufferSubAllocator::init(MemAllocator* memAllocator, VkDeviceSize blockSize, VkBufferUsageFlags bufferUsageFlags, VkMemoryPropertyFlags memPropFlags, bool mapped, const std::vector<uint32_t>& sharingQueueFamilyIndices) { assert(!m_device); m_memAllocator = memAllocator; m_device = memAllocator->getDevice(); m_blockSize = std::min(blockSize, ((uint64_t(1) << Handle::BLOCKBITS) - 1) * uint64_t(BASE_ALIGNMENT)); m_bufferUsageFlags = bufferUsageFlags; m_memoryPropFlags = memPropFlags; m_memoryTypeIndex = ~0; m_keepLastBlock = true; m_mapped = mapped; m_sharingQueueFamilyIndices = sharingQueueFamilyIndices; m_freeBlockIndex = INVALID_ID_INDEX; m_usedSize = 0; m_allocatedSize = 0; } void BufferSubAllocator::deinit() { if(!m_memAllocator) return; free(false); m_blocks.clear(); m_memAllocator = nullptr; } BufferSubAllocator::Handle BufferSubAllocator::subAllocate(VkDeviceSize size, uint32_t align) { uint32_t usedOffset; uint32_t usedSize; uint32_t usedAligned; uint32_t blockIndex = INVALID_ID_INDEX; // if size either doesn't fit in the bits within the handle // or we are bigger than the default block size, we use a full dedicated block // for this allocation bool isDedicated = Handle::needsDedicated(size, align) || size > m_blockSize; if(!isDedicated) { // Find the first non-dedicated block that can fit the allocation for(uint32_t i = 0; i < (uint32_t)m_blocks.size(); i++) { Block& block = m_blocks[i]; if(!block.isDedicated && block.buffer && block.range.subAllocate((uint32_t)size, align, usedOffset, usedAligned, usedSize)) { blockIndex = block.index; break; } } } if(blockIndex == INVALID_ID_INDEX) { if(m_freeBlockIndex != INVALID_ID_INDEX) { Block& block = m_blocks[m_freeBlockIndex]; m_freeBlockIndex = setIndexValue(block.index, m_freeBlockIndex); blockIndex = block.index; } else { uint32_t newIndex = (uint32_t)m_blocks.size(); m_blocks.resize(m_blocks.size() + 1); Block& block = m_blocks[newIndex]; block.index = newIndex; blockIndex = newIndex; } Block& block = m_blocks[blockIndex]; block.size = std::max(m_blockSize, size); if(!isDedicated) { // only adjust size if not dedicated. // warning this lowers from 64 bit to 32 bit size, which should be fine given // such big allocations will trigger the dedicated path block.size = block.range.alignedSize((uint32_t)block.size); } VkResult result = allocBlock(block, blockIndex, block.size); NVVK_CHECK(result); if(result != VK_SUCCESS) { return Handle(); } block.isDedicated = isDedicated; if(!isDedicated) { // Dedicated blocks don't allow for subranges, so don't initialize the range allocator block.range.init((uint32_t)block.size); block.range.subAllocate((uint32_t)size, align, usedOffset, usedAligned, usedSize); m_regularBlocks++; } } Handle sub; if(!sub.setup(blockIndex, isDedicated ? 0 : usedOffset, isDedicated ? size : uint64_t(usedSize), isDedicated)) { return Handle(); } // append used space for stats m_usedSize += sub.getSize(); return sub; } void BufferSubAllocator::subFree(Handle sub) { if(!sub) return; Block& block = getBlock(sub.blockIndex); bool isDedicated = sub.isDedicated(); if(!isDedicated) { block.range.subFree(uint32_t(sub.getOffset()), uint32_t(sub.getSize())); } m_usedSize -= sub.getSize(); if(isDedicated || (block.range.isEmpty() && (!m_keepLastBlock || m_regularBlocks > 1))) { if(!isDedicated) { m_regularBlocks--; } freeBlock(block); } } float BufferSubAllocator::getUtilization(VkDeviceSize& allocatedSize, VkDeviceSize& usedSize) const { allocatedSize = m_allocatedSize; usedSize = m_usedSize; return float(double(usedSize) / double(allocatedSize)); } bool BufferSubAllocator::fitsInAllocated(VkDeviceSize size, uint32_t alignment) const { if(Handle::needsDedicated(size, alignment)) { return false; } for(const auto& block : m_blocks) { if(block.buffer && !block.isDedicated) { if(block.range.isAvailable((uint32_t)size, (uint32_t)alignment)) { return true; } } } return false; } void BufferSubAllocator::free(bool onlyEmpty) { for(uint32_t i = 0; i < (uint32_t)m_blocks.size(); i++) { Block& block = m_blocks[i]; if(block.buffer && (!onlyEmpty || (!block.isDedicated && block.range.isEmpty()))) { freeBlock(block); } } if(!onlyEmpty) { m_blocks.clear(); m_freeBlockIndex = INVALID_ID_INDEX; } } void BufferSubAllocator::freeBlock(Block& block) { m_allocatedSize -= block.size; BGFX_VKAPI(vkDestroyBuffer)(m_device, block.buffer, nullptr); if(block.mapping) { m_memAllocator->unmap(block.memory); } m_memAllocator->freeMemory(block.memory); if(!block.isDedicated) { block.range.deinit(); } block.memory = NullMemHandle; block.buffer = VK_NULL_HANDLE; block.mapping = nullptr; block.isDedicated = false; // update the block.index with the current head of the free list // pop its old value m_freeBlockIndex = setIndexValue(block.index, m_freeBlockIndex); } VkResult BufferSubAllocator::allocBlock(Block& block, uint32_t index, VkDeviceSize size) { std::string debugName = m_debugName + ":block:" + std::to_string(index); VkResult result; VkBufferCreateInfo createInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; createInfo.size = size; createInfo.usage = m_bufferUsageFlags; createInfo.sharingMode = m_sharingQueueFamilyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE; createInfo.pQueueFamilyIndices = m_sharingQueueFamilyIndices.data(); createInfo.queueFamilyIndexCount = static_cast<uint32_t>(m_sharingQueueFamilyIndices.size()); VkBuffer buffer = VK_NULL_HANDLE; result = BGFX_VKAPI(vkCreateBuffer)(m_device, &createInfo, nullptr, &buffer); if(result != VK_SUCCESS) { NVVK_CHECK(result); return result; } bgfx::DebugUtil(m_device).setObjectName(buffer, debugName); VkMemoryRequirements2 memReqs = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; VkBufferMemoryRequirementsInfo2 bufferReqs = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2}; bufferReqs.buffer = buffer; BGFX_VKAPI(vkGetBufferMemoryRequirements2)(m_device, &bufferReqs, &memReqs); if(m_memoryTypeIndex == ~0) { VkPhysicalDeviceMemoryProperties memoryProperties; BGFX_VKAPI(vkGetPhysicalDeviceMemoryProperties)(m_memAllocator->getPhysicalDevice(), &memoryProperties); VkMemoryPropertyFlags memProps = m_memoryPropFlags; // Find an available memory type that satisfies the requested properties. for(uint32_t memoryTypeIndex = 0; memoryTypeIndex < memoryProperties.memoryTypeCount; ++memoryTypeIndex) { if((memReqs.memoryRequirements.memoryTypeBits & (1 << memoryTypeIndex)) && (memoryProperties.memoryTypes[memoryTypeIndex].propertyFlags & memProps) == memProps) { m_memoryTypeIndex = memoryTypeIndex; break; } } } if(m_memoryTypeIndex == ~0) { assert(0 && "could not find memoryTypeIndex\n"); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); return VK_ERROR_INCOMPATIBLE_DRIVER; } MemAllocateInfo memAllocateInfo(memReqs.memoryRequirements, m_memoryPropFlags, false); memAllocateInfo.setDebugName(debugName); MemHandle memory = m_memAllocator->allocMemory(memAllocateInfo); if(!memory) { assert(0 && "could not allocate buffer\n"); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } MemAllocator::MemInfo memInfo = m_memAllocator->getMemoryInfo(memory); VkBindBufferMemoryInfo bindInfos = {VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO}; bindInfos.buffer = buffer; bindInfos.memory = memInfo.memory; bindInfos.memoryOffset = memInfo.offset; result = BGFX_VKAPI(vkBindBufferMemory2)(m_device, 1, &bindInfos); if(result == VK_SUCCESS) { if(m_mapped) { block.mapping = m_memAllocator->mapT<uint8_t>(memory); } else { block.mapping = nullptr; } if(!m_mapped || block.mapping) { if(m_bufferUsageFlags & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) { VkBufferDeviceAddressInfo info = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; info.buffer = buffer; block.address = BGFX_VKAPI(vkGetBufferDeviceAddress)(m_device, &info); } block.memory = memory; block.buffer = buffer; m_allocatedSize += block.size; return result; } } // error case NVVK_CHECK(result); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); m_memAllocator->freeMemory(memory); return result; } } // namespace bgfx
10,279
3,642
#include "net.h" #include "opencv2/opencv.hpp" #include "mrutil.h" #define USE_INT8 0 #if _WIN32 #pragma comment(lib,"ncnn.lib") #endif const char* class_names[] = {"face", "mask"}; std::string modelname = "mask"; #if USE_INT8 modelname = modelname + "-int8"; #endif int input_size = 160; const float mean_vals[3] = {127.5f, 127.5f, 127.5f}; const float norm_vals[3] = {1.0/127.5, 1.0/127.5, 1.0/127.5}; ncnn::Net net; int detect(const cv::Mat& img, float threshold = 0.5){ int img_h = img.size().height; int img_w = img.size().width; ncnn::Mat in = ncnn::Mat::from_pixels_resize(img.data, ncnn::Mat::PIXEL_BGR, img.cols, img.rows, input_size, input_size); in.substract_mean_normalize(mean_vals, norm_vals); ncnn::Mat out; ncnn::Extractor ex = net.create_extractor(); ex.set_light_mode(true); ex.set_num_threads(4); cv::TickMeter tm; tm.start(); #if USE_PARAM_BIN ex.input(mobilenet_ssd_voc_ncnn_param_id::BLOB_data, in); ex.extract(mobilenet_ssd_voc_ncnn_param_id::BLOB_detection_out, out); #else ex.input("data", in); ex.extract("detection_out", out); #endif tm.stop(); std::cout << tm.getTimeMilli() << "ms" << std::endl; for (int i = 0; i < out.h; i++){ const float *values = out.row(i); std::string label = class_names[int(values[0])-1] + double2string(values[1]); int x1 = values[2] * img_w; int y1 = values[3] * img_h; int x2 = values[4] * img_w; int y2 = values[5] * img_h; cv::rectangle(img, {x1,y1},{x2,y2},{255,0,0}); cv::putText(img, label, {x1,y1},1,1,{0,0,255}); } cv::imshow("img",img); cv::waitKey(1); return 0; } int test_image(std::string imagepath, int testnum = 1){ cv::Mat img = cv::imread(imagepath); for (int i = 0; i < testnum; i++){ detect(img); } cv::waitKey(); return 0; } int test_camera() { cv::VideoCapture cap(0); cv::Mat img; while (true){ cap >> img; if (!img.data) { break; } detect(img); } return 0; } int main(int argc, char*argv[]){ #if NCNN_VULKAN ncnn::create_gpu_instance(); #endif net.load_param((modelname + ".param").c_str()); net.load_model((modelname + ".bin").c_str()); std::string imgpath = "images/test.jpg"; if (argc > 1) { imgpath = argv[1]; } test_image(imgpath); //test_camera(); return 0; }
2,410
1,040