hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
922d7425276ac5108fe2404b664bb1b4b9d66b8e
31,800
hpp
C++
3rdparty/GPSTk/core/lib/TimeHandling/Epoch.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/lib/TimeHandling/Epoch.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/lib/TimeHandling/Epoch.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /// @file Epoch.hpp #ifndef GPSTK_EPOCH_HPP #define GPSTK_EPOCH_HPP #include "MathBase.hpp" #include "Exception.hpp" #include "StringUtils.hpp" #include "GPSZcount.hpp" #include "CommonTime.hpp" #include "TimeTag.hpp" #include "SystemTime.hpp" #include "JulianDate.hpp" #include "MJD.hpp" #include "YDSTime.hpp" #include "CivilTime.hpp" #include "GPSWeekZcount.hpp" #include "GPSWeekSecond.hpp" #include "BDSWeekSecond.hpp" #include "GALWeekSecond.hpp" #include "QZSWeekSecond.hpp" namespace gpstk { /** @defgroup TimeHandling Time Representation */ //@{ /** * @todo Fix these comments. * * A time representation class for all common time formats, including * GPS. There is a seamless conversion between dates, times, and both, * as well as the ability to input and output the stored day-time in * formatted strings (printf() and scanf()). * * Internally, the representation of day and time uses a CommonTime * object. @see CommonTime * * In addition, the representation includes a tolerance value which is * used in CommonTime comparisons. It defaults to the value of the static * gpstk::Epoch::EPOCH_TOLERANCE, but this can be modified with the * static method setEpochTolerance(). Several different default * tolerances have been defined and are in the Epoch-Specific * Definitions section. The tolerance can also be changed on a per-object * basis with the setTolerance() member function. All comparisons are * done using the tolerance as a range for the comparison. * So, for example, operator==() returns true if the times are within * 'tolerance' seconds. Once set for each object, the tolerance is * appropriately "carried forward" to new objects through the copy * operator (operator=), the copy constructor, and elsewhere. * * The internal representation is manipulated using four fundamental * routines, two that convert between 'jday' (the integer * representation of JD) and calendar date: year/month/day-of-month, * and two that convert between seconds-of-day and hour/minute/second. * These routines can be found in the TimeConverters.hpp file. * The range of validity of the jday--calendar routines is approximately * 4317 B.C. to 4317 A.D.; these limits are incorporated into constants * Epoch::BEGINNING_OF_TIME and Epoch::END_OF_TIME. * * * All Epoch objects that lie outside these limits are disallowed. * * * This representation separates day and time-of-day cleanly. * Because day and time are logically separated, it is possible to use * Epoch for day only, or for time only. Thus, for example, one * could instantiate a Epoch object and only manipulate the date, * without reference to time-of-day; or vice-versa. [However in this * regard note that the default constructor for Epoch sets the * data, not to zero, but to the current (system) time.] * * When constructing Epoch objects from GPS time values -- such as * GPS week and seconds of weeks, or GPS week and z count -- there * may be ambiguity associated with the GPS week. Many receivers * and receiver processing software store the GPS week as it appears * in the NAV message, as a 10-bit number. This leads to a 1024 week * ambiguity when 10-bit GPS weeks are used to specify a Epoch. * In general, Epoch uses the system time to disambiguate which * 1024 week period to use. This is a good assumption except when * processing binary data from before GPS week rollover, which * occured on August 22, 1999. * */ class Epoch { public: /** * @ingroup exceptionclass * Epoch basic exception class. * @todo Do we need this, or can we get by with InvaildRequest * and/or InvalidParameter? */ NEW_EXCEPTION_CLASS(EpochException, gpstk::Exception); /** * @ingroup exceptionclass * Epoch formatting ("printing") error exception class. */ NEW_EXCEPTION_CLASS(FormatException, gpstk::Exception); /** * @name Epoch-Specific Definitions * All of these tolerances are 1/2 of the tolerance they specify. * So one nsec tolerance is actually 1/2 an ns added to the time * in units of days. */ //@{ /// One nanosecond tolerance. static const double ONE_NSEC_TOLERANCE; /// One microsecond tolerance. static const double ONE_USEC_TOLERANCE; /// One millisecond tolerance. static const double ONE_MSEC_TOLERANCE; /// One second tolerance. static const double ONE_SEC_TOLERANCE; /// One minute tolerance. static const double ONE_MIN_TOLERANCE; /// One hour tolerance. static const double ONE_HOUR_TOLERANCE; /// Default tolerance for time equality in days. static double EPOCH_TOLERANCE; /// Earliest representable Epoch. static const Epoch BEGINNING_OF_TIME; /// Latest Representable Epoch. static const Epoch END_OF_TIME; /// This is how an Epoch is printed by default. static std::string PRINT_FORMAT; //@} /// @name Tolerance Functions //@{ /// Changes the EPOCH_TOLERANCE for all Epoch objects static double setEpochTolerance(double tol) throw() { return EPOCH_TOLERANCE = tol; } /// Returns the current EPOCH_TOLERANCE. static double getEpochTolerance() throw() { return EPOCH_TOLERANCE; } /** * Sets the tolerance for output and comparisons on this object only. * See the constants in this file (e.g. ONE_NSEC_TOLERANCE) * for some easy to use tolerance values. * @param tol Tolerance in days to be used by comparison operators. * @sa Epoch-Specific Definitions */ Epoch& setTolerance(double tol) throw(); /** * Return the tolerance value currently in use by this object. * @return the current tolerance value (in seconds, of course) */ double getTolerance() const throw() { return tolerance; } //@} /// @name Constructors and Destructor //@{ /** * Default Constructor. * Initializes to current system time or to the given TimeTag. * TimeTag-covered constructors: * year, month, day, hour, minute, second (CivilTime) * long double mjd (MJD) * double mjd (MJD) * year, doy, sod (YDSTime) * Unix struct timeval (UnixTime) * GPS full week and second (GPSWeekSecond) */ Epoch(const TimeTag& tt = SystemTime()) throw(EpochException); /** * CommonTime Constructor. * Set the time using the given CommonTime object. */ Epoch(const CommonTime& ct) throw(); /** * TimeTag + Year Constructor. * Set the current time using the given year as a hint. * For example, when one only knows the 10-bit GPS week, one could * could use a "hint" year to figure out which Epoch the week was in. * TimeTag + year -covered constructors: * gps 10-bit week and second and year (GPSEpochWeekSecond + year) * gps week and zcount and year (GPSWeekZcount + year) */ Epoch(const WeekSecond& tt, short year) throw(EpochException); /** GPSZcount Constructor. * Set the current time using the given GPSZcount. */ Epoch(const GPSZcount& gzc) throw(); // Other Constructors: // gps 29-bit zcount w/ epoch determined by current system time // (GPSZcount29 + SystemTime) /// Destructor. ~Epoch() throw() {} //@} /// @name Assignment and Copy //@{ /// Copy constructor. Epoch(const Epoch &right) throw(); /// Assignment operator. Epoch& operator=(const Epoch& right) throw(); //@} /// @name Arithmetic //@{ /** * Epoch difference function. * @param right Epoch to subtract from this one. * @return difference in seconds. */ double operator-(const Epoch& right) const throw(); /** * Add seconds to this time. * @param sec Number of seconds to increase this time by. * @return The new time incremented by \c sec. */ Epoch operator+(double sec) const throw(EpochException); /** * Subtract seconds from this time. * @param sec Number of seconds to decrease this time by. * @return The new time decremented by \c sec. */ Epoch operator-(double sec) const throw(EpochException); /** * Add seconds to this time. * @param sec Number of seconds to increase this time by. * @throws EpochException on over/under-flow */ Epoch& operator+=(double sec) throw(EpochException); /** * Subtract seconds from this time. * @param sec Number of seconds to decrease this time by. * @throws EpochException on over/under-flow */ Epoch& operator-=(double sec) throw(EpochException); /** * Add (double) seconds to this time. * @param seconds Number of seconds to increase this time by. * @throws EpochException on over/under-flow */ Epoch& addSeconds(double seconds) throw(EpochException); /** * Add (integer) seconds to this time. * @param seconds Number of seconds to increase this time by. * @throws EpochException on over/under-flow */ Epoch& addSeconds(long seconds) throw(EpochException); /** * Add (integer) milliseconds to this time. * @param msec Number of milliseconds to increase this time by. * @throws EpochException on over/under-flow */ Epoch& addMilliSeconds(long msec) throw(EpochException); /** * Add (integer) microseconds to this time. * @param usec Number of microseconds to increase this time by. * @throws EpochException on over/under-flow */ Epoch& addMicroSeconds(long usec) throw(EpochException); //@} /// @name Comparisons //@{ bool operator==(const Epoch &right) const throw(); bool operator!=(const Epoch &right) const throw(); bool operator<(const Epoch &right) const throw(); bool operator>(const Epoch &right) const throw(); bool operator<=(const Epoch &right) const throw(); bool operator>=(const Epoch &right) const throw(); //@} /// @name Accessor Methods (get and set) //@{ /// Get the specified TimeTag. /// This function converts the internal store into the requested /// TimeTag type. template <class TimeTagType> TimeTagType get() const throw(EpochException); /// Get Julian Date JD /// @Warning For some compilers, this result may have diminished /// accuracy. inline long double JD() const throw(EpochException); /// Get Modified Julian Date MJD /// @Warning For some compilers, this result may have diminished /// accuracy. inline long double MJD() const throw(EpochException); /// Get year. inline short year() const throw(EpochException); /// Get month of year. inline short month() const throw(EpochException); /// Get day of month. inline short day() const throw(EpochException); /// Get day of week inline short dow() const throw(EpochException); /// Get hour of day. inline short hour() const throw(EpochException); /// Get minutes of hour. inline short minute() const throw(EpochException); /// Get seconds of minute. inline double second() const throw(EpochException); /// Get seconds of day. inline double sod() const throw(EpochException); /// Get 10-bit GPS week inline short GPSModWeek() const throw(EpochException); /// Get 10-bit GPS week, deprecated, use GPSModWeek() inline short GPSweek10() const throw(EpochException); /// Get normal (19 bit) zcount. inline long GPSzcount() const throw(EpochException); /// Same as GPSzcount() but without rounding to nearest zcount. inline long GPSzcountFloor() const throw(EpochException); /** * Get time as 32 bit Z count. * The 13 MSBs are week modulo 1024, 19 LSBs are seconds of * week in Zcounts. */ inline unsigned long GPSzcount32() const throw(EpochException); /// Same as fullZcount() but without rounding to nearest zcount. inline unsigned long GPSzcount32Floor() const throw(EpochException); /// Get GPS second of week. inline double GPSsow() const throw(EpochException); /// Get full (>10 bits) week inline short GPSweek() const throw(EpochException); /// Get BDS second of week. inline double BDSsow() const throw(EpochException); /// Get full BDS week inline short BDSweek() const throw(EpochException); /// Get mod (short) BDS week inline short BDSModWeek() const throw(EpochException); /// Get QZS second of week. inline double QZSsow() const throw(EpochException); /// Get full QZS week inline short QZSweek() const throw(EpochException); /// Get mod (short) QZS week inline short QZSModWeek() const throw(EpochException); /// Get GAL second of week. inline double GALsow() const throw(EpochException); /// Get full GAL week inline short GALweek() const throw(EpochException); /// Get mod (short) GAL week inline short GALModWeek() const throw(EpochException); /// Get day of year. inline short doy() const throw(EpochException); /// Get object time as a (long double) modified Julian date. /// @Warning For some compilers, this result may have diminished /// accuracy. inline long double getMJDasLongDouble() const throw(EpochException); /// Get object time in UNIX timeval structure. inline struct timeval unixTime() const throw(EpochException); /// Convert this object to a GPSZcount object. operator GPSZcount() const throw(EpochException); /// Convert this object to a CommonTime object. operator CommonTime() const throw(); /// @todo Could we get away with just CommonTime sets? The TimeTags /// can convert themselves to CommonTime objects. That's what we /// do internally anyway... /** Set the object using a TimeTag object. * @param tt the TimeTag to which to set this object (Defaults * to SystemTime()). * @return a reference to this object. */ Epoch& set(const TimeTag& tt = SystemTime()) throw(EpochException); /** Set the object using a TimeTag and a year as a hint. * @param tt the TimeTag to which to set this object. * @param year the "hint" year * @return a reference to this object. */ Epoch& set(const WeekSecond& tt, short year) throw(EpochException); /** * Set the object using the give CommonTime. * @param c the CommonTime object to set to * @return a reference to this object. */ Epoch& set(const CommonTime& c) throw(); /** * Set the object using a GPSZcount object. */ Epoch& set(const GPSZcount& z) throw(EpochException); /** * Set the object's time using a CommonTime object. This operation * leaves the object's date unchanged. * @note as TimeTags can be implicitly converted to CommonTime * objects, this method works for them as well. */ Epoch& setTime(const CommonTime& ct) throw(EpochException); /** * Set the object's date using a CommonTime object. This operation * leaves the object's time unchanged. * @note as TimeTags can be implicitly converted to CommonTime * objects, this method works for them as well. */ Epoch& setDate(const CommonTime& ct) throw(EpochException); /** * Set the object time to the current local time. * @todo What is this? */ Epoch& setLocalTime() throw(EpochException); // other sets: // ymdhms // week and sow (if week is 10-bit, set epoch from system time) // week and zcount (if week is 10-bit, set epoch from system time) // week, zcount, year (if week is 10-bit, set epoch from given year) // week, sow, year (if week is 10-bit, set epoch from given year) // gps 29-bit zcount (epoch determined by system time) // gps full week and sow // gps full week and zcount // year, doy, sod // long double mjd // double mjd // Unix struct timeval // ANSI time // YMD, (year/doy) w/ time unchanged // HMS, sod w/ date unchanged //@} /// @name Printing and Scanning Methods //@{ /// @todo Someone figure out how to make the table below show up /// nice in doxygen. /** * Similar to scanf, this function takes a string and a * format describing string in order to read in * values. The parameters it can take are listed below and * described above with the printf() function. * * The specification must resolve to a day at a minimum * level. The following table lists combinations that give valid * times. Anything more or other combinations will give * unknown (read as: "bad") results so don't try it. Anything * less will throw an exception. If nothing changes the time * of day, it will default to midnight. Also, the year * defaults to the current year if a year isn't specified * or can't be determined. * * @code * 1 of... and 1 of.... optional... * %C * %G %w %g %Z %Y %y %E (GPS) * %e %w %g %Y %y %R (BDS) * %l %w %g %Y %y %T (GAL) * %i %w %g %Y %y %V (QZS) * %F %w %g %Z (GPS) * %D %w %g (BDS) * %L %w %g (GAL) * %I %w %g (QZS) * %m %B %b %a %A %d %Y %y %H %M %S * %Q * %j %Y %y %s * @endcode * * So * @code * time.setToString("Aug 1, 2000 20:20:20", "%b %d, %Y %H:%M:%S") * @endcode * works but * @code * time.setToString("Aug 2000", "%b %Y") * @endcode * doesn't work (incomplete specification because it doesn't specify * a day). * * Don't worry about counting whitespace - this function will * take care of that. Just make sure that the extra stuff in * the format string (ie '.' ',') are in the same relative * location as they are in the actual string. (see in the * example above)) * * @param str string to get date/time from. * @param fmt format to use to parse \c str. * @throw EpochException if \c fmt is an incomplete specification * @throw FormatException if unable to scan \c str. * @throw StringException if an error occurs manipulating the * \c str or \c fmt strings. * @return a reference to this object. */ Epoch& scanf(const std::string& str, const std::string& fmt) throw(StringUtils::StringException, InvalidRequest); // if you can see this, ignore the \'s below, as they are for // the nasty html-ifying of doxygen. Browsers try and // interpret the % and they get all messed up. /** * Format this time into a string. * * @note * Whenever a format is added or removed from the Epoch * class, it more than likely should also be added or removed * from the FileSpec class. Additionally, the format * character must not conflict with any of the existing * format characters in Epoch or FileSpec. * * Generate and return a string containing a formatted * date, formatted by the specification \c fmt. * * \li \%Y year() * \li \%y year() % 100 * \li \%m month() * \li \%d day() * \li \%H hour() * \li \%M minute() * \li \%S (short)second() * \li \%f second() * \li \%E GPS getEpoch() * \li \%G GPS getModWeek() * \li \%F GPS getWeek() * \li \%g GPS/BDS/GAL/QZS sow() or getSOW() * \li \%Z GPSzcount() * \li \%z GPSzcountFloor() * \li \%R BDS getEpoch() * \li \%D BDS getWeek() * \li \%e BDS getModWeek() * \li \%T GAL getEpoch() * \li \%L GAL getWeek() * \li \%l GAL getModWeek() * \li \%V QZS getEpoch() * \li \%I QZS getWeek() * \li \%i QZS getModWeek() * \li \%s DOYsecond() * \li \%Q MJDdate() * \li \%w dayOfWeek() or GPSday() * \li \%b MonthAbbrevName[month()] * \li \%B MonthName[month()] * \li \%a DayOfWeekAbbrevName[dayOfWeek()] * \li \%A DayOfWeekName[dayOfWeek()] * \li \%j DOYday() or DOY() * \li \%U unixTime().tv_sec * \li \%u unixTime().tv_usec * \li \%C fullZcount() * \li \%c fullZcountFloor() * * @warning See above note. * * @param fmt format to use for this time. * @return a string containing this time in the * representation specified by \c fmt. */ std::string printf(const std::string& fmt = PRINT_FORMAT) const throw(StringUtils::StringException); //@} private: /// @name Private Methods and Data Members //@{ /// This is the core of the Epoch. /// @see CommonTime.hpp CommonTime core; /// double tolerance used in comparisons (seconds) double tolerance; //@} }; // end class Epoch /** * Stream output for Epoch objects. Typically used for debugging. * @param s stream to append formatted Epoch to. * @param t Epoch to append to stream \c s. * @return reference to \c s. */ std::ostream& operator<<( std::ostream& s, const Epoch& t ); //@} template <class TimeTagType> TimeTagType Epoch::get() const throw(EpochException) { try { return TimeTagType(core); } catch( Exception& e) { EpochException ee(e); GPSTK_THROW(ee); } } /// Get Julian Date JD /// @warning For some compilers, this result may have diminished /// accuracy. long double Epoch::JD() const throw(Epoch::EpochException) { return get<JulianDate>().jd; } /// Get Modified Julian Date MJD /// @warning For some compilers, this result may have diminished /// accuracy. long double Epoch::MJD() const throw(Epoch::EpochException) { return get<gpstk::MJD>().mjd; // gpstk to distinguish from Epoch::MJD } /// Get year. short Epoch::year() const throw(Epoch::EpochException) { return static_cast<short>(get<CivilTime>().year); } /// Get month of year. short Epoch::month() const throw(Epoch::EpochException) { return static_cast<short>(get<CivilTime>().month); } /// Get day of month. short Epoch::day() const throw(Epoch::EpochException) { return static_cast<short>(get<CivilTime>().day); } /// Get day of week short Epoch::dow() const throw(Epoch::EpochException) { return (((static_cast<long>(JD()) % 7) + 1) % 7) ; } /// Get hour of day. short Epoch::hour() const throw(Epoch::EpochException) { return static_cast<short>(get<CivilTime>().hour); } /// Get minutes of hour. short Epoch::minute() const throw(Epoch::EpochException) { return static_cast<short>(get<CivilTime>().minute); } /// Get seconds of minute. double Epoch::second() const throw(Epoch::EpochException) { return get<CivilTime>().second; } /// Get seconds of day. double Epoch::sod() const throw(Epoch::EpochException) { return get<YDSTime>().sod; } /// Get 10-bit GPS week. Deprecated, used GPSModWeek() short Epoch::GPSweek10() const throw(Epoch::EpochException) { return GPSModWeek(); } /// Get 10-bit GPS week short Epoch::GPSModWeek() const throw(Epoch::EpochException) { return static_cast<short>(get<GPSWeekSecond>().getModWeek()); } /// Get normal (19 bit) zcount. long Epoch::GPSzcount() const throw(Epoch::EpochException) { return get<GPSWeekZcount>().zcount; } /// Same as GPSzcount() but without rounding to nearest zcount. long Epoch::GPSzcountFloor() const throw(Epoch::EpochException) { Epoch e = *this + .75; // add half a zcount return e.get<GPSWeekZcount>().zcount; } /// Get time as 32 bit Z count. /// The 13 MSBs are week modulo 1024, 19 LSBs are seconds of /// week in Zcounts. unsigned long Epoch::GPSzcount32() const throw(Epoch::EpochException) { return get<GPSWeekZcount>().getZcount32(); } /// Same as fullZcount() but without rounding to nearest zcount. unsigned long Epoch::GPSzcount32Floor() const throw(Epoch::EpochException) { Epoch e = *this + .75; // add half a zcount return e.get<GPSWeekZcount>().getZcount32(); } /// Get GPS second of week. double Epoch::GPSsow() const throw(Epoch::EpochException) { return get<GPSWeekSecond>().sow; } /// Get full (>10 bits) week short Epoch::GPSweek() const throw(Epoch::EpochException) { return static_cast<short>(get<GPSWeekSecond>().week); } /// Get BDS second of week. double Epoch::BDSsow() const throw(Epoch::EpochException) { return get<BDSWeekSecond>().sow; } /// Get full BDS week short Epoch::BDSweek() const throw(Epoch::EpochException) { return static_cast<short>(get<BDSWeekSecond>().week); } /// Get mod (short) BDS week short Epoch::BDSModWeek() const throw(Epoch::EpochException) { return static_cast<short>(get<BDSWeekSecond>().getModWeek()); } /// Get QZS second of week. double Epoch::QZSsow() const throw(Epoch::EpochException) { return get<QZSWeekSecond>().sow; } /// Get full QZS week short Epoch::QZSweek() const throw(Epoch::EpochException) { return static_cast<short>(get<QZSWeekSecond>().week); } /// Get mod (short) QZS week short Epoch::QZSModWeek() const throw(Epoch::EpochException) { return static_cast<short>(get<QZSWeekSecond>().getModWeek()); } /// Get GAL second of week. double Epoch::GALsow() const throw(Epoch::EpochException) { return get<GALWeekSecond>().sow; } /// Get full GAL week short Epoch::GALweek() const throw(Epoch::EpochException) { return static_cast<short>(get<GALWeekSecond>().week); } /// Get mod (short) GAL week short Epoch::GALModWeek() const throw(Epoch::EpochException) { return static_cast<short>(get<GALWeekSecond>().getModWeek()); } /// Get day of year. short Epoch::doy() const throw(Epoch::EpochException) { return static_cast<short>(get<YDSTime>().doy); } /// Get object time in UNIX timeval structure. struct timeval Epoch::unixTime() const throw(Epoch::EpochException) { return get<UnixTime>().tv; } } // namespace gpstk #endif // GPSTK_EPOCH_HPP
33.333333
80
0.564214
[ "object" ]
9239b3b1afbac3f0ada9ab46fd929bee644ff173
18,949
cpp
C++
Samples/SensorStreamViewer/SensorStreamViewer.xaml.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
250
2017-07-26T20:54:22.000Z
2019-05-03T09:21:12.000Z
Samples/SensorStreamViewer/SensorStreamViewer.xaml.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
79
2017-08-08T20:08:02.000Z
2019-05-06T14:32:45.000Z
Samples/SensorStreamViewer/SensorStreamViewer.xaml.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
88
2017-07-28T09:11:51.000Z
2019-05-04T03:48:44.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "SensorImageControl.xaml.h" #include "SensorStreamViewer.xaml.h" #include "SensorStreamViewer.g.h" #include "FrameRenderer.h" #include <unordered_set> using namespace SensorStreaming; using namespace concurrency; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Imaging; using namespace Windows::Media::Capture; using namespace Windows::Media::Capture::Frames; using namespace Windows::UI::Xaml::Media::Imaging; SensorStreamViewer::SensorStreamViewer() { InitializeComponent(); m_logger = ref new SimpleLogger(outputTextBlock); this->PlayStopButton->IsEnabled = false; } SensorStreaming::SensorStreamViewer::~SensorStreamViewer() { CleanupMediaCaptureAsync(); } void SensorStreaming::SensorStreamViewer::Start() { LoadMediaSourceAsync(); } void SensorStreaming::SensorStreamViewer::Stop() { auto cleanUpTask = CleanupMediaCaptureAsync(); cleanUpTask.wait(); } void SensorStreamViewer::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) { LoadMediaSourceAsync(); } void SensorStreamViewer::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) { CleanupMediaCaptureAsync(); } void SensorStreamViewer::NextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { LoadMediaSourceAsync(); } task<void> SensorStreamViewer::LoadMediaSourceAsync() { return LoadMediaSourceWorkerAsync() .then([this]() { }, task_continuation_context::use_current()); } int MFSourceIdToStreamId(const std::wstring& sourceIdStr) { size_t start = sourceIdStr.find_first_of(L'#'); size_t end = sourceIdStr.find_first_of(L'@'); VERIFY(start != std::wstring::npos); VERIFY(end != std::wstring::npos); VERIFY(end > start); std::wstring idStr = sourceIdStr.substr(start + 1, end - start - 1); VERIFY(idStr.size() != 0); std::wstringstream wss(idStr); int id = 0; VERIFY(wss >> id); return id; } task<void> SensorStreamViewer::LoadMediaSourceWorkerAsync() { return CleanupMediaCaptureAsync() .then([this]() { return create_task(MediaFrameSourceGroup::FindAllAsync()); }, task_continuation_context::get_current_winrt_context()) .then([this](IVectorView<MediaFrameSourceGroup^>^ allGroups) { if (allGroups->Size == 0) { m_logger->Log("No source groups found."); return task_from_result(); } MediaFrameSourceGroup^ selectedGroup; for (uint32_t i = 0; i < allGroups->Size; ++i) { MediaFrameSourceGroup^ candidateGroup = allGroups->GetAt(i); if (candidateGroup->DisplayName == "Sensor Streaming") { m_selectedSourceGroupIndex = i; selectedGroup = candidateGroup; break; } } if (!selectedGroup) { m_logger->Log("No Sensor Streaming groups found."); return task_from_result(); } m_logger->Log("Found " + allGroups->Size.ToString() + " groups and " + "selecting index [" + m_selectedSourceGroupIndex.ToString() + "] : " + selectedGroup->DisplayName); // Initialize MediaCapture with selected group. return TryInitializeMediaCaptureAsync(selectedGroup) .then([this, selectedGroup](bool initialized) { if (!initialized) { return CleanupMediaCaptureAsync(); } // Set up frame readers, register event handlers and start streaming. auto startedKinds = std::make_shared<std::unordered_set<MediaFrameSourceKind>>(); task<void> createReadersTask = task_from_result(); for (IKeyValuePair<String^, MediaFrameSource^>^ kvp : m_mediaCapture->FrameSources) { std::lock_guard<std::mutex> lockGuard(m_volatileState.m_mutex); MediaFrameSource^ source = kvp->Value; MediaFrameSourceKind kind = source->Info->SourceKind; std::wstring sourceIdStr(source->Info->Id->Data()); int id = MFSourceIdToStreamId(sourceIdStr); Platform::String^ sensorName(kind.ToString()); #if DEBUG_PRINT_PROPERTIES DebugOutputAllProperties(source->Info->Properties); #endif GetSensorName(source, sensorName); // Create the Sensor views SensorImageControl^ imageControl = ref new SensorImageControl(id, sensorName); m_volatileState.m_frameRenderers[id] = imageControl->GetRenderer(); m_volatileState.m_frameRenderers[id]->SetSensorName(sensorName); Windows::UI::Core::CoreDispatcher^ uiThreadDispatcher = Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher; uiThreadDispatcher->RunAsync( Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler( [this, imageControl, id]() { StreamGrid->Children->Append(imageControl); imageControl->SetValue(Windows::UI::Xaml::Controls::Grid::RowProperty, id / 4); imageControl->SetValue(Windows::UI::Xaml::Controls::Grid::ColumnProperty, id - ((id / 4) * 4)); #if 0 imageControl->PointerPressed += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &SensorStreaming::SensorStreamViewer::OnPointerPressed); #endif imageControl->Background = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green); })); // Read all frames the first time if (m_volatileState.m_firstRunComplete && (id != m_volatileState.m_selectedStreamId)) { continue; } createReadersTask = createReadersTask.then([this, startedKinds, source, kind, id]() { // Look for a format which the FrameRenderer can render. String^ requestedSubtype = nullptr; auto found = std::find_if(begin(source->SupportedFormats), end(source->SupportedFormats), [&](MediaFrameFormat^ format) { requestedSubtype = FrameRenderer::GetSubtypeForFrameReader(kind, format); return requestedSubtype != nullptr; }); if (requestedSubtype == nullptr) { // No acceptable format was found. Ignore this source. return task_from_result(); } // Tell the source to use the format we can render. return create_task(source->SetFormatAsync(*found)) .then([this, source, requestedSubtype]() { return create_task(m_mediaCapture->CreateFrameReaderAsync(source, requestedSubtype)); }, task_continuation_context::get_current_winrt_context()) .then([this, kind, source, id](MediaFrameReader^ frameReader) { std::lock_guard<std::mutex> lockGuard(m_volatileState.m_mutex); // Add frame reader to the internal lookup m_volatileState.m_FrameReadersToSourceIdMap[frameReader->GetHashCode()] = id; EventRegistrationToken token = frameReader->FrameArrived += ref new TypedEventHandler<MediaFrameReader^, MediaFrameArrivedEventArgs^>(this, &SensorStreamViewer::FrameReader_FrameArrived); // Keep track of created reader and event handler so it can be stopped later. m_volatileState.m_readers.push_back(std::make_pair(frameReader, token)); m_logger->Log(kind.ToString() + " reader created"); return create_task(frameReader->StartAsync()); }, task_continuation_context::get_current_winrt_context()) .then([this, kind, startedKinds](MediaFrameReaderStartStatus status) { if (status == MediaFrameReaderStartStatus::Success) { m_logger->Log("Started " + kind.ToString() + " reader."); startedKinds->insert(kind); } else { m_logger->Log("Unable to start " + kind.ToString() + " reader. Error: " + status.ToString()); } }, task_continuation_context::get_current_winrt_context()); }, task_continuation_context::get_current_winrt_context()); } // Run the loop and see if any sources were used. return createReadersTask.then([this, startedKinds, selectedGroup]() { if (startedKinds->size() == 0) { m_logger->Log("No eligible sources in " + selectedGroup->DisplayName + "."); } }, task_continuation_context::get_current_winrt_context()); }, task_continuation_context::get_current_winrt_context()); }, task_continuation_context::get_current_winrt_context()); } task<bool> SensorStreamViewer::TryInitializeMediaCaptureAsync(MediaFrameSourceGroup^ group) { if (m_mediaCapture != nullptr) { // Already initialized. return task_from_result(true); } // Initialize mediacapture with the source group. m_mediaCapture = ref new MediaCapture(); auto settings = ref new MediaCaptureInitializationSettings(); // Select the source we will be reading from. settings->SourceGroup = group; // This media capture can share streaming with other apps. settings->SharingMode = MediaCaptureSharingMode::SharedReadOnly; // Only stream video and don't initialize audio capture devices. settings->StreamingCaptureMode = StreamingCaptureMode::Video; // Set to CPU to ensure frames always contain CPU SoftwareBitmap images, // instead of preferring GPU D3DSurface images. settings->MemoryPreference = MediaCaptureMemoryPreference::Cpu; // Only stream video and don't initialize audio capture devices. settings->StreamingCaptureMode = StreamingCaptureMode::Video; // Initialize MediaCapture with the specified group. // This must occur on the UI thread because some device families // (such as Xbox) will prompt the user to grant consent for the // app to access cameras. // This can raise an exception if the source no longer exists, // or if the source could not be initialized. return create_task(m_mediaCapture->InitializeAsync(settings)) .then([this](task<void> initializeMediaCaptureTask) { try { // Get the result of the initialization. This call will throw if initialization failed // This pattern is docuemnted at https://msdn.microsoft.com/en-us/library/dd997692.aspx initializeMediaCaptureTask.get(); m_logger->Log("MediaCapture is successfully initialized in shared mode."); return true; } catch (Exception^ exception) { m_logger->Log("Failed to initialize media capture: " + exception->Message); return false; } }); } /// Unregisters FrameArrived event handlers, stops and disposes frame readers /// and disposes the MediaCapture object. task<void> SensorStreamViewer::CleanupMediaCaptureAsync() { task<void> cleanupTask = task_from_result(); if (m_mediaCapture != nullptr) { std::lock_guard<std::mutex> lockGuard(m_volatileState.m_mutex); for (auto& readerAndToken : m_volatileState.m_readers) { MediaFrameReader^ reader = readerAndToken.first; EventRegistrationToken token = readerAndToken.second; reader->FrameArrived -= token; cleanupTask = cleanupTask && create_task(reader->StopAsync()); } cleanupTask = cleanupTask.then([this] { m_logger->Log("Cleaning up MediaCapture..."); m_volatileState.m_readers.clear(); m_volatileState.m_frameRenderers.clear(); m_volatileState.m_FrameReadersToSourceIdMap.clear(); m_volatileState.m_frameCount.clear(); m_mediaCapture = nullptr; }); } return cleanupTask; } static Platform::String^ PropertyGuidToString(Platform::Guid& guid) { if (guid == Platform::Guid(MFSampleExtension_DeviceTimestamp)) { return L"MFSampleExtension_DeviceTimestamp"; } else if (guid == Platform::Guid(MFSampleExtension_Spatial_CameraViewTransform)) { return L"MFSampleExtension_Spatial_CameraViewTransform"; } else if (guid == Platform::Guid(MFSampleExtension_Spatial_CameraCoordinateSystem)) { return L"MFSampleExtension_Spatial_CameraCoordinateSystem"; } else if (guid == Platform::Guid(MFSampleExtension_Spatial_CameraProjectionTransform)) { return L"MFSampleExtension_Spatial_CameraProjectionTransform"; } else if (guid == Platform::Guid(MFSampleExtension_DeviceReferenceSystemTime)) { return L"MFSampleExtension_DeviceReferenceSystemTime"; } else if (guid == Platform::Guid(MFSampleExtension_CameraExtrinsics)) { return L"MFSampleExtension_CameraExtrinsics"; } else if (guid == Platform::Guid(MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES)) { return L"MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES"; } else if (guid == Platform::Guid(MF_MT_USER_DATA)) { return L"MF_MT_USER_DATA"; } else { return guid.ToString(); } } void SensorStreamViewer::DebugOutputAllProperties(Windows::Foundation::Collections::IMapView<Platform::Guid, Platform::Object^>^ properties) { if (IsDebuggerPresent()) { auto itr = properties->First(); while (itr->HasCurrent) { auto current = itr->Current; auto keyString = PropertyGuidToString(current->Key); OutputDebugStringW(reinterpret_cast<const wchar_t*>(keyString->Data())); OutputDebugStringW(L"\n"); itr->MoveNext(); } } } void SensorStreamViewer::FrameReader_FrameArrived(MediaFrameReader^ sender, MediaFrameArrivedEventArgs^ args) { // TryAcquireLatestFrame will return the latest frame that has not yet been acquired. // This can return null if there is no such frame, or if the reader is not in the // "Started" state. The latter can occur if a FrameArrived event was in flight // when the reader was stopped. if (sender == nullptr) { return; } if (MediaFrameReference^ frame = sender->TryAcquireLatestFrame()) { if (frame != nullptr) { FrameRenderer^ frameRenderer = nullptr; { std::lock_guard<std::mutex> lockGuard(m_volatileState.m_mutex); // Find the corresponding source id VERIFY(m_volatileState.m_FrameReadersToSourceIdMap.count(sender->GetHashCode()) != 0); int sourceId = m_volatileState.m_FrameReadersToSourceIdMap[sender->GetHashCode()]; frameRenderer = m_volatileState.m_frameRenderers[sourceId]; m_volatileState.m_frameCount[sourceId]++; if (!m_volatileState.m_firstRunComplete) { // first run is complete if all the streams have atleast one frame bool allStreamsGotFrames = (m_volatileState.m_frameCount.size() == m_volatileState.m_frameRenderers.size()); m_volatileState.m_firstRunComplete = allStreamsGotFrames; #if 0 if (allStreamsGotFrames) { m_volatileState.m_selectedStreamId = 1; LoadMediaSourceAsync(); } #endif } } if (frameRenderer) { frameRenderer->ProcessFrame(frame); } } } } bool SensorStreamViewer::GetSensorName(Windows::Media::Capture::Frames::MediaFrameSource^ source, Platform::String^& name) { bool success = false; if (source->Info->Properties->HasKey(MF_MT_USER_DATA)) { Platform::Object^ mfMtUserData = source->Info->Properties->Lookup( MF_MT_USER_DATA); Platform::Array<byte>^ sensorNameAsPlatformArray = safe_cast<Platform::IBoxArray<byte>^>( mfMtUserData)->Value; name = ref new Platform::String( reinterpret_cast<const wchar_t*>( sensorNameAsPlatformArray->Data)); success = true; } return success; } void SensorStreaming::SensorStreamViewer::PlayStopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { this->Stop(); } void SensorStreaming::SensorStreamViewer::OnPointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e) { auto imageControl = dynamic_cast<SensorImageControl^>(sender); if (imageControl != nullptr) { std::lock_guard<std::mutex> lockGuard(m_volatileState.m_mutex); if (imageControl->GetId() != m_volatileState.m_selectedStreamId) { m_volatileState.m_selectedStreamId = imageControl->GetId(); LoadMediaSourceAsync(); } } }
37.973948
169
0.604623
[ "render", "object" ]
9239b4ca41e63e9fbf93b26bedf65c05b69e25d0
546
cpp
C++
contest-1000-problem-A.cpp
ss6364/CodeForces-contests
40a2ea7fd75d754d9c42c596c5bbfccf8b3ebdc1
[ "Unlicense" ]
2
2019-05-06T04:29:05.000Z
2019-05-06T09:19:03.000Z
contest-1000-problem-A.cpp
ss6364/CodeForces-contests
40a2ea7fd75d754d9c42c596c5bbfccf8b3ebdc1
[ "Unlicense" ]
null
null
null
contest-1000-problem-A.cpp
ss6364/CodeForces-contests
40a2ea7fd75d754d9c42c596c5bbfccf8b3ebdc1
[ "Unlicense" ]
null
null
null
#include<bits/stdc++.h> using namespace std ; int main(){ int n,count=0; cin>>n; int n2=n; char a[1000],b[1000]; vector<string> vect1; vector<string> vect; while(n--){ cin>>a; vect.push_back(a); } n=n2; while(n2--){ cin>>b; vect2.push_back(a); } vect.sort(vect.begin(),vect.end()); vect1.sort(vect1.begin(),vect1.end()); for(int i=0;i<n;i++){ int l=strlen(vect[i]); char s[1000],s2[1000]; s=vect[i]; s2=vect1[i]; for(int j=0;j<l;j++){ if(s[j]!=s2[j]){ count++; } } } cout<<count<<endl; return 0 ; }
15.6
39
0.565934
[ "vector" ]
923dd141f05e2422ef308916ad213394d8f3e518
1,527
cc
C++
gquiche/quic/tools/quic_server_bin.cc
Moxoo/quiche
16a9562e5040eeac7263ace423fedaf7202f24c5
[ "Apache-2.0" ]
null
null
null
gquiche/quic/tools/quic_server_bin.cc
Moxoo/quiche
16a9562e5040eeac7263ace423fedaf7202f24c5
[ "Apache-2.0" ]
null
null
null
gquiche/quic/tools/quic_server_bin.cc
Moxoo/quiche
16a9562e5040eeac7263ace423fedaf7202f24c5
[ "Apache-2.0" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // A binary wrapper for QuicServer. It listens forever on --port // (default 6121) until it's killed or ctrl-cd to death. #include <vector> #include "gquiche/quic/core/quic_versions.h" #include "gquiche/quic/platform/api/quic_flags.h" #include "gquiche/quic/platform/api/quic_system_event_loop.h" #include "gquiche/quic/tools/quic_epoll_server_factory.h" #include "gquiche/quic/tools/quic_toy_server.h" #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, verbosity, 0, "The verbosity will be set."); int main(int argc, char* argv[]) { QuicSystemEventLoop event_loop("quic_server"); const char* usage = "Usage: quic_server [options]"; std::vector<std::string> non_option_args = quic::QuicParseCommandLineFlags(usage, argc, argv); if (!non_option_args.empty()) { quic::QuicPrintCommandLineFlagHelp(usage); exit(0); } auto logger = spdlog::stdout_color_mt("quic-server"); quiche::GetLogger().swap(*logger); quiche::SetVerbosityLogThreshold(GetQuicFlag(FLAGS_verbosity)); quic::QuicToyServer::MemoryCacheBackendFactory backend_factory; quic::QuicEpollServerFactory server_factory; quic::QuicToyServer server(&backend_factory, &server_factory); return server.Start(); }
36.357143
73
0.715783
[ "vector" ]
9243edd29879c399f0f81d5c14936b7e9349bdbc
1,899
cc
C++
src/abc065/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc065/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc065/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<vector<pair<ll, int>>> build_graph(int n, vector<ll> x, vector<ll> y) { vector<vector<pair<ll, int>>> edges(n, vector<pair<ll, int>>()); vector<int> ids(n); iota(ids.begin(), ids.end(), 0); sort(ids.begin(), ids.end(), [&](int i, int j) { return x[i] < x[j]; }); for(int i = 0; i < n - 1; i++) { int id = ids[i]; int next_id = ids[i + 1]; edges[id].push_back(make_pair(abs(x[id] - x[next_id]), next_id)); edges[next_id].push_back(make_pair(abs(x[id] - x[next_id]), id)); } sort(ids.begin(), ids.end(), [&](int i, int j) { return y[i] < y[j]; }); for(int i = 0; i < n - 1; i++) { int id = ids[i]; int next_id = ids[i + 1]; edges[id].push_back(make_pair(abs(y[id] - y[next_id]), next_id)); edges[next_id].push_back(make_pair(abs(y[id] - y[next_id]), id)); } return edges; } ll solve(int n, vector<ll> x, vector<ll> y) { vector<vector<pair<ll, int>>> edges = build_graph(n, x, y); vector<bool> used(n, false); priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> que; for(int i = 0; i < (int)edges[0].size(); i++) { que.push(edges[0][i]); } used[0] = true; ll res = 0; while(!que.empty()) { pair<ll, int> v = que.top(); que.pop(); if(used[v.second]) continue; used[v.second] = true; for(int i = 0; i < (int)edges[v.second].size(); i++) { auto edge = edges[v.second][i]; if(!used[edge.second]) { que.push(edge); } } res += v.first; } return res; } /* int main() { int n; cin >> n; vector<ll> x(n), y(n); for(int i = 0; i < n; i++) { cin >> x[i] >> y[i]; } cout << solve(n, x, y); } */
27.926471
80
0.493944
[ "vector" ]
92480632bb1008254e38bd289576267ad346232f
4,679
cxx
C++
physics/neutron/nudy/src/TNudyEndfTab1.cxx
Geant-RnD/geant
ffff95e23547531f3254ada2857c062a31f33e8f
[ "ECL-2.0", "Apache-2.0" ]
2
2016-10-16T14:37:42.000Z
2018-04-05T15:49:09.000Z
physics/neutron/nudy/src/TNudyEndfTab1.cxx
Geant-RnD/geant
ffff95e23547531f3254ada2857c062a31f33e8f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
physics/neutron/nudy/src/TNudyEndfTab1.cxx
Geant-RnD/geant
ffff95e23547531f3254ada2857c062a31f33e8f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* This is the main class supporting an ENDF section in R-ENDF format */ // @(#)root/meta:$Id: TNuEndf.h 29000 2009-06-15 13:53:52Z rdm $ // Author: F.Carminati 02/05/09 #include "Geant/TNudyEndfTab1.h" using namespace Nudy; #ifdef USE_ROOT ClassImp(TNudyEndfTab1) #endif //_______________________________________________________________________________ TNudyEndfTab1::TNudyEndfTab1() : TNudyEndfCont(), fNBT(NULL), fINT(NULL), fX(NULL), fY(NULL) { // // Default constructor // } //_______________________________________________________________________________ TNudyEndfTab1::TNudyEndfTab1(TNudyEndfTab1 *tab, int n1, int n2) : TNudyEndfCont(tab->GetC1(), tab->GetC2(), tab->GetL1(), tab->GetL2(), n1, n2), fNBT(new int[n1]), fINT(new int[n1]), fX(new double[n2]), fY(new double[n2]) { memcpy(fNBT, tab->NBT(), sizeof(int) * tab->GetN1()); memcpy(fINT, tab->INT(), sizeof(int) * tab->GetN1()); memcpy(fX, tab->X(), sizeof(double) * tab->GetN2()); memcpy(fY, tab->Y(), sizeof(double) * tab->GetN2()); } //_______________________________________________________________________________ TNudyEndfTab1::TNudyEndfTab1(double c1, double c2, int l1, int l2, int n1, int n2) : TNudyEndfCont(c1, c2, l1, l2, n1, n2), fNBT(new int[n1]), fINT(new int[n1]), fX(new double[n2]), fY(new double[n2]) { // // Standard constructor // } //_______________________________________________________________________________ TNudyEndfTab1::~TNudyEndfTab1() { // printf("Deleting Tab1\n"); delete[] fNBT; delete[] fINT; delete[] fX; delete[] fY; } //_______________________________________________________________________________ void TNudyEndfTab1::Equate(TNudyEndfTab1 *tab) { SetCont(tab->GetC1(), tab->GetC2(), tab->GetL1(), tab->GetL2(), tab->GetN1(), tab->GetN2()); memcpy(fNBT, tab->NBT(), sizeof(int) * tab->GetN1()); memcpy(fINT, tab->INT(), sizeof(int) * tab->GetN1()); memcpy(fX, tab->X(), sizeof(double) * tab->GetN2()); memcpy(fY, tab->Y(), sizeof(double) * tab->GetN2()); } //______________________________________________________________________________ void TNudyEndfTab1::SetCont(double c1, double c2, int l1, int l2, int n1, int n2) { TNudyEndfCont::SetCont(c1, c2, l1, l2, n1, n2); delete[] fNBT; delete[] fINT; delete[] fX; delete[] fY; fNBT = new int[n1]; fINT = new int[n1]; fX = new double[n2]; fY = new double[n2]; } //_______________________________________________________________________________ void TNudyEndfTab1::SetContMF(int mat, int mt, int mf) { TNudyEndfCont::SetContMF(mat, mt, mf); } // // Dumps Tab1 records to ENDF //______________________________________________________________________________ void TNudyEndfTab1::DumpENDF(int mat, int mf, int mt, int &ns, int flags) { char s1[14], s2[14]; F2F(fC1, s1); F2F(fC2, s2); printf("%11s%11s%11d%11d%11d%11d", s1, s2, fL1, fL2, fN1, fN2); printf("%4d%2d%3d%5d", mat, mf, mt, ns); if (ns < 99999) ns++; else ns = 1; if (flags) printf(" ---CONT TAB1\n"); else printf("\n"); for (int i = 0; i < GetNR(); i++) { // print NBT(N) INT(N) if (i % 3 == 0 && i != 0) { printf("%4d%2d%3d%5d", mat, mf, mt, ns); if (ns < 99999) ns++; else ns = 1; if (flags) printf(" ---NBT(%d,%d,%d) TAB1\n", i - 2, i - 1, i); else printf("\n"); } printf("%11d%11d", GetNBT(i), GetINT(i)); } // Pad blank columns if (3 - (GetNR() % 3) < 3) { for (int i = 0; i < 3 - (GetNR() % 3); i++) { printf("%22s", " "); } } printf("%4d%2d%3d%5d", mat, mf, mt, ns); if (ns < 99999) ns++; else ns = 1; if (flags) printf(" ---NBT(%d,%d,%d) TAB1\n", (GetNR() - (GetNR() % 3)) + 1, (GetNR() - (GetNR() % 3)) + 2, (GetNR() - (GetNR() % 3)) + 3); else printf("\n"); for (int i = 0; i < GetNP();) { // print 6I11 F2F(GetX(i), s1); F2F(GetY(i), s2); printf("%11s%11s", s1, s2); if ((++i) % 3 == 0) { printf("%4d%2d%3d%5d", mat, mf, mt, ns); if (ns < 99999) ns++; else ns = 1; if (flags) printf(" ---XY(%d,%d,%d) TAB1\n", i - 2, i - 1, i); else printf("\n"); } } // Pad Blank Columns if (3 - (GetNP() % 3) < 3) { for (int i = 0; i < 3 - (GetNP() % 3); i++) { printf("%22s", " "); } printf("%4d%2d%3d%5d", mat, mf, mt, ns); if (ns < 99999) ns++; else ns = 1; if (flags) printf(" ---XY(%d,%d,%d) TAB1\n", (GetNP() - (GetNP() % 3)) + 1, (GetNP() - (GetNP() % 3)) + 2, (GetNP() - (GetNP() % 3)) + 3); else printf("\n"); } }
28.186747
103
0.584527
[ "3d" ]
925495b284f920635c81b09dcfef7d9882d8807f
598
cpp
C++
clu/Operators/FullFileOperator.cpp
ShaiRoitman/clu
c8816455a78ed70d1885fa23f6442d1d2a823a16
[ "MIT" ]
null
null
null
clu/Operators/FullFileOperator.cpp
ShaiRoitman/clu
c8816455a78ed70d1885fa23f6442d1d2a823a16
[ "MIT" ]
3
2017-01-10T18:37:43.000Z
2017-01-15T07:11:46.000Z
clu/Operators/FullFileOperator.cpp
ShaiRoitman/clu
c8816455a78ed70d1885fa23f6442d1d2a823a16
[ "MIT" ]
null
null
null
#include "FullFileOperator.h" bool FullFileOperator::OnLineRead(string& line) { m_data.push_back(line); return true; } void FullFileOperator::PrintData() { for (vector<string>::iterator iter = m_data.begin(); iter != m_data.end(); ++iter) { string& cur_line = *iter; m_OutputHandler->OutputLineFeed(cur_line); } } void FullFileOperator::PrintReverseData() { for (vector<string>::reverse_iterator iter = m_data.rbegin(); iter != m_data.rend(); ++iter) { string& cur_line = *iter; m_OutputHandler->OutputLineFeed(cur_line); } } void FullFileOperator::OnEnd() { m_data.clear(); }
19.290323
93
0.70903
[ "vector" ]
925b4c0461f7cbf5d3195e3b833065c435632dc1
107,211
hpp
C++
include/System/DateTimeParse.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/DateTimeParse.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/DateTimeParse.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: DateTime struct DateTime; // Forward declaring type: DateTimeResult struct DateTimeResult; // Forward declaring type: TimeSpan struct TimeSpan; // Forward declaring type: __DTString struct __DTString; // Skipping declaration: DS because it is already included! // Forward declaring type: DateTimeToken struct DateTimeToken; // Forward declaring type: DateTimeRawInfo struct DateTimeRawInfo; // Forward declaring type: ParsingInfo struct ParsingInfo; // Forward declaring type: Exception class Exception; } // Forward declaring namespace: System::Globalization namespace System::Globalization { // Forward declaring type: DateTimeFormatInfo class DateTimeFormatInfo; // Forward declaring type: DateTimeStyles struct DateTimeStyles; // Forward declaring type: Calendar class Calendar; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: System namespace System { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.DateTimeParse // [TokenAttribute] Offset: FFFFFFFF class DateTimeParse : public ::Il2CppObject { public: // Nested type: System::DateTimeParse::MatchNumberDelegate class MatchNumberDelegate; // Nested type: System::DateTimeParse::DTT struct DTT; // Nested type: System::DateTimeParse::TM struct TM; // Nested type: System::DateTimeParse::DS struct DS; // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: System.DateTimeParse/System.DS // [TokenAttribute] Offset: FFFFFFFF struct DS/*, public System::Enum*/ { public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: DS constexpr DS(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator System::Enum operator System::Enum() noexcept { return *reinterpret_cast<System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public System.DateTimeParse/System.DS BEGIN static constexpr const int BEGIN = 0; // Get static field: static public System.DateTimeParse/System.DS BEGIN static System::DateTimeParse::DS _get_BEGIN(); // Set static field: static public System.DateTimeParse/System.DS BEGIN static void _set_BEGIN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS N static constexpr const int N = 1; // Get static field: static public System.DateTimeParse/System.DS N static System::DateTimeParse::DS _get_N(); // Set static field: static public System.DateTimeParse/System.DS N static void _set_N(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS NN static constexpr const int NN = 2; // Get static field: static public System.DateTimeParse/System.DS NN static System::DateTimeParse::DS _get_NN(); // Set static field: static public System.DateTimeParse/System.DS NN static void _set_NN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_Nd static constexpr const int D_Nd = 3; // Get static field: static public System.DateTimeParse/System.DS D_Nd static System::DateTimeParse::DS _get_D_Nd(); // Set static field: static public System.DateTimeParse/System.DS D_Nd static void _set_D_Nd(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_NN static constexpr const int D_NN = 4; // Get static field: static public System.DateTimeParse/System.DS D_NN static System::DateTimeParse::DS _get_D_NN(); // Set static field: static public System.DateTimeParse/System.DS D_NN static void _set_D_NN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_NNd static constexpr const int D_NNd = 5; // Get static field: static public System.DateTimeParse/System.DS D_NNd static System::DateTimeParse::DS _get_D_NNd(); // Set static field: static public System.DateTimeParse/System.DS D_NNd static void _set_D_NNd(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_M static constexpr const int D_M = 6; // Get static field: static public System.DateTimeParse/System.DS D_M static System::DateTimeParse::DS _get_D_M(); // Set static field: static public System.DateTimeParse/System.DS D_M static void _set_D_M(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_MN static constexpr const int D_MN = 7; // Get static field: static public System.DateTimeParse/System.DS D_MN static System::DateTimeParse::DS _get_D_MN(); // Set static field: static public System.DateTimeParse/System.DS D_MN static void _set_D_MN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_NM static constexpr const int D_NM = 8; // Get static field: static public System.DateTimeParse/System.DS D_NM static System::DateTimeParse::DS _get_D_NM(); // Set static field: static public System.DateTimeParse/System.DS D_NM static void _set_D_NM(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_MNd static constexpr const int D_MNd = 9; // Get static field: static public System.DateTimeParse/System.DS D_MNd static System::DateTimeParse::DS _get_D_MNd(); // Set static field: static public System.DateTimeParse/System.DS D_MNd static void _set_D_MNd(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_NDS static constexpr const int D_NDS = 10; // Get static field: static public System.DateTimeParse/System.DS D_NDS static System::DateTimeParse::DS _get_D_NDS(); // Set static field: static public System.DateTimeParse/System.DS D_NDS static void _set_D_NDS(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_Y static constexpr const int D_Y = 11; // Get static field: static public System.DateTimeParse/System.DS D_Y static System::DateTimeParse::DS _get_D_Y(); // Set static field: static public System.DateTimeParse/System.DS D_Y static void _set_D_Y(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_YN static constexpr const int D_YN = 12; // Get static field: static public System.DateTimeParse/System.DS D_YN static System::DateTimeParse::DS _get_D_YN(); // Set static field: static public System.DateTimeParse/System.DS D_YN static void _set_D_YN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_YNd static constexpr const int D_YNd = 13; // Get static field: static public System.DateTimeParse/System.DS D_YNd static System::DateTimeParse::DS _get_D_YNd(); // Set static field: static public System.DateTimeParse/System.DS D_YNd static void _set_D_YNd(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_YM static constexpr const int D_YM = 14; // Get static field: static public System.DateTimeParse/System.DS D_YM static System::DateTimeParse::DS _get_D_YM(); // Set static field: static public System.DateTimeParse/System.DS D_YM static void _set_D_YM(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_YMd static constexpr const int D_YMd = 15; // Get static field: static public System.DateTimeParse/System.DS D_YMd static System::DateTimeParse::DS _get_D_YMd(); // Set static field: static public System.DateTimeParse/System.DS D_YMd static void _set_D_YMd(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS D_S static constexpr const int D_S = 16; // Get static field: static public System.DateTimeParse/System.DS D_S static System::DateTimeParse::DS _get_D_S(); // Set static field: static public System.DateTimeParse/System.DS D_S static void _set_D_S(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS T_S static constexpr const int T_S = 17; // Get static field: static public System.DateTimeParse/System.DS T_S static System::DateTimeParse::DS _get_T_S(); // Set static field: static public System.DateTimeParse/System.DS T_S static void _set_T_S(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS T_Nt static constexpr const int T_Nt = 18; // Get static field: static public System.DateTimeParse/System.DS T_Nt static System::DateTimeParse::DS _get_T_Nt(); // Set static field: static public System.DateTimeParse/System.DS T_Nt static void _set_T_Nt(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS T_NNt static constexpr const int T_NNt = 19; // Get static field: static public System.DateTimeParse/System.DS T_NNt static System::DateTimeParse::DS _get_T_NNt(); // Set static field: static public System.DateTimeParse/System.DS T_NNt static void _set_T_NNt(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS ERROR static constexpr const int ERROR = 20; // Get static field: static public System.DateTimeParse/System.DS ERROR static System::DateTimeParse::DS _get_ERROR(); // Set static field: static public System.DateTimeParse/System.DS ERROR static void _set_ERROR(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_NN static constexpr const int DX_NN = 21; // Get static field: static public System.DateTimeParse/System.DS DX_NN static System::DateTimeParse::DS _get_DX_NN(); // Set static field: static public System.DateTimeParse/System.DS DX_NN static void _set_DX_NN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_NNN static constexpr const int DX_NNN = 22; // Get static field: static public System.DateTimeParse/System.DS DX_NNN static System::DateTimeParse::DS _get_DX_NNN(); // Set static field: static public System.DateTimeParse/System.DS DX_NNN static void _set_DX_NNN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_MN static constexpr const int DX_MN = 23; // Get static field: static public System.DateTimeParse/System.DS DX_MN static System::DateTimeParse::DS _get_DX_MN(); // Set static field: static public System.DateTimeParse/System.DS DX_MN static void _set_DX_MN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_NM static constexpr const int DX_NM = 24; // Get static field: static public System.DateTimeParse/System.DS DX_NM static System::DateTimeParse::DS _get_DX_NM(); // Set static field: static public System.DateTimeParse/System.DS DX_NM static void _set_DX_NM(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_MNN static constexpr const int DX_MNN = 25; // Get static field: static public System.DateTimeParse/System.DS DX_MNN static System::DateTimeParse::DS _get_DX_MNN(); // Set static field: static public System.DateTimeParse/System.DS DX_MNN static void _set_DX_MNN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_DS static constexpr const int DX_DS = 26; // Get static field: static public System.DateTimeParse/System.DS DX_DS static System::DateTimeParse::DS _get_DX_DS(); // Set static field: static public System.DateTimeParse/System.DS DX_DS static void _set_DX_DS(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_DSN static constexpr const int DX_DSN = 27; // Get static field: static public System.DateTimeParse/System.DS DX_DSN static System::DateTimeParse::DS _get_DX_DSN(); // Set static field: static public System.DateTimeParse/System.DS DX_DSN static void _set_DX_DSN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_NDS static constexpr const int DX_NDS = 28; // Get static field: static public System.DateTimeParse/System.DS DX_NDS static System::DateTimeParse::DS _get_DX_NDS(); // Set static field: static public System.DateTimeParse/System.DS DX_NDS static void _set_DX_NDS(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_NNDS static constexpr const int DX_NNDS = 29; // Get static field: static public System.DateTimeParse/System.DS DX_NNDS static System::DateTimeParse::DS _get_DX_NNDS(); // Set static field: static public System.DateTimeParse/System.DS DX_NNDS static void _set_DX_NNDS(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_YNN static constexpr const int DX_YNN = 30; // Get static field: static public System.DateTimeParse/System.DS DX_YNN static System::DateTimeParse::DS _get_DX_YNN(); // Set static field: static public System.DateTimeParse/System.DS DX_YNN static void _set_DX_YNN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_YMN static constexpr const int DX_YMN = 31; // Get static field: static public System.DateTimeParse/System.DS DX_YMN static System::DateTimeParse::DS _get_DX_YMN(); // Set static field: static public System.DateTimeParse/System.DS DX_YMN static void _set_DX_YMN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_YN static constexpr const int DX_YN = 32; // Get static field: static public System.DateTimeParse/System.DS DX_YN static System::DateTimeParse::DS _get_DX_YN(); // Set static field: static public System.DateTimeParse/System.DS DX_YN static void _set_DX_YN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_YM static constexpr const int DX_YM = 33; // Get static field: static public System.DateTimeParse/System.DS DX_YM static System::DateTimeParse::DS _get_DX_YM(); // Set static field: static public System.DateTimeParse/System.DS DX_YM static void _set_DX_YM(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS TX_N static constexpr const int TX_N = 34; // Get static field: static public System.DateTimeParse/System.DS TX_N static System::DateTimeParse::DS _get_TX_N(); // Set static field: static public System.DateTimeParse/System.DS TX_N static void _set_TX_N(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS TX_NN static constexpr const int TX_NN = 35; // Get static field: static public System.DateTimeParse/System.DS TX_NN static System::DateTimeParse::DS _get_TX_NN(); // Set static field: static public System.DateTimeParse/System.DS TX_NN static void _set_TX_NN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS TX_NNN static constexpr const int TX_NNN = 36; // Get static field: static public System.DateTimeParse/System.DS TX_NNN static System::DateTimeParse::DS _get_TX_NNN(); // Set static field: static public System.DateTimeParse/System.DS TX_NNN static void _set_TX_NNN(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS TX_TS static constexpr const int TX_TS = 37; // Get static field: static public System.DateTimeParse/System.DS TX_TS static System::DateTimeParse::DS _get_TX_TS(); // Set static field: static public System.DateTimeParse/System.DS TX_TS static void _set_TX_TS(System::DateTimeParse::DS value); // static field const value: static public System.DateTimeParse/System.DS DX_NNY static constexpr const int DX_NNY = 38; // Get static field: static public System.DateTimeParse/System.DS DX_NNY static System::DateTimeParse::DS _get_DX_NNY(); // Set static field: static public System.DateTimeParse/System.DS DX_NNY static void _set_DX_NNY(System::DateTimeParse::DS value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // System.DateTimeParse/System.DS #pragma pack(pop) static check_size<sizeof(DateTimeParse::DS), 0 + sizeof(int)> __System_DateTimeParse_DSSizeCheck; static_assert(sizeof(DateTimeParse::DS) == 0x4); // Creating value type constructor for type: DateTimeParse DateTimeParse() noexcept {} // Get static field: static System.DateTimeParse/System.MatchNumberDelegate m_hebrewNumberParser static System::DateTimeParse::MatchNumberDelegate* _get_m_hebrewNumberParser(); // Set static field: static System.DateTimeParse/System.MatchNumberDelegate m_hebrewNumberParser static void _set_m_hebrewNumberParser(System::DateTimeParse::MatchNumberDelegate* value); // Get static field: static private System.DateTimeParse/System.DS[][] dateParsingStates static ::Array<::Array<System::DateTimeParse::DS>*>* _get_dateParsingStates(); // Set static field: static private System.DateTimeParse/System.DS[][] dateParsingStates static void _set_dateParsingStates(::Array<::Array<System::DateTimeParse::DS>*>* value); // static private System.Void .cctor() // Offset: 0x1B5B550 static void _cctor(); // static System.DateTime ParseExact(System.String s, System.String format, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles style) // Offset: 0x1B52BFC static System::DateTime ParseExact(::Il2CppString* s, ::Il2CppString* format, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles style); // static System.Boolean TryParseExact(System.String s, System.String format, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles style, ref System.DateTimeResult result) // Offset: 0x1B52D1C static bool TryParseExact(::Il2CppString* s, ::Il2CppString* format, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles style, ByRef<System::DateTimeResult> result); // static System.Boolean TryParseExactMultiple(System.String s, System.String[] formats, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles style, out System.DateTime result, out System.TimeSpan offset) // Offset: 0x1B52894 static bool TryParseExactMultiple(::Il2CppString* s, ::Array<::Il2CppString*>* formats, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles style, ByRef<System::DateTime> result, ByRef<System::TimeSpan> offset); // static System.Boolean TryParseExactMultiple(System.String s, System.String[] formats, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles style, ref System.DateTimeResult result) // Offset: 0x1B53620 static bool TryParseExactMultiple(::Il2CppString* s, ::Array<::Il2CppString*>* formats, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles style, ByRef<System::DateTimeResult> result); // static private System.Boolean MatchWord(ref System.__DTString str, System.String target) // Offset: 0x1B537FC static bool MatchWord(ByRef<System::__DTString> str, ::Il2CppString* target); // static private System.Boolean GetTimeZoneName(ref System.__DTString str) // Offset: 0x1B53944 static bool GetTimeZoneName(ByRef<System::__DTString> str); // static System.Boolean IsDigit(System.Char ch) // Offset: 0x1B539F4 static bool IsDigit(::Il2CppChar ch); // static private System.Boolean ParseFraction(ref System.__DTString str, out System.Double result) // Offset: 0x1B53A08 static bool ParseFraction(ByRef<System::__DTString> str, ByRef<double> result); // static private System.Boolean ParseTimeZone(ref System.__DTString str, ref System.TimeSpan result) // Offset: 0x1B53AEC static bool ParseTimeZone(ByRef<System::__DTString> str, ByRef<System::TimeSpan> result); // static private System.Boolean HandleTimeZone(ref System.__DTString str, ref System.DateTimeResult result) // Offset: 0x1B53D80 static bool HandleTimeZone(ByRef<System::__DTString> str, ByRef<System::DateTimeResult> result); // static private System.Boolean Lex(System.DateTimeParse/System.DS dps, ref System.__DTString str, ref System.DateTimeToken dtok, ref System.DateTimeRawInfo raw, ref System.DateTimeResult result, ref System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles styles) // Offset: 0x1B53EF4 static bool Lex(System::DateTimeParse::DS dps, ByRef<System::__DTString> str, ByRef<System::DateTimeToken> dtok, ByRef<System::DateTimeRawInfo> raw, ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeFormatInfo*> dtfi, System::Globalization::DateTimeStyles styles); // static private System.Boolean VerifyValidPunctuation(ref System.__DTString str) // Offset: 0x1B54FC8 static bool VerifyValidPunctuation(ByRef<System::__DTString> str); // static private System.Boolean GetYearMonthDayOrder(System.String datePattern, System.Globalization.DateTimeFormatInfo dtfi, out System.Int32 order) // Offset: 0x1B55140 static bool GetYearMonthDayOrder(::Il2CppString* datePattern, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> order); // static private System.Boolean GetYearMonthOrder(System.String pattern, System.Globalization.DateTimeFormatInfo dtfi, out System.Int32 order) // Offset: 0x1B553E8 static bool GetYearMonthOrder(::Il2CppString* pattern, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> order); // static private System.Boolean GetMonthDayOrder(System.String pattern, System.Globalization.DateTimeFormatInfo dtfi, out System.Int32 order) // Offset: 0x1B555A4 static bool GetMonthDayOrder(::Il2CppString* pattern, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> order); // static private System.Boolean TryAdjustYear(ref System.DateTimeResult result, System.Int32 year, out System.Int32 adjustedYear) // Offset: 0x1B557A8 static bool TryAdjustYear(ByRef<System::DateTimeResult> result, int year, ByRef<int> adjustedYear); // static private System.Boolean SetDateYMD(ref System.DateTimeResult result, System.Int32 year, System.Int32 month, System.Int32 day) // Offset: 0x1B558A8 static bool SetDateYMD(ByRef<System::DateTimeResult> result, int year, int month, int day); // static private System.Boolean SetDateMDY(ref System.DateTimeResult result, System.Int32 month, System.Int32 day, System.Int32 year) // Offset: 0x1B5591C static bool SetDateMDY(ByRef<System::DateTimeResult> result, int month, int day, int year); // static private System.Boolean SetDateDMY(ref System.DateTimeResult result, System.Int32 day, System.Int32 month, System.Int32 year) // Offset: 0x1B559A8 static bool SetDateDMY(ByRef<System::DateTimeResult> result, int day, int month, int year); // static private System.Boolean SetDateYDM(ref System.DateTimeResult result, System.Int32 year, System.Int32 day, System.Int32 month) // Offset: 0x1B55A34 static bool SetDateYDM(ByRef<System::DateTimeResult> result, int year, int day, int month); // static private System.Void GetDefaultYear(ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles) // Offset: 0x1B55AC0 static void GetDefaultYear(ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles); // static private System.Boolean GetDayOfNN(ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B55C8C static bool GetDayOfNN(ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfNNN(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B55E20 static bool GetDayOfNNN(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfMN(ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B560F0 static bool GetDayOfMN(ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetHebrewDayOfNM(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B5631C static bool GetHebrewDayOfNM(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfNM(ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56468 static bool GetDayOfNM(ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfMNN(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56694 static bool GetDayOfMNN(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfYNN(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56984 static bool GetDayOfYNN(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfNNY(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56AE0 static bool GetDayOfNNY(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfYMN(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56C64 static bool GetDayOfYMN(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfYN(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56D2C static bool GetDayOfYN(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean GetDayOfYM(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B56DF4 static bool GetDayOfYM(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Void AdjustTimeMark(System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeRawInfo raw) // Offset: 0x1B56EB4 static void AdjustTimeMark(System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeRawInfo> raw); // static private System.Boolean AdjustHour(ref System.Int32 hour, System.DateTimeParse/System.TM timeMark) // Offset: 0x1B56F28 static bool AdjustHour(ByRef<int> hour, System::DateTimeParse::TM timeMark); // static private System.Boolean GetTimeOfN(System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeResult result, ref System.DateTimeRawInfo raw) // Offset: 0x1B56F70 static bool GetTimeOfN(System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw); // static private System.Boolean GetTimeOfNN(System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeResult result, ref System.DateTimeRawInfo raw) // Offset: 0x1B57008 static bool GetTimeOfNN(System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw); // static private System.Boolean GetTimeOfNNN(System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeResult result, ref System.DateTimeRawInfo raw) // Offset: 0x1B570A0 static bool GetTimeOfNNN(System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw); // static private System.Boolean GetDateOfDSN(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw) // Offset: 0x1B57144 static bool GetDateOfDSN(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw); // static private System.Boolean GetDateOfNDS(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw) // Offset: 0x1B571D8 static bool GetDateOfNDS(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw); // static private System.Boolean GetDateOfNNDS(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B572A0 static bool GetDateOfNNDS(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static private System.Boolean ProcessDateTimeSuffix(ref System.DateTimeResult result, ref System.DateTimeRawInfo raw, ref System.DateTimeToken dtok) // Offset: 0x1B574F0 static bool ProcessDateTimeSuffix(ByRef<System::DateTimeResult> result, ByRef<System::DateTimeRawInfo> raw, ByRef<System::DateTimeToken> dtok); // static System.Boolean ProcessHebrewTerminalState(System.DateTimeParse/System.DS dps, ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B575E8 static bool ProcessHebrewTerminalState(System::DateTimeParse::DS dps, ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static System.Boolean ProcessTerminaltState(System.DateTimeParse/System.DS dps, ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles, ref System.DateTimeRawInfo raw, System.Globalization.DateTimeFormatInfo dtfi) // Offset: 0x1B54BC8 static bool ProcessTerminaltState(System::DateTimeParse::DS dps, ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles, ByRef<System::DateTimeRawInfo> raw, System::Globalization::DateTimeFormatInfo* dtfi); // static System.DateTime Parse(System.String s, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles styles) // Offset: 0x1B578CC static System::DateTime Parse(::Il2CppString* s, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles styles); // static System.Boolean TryParse(System.String s, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles styles, out System.DateTime result) // Offset: 0x1B580BC static bool TryParse(::Il2CppString* s, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles styles, ByRef<System::DateTime> result); // static System.Boolean TryParse(System.String s, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles styles, ref System.DateTimeResult result) // Offset: 0x1B579BC static bool TryParse(::Il2CppString* s, System::Globalization::DateTimeFormatInfo* dtfi, System::Globalization::DateTimeStyles styles, ByRef<System::DateTimeResult> result); // static private System.Boolean DetermineTimeZoneAdjustments(ref System.DateTimeResult result, System.Globalization.DateTimeStyles styles, System.Boolean bTimeOnly) // Offset: 0x1B5896C static bool DetermineTimeZoneAdjustments(ByRef<System::DateTimeResult> result, System::Globalization::DateTimeStyles styles, bool bTimeOnly); // static private System.Boolean DateTimeOffsetTimeZonePostProcessing(ref System.DateTimeResult result, System.Globalization.DateTimeStyles styles) // Offset: 0x1B58B38 static bool DateTimeOffsetTimeZonePostProcessing(ByRef<System::DateTimeResult> result, System::Globalization::DateTimeStyles styles); // static private System.Boolean AdjustTimeZoneToUniversal(ref System.DateTimeResult result) // Offset: 0x1B58D40 static bool AdjustTimeZoneToUniversal(ByRef<System::DateTimeResult> result); // static private System.Boolean AdjustTimeZoneToLocal(ref System.DateTimeResult result, System.Boolean bTimeOnly) // Offset: 0x1B58E10 static bool AdjustTimeZoneToLocal(ByRef<System::DateTimeResult> result, bool bTimeOnly); // static private System.Boolean ParseISO8601(ref System.DateTimeRawInfo raw, ref System.__DTString str, System.Globalization.DateTimeStyles styles, ref System.DateTimeResult result) // Offset: 0x1B581FC static bool ParseISO8601(ByRef<System::DateTimeRawInfo> raw, ByRef<System::__DTString> str, System::Globalization::DateTimeStyles styles, ByRef<System::DateTimeResult> result); // static System.Boolean MatchHebrewDigits(ref System.__DTString str, System.Int32 digitLen, out System.Int32 number) // Offset: 0x1B590B4 static bool MatchHebrewDigits(ByRef<System::__DTString> str, int digitLen, ByRef<int> number); // static System.Boolean ParseDigits(ref System.__DTString str, System.Int32 digitLen, out System.Int32 result) // Offset: 0x1B5900C static bool ParseDigits(ByRef<System::__DTString> str, int digitLen, ByRef<int> result); // static System.Boolean ParseDigits(ref System.__DTString str, System.Int32 minDigitLen, System.Int32 maxDigitLen, out System.Int32 result) // Offset: 0x1B591A0 static bool ParseDigits(ByRef<System::__DTString> str, int minDigitLen, int maxDigitLen, ByRef<int> result); // static private System.Boolean ParseFractionExact(ref System.__DTString str, System.Int32 maxDigitLen, ref System.Double result) // Offset: 0x1B5925C static bool ParseFractionExact(ByRef<System::__DTString> str, int maxDigitLen, ByRef<double> result); // static private System.Boolean ParseSign(ref System.__DTString str, ref System.Boolean result) // Offset: 0x1B5938C static bool ParseSign(ByRef<System::__DTString> str, ByRef<bool> result); // static private System.Boolean ParseTimeZoneOffset(ref System.__DTString str, System.Int32 len, ref System.TimeSpan result) // Offset: 0x1B593F4 static bool ParseTimeZoneOffset(ByRef<System::__DTString> str, int len, ByRef<System::TimeSpan> result); // static private System.Boolean MatchAbbreviatedMonthName(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.Int32 result) // Offset: 0x1B595B0 static bool MatchAbbreviatedMonthName(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> result); // static private System.Boolean MatchMonthName(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.Int32 result) // Offset: 0x1B59728 static bool MatchMonthName(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> result); // static private System.Boolean MatchAbbreviatedDayName(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.Int32 result) // Offset: 0x1B598DC static bool MatchAbbreviatedDayName(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> result); // static private System.Boolean MatchDayName(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.Int32 result) // Offset: 0x1B599F0 static bool MatchDayName(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> result); // static private System.Boolean MatchEraName(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.Int32 result) // Offset: 0x1B59B04 static bool MatchEraName(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<int> result); // static private System.Boolean MatchTimeMark(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeParse/System.TM result) // Offset: 0x1B59C48 static bool MatchTimeMark(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeParse::TM> result); // static private System.Boolean MatchAbbreviatedTimeMark(ref System.__DTString str, System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeParse/System.TM result) // Offset: 0x1B59D54 static bool MatchAbbreviatedTimeMark(ByRef<System::__DTString> str, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeParse::TM> result); // static private System.Boolean CheckNewValue(ref System.Int32 currentValue, System.Int32 newValue, System.Char patternChar, ref System.DateTimeResult result) // Offset: 0x1B59E18 static bool CheckNewValue(ByRef<int> currentValue, int newValue, ::Il2CppChar patternChar, ByRef<System::DateTimeResult> result); // static private System.DateTime GetDateTimeNow(ref System.DateTimeResult result, ref System.Globalization.DateTimeStyles styles) // Offset: 0x1B55B6C static System::DateTime GetDateTimeNow(ByRef<System::DateTimeResult> result, ByRef<System::Globalization::DateTimeStyles> styles); // static private System.Boolean CheckDefaultDateTime(ref System.DateTimeResult result, ref System.Globalization.Calendar cal, System.Globalization.DateTimeStyles styles) // Offset: 0x1B586EC static bool CheckDefaultDateTime(ByRef<System::DateTimeResult> result, ByRef<System::Globalization::Calendar*> cal, System::Globalization::DateTimeStyles styles); // static private System.String ExpandPredefinedFormat(System.String format, ref System.Globalization.DateTimeFormatInfo dtfi, ref System.ParsingInfo parseInfo, ref System.DateTimeResult result) // Offset: 0x1B59ECC static ::Il2CppString* ExpandPredefinedFormat(::Il2CppString* format, ByRef<System::Globalization::DateTimeFormatInfo*> dtfi, ByRef<System::ParsingInfo> parseInfo, ByRef<System::DateTimeResult> result); // static private System.Boolean ParseByFormat(ref System.__DTString str, ref System.__DTString format, ref System.ParsingInfo parseInfo, System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeResult result) // Offset: 0x1B5A270 static bool ParseByFormat(ByRef<System::__DTString> str, ByRef<System::__DTString> format, ByRef<System::ParsingInfo> parseInfo, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeResult> result); // static System.Boolean TryParseQuoteString(System.String format, System.Int32 pos, System.Text.StringBuilder result, out System.Int32 returnValue) // Offset: 0x1B5B464 static bool TryParseQuoteString(::Il2CppString* format, int pos, System::Text::StringBuilder* result, ByRef<int> returnValue); // static private System.Boolean DoStrictParse(System.String s, System.String formatParam, System.Globalization.DateTimeStyles styles, System.Globalization.DateTimeFormatInfo dtfi, ref System.DateTimeResult result) // Offset: 0x1B52FE8 static bool DoStrictParse(::Il2CppString* s, ::Il2CppString* formatParam, System::Globalization::DateTimeStyles styles, System::Globalization::DateTimeFormatInfo* dtfi, ByRef<System::DateTimeResult> result); // static private System.Exception GetDateTimeParseException(ref System.DateTimeResult result) // Offset: 0x1B52E44 static System::Exception* GetDateTimeParseException(ByRef<System::DateTimeResult> result); }; // System.DateTimeParse #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::DateTimeParse*, "System", "DateTimeParse"); DEFINE_IL2CPP_ARG_TYPE(System::DateTimeParse::DS, "System", "DateTimeParse/DS"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::DateTimeParse::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::DateTimeParse::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseExact // Il2CppName: ParseExact template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::DateTime (*)(::Il2CppString*, ::Il2CppString*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles)>(&System::DateTimeParse::ParseExact)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* style = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseExact", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, format, dtfi, style}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryParseExact // Il2CppName: TryParseExact template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, ::Il2CppString*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::TryParseExact)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* style = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryParseExact", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, format, dtfi, style, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryParseExactMultiple // Il2CppName: TryParseExactMultiple template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, ::Array<::Il2CppString*>*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles, ByRef<System::DateTime>, ByRef<System::TimeSpan>)>(&System::DateTimeParse::TryParseExactMultiple)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* formats = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "String"), 1)->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* style = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTime")->this_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "TimeSpan")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryParseExactMultiple", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, formats, dtfi, style, result, offset}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryParseExactMultiple // Il2CppName: TryParseExactMultiple template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, ::Array<::Il2CppString*>*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::TryParseExactMultiple)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* formats = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "String"), 1)->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* style = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryParseExactMultiple", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, formats, dtfi, style, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchWord // Il2CppName: MatchWord template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, ::Il2CppString*)>(&System::DateTimeParse::MatchWord)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* target = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchWord", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, target}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetTimeZoneName // Il2CppName: GetTimeZoneName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>)>(&System::DateTimeParse::GetTimeZoneName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetTimeZoneName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str}); } }; // Writing MetadataGetter for method: System::DateTimeParse::IsDigit // Il2CppName: IsDigit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppChar)>(&System::DateTimeParse::IsDigit)> { static const MethodInfo* get() { static auto* ch = &::il2cpp_utils::GetClassFromName("System", "Char")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "IsDigit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ch}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseFraction // Il2CppName: ParseFraction template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, ByRef<double>)>(&System::DateTimeParse::ParseFraction)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Double")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseFraction", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseTimeZone // Il2CppName: ParseTimeZone template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, ByRef<System::TimeSpan>)>(&System::DateTimeParse::ParseTimeZone)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "TimeSpan")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseTimeZone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::HandleTimeZone // Il2CppName: HandleTimeZone template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::HandleTimeZone)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "HandleTimeZone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::Lex // Il2CppName: Lex template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::DateTimeParse::DS, ByRef<System::__DTString>, ByRef<System::DateTimeToken>, ByRef<System::DateTimeRawInfo>, ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeFormatInfo*>, System::Globalization::DateTimeStyles)>(&System::DateTimeParse::Lex)> { static const MethodInfo* get() { static auto* dps = &::il2cpp_utils::GetClassFromName("System", "DateTimeParse/DS")->byval_arg; static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtok = &::il2cpp_utils::GetClassFromName("System", "DateTimeToken")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "Lex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dps, str, dtok, raw, result, dtfi, styles}); } }; // Writing MetadataGetter for method: System::DateTimeParse::VerifyValidPunctuation // Il2CppName: VerifyValidPunctuation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>)>(&System::DateTimeParse::VerifyValidPunctuation)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "VerifyValidPunctuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetYearMonthDayOrder // Il2CppName: GetYearMonthDayOrder template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::GetYearMonthDayOrder)> { static const MethodInfo* get() { static auto* datePattern = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* order = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetYearMonthDayOrder", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{datePattern, dtfi, order}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetYearMonthOrder // Il2CppName: GetYearMonthOrder template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::GetYearMonthOrder)> { static const MethodInfo* get() { static auto* pattern = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* order = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetYearMonthOrder", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pattern, dtfi, order}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetMonthDayOrder // Il2CppName: GetMonthDayOrder template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::GetMonthDayOrder)> { static const MethodInfo* get() { static auto* pattern = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* order = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetMonthDayOrder", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pattern, dtfi, order}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryAdjustYear // Il2CppName: TryAdjustYear template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, int, ByRef<int>)>(&System::DateTimeParse::TryAdjustYear)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* year = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* adjustedYear = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryAdjustYear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, year, adjustedYear}); } }; // Writing MetadataGetter for method: System::DateTimeParse::SetDateYMD // Il2CppName: SetDateYMD template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, int, int, int)>(&System::DateTimeParse::SetDateYMD)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* year = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* month = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* day = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "SetDateYMD", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, year, month, day}); } }; // Writing MetadataGetter for method: System::DateTimeParse::SetDateMDY // Il2CppName: SetDateMDY template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, int, int, int)>(&System::DateTimeParse::SetDateMDY)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* month = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* day = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* year = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "SetDateMDY", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, month, day, year}); } }; // Writing MetadataGetter for method: System::DateTimeParse::SetDateDMY // Il2CppName: SetDateDMY template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, int, int, int)>(&System::DateTimeParse::SetDateDMY)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* day = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* month = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* year = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "SetDateDMY", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, day, month, year}); } }; // Writing MetadataGetter for method: System::DateTimeParse::SetDateYDM // Il2CppName: SetDateYDM template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, int, int, int)>(&System::DateTimeParse::SetDateYDM)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* year = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* day = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* month = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "SetDateYDM", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, year, day, month}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDefaultYear // Il2CppName: GetDefaultYear template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>)>(&System::DateTimeParse::GetDefaultYear)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDefaultYear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfNN // Il2CppName: GetDayOfNN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfNN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfNN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfNNN // Il2CppName: GetDayOfNNN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfNNN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfNNN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfMN // Il2CppName: GetDayOfMN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfMN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfMN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetHebrewDayOfNM // Il2CppName: GetHebrewDayOfNM template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetHebrewDayOfNM)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetHebrewDayOfNM", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfNM // Il2CppName: GetDayOfNM template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfNM)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfNM", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfMNN // Il2CppName: GetDayOfMNN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfMNN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfMNN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfYNN // Il2CppName: GetDayOfYNN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfYNN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfYNN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfNNY // Il2CppName: GetDayOfNNY template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfNNY)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfNNY", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfYMN // Il2CppName: GetDayOfYMN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfYMN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfYMN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfYN // Il2CppName: GetDayOfYN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfYN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfYN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDayOfYM // Il2CppName: GetDayOfYM template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDayOfYM)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDayOfYM", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::AdjustTimeMark // Il2CppName: AdjustTimeMark template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeRawInfo>)>(&System::DateTimeParse::AdjustTimeMark)> { static const MethodInfo* get() { static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "AdjustTimeMark", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dtfi, raw}); } }; // Writing MetadataGetter for method: System::DateTimeParse::AdjustHour // Il2CppName: AdjustHour template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<int>, System::DateTimeParse::TM)>(&System::DateTimeParse::AdjustHour)> { static const MethodInfo* get() { static auto* hour = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; static auto* timeMark = &::il2cpp_utils::GetClassFromName("System", "DateTimeParse/TM")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "AdjustHour", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{hour, timeMark}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetTimeOfN // Il2CppName: GetTimeOfN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>)>(&System::DateTimeParse::GetTimeOfN)> { static const MethodInfo* get() { static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetTimeOfN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dtfi, result, raw}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetTimeOfNN // Il2CppName: GetTimeOfNN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>)>(&System::DateTimeParse::GetTimeOfNN)> { static const MethodInfo* get() { static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetTimeOfNN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dtfi, result, raw}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetTimeOfNNN // Il2CppName: GetTimeOfNNN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>)>(&System::DateTimeParse::GetTimeOfNNN)> { static const MethodInfo* get() { static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetTimeOfNNN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dtfi, result, raw}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDateOfDSN // Il2CppName: GetDateOfDSN template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>)>(&System::DateTimeParse::GetDateOfDSN)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDateOfDSN", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDateOfNDS // Il2CppName: GetDateOfNDS template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>)>(&System::DateTimeParse::GetDateOfNDS)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDateOfNDS", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDateOfNNDS // Il2CppName: GetDateOfNNDS template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::GetDateOfNNDS)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDateOfNNDS", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ProcessDateTimeSuffix // Il2CppName: ProcessDateTimeSuffix template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::DateTimeRawInfo>, ByRef<System::DateTimeToken>)>(&System::DateTimeParse::ProcessDateTimeSuffix)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtok = &::il2cpp_utils::GetClassFromName("System", "DateTimeToken")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ProcessDateTimeSuffix", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, raw, dtok}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ProcessHebrewTerminalState // Il2CppName: ProcessHebrewTerminalState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::DateTimeParse::DS, ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::ProcessHebrewTerminalState)> { static const MethodInfo* get() { static auto* dps = &::il2cpp_utils::GetClassFromName("System", "DateTimeParse/DS")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ProcessHebrewTerminalState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dps, result, styles, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ProcessTerminaltState // Il2CppName: ProcessTerminaltState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::DateTimeParse::DS, ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>, ByRef<System::DateTimeRawInfo>, System::Globalization::DateTimeFormatInfo*)>(&System::DateTimeParse::ProcessTerminaltState)> { static const MethodInfo* get() { static auto* dps = &::il2cpp_utils::GetClassFromName("System", "DateTimeParse/DS")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ProcessTerminaltState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dps, result, styles, raw, dtfi}); } }; // Writing MetadataGetter for method: System::DateTimeParse::Parse // Il2CppName: Parse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::DateTime (*)(::Il2CppString*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles)>(&System::DateTimeParse::Parse)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "Parse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, dtfi, styles}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryParse // Il2CppName: TryParse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles, ByRef<System::DateTime>)>(&System::DateTimeParse::TryParse)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTime")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryParse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, dtfi, styles, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryParse // Il2CppName: TryParse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, System::Globalization::DateTimeFormatInfo*, System::Globalization::DateTimeStyles, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::TryParse)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryParse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, dtfi, styles, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::DetermineTimeZoneAdjustments // Il2CppName: DetermineTimeZoneAdjustments template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, System::Globalization::DateTimeStyles, bool)>(&System::DateTimeParse::DetermineTimeZoneAdjustments)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* bTimeOnly = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "DetermineTimeZoneAdjustments", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles, bTimeOnly}); } }; // Writing MetadataGetter for method: System::DateTimeParse::DateTimeOffsetTimeZonePostProcessing // Il2CppName: DateTimeOffsetTimeZonePostProcessing template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, System::Globalization::DateTimeStyles)>(&System::DateTimeParse::DateTimeOffsetTimeZonePostProcessing)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "DateTimeOffsetTimeZonePostProcessing", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles}); } }; // Writing MetadataGetter for method: System::DateTimeParse::AdjustTimeZoneToUniversal // Il2CppName: AdjustTimeZoneToUniversal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>)>(&System::DateTimeParse::AdjustTimeZoneToUniversal)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "AdjustTimeZoneToUniversal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::AdjustTimeZoneToLocal // Il2CppName: AdjustTimeZoneToLocal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, bool)>(&System::DateTimeParse::AdjustTimeZoneToLocal)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* bTimeOnly = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "AdjustTimeZoneToLocal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, bTimeOnly}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseISO8601 // Il2CppName: ParseISO8601 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeRawInfo>, ByRef<System::__DTString>, System::Globalization::DateTimeStyles, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::ParseISO8601)> { static const MethodInfo* get() { static auto* raw = &::il2cpp_utils::GetClassFromName("System", "DateTimeRawInfo")->this_arg; static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseISO8601", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{raw, str, styles, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchHebrewDigits // Il2CppName: MatchHebrewDigits template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, int, ByRef<int>)>(&System::DateTimeParse::MatchHebrewDigits)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* digitLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* number = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchHebrewDigits", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, digitLen, number}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseDigits // Il2CppName: ParseDigits template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, int, ByRef<int>)>(&System::DateTimeParse::ParseDigits)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* digitLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseDigits", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, digitLen, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseDigits // Il2CppName: ParseDigits template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, int, int, ByRef<int>)>(&System::DateTimeParse::ParseDigits)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* minDigitLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* maxDigitLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseDigits", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, minDigitLen, maxDigitLen, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseFractionExact // Il2CppName: ParseFractionExact template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, int, ByRef<double>)>(&System::DateTimeParse::ParseFractionExact)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* maxDigitLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Double")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseFractionExact", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, maxDigitLen, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseSign // Il2CppName: ParseSign template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, ByRef<bool>)>(&System::DateTimeParse::ParseSign)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Boolean")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseSign", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseTimeZoneOffset // Il2CppName: ParseTimeZoneOffset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, int, ByRef<System::TimeSpan>)>(&System::DateTimeParse::ParseTimeZoneOffset)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* len = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "TimeSpan")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseTimeZoneOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, len, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchAbbreviatedMonthName // Il2CppName: MatchAbbreviatedMonthName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::MatchAbbreviatedMonthName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchAbbreviatedMonthName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchMonthName // Il2CppName: MatchMonthName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::MatchMonthName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchMonthName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchAbbreviatedDayName // Il2CppName: MatchAbbreviatedDayName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::MatchAbbreviatedDayName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchAbbreviatedDayName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchDayName // Il2CppName: MatchDayName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::MatchDayName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchDayName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchEraName // Il2CppName: MatchEraName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<int>)>(&System::DateTimeParse::MatchEraName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchEraName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchTimeMark // Il2CppName: MatchTimeMark template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeParse::TM>)>(&System::DateTimeParse::MatchTimeMark)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeParse/TM")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchTimeMark", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::MatchAbbreviatedTimeMark // Il2CppName: MatchAbbreviatedTimeMark template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeParse::TM>)>(&System::DateTimeParse::MatchAbbreviatedTimeMark)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeParse/TM")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "MatchAbbreviatedTimeMark", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::CheckNewValue // Il2CppName: CheckNewValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<int>, int, ::Il2CppChar, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::CheckNewValue)> { static const MethodInfo* get() { static auto* currentValue = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; static auto* newValue = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* patternChar = &::il2cpp_utils::GetClassFromName("System", "Char")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "CheckNewValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{currentValue, newValue, patternChar, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDateTimeNow // Il2CppName: GetDateTimeNow template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::DateTime (*)(ByRef<System::DateTimeResult>, ByRef<System::Globalization::DateTimeStyles>)>(&System::DateTimeParse::GetDateTimeNow)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDateTimeNow", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, styles}); } }; // Writing MetadataGetter for method: System::DateTimeParse::CheckDefaultDateTime // Il2CppName: CheckDefaultDateTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::DateTimeResult>, ByRef<System::Globalization::Calendar*>, System::Globalization::DateTimeStyles)>(&System::DateTimeParse::CheckDefaultDateTime)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; static auto* cal = &::il2cpp_utils::GetClassFromName("System.Globalization", "Calendar")->this_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "CheckDefaultDateTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result, cal, styles}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ExpandPredefinedFormat // Il2CppName: ExpandPredefinedFormat template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (*)(::Il2CppString*, ByRef<System::Globalization::DateTimeFormatInfo*>, ByRef<System::ParsingInfo>, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::ExpandPredefinedFormat)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->this_arg; static auto* parseInfo = &::il2cpp_utils::GetClassFromName("System", "ParsingInfo")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ExpandPredefinedFormat", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, dtfi, parseInfo, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::ParseByFormat // Il2CppName: ParseByFormat template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(ByRef<System::__DTString>, ByRef<System::__DTString>, ByRef<System::ParsingInfo>, System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::ParseByFormat)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* format = &::il2cpp_utils::GetClassFromName("System", "__DTString")->this_arg; static auto* parseInfo = &::il2cpp_utils::GetClassFromName("System", "ParsingInfo")->this_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "ParseByFormat", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, format, parseInfo, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::TryParseQuoteString // Il2CppName: TryParseQuoteString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, int, System::Text::StringBuilder*, ByRef<int>)>(&System::DateTimeParse::TryParseQuoteString)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* pos = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System.Text", "StringBuilder")->byval_arg; static auto* returnValue = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "TryParseQuoteString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, pos, result, returnValue}); } }; // Writing MetadataGetter for method: System::DateTimeParse::DoStrictParse // Il2CppName: DoStrictParse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, ::Il2CppString*, System::Globalization::DateTimeStyles, System::Globalization::DateTimeFormatInfo*, ByRef<System::DateTimeResult>)>(&System::DateTimeParse::DoStrictParse)> { static const MethodInfo* get() { static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* formatParam = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* styles = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeStyles")->byval_arg; static auto* dtfi = &::il2cpp_utils::GetClassFromName("System.Globalization", "DateTimeFormatInfo")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "DoStrictParse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, formatParam, styles, dtfi, result}); } }; // Writing MetadataGetter for method: System::DateTimeParse::GetDateTimeParseException // Il2CppName: GetDateTimeParseException template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Exception* (*)(ByRef<System::DateTimeResult>)>(&System::DateTimeParse::GetDateTimeParseException)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "DateTimeResult")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::DateTimeParse*), "GetDateTimeParseException", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result}); } };
78.142128
348
0.744942
[ "vector" ]
925bf6bbf7d49587e4fdf0f403ed23c6c1e90b3e
6,669
cpp
C++
include/rogue.cpp
denisjackman/Cee
2176e9dccc17ac93463bd5473f437f1c76ba9c3c
[ "CC-BY-4.0" ]
null
null
null
include/rogue.cpp
denisjackman/Cee
2176e9dccc17ac93463bd5473f437f1c76ba9c3c
[ "CC-BY-4.0" ]
2
2016-06-30T14:31:43.000Z
2016-07-01T08:43:03.000Z
include/rogue.cpp
denisjackman/game
2176e9dccc17ac93463bd5473f437f1c76ba9c3c
[ "CC-BY-4.0" ]
null
null
null
#include <string> #include <iostream> #include <stdio.h> #include "../include/constants.h" #include "../include/rogue.h" using namespace std; void CreatureDefence(creature_type creature) { if (creature.cdefense & CD_SLAY_DRAGON) { cout << creature.name << " can be damaged by slay dragon " << endl; } if (creature.cdefense & CD_SLAY_ANIMAL) { cout << creature.name << " can be damaged by slay animal " << endl; } if (creature.cdefense & CD_SLAY_EVIL) { cout << creature.name << " can be damaged by slay evil " << endl; } if (creature.cdefense & CD_SLAY_UNDEAD) { cout << creature.name << " can be damaged by slay undead " << endl; } if (creature.cdefense & CD_FROST) { cout << creature.name << " can be slain by frost " << endl; } if (creature.cdefense & CD_FIRE) { cout << creature.name << " can be slain by fire " << endl; } if (creature.cdefense & CD_POISON) { cout << creature.name << " can be slain by poison" << endl; } if (creature.cdefense & CD_ACID) { cout << creature.name << " can be slain by acid " << endl; } if (creature.cdefense & CD_LIGHT) { cout << creature.name << " can be slain by light" << endl; } if (creature.cdefense & CD_STONE_TO_MUD) { cout << creature.name << " can be slain by stone to mud" << endl; } if (creature.cdefense & CD_NO_CHARM) { cout << creature.name << " cannot be charmed" << endl; } if (creature.cdefense & CD_INFRAVISION) { cout << creature.name << " can be seen by infravision " << endl; } if (creature.cdefense & CD_MAX_HIT) { cout << creature.name << " has maximum hit dice " << endl; } } void CreatureMove(creature_type creature) { if (creature.cmove & CM_MOVE_ATTACK) { cout << creature.name << " can move to attack " << endl; } if (creature.cmove & CM_MOVE_NORMAL) { cout << creature.name << " can move normally " << endl; } if (creature.cmove & CM_MOVE_TWENTY) { cout << creature.name << " can move at 20% speed " << endl; } if (creature.cmove & CM_MOVE_FORTY) { cout << creature.name << " can move at 40% speed " << endl; } if (creature.cmove & CM_MOVE_SEVENTY) { cout << creature.name << " can move at 470% speed " << endl; } if (creature.cmove & CM_MOVE_INVISIBLE) { cout << creature.name << " can move while invisible" << endl; } if (creature.cmove & CM_THRU_DOORS) { cout << creature.name << " can be go through doors " << endl; } if (creature.cmove & CM_PICKUP_OBJECTS) { cout << creature.name << " can pickup objects " << endl; } if (creature.cmove & CM_MULTIPLY_MONST) { cout << creature.name << " can multiply " << endl; } if (creature.cmove & CM_CARRIES_OBJECT) { cout << creature.name << " will carry an object " << endl; } if (creature.cmove & CM_CARRIES_GOLD) { cout << creature.name << " will carry gold " << endl; } if (creature.cmove & CM_CARRIES_60) { cout << creature.name << " will carry object 60% of the time " << endl; } if (creature.cmove & CM_CARRIES_90) { cout << creature.name << " will carry object 90% of the time " << endl; } if (creature.cmove & CM_CARRY_RAND1) { cout << creature.name << " will carry up to one random object" << endl; } if (creature.cmove & CM_CARRY_RAND2) { cout << creature.name << " will carry up to two random objects" << endl; } if (creature.cmove & CM_CARRY_RAND4) { cout << creature.name << " will carry up to four random objects" << endl; } if (creature.cmove & CM_WIN_GAME) { cout << creature.name << " is a Game Winner!" << endl; } } void CreatureSpells(creature_type creature) { int spellfreq = 0; if (creature.spells & CS_FREQ_1) { spellfreq += 1; } if (creature.spells & CS_FREQ_2) { spellfreq += 2; } if (creature.spells & CS_FREQ_3) { spellfreq += 4; } if (creature.spells & CS_FREQ_4) { spellfreq += 8; } cout << creature.name << " has a spell frequency of "<< spellfreq << endl; if (creature.spells & CS_TPORT_BLINK) { cout << creature.name << " can cast Blink!" << endl; } if (creature.spells & CS_TPORT_LONG) { cout << creature.name << " can cast Teleport Self!" << endl; } if (creature.spells & CS_TPORT_PLAYER) { cout << creature.name << " can cast Teleport Player!" << endl; } if (creature.spells & CS_LIGHT_WOUND) { cout << creature.name << " can cast Light Wound" << endl; } if (creature.spells & CS_SERIOUS_WOUND) { cout << creature.name << " can cast Serious Wound" << endl; } if (creature.spells & CS_PARALYSIS) { cout << creature.name << " can cast Paralysis!" << endl; } if (creature.spells & CS_BLINDNESS) { cout << creature.name << " can cast Blindness!" << endl; } if (creature.spells & CS_CONFUSION) { cout << creature.name << " can cast Confusion!" << endl; } if (creature.spells & CS_FEAR) { cout << creature.name << " can cast Fear!" << endl; } if (creature.spells & CS_SUMM_MONSTER) { cout << creature.name << " can cast Summon Monster!" << endl; } if (creature.spells & CS_SUMM_UNDEAD) { cout << creature.name << " can cast Summon Undead!" << endl; } if (creature.spells & CS_SLOW) { cout << creature.name << " can cast Slow!" << endl; } if (creature.spells & CS_DRAIN_MANA) { cout << creature.name << " can cast Drain Mana!" << endl; } if (creature.spells & CS_LIGHTNING) { cout << creature.name << " can cast Lightning!" << endl; } if (creature.spells & CS_GAS) { cout << creature.name << " can cast Gas!" << endl; } if (creature.spells & CS_ACID) { cout << creature.name << " can cast Acid!" << endl; } if (creature.spells & CS_FROST) { cout << creature.name << " can cast Frost!" << endl; } if (creature.spells & CS_FIRE) { cout << creature.name << " can cast Fire!" << endl; } } void CreatureHitDice(creature_type creature) { cout << creature.name << " has between " << to_string(creature.hd[1]) << " and " << creature.hd[1] * creature.hd[2] << " HP " << endl; }
27.557851
138
0.557955
[ "object" ]
925d3599d14f243f345ec65287c9e9573573f666
111,331
cpp
C++
Bld1/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs9.cpp
Reality-Hack-2022/TEAM-30
f3346ea1d7aa307f518730f12ec42cd18f5543e6
[ "MIT" ]
1
2022-03-28T07:59:17.000Z
2022-03-28T07:59:17.000Z
Bld1/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs9.cpp
Reality-Hack-2022/TEAM-30
f3346ea1d7aa307f518730f12ec42cd18f5543e6
[ "MIT" ]
null
null
null
Bld1/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs9.cpp
Reality-Hack-2022/TEAM-30
f3346ea1d7aa307f518730f12ec42cd18f5543e6
[ "MIT" ]
1
2022-03-26T18:23:31.000Z
2022-03-26T18:23:31.000Z
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <limits> #include "vm/CachedCCWBase.h" #include "utils/New.h" // System.Collections.Generic.IEqualityComparer`1<System.Int32> struct IEqualityComparer_1_t62010156673DE1460AB1D1CEBE5DCD48665E1A38; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,UnityEngine.InputSystem.InputDevice> struct KeyCollection_t5BE70A16AB71FB272DCD7E1DA7B387098D2B0120; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,System.Int32> struct KeyCollection_tDB6919EBDF36E83E708A483A6C4CF8065F62D1E0; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,System.Int64> struct KeyCollection_t6C75FA39C169AFB913CD046927B28E95AA96C54A; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,UnityEngine.Material> struct KeyCollection_t193AE2D2720028E6C67183D0B8776FC0C389765D; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,UnityEngine.EventSystems.PointerEventData> struct KeyCollection_tD2C5F600E93DE7B92ABF7BC7E8A932E27D940212; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,Microsoft.MixedReality.Toolkit.SpatialAwareness.SpatialAwarenessMeshObject> struct KeyCollection_tD20167A0CD28EAA4DE363BB48DE5D6C737BE5302; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,System.String> struct KeyCollection_t95CEC57CA04600603C7E9067D11E724EE99AD7D1; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Int32,TMPro.TMP_ColorGradient> struct KeyCollection_tCE7752ED00F7F3D67E6F2360D066F92B47831981; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,UnityEngine.InputSystem.InputDevice> struct ValueCollection_tC0183EB9B565CC716E5BD56C2D1784AC1E2373B1; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,System.Int32> struct ValueCollection_t8738745D8513A557A82E6E097DF4D4E70D5253C2; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,System.Int64> struct ValueCollection_tDD2C80682AF4CF18883668E136B1980110C79D95; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,UnityEngine.Material> struct ValueCollection_t45CC083597229265F7ED085E423FB1A7BF762BA3; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,UnityEngine.EventSystems.PointerEventData> struct ValueCollection_t28C5EADCF5205986726B544E972D81491CD308DA; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,Microsoft.MixedReality.Toolkit.SpatialAwareness.SpatialAwarenessMeshObject> struct ValueCollection_t532B14D24FC92E18A887848D100E3825432ECF59; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,System.String> struct ValueCollection_t5C221D6474B57B05A1EF91C1C6A7B1FA1CF361BF; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Int32,TMPro.TMP_ColorGradient> struct ValueCollection_t0A4E0F9662AF7EF0D0D0E1E70988F30A0717AA41; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,UnityEngine.InputSystem.InputDevice>[] struct EntryU5BU5D_t66E809E1E397459855D5851348355DDC4327DC40; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,System.Int32>[] struct EntryU5BU5D_tB55287EA11F7C665F930EF3A359F186CD3AE5EC1; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,System.Int64>[] struct EntryU5BU5D_tB210152E9D3EBE4609E3432D20C529E7C1B65D44; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,UnityEngine.Material>[] struct EntryU5BU5D_tABE076887DFD24028C536C77C7C7DCCD66ACA8A7; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,UnityEngine.EventSystems.PointerEventData>[] struct EntryU5BU5D_t3D89719784232B784AF24BDF458050EC3BF780AF; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,Microsoft.MixedReality.Toolkit.SpatialAwareness.SpatialAwarenessMeshObject>[] struct EntryU5BU5D_t8344B8670E5D8DDCF5FDDEDD27DBB8D417B58898; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,System.String>[] struct EntryU5BU5D_t0760EF54F1EA7070181C04D5D34118DC91F943ED; // System.Collections.Generic.Dictionary`2/Entry<System.Int32,TMPro.TMP_ColorGradient>[] struct EntryU5BU5D_tD8D7AD456FCCA071CB20981E7A68D2BFE029FA8C; // System.Int32[] struct Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32; // System.String struct String_t; struct IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB; struct IIterator_1_t90E26C41183EBF622D2BBB227E37A898BAA6B97B; struct IIterator_1_tAB0C1B446829B226CAAD72C2FBCB3E1FBB5A4C71; struct IIterator_1_tCAC42F4EF69B7F9727A04F84FB9773E96CB8DFC9; struct IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A; struct IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61; struct IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Windows.Foundation.Collections.IIterable`1<System.Collections.Generic.KeyValuePair`2<System.Int32,System.Int32>> struct NOVTABLE IIterable_1_tD388FA3CB5D870407558B6357E3097F22416E7E3 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IIterable_1_First_m9E67B40CA2B0E8AB40AC60919F35CDBAF4907598(IIterator_1_tAB0C1B446829B226CAAD72C2FBCB3E1FBB5A4C71** comReturnValue) = 0; }; // Windows.Foundation.Collections.IIterable`1<System.Collections.Generic.KeyValuePair`2<System.Int32,System.Int64>> struct NOVTABLE IIterable_1_tD7A5412C67484BA2083059C445DC95E7BC6041C7 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IIterable_1_First_mC90DE28333E7B75BCEE7ADDA4E3BE0A56EEEB649(IIterator_1_tCAC42F4EF69B7F9727A04F84FB9773E96CB8DFC9** comReturnValue) = 0; }; // Windows.Foundation.Collections.IIterable`1<System.Collections.Generic.KeyValuePair`2<System.Int32,System.String>> struct NOVTABLE IIterable_1_tFC0F28A8493453E790566AD9BF521EB99E862227 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IIterable_1_First_m14DE8FC349ACC550CA242FB49577D6B0AF1C1EB1(IIterator_1_t90E26C41183EBF622D2BBB227E37A898BAA6B97B** comReturnValue) = 0; }; // Windows.Foundation.Collections.IMapView`2<System.Int32,System.Int32> struct NOVTABLE IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IMapView_2_Lookup_mEB4A4831069E064FC0A807E20E51095F61208AAF(int32_t ___key0, int32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_get_Size_mDBDA039F45FE7DAB8B299F8284D620683947C20D(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_HasKey_m3BE9E9A164CFAD5EBF9879319054D86AAA4D529C(int32_t ___key0, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_Split_m6869EE64C18723F0BB0D10417E11AA80918D1295(IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** ___first0, IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** ___second1) = 0; }; // Windows.Foundation.Collections.IMapView`2<System.Int32,System.Int64> struct NOVTABLE IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IMapView_2_Lookup_m1D42C30FE9DDE2255F85A4128C70FBC74070E24A(int32_t ___key0, int64_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_get_Size_mE5B4042270AF83F3467CED1201613AF6870931F1(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_HasKey_m70F1D85335051378EC9751B6CF4AAEE9F5AB6288(int32_t ___key0, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_Split_m5ACA09637DDBA456BDE48B599992DD4316CEDC0A(IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** ___first0, IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** ___second1) = 0; }; // Windows.Foundation.Collections.IMapView`2<System.Int32,System.String> struct NOVTABLE IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IMapView_2_Lookup_m6C3FB595F2E75BA520D8DD9CAA9B6D3F73DD9E81(int32_t ___key0, Il2CppHString* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_get_Size_m3EE77EBA65F7B85780CE3CD3E9FBEED16D13FBEB(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_HasKey_m6F79F442D9D546B542483DBCC15739DF4C1CA6A0(int32_t ___key0, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMapView_2_Split_m12E007F56F41C3C40A71A9B19D78FDE3485A68BF(IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** ___first0, IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** ___second1) = 0; }; // Windows.Foundation.Collections.IMap`2<System.Int32,System.Int32> struct NOVTABLE IMap_2_t2D2887BEE348A15C28549CB5E6D3D465077579B1 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IMap_2_Lookup_mAB2557F89B67970660EAEA867C160D8B4519A59B(int32_t ___key0, int32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_get_Size_mA1A1CCC776D0A04E6CB464990ACA1A8A24B8FB99(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_HasKey_m09F3138AF64D40439835CED4FA397E6A5567B69F(int32_t ___key0, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_GetView_m49BD462B6D6FBA94E03FC317B3F348E400D8D059(IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Insert_m26A58381A4B7979D7635D8C6BABB43581F277A1E(int32_t ___key0, int32_t ___value1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Remove_mBEBB5F63E6AF3D5EC5F85CEC6FF599CF27892CA3(int32_t ___key0) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Clear_mFC61A1262C6FF5614B12B0D00A26C3B01B909312() = 0; }; // Windows.Foundation.Collections.IMap`2<System.Int32,System.Int64> struct NOVTABLE IMap_2_t131C1AAB31D1D45DD27D52AC64C0A5BCD9788170 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IMap_2_Lookup_mD086C909F276F0A409C254386A5433BA1D8E4DA1(int32_t ___key0, int64_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_get_Size_mF7543BFD7482B050F35BE3CABFB5B6A903300CE7(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_HasKey_m1543A9B7F80B3A5489328F1F77CB0691655EA012(int32_t ___key0, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_GetView_mF5636C470F31A6C155D5AAA77FB9BD0442C34E04(IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Insert_mD8D2C48C925DF3B8A1F36EB5D923E7798AAD25AD(int32_t ___key0, int64_t ___value1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Remove_m588519BFAFF613E05C992F17D2D10A9104A5C511(int32_t ___key0) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Clear_mF043DFCA2742D3F57D3380D0D42A6D7DD46867C7() = 0; }; // Windows.Foundation.Collections.IMap`2<System.Int32,System.String> struct NOVTABLE IMap_2_t6D83CFC4BB5F39D14238C2A6C38DB1D7D36E9EE3 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IMap_2_Lookup_mDB3DE71A1EF4936EF85DC58F72AE18C4DEA7AEA4(int32_t ___key0, Il2CppHString* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_get_Size_m6F21CB368462EE986560EFB89B18F2EB87266C65(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_HasKey_m1C1D3DFD5C4CFE039AB133F6FCD00923AA128825(int32_t ___key0, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_GetView_m388C3012C136C6DF202561F3223E1937B3126DC5(IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Insert_mD0EE050C010FEBDF35A137076BB5B9C8D7C134F8(int32_t ___key0, Il2CppHString ___value1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Remove_mC0F7A2C3AA571DFBB44D55A01F218C9303BF0005(int32_t ___key0) = 0; virtual il2cpp_hresult_t STDCALL IMap_2_Clear_m2B14C4BB95BEBBA259CCB82E215F6D503A0B8708() = 0; }; // Windows.UI.Xaml.Interop.IBindableIterable struct NOVTABLE IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) = 0; }; // System.Object // System.Collections.Generic.Dictionary`2<System.Int32,UnityEngine.InputSystem.InputDevice> struct Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t66E809E1E397459855D5851348355DDC4327DC40* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t5BE70A16AB71FB272DCD7E1DA7B387098D2B0120 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_tC0183EB9B565CC716E5BD56C2D1784AC1E2373B1 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___entries_1)); } inline EntryU5BU5D_t66E809E1E397459855D5851348355DDC4327DC40* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t66E809E1E397459855D5851348355DDC4327DC40** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t66E809E1E397459855D5851348355DDC4327DC40* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___keys_7)); } inline KeyCollection_t5BE70A16AB71FB272DCD7E1DA7B387098D2B0120 * get_keys_7() const { return ___keys_7; } inline KeyCollection_t5BE70A16AB71FB272DCD7E1DA7B387098D2B0120 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t5BE70A16AB71FB272DCD7E1DA7B387098D2B0120 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ___values_8)); } inline ValueCollection_tC0183EB9B565CC716E5BD56C2D1784AC1E2373B1 * get_values_8() const { return ___values_8; } inline ValueCollection_tC0183EB9B565CC716E5BD56C2D1784AC1E2373B1 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_tC0183EB9B565CC716E5BD56C2D1784AC1E2373B1 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,System.Int32> struct Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tB55287EA11F7C665F930EF3A359F186CD3AE5EC1* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tDB6919EBDF36E83E708A483A6C4CF8065F62D1E0 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t8738745D8513A557A82E6E097DF4D4E70D5253C2 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___entries_1)); } inline EntryU5BU5D_tB55287EA11F7C665F930EF3A359F186CD3AE5EC1* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tB55287EA11F7C665F930EF3A359F186CD3AE5EC1** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tB55287EA11F7C665F930EF3A359F186CD3AE5EC1* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___keys_7)); } inline KeyCollection_tDB6919EBDF36E83E708A483A6C4CF8065F62D1E0 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tDB6919EBDF36E83E708A483A6C4CF8065F62D1E0 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tDB6919EBDF36E83E708A483A6C4CF8065F62D1E0 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ___values_8)); } inline ValueCollection_t8738745D8513A557A82E6E097DF4D4E70D5253C2 * get_values_8() const { return ___values_8; } inline ValueCollection_t8738745D8513A557A82E6E097DF4D4E70D5253C2 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t8738745D8513A557A82E6E097DF4D4E70D5253C2 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,System.Int64> struct Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tB210152E9D3EBE4609E3432D20C529E7C1B65D44* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t6C75FA39C169AFB913CD046927B28E95AA96C54A * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_tDD2C80682AF4CF18883668E136B1980110C79D95 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___entries_1)); } inline EntryU5BU5D_tB210152E9D3EBE4609E3432D20C529E7C1B65D44* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tB210152E9D3EBE4609E3432D20C529E7C1B65D44** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tB210152E9D3EBE4609E3432D20C529E7C1B65D44* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___keys_7)); } inline KeyCollection_t6C75FA39C169AFB913CD046927B28E95AA96C54A * get_keys_7() const { return ___keys_7; } inline KeyCollection_t6C75FA39C169AFB913CD046927B28E95AA96C54A ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t6C75FA39C169AFB913CD046927B28E95AA96C54A * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ___values_8)); } inline ValueCollection_tDD2C80682AF4CF18883668E136B1980110C79D95 * get_values_8() const { return ___values_8; } inline ValueCollection_tDD2C80682AF4CF18883668E136B1980110C79D95 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_tDD2C80682AF4CF18883668E136B1980110C79D95 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,UnityEngine.Material> struct Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tABE076887DFD24028C536C77C7C7DCCD66ACA8A7* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t193AE2D2720028E6C67183D0B8776FC0C389765D * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t45CC083597229265F7ED085E423FB1A7BF762BA3 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___entries_1)); } inline EntryU5BU5D_tABE076887DFD24028C536C77C7C7DCCD66ACA8A7* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tABE076887DFD24028C536C77C7C7DCCD66ACA8A7** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tABE076887DFD24028C536C77C7C7DCCD66ACA8A7* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___keys_7)); } inline KeyCollection_t193AE2D2720028E6C67183D0B8776FC0C389765D * get_keys_7() const { return ___keys_7; } inline KeyCollection_t193AE2D2720028E6C67183D0B8776FC0C389765D ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t193AE2D2720028E6C67183D0B8776FC0C389765D * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ___values_8)); } inline ValueCollection_t45CC083597229265F7ED085E423FB1A7BF762BA3 * get_values_8() const { return ___values_8; } inline ValueCollection_t45CC083597229265F7ED085E423FB1A7BF762BA3 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t45CC083597229265F7ED085E423FB1A7BF762BA3 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,UnityEngine.EventSystems.PointerEventData> struct Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t3D89719784232B784AF24BDF458050EC3BF780AF* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tD2C5F600E93DE7B92ABF7BC7E8A932E27D940212 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t28C5EADCF5205986726B544E972D81491CD308DA * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___entries_1)); } inline EntryU5BU5D_t3D89719784232B784AF24BDF458050EC3BF780AF* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t3D89719784232B784AF24BDF458050EC3BF780AF** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t3D89719784232B784AF24BDF458050EC3BF780AF* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___keys_7)); } inline KeyCollection_tD2C5F600E93DE7B92ABF7BC7E8A932E27D940212 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tD2C5F600E93DE7B92ABF7BC7E8A932E27D940212 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tD2C5F600E93DE7B92ABF7BC7E8A932E27D940212 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ___values_8)); } inline ValueCollection_t28C5EADCF5205986726B544E972D81491CD308DA * get_values_8() const { return ___values_8; } inline ValueCollection_t28C5EADCF5205986726B544E972D81491CD308DA ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t28C5EADCF5205986726B544E972D81491CD308DA * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,Microsoft.MixedReality.Toolkit.SpatialAwareness.SpatialAwarenessMeshObject> struct Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t8344B8670E5D8DDCF5FDDEDD27DBB8D417B58898* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tD20167A0CD28EAA4DE363BB48DE5D6C737BE5302 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t532B14D24FC92E18A887848D100E3825432ECF59 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___entries_1)); } inline EntryU5BU5D_t8344B8670E5D8DDCF5FDDEDD27DBB8D417B58898* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t8344B8670E5D8DDCF5FDDEDD27DBB8D417B58898** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t8344B8670E5D8DDCF5FDDEDD27DBB8D417B58898* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___keys_7)); } inline KeyCollection_tD20167A0CD28EAA4DE363BB48DE5D6C737BE5302 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tD20167A0CD28EAA4DE363BB48DE5D6C737BE5302 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tD20167A0CD28EAA4DE363BB48DE5D6C737BE5302 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ___values_8)); } inline ValueCollection_t532B14D24FC92E18A887848D100E3825432ECF59 * get_values_8() const { return ___values_8; } inline ValueCollection_t532B14D24FC92E18A887848D100E3825432ECF59 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t532B14D24FC92E18A887848D100E3825432ECF59 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,System.String> struct Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t0760EF54F1EA7070181C04D5D34118DC91F943ED* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t95CEC57CA04600603C7E9067D11E724EE99AD7D1 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t5C221D6474B57B05A1EF91C1C6A7B1FA1CF361BF * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___entries_1)); } inline EntryU5BU5D_t0760EF54F1EA7070181C04D5D34118DC91F943ED* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t0760EF54F1EA7070181C04D5D34118DC91F943ED** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t0760EF54F1EA7070181C04D5D34118DC91F943ED* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___keys_7)); } inline KeyCollection_t95CEC57CA04600603C7E9067D11E724EE99AD7D1 * get_keys_7() const { return ___keys_7; } inline KeyCollection_t95CEC57CA04600603C7E9067D11E724EE99AD7D1 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t95CEC57CA04600603C7E9067D11E724EE99AD7D1 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ___values_8)); } inline ValueCollection_t5C221D6474B57B05A1EF91C1C6A7B1FA1CF361BF * get_values_8() const { return ___values_8; } inline ValueCollection_t5C221D6474B57B05A1EF91C1C6A7B1FA1CF361BF ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t5C221D6474B57B05A1EF91C1C6A7B1FA1CF361BF * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Int32,TMPro.TMP_ColorGradient> struct Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tD8D7AD456FCCA071CB20981E7A68D2BFE029FA8C* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tCE7752ED00F7F3D67E6F2360D066F92B47831981 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t0A4E0F9662AF7EF0D0D0E1E70988F30A0717AA41 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___entries_1)); } inline EntryU5BU5D_tD8D7AD456FCCA071CB20981E7A68D2BFE029FA8C* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tD8D7AD456FCCA071CB20981E7A68D2BFE029FA8C** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tD8D7AD456FCCA071CB20981E7A68D2BFE029FA8C* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___keys_7)); } inline KeyCollection_tCE7752ED00F7F3D67E6F2360D066F92B47831981 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tCE7752ED00F7F3D67E6F2360D066F92B47831981 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tCE7752ED00F7F3D67E6F2360D066F92B47831981 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ___values_8)); } inline ValueCollection_t0A4E0F9662AF7EF0D0D0E1E70988F30A0717AA41 * get_values_8() const { return ___values_8; } inline ValueCollection_t0A4E0F9662AF7EF0D0D0E1E70988F30A0717AA41 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t0A4E0F9662AF7EF0D0D0E1E70988F30A0717AA41 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif il2cpp_hresult_t IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue); il2cpp_hresult_t IMap_2_Lookup_mAB2557F89B67970660EAEA867C160D8B4519A59B_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, int32_t* comReturnValue); il2cpp_hresult_t IMap_2_get_Size_mA1A1CCC776D0A04E6CB464990ACA1A8A24B8FB99_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IMap_2_HasKey_m09F3138AF64D40439835CED4FA397E6A5567B69F_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, bool* comReturnValue); il2cpp_hresult_t IMap_2_GetView_m49BD462B6D6FBA94E03FC317B3F348E400D8D059_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** comReturnValue); il2cpp_hresult_t IMap_2_Insert_m26A58381A4B7979D7635D8C6BABB43581F277A1E_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, int32_t ___value1, bool* comReturnValue); il2cpp_hresult_t IMap_2_Remove_mBEBB5F63E6AF3D5EC5F85CEC6FF599CF27892CA3_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0); il2cpp_hresult_t IMap_2_Clear_mFC61A1262C6FF5614B12B0D00A26C3B01B909312_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IIterable_1_First_m9E67B40CA2B0E8AB40AC60919F35CDBAF4907598_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IIterator_1_tAB0C1B446829B226CAAD72C2FBCB3E1FBB5A4C71** comReturnValue); il2cpp_hresult_t IMapView_2_Lookup_mEB4A4831069E064FC0A807E20E51095F61208AAF_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, int32_t* comReturnValue); il2cpp_hresult_t IMapView_2_get_Size_mDBDA039F45FE7DAB8B299F8284D620683947C20D_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IMapView_2_HasKey_m3BE9E9A164CFAD5EBF9879319054D86AAA4D529C_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, bool* comReturnValue); il2cpp_hresult_t IMapView_2_Split_m6869EE64C18723F0BB0D10417E11AA80918D1295_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** ___first0, IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** ___second1); il2cpp_hresult_t IMap_2_Lookup_mD086C909F276F0A409C254386A5433BA1D8E4DA1_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, int64_t* comReturnValue); il2cpp_hresult_t IMap_2_get_Size_mF7543BFD7482B050F35BE3CABFB5B6A903300CE7_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IMap_2_HasKey_m1543A9B7F80B3A5489328F1F77CB0691655EA012_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, bool* comReturnValue); il2cpp_hresult_t IMap_2_GetView_mF5636C470F31A6C155D5AAA77FB9BD0442C34E04_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** comReturnValue); il2cpp_hresult_t IMap_2_Insert_mD8D2C48C925DF3B8A1F36EB5D923E7798AAD25AD_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, int64_t ___value1, bool* comReturnValue); il2cpp_hresult_t IMap_2_Remove_m588519BFAFF613E05C992F17D2D10A9104A5C511_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0); il2cpp_hresult_t IMap_2_Clear_mF043DFCA2742D3F57D3380D0D42A6D7DD46867C7_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IIterable_1_First_mC90DE28333E7B75BCEE7ADDA4E3BE0A56EEEB649_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IIterator_1_tCAC42F4EF69B7F9727A04F84FB9773E96CB8DFC9** comReturnValue); il2cpp_hresult_t IMapView_2_Lookup_m1D42C30FE9DDE2255F85A4128C70FBC74070E24A_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, int64_t* comReturnValue); il2cpp_hresult_t IMapView_2_get_Size_mE5B4042270AF83F3467CED1201613AF6870931F1_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IMapView_2_HasKey_m70F1D85335051378EC9751B6CF4AAEE9F5AB6288_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, bool* comReturnValue); il2cpp_hresult_t IMapView_2_Split_m5ACA09637DDBA456BDE48B599992DD4316CEDC0A_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** ___first0, IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** ___second1); il2cpp_hresult_t IMap_2_Lookup_mDB3DE71A1EF4936EF85DC58F72AE18C4DEA7AEA4_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, Il2CppHString* comReturnValue); il2cpp_hresult_t IMap_2_get_Size_m6F21CB368462EE986560EFB89B18F2EB87266C65_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IMap_2_HasKey_m1C1D3DFD5C4CFE039AB133F6FCD00923AA128825_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, bool* comReturnValue); il2cpp_hresult_t IMap_2_GetView_m388C3012C136C6DF202561F3223E1937B3126DC5_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** comReturnValue); il2cpp_hresult_t IMap_2_Insert_mD0EE050C010FEBDF35A137076BB5B9C8D7C134F8_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, Il2CppHString ___value1, bool* comReturnValue); il2cpp_hresult_t IMap_2_Remove_mC0F7A2C3AA571DFBB44D55A01F218C9303BF0005_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0); il2cpp_hresult_t IMap_2_Clear_m2B14C4BB95BEBBA259CCB82E215F6D503A0B8708_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IIterable_1_First_m14DE8FC349ACC550CA242FB49577D6B0AF1C1EB1_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IIterator_1_t90E26C41183EBF622D2BBB227E37A898BAA6B97B** comReturnValue); il2cpp_hresult_t IMapView_2_Lookup_m6C3FB595F2E75BA520D8DD9CAA9B6D3F73DD9E81_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, Il2CppHString* comReturnValue); il2cpp_hresult_t IMapView_2_get_Size_m3EE77EBA65F7B85780CE3CD3E9FBEED16D13FBEB_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IMapView_2_HasKey_m6F79F442D9D546B542483DBCC15739DF4C1CA6A0_ComCallableWrapperProjectedMethod(RuntimeObject* __this, int32_t ___key0, bool* comReturnValue); il2cpp_hresult_t IMapView_2_Split_m12E007F56F41C3C40A71A9B19D78FDE3485A68BF_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** ___first0, IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** ___second1); // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,UnityEngine.InputSystem.InputDevice> struct Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t3D9A2E4B61740D2FF9C269DA70E17270A366C986_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,System.Int32> struct Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08_ComCallableWrapper>, IMap_2_t2D2887BEE348A15C28549CB5E6D3D465077579B1, IIterable_1_tD388FA3CB5D870407558B6357E3097F22416E7E3, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61 { inline Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IMap_2_t2D2887BEE348A15C28549CB5E6D3D465077579B1::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IMap_2_t2D2887BEE348A15C28549CB5E6D3D465077579B1*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_tD388FA3CB5D870407558B6357E3097F22416E7E3::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_tD388FA3CB5D870407558B6357E3097F22416E7E3*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IMap_2_t2D2887BEE348A15C28549CB5E6D3D465077579B1::IID; interfaceIds[1] = IIterable_1_tD388FA3CB5D870407558B6357E3097F22416E7E3::IID; interfaceIds[2] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[3] = IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IMap_2_Lookup_mAB2557F89B67970660EAEA867C160D8B4519A59B(int32_t ___key0, int32_t* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_Lookup_mAB2557F89B67970660EAEA867C160D8B4519A59B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_get_Size_mA1A1CCC776D0A04E6CB464990ACA1A8A24B8FB99(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_get_Size_mA1A1CCC776D0A04E6CB464990ACA1A8A24B8FB99_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_HasKey_m09F3138AF64D40439835CED4FA397E6A5567B69F(int32_t ___key0, bool* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_HasKey_m09F3138AF64D40439835CED4FA397E6A5567B69F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_GetView_m49BD462B6D6FBA94E03FC317B3F348E400D8D059(IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** comReturnValue) IL2CPP_OVERRIDE { return IMap_2_GetView_m49BD462B6D6FBA94E03FC317B3F348E400D8D059_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_Insert_m26A58381A4B7979D7635D8C6BABB43581F277A1E(int32_t ___key0, int32_t ___value1, bool* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_Insert_m26A58381A4B7979D7635D8C6BABB43581F277A1E_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, ___value1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_Remove_mBEBB5F63E6AF3D5EC5F85CEC6FF599CF27892CA3(int32_t ___key0) IL2CPP_OVERRIDE { return IMap_2_Remove_mBEBB5F63E6AF3D5EC5F85CEC6FF599CF27892CA3_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0); } virtual il2cpp_hresult_t STDCALL IMap_2_Clear_mFC61A1262C6FF5614B12B0D00A26C3B01B909312() IL2CPP_OVERRIDE { return IMap_2_Clear_mFC61A1262C6FF5614B12B0D00A26C3B01B909312_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m9E67B40CA2B0E8AB40AC60919F35CDBAF4907598(IIterator_1_tAB0C1B446829B226CAAD72C2FBCB3E1FBB5A4C71** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m9E67B40CA2B0E8AB40AC60919F35CDBAF4907598_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_Lookup_mEB4A4831069E064FC0A807E20E51095F61208AAF(int32_t ___key0, int32_t* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_Lookup_mEB4A4831069E064FC0A807E20E51095F61208AAF_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_get_Size_mDBDA039F45FE7DAB8B299F8284D620683947C20D(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_get_Size_mDBDA039F45FE7DAB8B299F8284D620683947C20D_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_HasKey_m3BE9E9A164CFAD5EBF9879319054D86AAA4D529C(int32_t ___key0, bool* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_HasKey_m3BE9E9A164CFAD5EBF9879319054D86AAA4D529C_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_Split_m6869EE64C18723F0BB0D10417E11AA80918D1295(IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** ___first0, IMapView_2_t548EA6D6E616674BC67D13E4562AA912021A4E61** ___second1) IL2CPP_OVERRIDE { return IMapView_2_Split_m6869EE64C18723F0BB0D10417E11AA80918D1295_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___first0, ___second1); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t49CB072CAA9184D326107FA696BB354C43EB5E08_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,System.Int64> struct Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984_ComCallableWrapper>, IMap_2_t131C1AAB31D1D45DD27D52AC64C0A5BCD9788170, IIterable_1_tD7A5412C67484BA2083059C445DC95E7BC6041C7, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7 { inline Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IMap_2_t131C1AAB31D1D45DD27D52AC64C0A5BCD9788170::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IMap_2_t131C1AAB31D1D45DD27D52AC64C0A5BCD9788170*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_tD7A5412C67484BA2083059C445DC95E7BC6041C7::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_tD7A5412C67484BA2083059C445DC95E7BC6041C7*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IMap_2_t131C1AAB31D1D45DD27D52AC64C0A5BCD9788170::IID; interfaceIds[1] = IIterable_1_tD7A5412C67484BA2083059C445DC95E7BC6041C7::IID; interfaceIds[2] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[3] = IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IMap_2_Lookup_mD086C909F276F0A409C254386A5433BA1D8E4DA1(int32_t ___key0, int64_t* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_Lookup_mD086C909F276F0A409C254386A5433BA1D8E4DA1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_get_Size_mF7543BFD7482B050F35BE3CABFB5B6A903300CE7(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_get_Size_mF7543BFD7482B050F35BE3CABFB5B6A903300CE7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_HasKey_m1543A9B7F80B3A5489328F1F77CB0691655EA012(int32_t ___key0, bool* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_HasKey_m1543A9B7F80B3A5489328F1F77CB0691655EA012_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_GetView_mF5636C470F31A6C155D5AAA77FB9BD0442C34E04(IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** comReturnValue) IL2CPP_OVERRIDE { return IMap_2_GetView_mF5636C470F31A6C155D5AAA77FB9BD0442C34E04_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_Insert_mD8D2C48C925DF3B8A1F36EB5D923E7798AAD25AD(int32_t ___key0, int64_t ___value1, bool* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_Insert_mD8D2C48C925DF3B8A1F36EB5D923E7798AAD25AD_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, ___value1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_Remove_m588519BFAFF613E05C992F17D2D10A9104A5C511(int32_t ___key0) IL2CPP_OVERRIDE { return IMap_2_Remove_m588519BFAFF613E05C992F17D2D10A9104A5C511_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0); } virtual il2cpp_hresult_t STDCALL IMap_2_Clear_mF043DFCA2742D3F57D3380D0D42A6D7DD46867C7() IL2CPP_OVERRIDE { return IMap_2_Clear_mF043DFCA2742D3F57D3380D0D42A6D7DD46867C7_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_mC90DE28333E7B75BCEE7ADDA4E3BE0A56EEEB649(IIterator_1_tCAC42F4EF69B7F9727A04F84FB9773E96CB8DFC9** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_mC90DE28333E7B75BCEE7ADDA4E3BE0A56EEEB649_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_Lookup_m1D42C30FE9DDE2255F85A4128C70FBC74070E24A(int32_t ___key0, int64_t* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_Lookup_m1D42C30FE9DDE2255F85A4128C70FBC74070E24A_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_get_Size_mE5B4042270AF83F3467CED1201613AF6870931F1(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_get_Size_mE5B4042270AF83F3467CED1201613AF6870931F1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_HasKey_m70F1D85335051378EC9751B6CF4AAEE9F5AB6288(int32_t ___key0, bool* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_HasKey_m70F1D85335051378EC9751B6CF4AAEE9F5AB6288_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_Split_m5ACA09637DDBA456BDE48B599992DD4316CEDC0A(IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** ___first0, IMapView_2_tA6FA0DF533C0B6B506D0CE1F81728364B83DFBC7** ___second1) IL2CPP_OVERRIDE { return IMapView_2_Split_m5ACA09637DDBA456BDE48B599992DD4316CEDC0A_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___first0, ___second1); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t9AE0BA863BA88FABCBFC4CA835E0A6E00D948984_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,UnityEngine.Material> struct Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_tE3F17FC57643708975DF2782661AFB9CB1687991_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,UnityEngine.EventSystems.PointerEventData> struct Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t52ECB6047A9EDAD198D0CC53F331CDEAAA83BED8_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,Microsoft.MixedReality.Toolkit.SpatialAwareness.SpatialAwarenessMeshObject> struct Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_tBFEF92C709D6CF5C8220E4553DF6064FCB30A49B_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,System.String> struct Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB_ComCallableWrapper>, IMap_2_t6D83CFC4BB5F39D14238C2A6C38DB1D7D36E9EE3, IIterable_1_tFC0F28A8493453E790566AD9BF521EB99E862227, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A { inline Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IMap_2_t6D83CFC4BB5F39D14238C2A6C38DB1D7D36E9EE3::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IMap_2_t6D83CFC4BB5F39D14238C2A6C38DB1D7D36E9EE3*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_tFC0F28A8493453E790566AD9BF521EB99E862227::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_tFC0F28A8493453E790566AD9BF521EB99E862227*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IMap_2_t6D83CFC4BB5F39D14238C2A6C38DB1D7D36E9EE3::IID; interfaceIds[1] = IIterable_1_tFC0F28A8493453E790566AD9BF521EB99E862227::IID; interfaceIds[2] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[3] = IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IMap_2_Lookup_mDB3DE71A1EF4936EF85DC58F72AE18C4DEA7AEA4(int32_t ___key0, Il2CppHString* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_Lookup_mDB3DE71A1EF4936EF85DC58F72AE18C4DEA7AEA4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_get_Size_m6F21CB368462EE986560EFB89B18F2EB87266C65(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_get_Size_m6F21CB368462EE986560EFB89B18F2EB87266C65_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_HasKey_m1C1D3DFD5C4CFE039AB133F6FCD00923AA128825(int32_t ___key0, bool* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_HasKey_m1C1D3DFD5C4CFE039AB133F6FCD00923AA128825_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_GetView_m388C3012C136C6DF202561F3223E1937B3126DC5(IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** comReturnValue) IL2CPP_OVERRIDE { return IMap_2_GetView_m388C3012C136C6DF202561F3223E1937B3126DC5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_Insert_mD0EE050C010FEBDF35A137076BB5B9C8D7C134F8(int32_t ___key0, Il2CppHString ___value1, bool* comReturnValue) IL2CPP_OVERRIDE { return IMap_2_Insert_mD0EE050C010FEBDF35A137076BB5B9C8D7C134F8_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, ___value1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMap_2_Remove_mC0F7A2C3AA571DFBB44D55A01F218C9303BF0005(int32_t ___key0) IL2CPP_OVERRIDE { return IMap_2_Remove_mC0F7A2C3AA571DFBB44D55A01F218C9303BF0005_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0); } virtual il2cpp_hresult_t STDCALL IMap_2_Clear_m2B14C4BB95BEBBA259CCB82E215F6D503A0B8708() IL2CPP_OVERRIDE { return IMap_2_Clear_m2B14C4BB95BEBBA259CCB82E215F6D503A0B8708_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m14DE8FC349ACC550CA242FB49577D6B0AF1C1EB1(IIterator_1_t90E26C41183EBF622D2BBB227E37A898BAA6B97B** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m14DE8FC349ACC550CA242FB49577D6B0AF1C1EB1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_Lookup_m6C3FB595F2E75BA520D8DD9CAA9B6D3F73DD9E81(int32_t ___key0, Il2CppHString* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_Lookup_m6C3FB595F2E75BA520D8DD9CAA9B6D3F73DD9E81_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_get_Size_m3EE77EBA65F7B85780CE3CD3E9FBEED16D13FBEB(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_get_Size_m3EE77EBA65F7B85780CE3CD3E9FBEED16D13FBEB_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_HasKey_m6F79F442D9D546B542483DBCC15739DF4C1CA6A0(int32_t ___key0, bool* comReturnValue) IL2CPP_OVERRIDE { return IMapView_2_HasKey_m6F79F442D9D546B542483DBCC15739DF4C1CA6A0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___key0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IMapView_2_Split_m12E007F56F41C3C40A71A9B19D78FDE3485A68BF(IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** ___first0, IMapView_2_t34DF605D0FD6600E1AFA0C5217689101A8E2683A** ___second1) IL2CPP_OVERRIDE { return IMapView_2_Split_m12E007F56F41C3C40A71A9B19D78FDE3485A68BF_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___first0, ___second1); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t0ACB62D0885C7AB376463C70665400A39808C5FB_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Int32,TMPro.TMP_ColorGradient> struct Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t83EDCEFCBB12C89A61745514957F522FEF34EAE1_ComCallableWrapper(obj)); }
51.878378
416
0.837646
[ "object" ]
925d92131c484ae25146faeb740c5796a2c34d10
2,710
hpp
C++
fileid/document/excel/records/SupBookRecord.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
13
2016-03-13T17:57:46.000Z
2021-12-21T12:11:41.000Z
fileid/document/excel/records/SupBookRecord.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
9
2016-04-07T13:07:58.000Z
2020-05-30T13:31:59.000Z
fileid/document/excel/records/SupBookRecord.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
5
2017-04-20T14:47:55.000Z
2021-03-08T03:27:17.000Z
#pragma once #include "Record.hpp" #include "../structures/XLUnicodeString.hpp" namespace oless { namespace excel { namespace records { // see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/31ed3738-e4ff-4b60-804c-ac49ac1ee6c0 // The SupBook record specifies a supporting link and specifies the beginning of a collection of records as defined by the Globals Substream ABNF. The collection of records specifies the contents of an external workbook, DDE data source, or OLE data source. class SupBookRecord : public Record { public: unsigned short ctab; unsigned short cch; bool HasVirtPath = false; std::string virtPath; std::vector<std::string> rgst; SupBookRecord(unsigned short type, std::vector<uint8_t> data) : Record(type, data) { auto buffer = this->Data.data(); auto max = this->Data.size(); unsigned int index = 0; this->ctab = common::ReadUShort(buffer, max, index); index += 2; this->cch = common::ReadUShort(buffer, max, index); index += 2; if (index < max) { if (this->cch >= 0x01 && this->cch <= 0xFF) { this->HasVirtPath = true; this->virtPath == common::ReadString(buffer, max, index, this->cch); index += this->cch; } } if (index < max) { if (this->cch == 0x3A01 || this->cch == 0x0401) { for (unsigned int i = 0; i < this->ctab; i++) { auto s = oless::excel::structures::XLUnicodeString::Read(buffer, index, max); index += s.bytesRead; rgst.push_back(s.string); } } } } virtual std::string ToXml() const override { std::ostringstream str; str << "<Record>"; str << this->getBaseXml(); str << "<ctab>" << this->ctab << "</ctab>"; str << "<cch>" << this->cch << "</cch>"; if (this->HasVirtPath) { str << "<virtPath>" << this->virtPath << "</virtPath>"; } if (this->rgst.size() > 0) { str << "<rgst>"; for (auto it = this->rgst.begin(); it < this->rgst.end(); it++) { str << "<string>" << (*it) << "</string>"; } str << "</rgst>"; } str << "</Record>"; return str.str(); } virtual std::string ToJson() const override { std::ostringstream str; str << "{"; str << this->getBaseJson(); str << ",\"ctab\":" << this->ctab; str << ",\"cch\":" << this->cch; if (this->HasVirtPath) { str << ",\"virtPath\":\"" << this->virtPath << "\""; } if (this->rgst.size() > 0) { str << ",\"rgst\":[" << common::vector_join(this->rgst, ",", true) << "]"; } str << "}"; return str.str(); } }; } } }
29.78022
261
0.550185
[ "vector" ]
1789724b7d9482c54903202b0eb65dae3eddcc71
11,219
cpp
C++
encodedlength.cpp
billvaglienti/ProtoGen
55da08b1823be24b4247ecd54627c4590df79d13
[ "MIT" ]
22
2016-02-29T19:53:23.000Z
2022-03-31T04:54:48.000Z
encodedlength.cpp
billvaglienti/ProtoGen
55da08b1823be24b4247ecd54627c4590df79d13
[ "MIT" ]
72
2015-02-25T16:33:01.000Z
2021-10-31T19:52:18.000Z
encodedlength.cpp
billvaglienti/ProtoGen
55da08b1823be24b4247ecd54627c4590df79d13
[ "MIT" ]
12
2015-02-25T12:45:25.000Z
2021-11-16T22:07:39.000Z
#include "encodedlength.h" #include "shuntingyard.h" #include "protocolsupport.h" EncodedLength::EncodedLength() : minEncodedLength(), maxEncodedLength(), nonDefaultEncodedLength() { } /*! * Clear the encoded length */ void EncodedLength::clear(void) { minEncodedLength.clear(); maxEncodedLength.clear(); nonDefaultEncodedLength.clear(); } /*! * Determine if there is any data here * \return true if an length is recorded, else false */ bool EncodedLength::isEmpty(void) { return maxEncodedLength.empty(); } /*! * Determine if the length is zero * \return true if the maximum length is empty or is "0" */ bool EncodedLength::isZeroLength(void) const { if(collapseLengthString(maxEncodedLength, true).compare("0") == 0) return true; else return false; } /*! * Add successive length strings * \param length is the new length string to add * \param isString is true if this length is for a string * \param isVariable is true if this length is for a variable length array * \param isDependent is true if this length is for a field whose presence depends on another field * \parma isDefault is true if this lenght is for a default field. */ void EncodedLength::addToLength(const std::string & length, bool isString, bool isVariable, bool isDependent, bool isDefault) { if(length.empty()) return; addToLengthString(maxEncodedLength, length); // Default fields do not add to the length of anything else if(isDefault) return; // Length of everthing except default, strings are 1 byte if(isString) addToLengthString(nonDefaultEncodedLength, "1"); else addToLengthString(nonDefaultEncodedLength, length); // If not variable or dependent, then add to minimum length if(!isVariable && !isDependent) { // Strings add a minimum length of 1 byte if(isString) addToLengthString(minEncodedLength, "1"); else addToLengthString(minEncodedLength, length); } }// EncodedLength::addToLength /*! * Add a grouping of length strings to this length * \param rightLength is the length strings to add. * \param array is the array length, which can be empty. * \param isVariable is true if this length is for a variable length array. * \param isDependent is true if this length is for a field whose presence depends on another field. * \param array2d is the 2nd dimension array length, which can be empty. */ void EncodedLength::addToLength(const EncodedLength& rightLength, const std::string& array, bool isVariable, bool isDependent, const std::string& array2d) { addToLengthString(maxEncodedLength, rightLength.maxEncodedLength, array, array2d); addToLengthString(nonDefaultEncodedLength, rightLength.nonDefaultEncodedLength, array, array2d); // If not variable or dependent, then add to minimum length if(!isVariable && !isDependent) addToLengthString(minEncodedLength, rightLength.minEncodedLength, array, array2d); } /*! * Add a grouping of length strings * \param leftLength is the group that is incremented, can be NULL in which case this function does nothing. * \param rightLength is the length strings to add. * \param array is the array length, which can be empty. * \param isVariable is true if this length is for a variable length array. * \param isDependent is true if this length is for a field whose presence depends on another field. * \param array2d is the 2nd dimension array length, which can be empty. */ void EncodedLength::add(EncodedLength* leftLength, const EncodedLength& rightLength, const std::string& array, bool isVariable, bool isDependent, const std::string& array2d) { if(leftLength != NULL) leftLength->addToLength(rightLength, array, isVariable, isDependent, array2d); } /*! * Create a length string like "4 + 3 + N3D*2" by adding successive length strings * \param totalLength is the total length string * \param length is the new length to add * \param array is the number of times to add it */ void EncodedLength::addToLengthString(std::string & totalLength, std::string length, std::string array, std::string array2d) { bool ok; double number; int inumber; if(length.empty()) return; // Its possible that length represents something like 24*(6), // which we can resolve easily, so lets try number = ShuntingYard::computeInfix(length, &ok); if(ok) { // round to nearest integer if(number >= 0) inumber = (int)(number + 0.5); else inumber = (int)(number - 0.5); if(inumber == 0) return; length = std::to_string(inumber); } if(!array.empty() && array != "1") { // How we handle the array multiplier depends on the contents of length // We only expect length to have +, -, or * operators. If there are no // operators, or the only operators are multipliers, then we don't need // the parenthesis. Otherwise we do need them. if(array2d.empty() || (array2d == "1")) { if(length.find_first_of("+-/") != std::string::npos) length = array + "*(" + length + ")"; else length = array + "*" + length; } else { if(length.find_first_of("+-/") != std::string::npos) length = array + "*" + array2d + "*(" + length + ")"; else length = array + "*" + array2d + "*" + length; } } if(totalLength.empty()) totalLength = length; else { // Add them up totalLength = collapseLengthString(totalLength + "+" + length); }// if totalLength previously had data }// EncodedLength::addToLengthString /*! * Collapse a length string as best we can by summing terms * \param totalLength is the existing length string. * \param keepZero should be true keep "0" in the output. * \param minusOne should be true to subtract 1 from the output. * \return an equivalent collapsed string */ std::string EncodedLength::collapseLengthString(std::string totalLength, bool keepZero, bool minusOne) { int number = 0; // It might be that we can compute a value directly, give it a // try and see if we can save all the later effort bool ok; double dnumber = ShuntingYard::computeInfix(totalLength, &ok); if(ok) { // round to nearest integer if(dnumber >= 0) number = (int)(dnumber + 0.5); else number = (int)(dnumber - 0.5); // Handle the minus one here if(minusOne) number--; return std::to_string(number); } // We don't properly support collapsing strings with parenthesis /// TODO: support parenthesis using recursion if(totalLength.find_first_of("()") != std::string::npos) { if(minusOne) return totalLength + "-1"; else return totalLength; } // Split according to the pluses std::vector<std::string> list = split(totalLength, "+"); std::vector<std::string> others; // Some of these groups are simple numbers, some of them are not. We are going to re-order to put the numbers together number = 0; for(std::size_t i = 0; i < list.size(); i++) { if(list.at(i).empty()) continue; if(isNumber(list.at(i))) { number += std::stoi(list.at(i)); } else { others.push_back(list.at(i)); } }// for all the fragments // Handle the minus one here if(minusOne) number--; std::vector<std::vector<std::string>> pairlist; for(std::size_t i = 0; i < others.size(); i++) { // Separate a string like "1*N3D" into "1" and "N3D" pairlist.push_back(split(others.at(i), "*")); } others.clear(); std::string output; for(std::size_t i = 0; i < pairlist.size(); i++) { // Each entry should have two elements and the first should be a number, // if not then something weird happened, just put it back the way it was if((pairlist.at(i).size() != 2) || !isNumber(pairlist.at(i).at(0))) { if(pairlist.at(i).size() != 0) { if(!output.empty()) output += "+"; output += join(pairlist.at(i), "*"); } continue; } int counter = std::stoi(pairlist.at(i).at(0)); // Now go through all entries after this one to find anyone that is common for(std::size_t j = i + 1; j < pairlist.size(); j++) { // if its not a number, then we can't do anything with it, // we'll catch it in the outer loop when we get to it if((pairlist.at(j).size() != 2) || !isNumber(pairlist.at(j).at(0))) continue; // If the comparison is exactly the same, then we can add this one up if(pairlist.at(i).at(1) == pairlist.at(j).at(1)) { // These two are multiples of the same thing counter += std::stoi(pairlist.at(j).at(0)); // Clear this element, no contribution in the future. pairlist[j].clear(); } } // finally include this in the output if(counter != 0) { if(!output.empty()) output += "+"; output += std::to_string(counter) + "*" + pairlist.at(i).at(1); } } // A negative number outputs the "-" by default if(number < 0) output += std::to_string(number); else { if(number != 0) { if(output.empty()) output = std::to_string(number); else output += "+" + std::to_string(number); } } if((keepZero) && output.empty()) output = "0"; // It might be that we can compute a value now, give it a try dnumber = ShuntingYard::computeInfix(output, &ok); if(ok) { // round to nearest integer if(dnumber >= 0) number = (int)(dnumber + 0.5); else number = (int)(dnumber - 0.5); output = std::to_string(number); } return output; }// EncodedLength::collapseLengthString /*! * Subtract one from a length string * \param totalLength is the existing length string. * \param keepZero should be true keep "0" in the output. * \return the string with one less */ std::string EncodedLength::subtractOneFromLengthString(std::string totalLength, bool keepZero) { return EncodedLength::collapseLengthString(totalLength, keepZero, true); } /*! * Determine if a segment of text contains only decimal digits * \param text is the text to check * \return true if only decimal digits, else false */ bool EncodedLength::isNumber(const std::string& text) { /// TODO not sure if I need this size check if(text.size() <= 0) return false; // Only decimal digits and minus signs are OK return (text.find_first_not_of("-0123456789") == std::string::npos); }
30.158602
173
0.614137
[ "vector" ]
179382a2fbdb2fd1e5ddd3d0f5acb68b1b64223e
19,323
cpp
C++
src/databasetools.cpp
sfbg/harbour-vocabulary
778cbb610eab7fa7730d4ea26cb494ec0dfea37e
[ "Apache-2.0" ]
4
2016-10-25T09:52:20.000Z
2017-12-17T14:05:14.000Z
src/databasetools.cpp
sfbg/harbour-vocabulary
778cbb610eab7fa7730d4ea26cb494ec0dfea37e
[ "Apache-2.0" ]
29
2016-10-24T09:50:56.000Z
2021-10-03T00:32:55.000Z
src/databasetools.cpp
sfbg/harbour-vocabulary
778cbb610eab7fa7730d4ea26cb494ec0dfea37e
[ "Apache-2.0" ]
8
2017-03-22T17:54:13.000Z
2019-11-15T21:02:15.000Z
/* * Copyright 2017 Marcus Soll * * 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 "databasetools.h" #include <QDate> bool DatabaseTools::create_new_db() { DEBUG("Creating database"); QSqlQuery query(database); QStringList operations; operations.append("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)"); operations.append("CREATE TABLE language (rowid INTEGER PRIMARY KEY, language TEXT)"); operations.append("INSERT INTO language (rowid, language) VALUES (1, 'Default')"); operations.append("CREATE TABLE vocabulary (rowid INTEGER PRIMARY KEY, word TEXT, translation TEXT, priority INT, creation INT, modification INT, language INT, number_asked INT, number_correct INT, FOREIGN KEY(language) REFERENCES language(rowid))"); operations.append("CREATE INDEX index_vocabulary_language ON vocabulary(language)"); operations.append("CREATE INDEX index_vocabulary_creation ON vocabulary(creation)"); operations.append("CREATE INDEX index_vocabulary_modification ON vocabulary(modification)"); operations.append("CREATE INDEX index_vocabulary_word_nocase ON vocabulary(word COLLATE NOCASE)"); operations.append("CREATE INDEX index_vocabulary_translation_nocase ON vocabulary(translation COLLATE NOCASE)"); operations.append("CREATE INDEX index_vocabulary_number_asked ON vocabulary(number_asked)"); operations.append("CREATE INDEX index_vocabulary_number_correct ON vocabulary(number_correct)"); operations.append("CREATE INDEX index_vocabulary_percentage_correct ON vocabulary(CAST(number_correct AS REAL)/CAST(number_asked AS REAL))"); operations.append("INSERT INTO meta (key, value) VALUES ('version', '5')"); foreach(QString s, operations) { if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); CRITICAL(error); return false; } } return true; } bool DatabaseTools::test_and_update_db() { QSqlQuery query(database); QString s = QString("SELECT value FROM meta WHERE key='version'"); if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); CRITICAL(error); return false; } if(!query.isSelect()) { QString error = s; error.append(": No SELECT"); CRITICAL(error); return false; } if(!query.next()) { WARNING("No metadata 'version'"); return false; } switch(query.value(0).toInt()) { // Upgrade settings case 1: DEBUG("Database upgrade: 1 -> 2"); /* * This database update simplifies all words contained in the database. * It is needed because the old CSV import did not simplify. */ { QStringList to_update; s = "SELECT word FROM vocabulary"; query.clear(); query.prepare(s); if(!query.exec()) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } if(!query.isSelect()) { QString error = s; error.append(": No select"); WARNING(error); return false; } while(query.next()) { QString word = query.value(0).toString(); if(word.simplified() != word) { to_update << word; } } for(QStringList::iterator i = to_update.begin(); i != to_update.end(); ++i) { s = "UPDATE OR IGNORE vocabulary SET word=:new WHERE word=:old"; query.clear(); query.prepare(s); query.bindValue(":new", (*i).simplified()); query.bindValue(":old", *i); if(!query.exec()) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); } } query.clear(); s = "UPDATE meta SET value=2 WHERE key='version'"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); CRITICAL(error); return false; } } DEBUG("Upgrade complete"); case 2: /* * Move to new database format */ DEBUG("Database upgrade: 2 -> 3"); { std::vector<QString> words; std::vector<QString> translation; std::vector<int> priority; // At first fetch all vocabulary query.clear(); s = "SELECT word, translation, priority FROM vocabulary"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } if(!query.isSelect()) { QString error = s; error.append(": No select"); WARNING(error); return false; } while(query.next()) { words.emplace_back(query.value(0).toString()); translation.emplace_back(query.value(1).toString()); priority.emplace_back(query.value(2).toInt()); } // Now update db schema s = "DROP TABLE vocabulary"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE TABLE language (language TEXT)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "INSERT INTO language (rowid, language) VALUES (1, 'Default')"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE TABLE vocabulary (word TEXT, translation TEXT, priority INT, creation INT, modification INT, language INT, FOREIGN KEY(language) REFERENCES language(rowid))"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "UPDATE meta SET value='3' WHERE key='version'"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } // Insert vocabulary back to db database.transaction(); qint64 date = QDate::currentDate().toJulianDay(); s = "INSERT INTO vocabulary (word, translation, priority, creation, modification, language) VALUES (:word, :translation, :priority, :creation, :modification, :language)"; for(size_t index = 0; index < words.size(); ++index) { query.prepare(s); query.bindValue(":word", words[index]); query.bindValue(":translation", translation[index]); query.bindValue(":priority", priority[index]); query.bindValue(":creation", date); query.bindValue(":modification", date); query.bindValue(":language", 1); if(!query.exec()) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); database.rollback(); return false; } } database.commit(); } DEBUG("Upgrade complete"); case 3: /* * Added indices * * Use explicit rowid * https://sqlite.org/foreignkeys.html */ DEBUG("Database upgrade: 3 -> 4"); { std::vector<QString> v_words; std::vector<QString> v_translation; std::vector<int> v_priority; std::vector<qlonglong> v_creation; std::vector<qlonglong> v_modification; std::vector<int> v_language; std::vector<int> l_rowid; std::vector<QString> l_language; // Fetch all vocabulary query.clear(); s = "SELECT word,translation,priority,creation,modification,language FROM vocabulary"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } if(!query.isSelect()) { QString error = s; error.append(": No select"); WARNING(error); return false; } while(query.next()) { v_words.emplace_back(query.value(0).toString()); v_translation.emplace_back(query.value(1).toString()); v_priority.emplace_back(query.value(2).toInt()); v_creation.emplace_back(query.value(3).toLongLong()); v_modification.emplace_back(query.value(4).toLongLong()); v_language.emplace_back(query.value(5).toInt()); } // Fetch all languages query.clear(); s = "SELECT rowid,language FROM language"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } if(!query.isSelect()) { QString error = s; error.append(": No select"); WARNING(error); return false; } while(query.next()) { l_rowid.emplace_back(query.value(0).toInt()); l_language.emplace_back(query.value(1).toString()); } // Now update db schema s = "DROP TABLE vocabulary"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "DROP TABLE language"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE TABLE language (rowid INTEGER PRIMARY KEY, language TEXT)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE TABLE vocabulary (rowid INTEGER PRIMARY KEY, word TEXT, translation TEXT, priority INT, creation INT, modification INT, language INT, FOREIGN KEY(language) REFERENCES language(rowid))"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_language ON vocabulary(language)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_creation ON vocabulary(creation)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_modification ON vocabulary(modification)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "UPDATE meta SET value='4' WHERE key='version'"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } database.transaction(); // Insert languages back into db s = "INSERT INTO language (rowid, language) VALUES (:rowid, :language)"; for(size_t index = 0; index < l_rowid.size(); ++index) { query.prepare(s); query.bindValue(":rowid", l_rowid[index]); query.bindValue(":language", l_language[index]); if(!query.exec()) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); database.rollback(); return false; } } // Insert vocabulary back to db s = "INSERT INTO vocabulary (word, translation, priority, creation, modification, language) VALUES (:word, :translation, :priority, :creation, :modification, :language)"; for(size_t index = 0; index < v_words.size(); ++index) { query.prepare(s); query.bindValue(":word", v_words[index]); query.bindValue(":translation", v_translation[index]); query.bindValue(":priority", v_priority[index]); query.bindValue(":creation", v_creation[index]); query.bindValue(":modification", v_modification[index]); query.bindValue(":language", v_language[index]); if(!query.exec()) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); database.rollback(); return false; } } database.commit(); // Clean database - no hard failure! s = "VACUUM"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); } } DEBUG("Upgrade complete"); case 4: DEBUG("Database upgrade: 4 -> 5"); s = "CREATE INDEX index_vocabulary_word_nocase ON vocabulary(word COLLATE NOCASE)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_translation_nocase ON vocabulary(translation COLLATE NOCASE)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "ALTER TABLE vocabulary ADD COLUMN number_asked INT"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "UPDATE vocabulary SET number_asked=0"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "ALTER TABLE vocabulary ADD COLUMN number_correct INT"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "UPDATE vocabulary SET number_correct=0"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_number_asked ON vocabulary(number_asked)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_number_correct ON vocabulary(number_correct)"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "CREATE INDEX index_vocabulary_percentage_correct ON vocabulary(CAST(number_correct AS REAL)/CAST(number_asked AS REAL))"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } s = "UPDATE meta SET value='5' WHERE key='version'"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); return false; } // Clean database - no hard failure! s = "VACUUM"; if(!query.exec(s)) { QString error = s; error.append(": ").append(query.lastError().text()); WARNING(error); } DEBUG("Upgrade complete"); case 5: DEBUG("Database version: 5"); return true; break; default: /* Safeguard - if we reach this point something went REALLY wrong */ WARNING("Unknown database version"); return false; break; } }
33.144082
254
0.499871
[ "vector" ]
179756f6a350deb0cf123b0ec74a569e3e9b82df
2,005
cpp
C++
rclcpp/src/rclcpp/detail/utilities.cpp
jlack1987/rclcpp
d107a844eae6f4d6a86515f0b3e469802ab1e785
[ "Apache-2.0" ]
271
2015-04-07T15:26:53.000Z
2022-03-31T17:42:58.000Z
rclcpp/src/rclcpp/detail/utilities.cpp
jlack1987/rclcpp
d107a844eae6f4d6a86515f0b3e469802ab1e785
[ "Apache-2.0" ]
1,676
2015-01-15T23:46:56.000Z
2022-03-31T21:32:06.000Z
rclcpp/src/rclcpp/detail/utilities.cpp
irobot-ros/rclcpp
edcae47df2528a9c06cfd98f204ad9b5d2da56b4
[ "Apache-2.0" ]
299
2015-10-05T16:51:32.000Z
2022-03-30T11:23:18.000Z
// Copyright 2019 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "rclcpp/detail/utilities.hpp" #include <cassert> #include <string> #include <utility> #include <vector> #include "rclcpp/exceptions.hpp" #include "rcl/allocator.h" #include "rcl/arguments.h" namespace rclcpp { namespace detail { std::vector<std::string> get_unparsed_ros_arguments( int argc, char const * const argv[], rcl_arguments_t * arguments, rcl_allocator_t allocator) { (void)argc; std::vector<std::string> unparsed_ros_arguments; int unparsed_ros_args_count = rcl_arguments_get_count_unparsed_ros(arguments); if (unparsed_ros_args_count > 0) { int * unparsed_ros_args_indices = nullptr; rcl_ret_t ret = rcl_arguments_get_unparsed_ros(arguments, allocator, &unparsed_ros_args_indices); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "failed to get unparsed ROS arguments"); } try { for (int i = 0; i < unparsed_ros_args_count; ++i) { assert(unparsed_ros_args_indices[i] >= 0); assert(unparsed_ros_args_indices[i] < argc); unparsed_ros_arguments.push_back(argv[unparsed_ros_args_indices[i]]); } allocator.deallocate(unparsed_ros_args_indices, allocator.state); } catch (...) { allocator.deallocate(unparsed_ros_args_indices, allocator.state); throw; } } return unparsed_ros_arguments; } } // namespace detail } // namespace rclcpp
30.846154
92
0.727182
[ "vector" ]
179ea19a250b4154b35f9db64b14dfaeb94cf906
4,085
hpp
C++
src/Common.hpp
Yenaled/bustools
6fa0731f7f32c68645f0f60b1c1c89771b1c8061
[ "BSD-2-Clause" ]
null
null
null
src/Common.hpp
Yenaled/bustools
6fa0731f7f32c68645f0f60b1c1c89771b1c8061
[ "BSD-2-Clause" ]
null
null
null
src/Common.hpp
Yenaled/bustools
6fa0731f7f32c68645f0f60b1c1c89771b1c8061
[ "BSD-2-Clause" ]
null
null
null
#ifndef BUSTOOLS_COMMON_HPP #define BUSTOOLS_COMMON_HPP #include <cassert> #include <cmath> #include <algorithm> #include <stdint.h> #include <vector> #include <string> #include <unordered_map> #include <sstream> #define BUSTOOLS_VERSION "0.41.0" enum CAPTURE_TYPE : char { CAPTURE_NONE = 0, CAPTURE_TX, CAPTURE_BC, CAPTURE_UMI, CAPTURE_F }; enum SORT_TYPE : char { SORT_BC = 0, SORT_UMI, SORT_F, SORT_COUNT, SORT_F_BC }; enum PROJECT_TYPE : char { PROJECT_BC = 0, PROJECT_UMI, PROJECT_TX, PROJECT_F }; struct Bustools_opt { int threads; std::string whitelist; std::string output; std::vector<std::string> files; bool stream_in = false; bool stream_out = false; /* extract */ int nFastqs; std::vector<std::string> fastq; char type; int ec_d; int ec_dmin; size_t max_memory; std::string temp_files; /* count, and other things */ std::string count_genes; std::string count_ecs; std::string count_txp; bool count_em = false; bool count_cm = false; bool count_collapse = false; bool umi_gene_collapse = false; bool count_gene_multimapping = false; bool count_gen_hist = false; double count_downsampling_factor = 1.0; bool count_raw_counts = false; /* correct */ std::string dump; bool dump_bool = false; bool split_correct = false; /* predict */ std::string predict_input; //specified the same way as the output for count - count and histogram filenames will be created from this double predict_t = 0.0; //this is how far to predict, t=10 means that we will predict the change in expression at 10 times the number of reads /* clusterhist */ std::string cluster_input_file; /* project */ std::string map; std::string output_folder; /* capture */ std::string capture; bool complement = false; bool filter = false; /* whitelist */ int threshold; /* text */ bool text_dumpflags = false; bool text_dumppad = false; /* linker */ int start, end; Bustools_opt() : threads(1), max_memory(1ULL << 32), type(0), threshold(0), start(-1), end(-1) {} }; static const char alpha[4] = {'A', 'C', 'G', 'T'}; inline size_t rndup(size_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; v++; return v; } inline uint32_t rndup(uint32_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } struct SortedVectorHasher { size_t operator()(const std::vector<int32_t> &v) const { uint64_t r = 0; int i = 0; for (auto x : v) { uint64_t t = std::hash<int32_t>{}(x); t = (x >> i) | (x << (64 - i)); r = r ^ t; i = (i + 1) % 64; } return r; } }; std::vector<int32_t> intersect(std::vector<int32_t> &u, std::vector<int32_t> &v); std::vector<int32_t> union_vectors(const std::vector<std::vector<int32_t>> &v); std::vector<int32_t> intersect_vectors(const std::vector<std::vector<int32_t>> &v); int32_t intersect_ecs(const std::vector<int32_t> &ecs, std::vector<int32_t> &u, const std::vector<int32_t> &genemap, std::vector<std::vector<int32_t>> &ecmap, std::unordered_map<std::vector<int32_t>, int32_t, SortedVectorHasher> &ecmapinv, std::vector<std::vector<int32_t>> &ec2genes); void vt2gene(const std::vector<int32_t> &v, const std::vector<int32_t> &genemap, std::vector<int32_t> &glist); void intersect_genes_of_ecs(const std::vector<int32_t> &ecs, const std::vector<std::vector<int32_t>> &ec2genes, std::vector<int32_t> &glist); int32_t intersect_ecs_with_genes(const std::vector<int32_t> &ecs, const std::vector<int32_t> &genemap, std::vector<std::vector<int32_t>> &ecmap, std::unordered_map<std::vector<int32_t>, int32_t, SortedVectorHasher> &ecmapinv, std::vector<std::vector<int32_t>> &ec2genes, bool assumeIntersectionIsEmpty = true); void create_ec2genes(const std::vector<std::vector<int32_t>> &ecmap, const std::vector<int32_t> &genemap, std::vector<std::vector<int32_t>> &ec2gene); void copy_file(std::string src, std::string dest); #endif // BUSTOOLS_COMMON_HPP
24.171598
310
0.665606
[ "vector" ]
179ebbefdcdac1ad3a3e2774240f1de8e0c925c9
666
cpp
C++
atcoder/abc060-arc073/c.cpp
L3Sota/atcoder
7d9444e03837b537ebc6f4f917b9567af6cf5483
[ "MIT" ]
null
null
null
atcoder/abc060-arc073/c.cpp
L3Sota/atcoder
7d9444e03837b537ebc6f4f917b9567af6cf5483
[ "MIT" ]
null
null
null
atcoder/abc060-arc073/c.cpp
L3Sota/atcoder
7d9444e03837b537ebc6f4f917b9567af6cf5483
[ "MIT" ]
null
null
null
// DATA STRUCTURES #include <vector> // MISCELLANEOUS #include <iostream>//cin/cout/wcin/wcout/left/right/internal/dec/hex/oct/fixed/scientific #ifndef REPST #define REPST(i,n) for (size_t i = 0; i < n; ++i) #endif typedef unsigned long long ull; // -------------------------------------------------------------------------------------- using namespace std; int main(void) { size_t n; ull t; cin >> n >> t; std::vector<ull> v(n); REPST(i,n) cin >> v[i]; ull ends = 0; ull total = 0; REPST(i,n) { total += (ends <= v[i]) ? t : (v[i] + t - ends); ends = v[i] + t; } cout << total << '\n'; return 0; }
19.588235
89
0.477477
[ "vector" ]
17a227528e9c7e2e7bbbc25914b7cf21464764b1
4,674
hpp
C++
source/file-pool.hpp
ict-project/libict-queue
2f5a9a37873d195153200f209d73c1431818fdb0
[ "BSD-3-Clause" ]
null
null
null
source/file-pool.hpp
ict-project/libict-queue
2f5a9a37873d195153200f209d73c1431818fdb0
[ "BSD-3-Clause" ]
null
null
null
source/file-pool.hpp
ict-project/libict-queue
2f5a9a37873d195153200f209d73c1431818fdb0
[ "BSD-3-Clause" ]
null
null
null
//! @file //! @brief File pool module - header file. //! @author Mariusz Ornowski (mariusz.ornowski@ict-project.pl) //! @version 1.0 //! @date 2012-2021 //! @copyright ICT-Project Mariusz Ornowski (ict-project.pl) /* ************************************************************** Copyright (c) 2012-2021, ICT-Project Mariusz Ornowski (ict-project.pl) 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 ICT-Project Mariusz Ornowski nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************/ #ifndef _FILE_POOL_HEADER #define _FILE_POOL_HEADER //============================================ #include <string> #include <vector> #include "types.hpp" //============================================ namespace ict { namespace queue { namespace file { //=========================================== //! Pola plików, w których kolejka zapisuje dane. class pool{ private: //! Typ - numer pliku. typedef uint64_t number_t; //! Typ - Metadane pliku. struct item_t { ict::queue::types::path_t path; number_t number; }; //! Typ - lista plików. typedef std::vector<item_t> list_t; //! Ścieżka do katalogu z plikami. const ict::queue::types::path_t dir; //! Maksymalna liczba plików. std::size_t maxSize; //! Lista plików. list_t list; //! //! @brief Zwraca ścieżkę do pliku o podanum numerze. //! //! @param n Numer pliku. //! @return Ścieżka do pliku. //! ict::queue::types::path_t getPathString(number_t n) const; //! //! @brief Zwraca wyrażenie regularne do nazw plików. //! //! @return Wurażenie regularne. //! std::string getRegexString() const; //! //! @brief Ładuje listę plików ze wskazanego katalogu. //! void loadFileList(); //! //! @brief Tworzy nowy plik. //! //! @param path Ścieżka do pliku. //! void createFile(const ict::queue::types::path_t & path) const; //! //! @brief Usuwa istniejący plik. //! //! @param path Ścieżka do pliku. //! void removeFile(const ict::queue::types::path_t & path) const; public: //! //! @brief Konstruktor puli plików. //! //! @param dirname Ścieżka do katalogu z plikami. //! @param max Maksymalna liczba plików. //! pool(const ict::queue::types::path_t & dirname,const std::size_t & max=0xffffffff); //! //! @brief Zwraca ścieżkę do pliku o podanym indeksie. //! //! @param index Indeks pliku. //! @return Ścieżka do pliku. //! const ict::queue::types::path_t & getPath(const std::size_t & index=0) const; //! //! @brief Zwraca aktualny rozmiar puli plików. //! //! @return Rozmiar puli plików. //! std::size_t size() const; //! //! @brief Sprawdza, czy pula plików jest pusta. //! //! @return true Jest pusta. //! @return false Nie jest pusta. //! bool empty() const; //! //! @brief Dodaje nowy plik do puli (na początku). //! void pushFront(); //! //! @brief Usuwa plik z puli (na końcu). //! void popBack(); //! //! @brief Usuwa wszystkie pliki z puli. //! void clear(); }; //=========================================== } } } //============================================ #endif
34.367647
87
0.61703
[ "vector" ]
17a39b020143c32a67ae83bb5f23fc2414a9bde9
1,662
hh
C++
src/kafka/producer/batcher.hh
avelanarius/seastar
d56ec0b618d42b4b9c9dc4839fbd369ae845a94c
[ "Apache-2.0" ]
null
null
null
src/kafka/producer/batcher.hh
avelanarius/seastar
d56ec0b618d42b4b9c9dc4839fbd369ae845a94c
[ "Apache-2.0" ]
7
2019-11-19T14:43:39.000Z
2019-12-14T19:00:49.000Z
src/kafka/producer/batcher.hh
avelanarius/seastar
d56ec0b618d42b4b9c9dc4839fbd369ae845a94c
[ "Apache-2.0" ]
null
null
null
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2019 ScyllaDB Ltd. */ #pragma once #include <utility> #include <vector> #include "sender.hh" #include "../utils/retry_helper.hh" namespace seastar { namespace kafka { class batcher { private: std::vector<sender_message> _messages; lw_shared_ptr<metadata_manager> _metadata_manager; lw_shared_ptr<connection_manager> _connection_manager; retry_helper _retry_helper; public: batcher(lw_shared_ptr<metadata_manager> metadata_manager, lw_shared_ptr<connection_manager> connection_manager, uint32_t max_retries, const std::function<future<>(uint32_t)> &retry_strategy) : _metadata_manager(std::move(metadata_manager)), _connection_manager(std::move(connection_manager)), _retry_helper(max_retries, retry_strategy) {} void queue_message(sender_message message); future<> flush(uint32_t connection_timeout); }; } }
29.678571
90
0.734657
[ "vector" ]
17a48245eb3a97cdf40ad16a2589517198654013
7,669
cpp
C++
ZouavZEngine/src/Component/MeshRenderer.cpp
Neziiap/ZouavZEngine
7327053871ee5faaa8c87c81f79e093a81da5542
[ "Unlicense" ]
null
null
null
ZouavZEngine/src/Component/MeshRenderer.cpp
Neziiap/ZouavZEngine
7327053871ee5faaa8c87c81f79e093a81da5542
[ "Unlicense" ]
null
null
null
ZouavZEngine/src/Component/MeshRenderer.cpp
Neziiap/ZouavZEngine
7327053871ee5faaa8c87c81f79e093a81da5542
[ "Unlicense" ]
null
null
null
#include "Rendering/Camera.hpp" #include "GameObject.hpp" #include "Maths/Mat4.hpp" #include <glad/glad.h> #include <GLFW/glfw3.h> #include "System/ResourcesManager.hpp" #include "Component/MeshRenderer.hpp" #include "Component/Animation.hpp" #include "System/Debug.hpp" #include "imgui.h" MeshRenderer::MeshRenderer(GameObject* _gameObject, std::shared_ptr<Mesh>& _mesh, std::shared_ptr<Texture>& _texture, std::shared_ptr<Shader>& _shader, std::string _name) : Component(_gameObject, _name), mesh{ _mesh }, material{ _shader, _texture, {1.0f, 1.0f, 1.0f, 1.0f} } { //Update Animation component on load if exist Animation* animation = gameObject->GetComponent<Animation>(); if (animation) { animation->mesh = mesh.get(); animation->text = material.texture.get(); if (animation->currentAnimation) animation->currentAnimation->UpdateAnimationResources(&animation->rootNode, mesh.get()); } } MeshRenderer::MeshRenderer(GameObject* _gameObject, std::string _name) : Component(_gameObject, _name), mesh{ *ResourcesManager::GetResource<Mesh>("Default") } { Animation* animation = gameObject->GetComponent<Animation>(); if (animation) { animation->mesh = mesh.get(); animation->text = material.texture.get(); if (animation->currentAnimation) animation->currentAnimation->UpdateAnimationResources(&animation->rootNode, mesh.get()); } } MeshRenderer::~MeshRenderer() { if (mesh.use_count() == 2 && mesh->IsDeletable()) mesh->RemoveFromResourcesManager(); if (material.texture.use_count() == 2 && material.texture->IsDeletable()) material.texture->RemoveFromResourcesManager(); if (material.shader.use_count() == 2 && material.shader->IsDeletable()) material.shader->RemoveFromResourcesManager(); } void MeshRenderer::Draw(const Camera& _camera) { material.shader->Use(); glActiveTexture(GL_TEXTURE0); Texture::Use(material.texture.get()); material.shader->SetMatrix("model", Mat4::CreateTRSMatrix(GetGameObject().WorldPosition(), GetGameObject().WorldRotation(), GetGameObject().WorldScale())); material.shader->SetVector4("color", material.color); glBindVertexArray(mesh->GetID()); glDrawElements(GL_TRIANGLES, (GLsizei)mesh->GetNbElements(), GL_UNSIGNED_INT, 0); } void MeshRenderer::TextureEditor() { Animation* animComponent = gameObject->GetComponent<Animation>(); //Update texture of animation if (ResourcesManager::ResourceChanger<Texture>("Texture", material.texture)) { if(animComponent) animComponent->text = animComponent->text = material.texture.get(); } if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ProjectFile")) { ZASSERT(payload->DataSize == sizeof(std::string), "Error in add new texture"); std::string _path = *(const std::string*)payload->Data; std::string _truePath = _path; size_t start_pos = _truePath.find("\\"); _truePath.replace(start_pos, 1, "/"); if (_truePath.find(".png") != std::string::npos || _truePath.find(".jpg") != std::string::npos) { if (material.texture.use_count() == 2 && material.texture->IsDeletable()) ResourcesManager::RemoveResourceTexture(material.texture->GetName()); material.texture = *ResourcesManager::AddResourceTexture(_path.substr(_path.find_last_of("/\\") + 1), true, _truePath.c_str()); //Update animation texture if (animComponent) animComponent->text = material.texture.get(); } } ImGui::EndDragDropTarget(); } } void MeshRenderer::MeshEditor() { //Update animation component if exist Animation* animComponent = gameObject->GetComponent<Animation>(); if (ResourcesManager::ResourceChanger<Mesh>("Mesh", mesh)) { if (animComponent) { animComponent->mesh = mesh.get(); if (animComponent->currentAnimation) animComponent->currentAnimation->UpdateAnimationResources(&animComponent->rootNode, animComponent->mesh); } } if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ProjectFile")) { ZASSERT(payload->DataSize == sizeof(std::string), "Error in add new mesh"); std::string _path = *(const std::string*)payload->Data; std::string _truePath = _path; size_t start_pos = _truePath.find("\\"); _truePath.replace(start_pos, 1, "/"); if (_truePath.find(".fbx") != std::string::npos || _truePath.find(".obj") != std::string::npos || _truePath.find(".dae") != std::string::npos) { if (mesh.use_count() == 2 && mesh->IsDeletable()) ResourcesManager::RemoveResourceMesh(mesh->GetName()); mesh = *ResourcesManager::AddResourceMesh(_path.substr(_path.find_last_of("/\\") + 1), true, _truePath.c_str()); if (animComponent) { animComponent->mesh = mesh.get(); if (animComponent->currentAnimation) animComponent->currentAnimation->UpdateAnimationResources(&animComponent->rootNode, animComponent->mesh); } } } ImGui::EndDragDropTarget(); } } void MeshRenderer::ShaderEditor() { ResourcesManager::ResourceChanger<Shader>("Shader", material.shader); if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ProjectFile")) { ZASSERT(payload->DataSize == sizeof(std::string), "Error in add new shader"); std::string _path = *(const std::string*)payload->Data; std::string _truePath = _path; size_t start_pos = _truePath.find("\\"); _truePath.replace(start_pos, 1, "/"); if (_truePath.find(".shader") != std::string::npos) { if (material.shader.use_count() == 2 && material.shader->IsDeletable()) ResourcesManager::RemoveResourceShader(material.shader->GetName()); material.shader = *ResourcesManager::AddResourceShader(_path.substr(_path.find_last_of("/\\") + 1), true, _truePath.c_str()); } } ImGui::EndDragDropTarget(); } } void MeshRenderer::Editor() { TextureEditor(); MeshEditor(); ShaderEditor(); ImGui::ColorEdit4("Color : ", &material.color.x); } template <class Archive> static void MeshRenderer::load_and_construct(Archive& _ar, cereal::construct<MeshRenderer>& _construct) { std::string meshName; std::string meshPath; std::string textureName; std::string texturePath; std::string shaderName; std::string shaderPath; bool isMeshDeletebale; bool isTextureDeletebale; bool isShaderDeletebale; _ar(meshName, isMeshDeletebale, meshPath, textureName, isTextureDeletebale, texturePath, shaderName, isShaderDeletebale, shaderPath); _construct(GameObject::currentLoadedGameObject, *ResourcesManager::AddResourceMesh(meshName, isMeshDeletebale, meshPath.c_str()), *ResourcesManager::AddResourceTexture(textureName, isTextureDeletebale, texturePath.c_str()), *ResourcesManager::AddResourceShader(shaderName, isShaderDeletebale, shaderPath.c_str())); _ar(_construct->material.color, cereal::base_class<Component>(_construct.ptr())); }
39.127551
170
0.643369
[ "mesh", "model" ]
17a4f69d521acdc3699745e81fe1e011cf72cb86
7,721
hpp
C++
packages/+GT/GenericTargetCode/source/GenericTarget/UDPSocket.hpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
1
2021-02-02T09:01:24.000Z
2021-02-02T09:01:24.000Z
packages/+GT/GenericTargetCode/source/GenericTarget/UDPSocket.hpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
null
null
null
packages/+GT/GenericTargetCode/source/GenericTarget/UDPSocket.hpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
2
2021-02-02T09:01:45.000Z
2021-10-02T13:08:16.000Z
#pragma once #include <Endpoint.hpp> class UDPSocket { public: /** * @brief Create a UDP socket object. */ UDPSocket(); /** * @brief Destroy the UDP socket object. */ ~UDPSocket(); /** * @brief Open the socket. * @return 0 if success, < 0 if failure. */ int Open(void); /** * @brief Specify whether the socket is open or not. * @return True if socket is open, false otherwise. */ bool IsOpen(void); /** * @brief Close the socket. * @details Resets the port. */ void Close(void); /** * @brief Get the port bound to the socket. * @return The port if success, < 0 if failure or no port was bound. */ int GetPort(void); /** * @brief Bind a port to a socket. The socket must be opened. * @param [in] port A port that should be bound to the socket. * @param [in] ip The IP for this socket/interface, default to nullptr. Example: "127.0.0.1". If nullptr is set as parameter, INADDR_ANY will be used. * @return 0 if success, < 0 if failure or already bound. */ int Bind(uint16_t port, const char *ip = nullptr); /** * @brief Bind the next free port between portBegin and portEnd to the socket. The socket must be opened. If portBegin is greater than portEnd they will be swapped. * @param [in] portBegin The beginning port that should be bound to the socket. * @param [in] portEnd The ending port that should be bound to the socket. * @param [in] ip The IP for this socket/interface, default to nullptr. Example: "127.0.0.1". If nullptr is set as parameter, INADDR_ANY will be used. * @return The port that was bound with success, < 0 if failure or already bound. */ int Bind(uint16_t portBegin, uint16_t portEnd, const char *ip = nullptr); /** * @brief Set socket options using the setsockopt() function. * @param [in] level The level at which the option is defined (for example, SOL_SOCKET). * @param [in] optname The socket option for which the value is to be set (for example, SO_BROADCAST). * @param [in] optval A pointer to the buffer in which the value for the requested option is specified. * @param [in] optlen The size, in bytes, of the buffer pointed to by the optval parameter. * @return If no error occurs, zero is returned. */ int SetOption(int level, int optname, const void *optval, int optlen); /** * @brief Get socket option using the getsockopt() function. * @param [in] level The level at which the option is defined (for example, SOL_SOCKET). * @param [in] optname The socket option for which the value is to be retrieved (for example, SO_ACCEPTCONN). * @param [in] optval A pointer to the buffer in which the value for the requested option is to be returned. * @param [in] optlen A pointer to the size, in bytes, of the optval buffer. * @return If not error occurs, zero is returned. */ int GetOption(int level, int optname, void *optval, int *optlen); /** * @brief Set socket option to reuse the address. * @param [in] reuse True if address reuse should be enabled, false otherwise. * @return If no error occurs, zero is returned. */ int ReuseAddr(bool reuse); /** * @brief Set socket option to reuse the port to allow multiple sockets to use the same port number. * @param [in] reuse True if address reuse should be enabled, false otherwise. * @return If no error occurs, zero is returned. */ int ReusePort(bool reuse); /** * @brief Send bytes to endpoint. * @param [in] endpoint The endpoint where to send the bytes to. * @param [in] bytes Bytes that should be sent. * @param [in] size Number of bytes. * @return Number of bytes that have been sent. If an error occurred, the return value is < 0. */ int SendTo(Endpoint& endpoint, uint8_t *bytes, int size); /** * @brief Send a single broadcast message. * @param [in] destinationPort The destination port for the broadcast message. * @param [in] bytes Bytes that should be sent. * @param [in] size Number of bytes. * @return Number of bytes that have been sent. If an error occurred, the return value is < 0. * @details The socket option will be changed from unicast to broadcast. After transmission the socket option will be changed back to unicast. */ int Broadcast(uint16_t destinationPort, uint8_t *bytes, int size); /** * @brief Receive bytes from endpoint. * @param [out] endpoint Endpoint, where to store the sender information. * @param [out] bytes Pointer to data array, where received bytes should be stored. * @param [in] size The size of the data array. * @return Number of bytes that have been received. If an error occurred, the return value is < 0. */ int ReceiveFrom(Endpoint& endpoint, uint8_t *bytes, int size); /** * @brief Receive bytes from endpoint or time out. * @param [out] endpoint Endpoint, where to store the sender information. * @param [out] bytes Pointer to data array, where received bytes should be stored. * @param [in] size The size of the data array. * @param [in] timeout_s Timeout in seconds. * @return Number of bytes that have been received. If an error or timeout occurred, the return value is < 0. * @note IMPORTANT: DO NOT USE THIS MEMBER FUNCTION TO RECEIVE MULTICAST MESSAGES. */ int ReceiveFrom(Endpoint& endpoint, uint8_t *bytes, int size, uint32_t timeout_s); /** * @brief Join a multicast group. * @param [in] strGroup IPv4 address of the group. * @param [in] strInterface IPv4 address of the interface to be used for multicasting or nullptr if default interface should be used. * @return If no error occurs, zero is returned. */ int JoinMulticastGroup(const char* strGroup, const char* strInterface = nullptr); /** * @brief Leave a multicast group. * @param [in] strGroup IPv4 address of the group. * @param [in] strInterface IPv4 address of the interface to be used for multicasting or nullptr if default interface should be used. * @return If no error occurs, zero is returned. */ int LeaveMulticastGroup(const char* strGroup, const char* strInterface = nullptr); /** * @brief Set the interface for the transmission of multicast messages. * @param [in] ip IPv4 interface. * @param [in] strInterface IPv4 address of the interface to be used for multicasting or nullptr if default interface should be used. * @return If no error occurs, zero is returned. */ int SetMulticastInterface(const char* ip, const char* strInterface = nullptr); /** * @brief Set time-to-live multicast messages. * @param [in] ttl Time-to-live. * @return If no error occurs, zero is returned. */ int SetMulticastTTL(uint8_t ttl); private: std::atomic<int> _socket; ///< Socket value. std::atomic<int> _port; ///< Port value. };
45.686391
173
0.610025
[ "object" ]
17a8e53607b4f97ea9d10ae886d223d5eb41c75b
9,248
cpp
C++
vm/external_libs/llvm/tools/llvm-prof/llvm-prof.cpp
marnen/rubinius
05b3f9789d01bada0604a7f09921c956bc9487e7
[ "BSD-3-Clause" ]
1
2016-05-08T16:58:14.000Z
2016-05-08T16:58:14.000Z
vm/external_libs/llvm/tools/llvm-prof/llvm-prof.cpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
vm/external_libs/llvm/tools/llvm-prof/llvm-prof.cpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "llvm/InstrTypes.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/System/Signals.h" #include <algorithm> #include <iostream> #include <iomanip> #include <map> #include <set> using namespace llvm; namespace { cl::opt<std::string> BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); cl::opt<bool> PrintAllCode("print-all-code", cl::desc("Print annotated code for the entire program")); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; std::map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF, std::map<ProfileInfoLoader::Edge, unsigned> &EF) : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << "\t;;; Basic block executed " << Count << " times.\n"; else OS << "\t;;; Never executed!\n"; } virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, std::ostream &OS){ if (EdgeFreqs.empty()) return; // Figure out how many times each successor executed. std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts; const TerminatorInst *TI = BB->getTerminator(); std::map<ProfileInfoLoader::Edge, unsigned>::iterator I = EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U)); for (; I != EdgeFreqs.end() && I->first.first == BB; ++I) if (I->second) SuccCounts.push_back(std::make_pair(TI->getSuccessor(I->first.second), I->second)); if (!SuccCounts.empty()) { OS << "\t;;; Out-edge counts:"; for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i) OS << " [" << SuccCounts[i].second << " -> " << SuccCounts[i].first->getName() << "]"; OS << "\n"; } } }; } int main(int argc, char **argv) { llvm_shutdown_obj X; // Call llvm_shutdown() on exit. try { cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n"); sys::PrintStackTraceOnErrorSignal(); // Read in the bitcode file... std::string ErrorMessage; Module *M = 0; if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile, &ErrorMessage)) { M = ParseBitcodeFile(Buffer, &ErrorMessage); delete Buffer; } if (M == 0) { std::cerr << argv[0] << ": " << BitcodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfoLoader PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; std::map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); uint64_t TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... std::cout << " ## Frequency\n"; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { std::cout << "\n NOTE: " << e-i << " function" << (e-i-1 ? "s were" : " was") << " never executed!\n"; break; } std::cout << std::setw(3) << i+1 << ". " << std::setw(5) << FunctionCounts[i].second << "/" << TotalExecutions << " " << FunctionCounts[i].first->getName().c_str() << "\n"; } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... std::cout <<" ## %% \tFrequency\n"; unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { if (Counts[i].second == 0) break; Function *F = Counts[i].first->getParent(); std::cout << std::setw(3) << i+1 << ". " << std::setw(5) << std::setprecision(2) << Counts[i].second/(double)TotalExecutions*100 << "% " << std::setw(5) << Counts[i].second << "/" << TotalExecutions << "\t" << F->getName().c_str() << "() - " << Counts[i].first->getName().c_str() << "\n"; FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PI.hasAccurateEdgeCounts()) { std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts; PI.getEdgeCounts(Counts); EdgeFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM || PrintAllCode) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs); if (FunctionsToPrint.empty() || PrintAllCode) M->print(std::cout, &PA); else // Print just a subset of the functions... for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } return 0; } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } return 1; }
36.698413
80
0.569312
[ "vector" ]
17afdca529bdfebf1ebb5996c7312218b720e182
1,695
hpp
C++
inc/vpp/stage/tracker.hpp
ezdayo/vpp
90d13ed9ab49ff0db7188ef72a89821f0c14a9bf
[ "MIT" ]
1
2020-06-18T14:01:50.000Z
2020-06-18T14:01:50.000Z
inc/vpp/stage/tracker.hpp
ezdayo/vpp
90d13ed9ab49ff0db7188ef72a89821f0c14a9bf
[ "MIT" ]
null
null
null
inc/vpp/stage/tracker.hpp
ezdayo/vpp
90d13ed9ab49ff0db7188ef72a89821f0c14a9bf
[ "MIT" ]
null
null
null
/** * * @file vpp/stage/tracker.hpp * * @brief These is the VPP tracker stage definitions * * This file is part of the VPP framework (see link). * * @author Olivier Stoltz-Douchet <ezdayo@gmail.com> * * @copyright (c) 2019-2020 Olivier Stoltz-Douchet * @license http://opensource.org/licenses/MIT MIT * @link https://github.com/ezdayo/vpp * **/ #pragma once #include "vpp/engine/tracker/camshift.hpp" #include "vpp/engine/tracker/history.hpp" #include "vpp/engine/tracker/kalman.hpp" #include "vpp/engine/tracker/none.hpp" #include "vpp/engine/tracker/ocv.hpp" #include "vpp/stage.hpp" #include "vpp/util/observability.hpp" #include <mutex> namespace VPP { namespace Stage { class Tracker : public Stage::ForScene { public: Tracker() noexcept; ~Tracker() noexcept = default; VPP::Engine::Tracker::OCV ocv; VPP::Engine::Tracker::CamShift camshift; VPP::Engine::Tracker::Kalman kalman; VPP::Engine::Tracker::History history; VPP::Engine::Tracker::None none; void snapshot(Scene &s) noexcept; void snapshot(std::vector<Zone> &entering, std::vector<Zone> &leaving) noexcept; void snapshot(Scene &s, std::vector<Zone> &entering, std::vector<Zone> &leaving) noexcept; virtual Error::Type process(Scene &s) noexcept override; Util::Notifier<Scene, std::vector<Zone>, std::vector<Zone>> event; protected: std::mutex synchro; Scene latest; std::vector<Zone> added; std::vector<Zone> removed; }; } // namespace Stage } // namespace VPP
27.33871
74
0.621829
[ "vector" ]
17b2237057d27c26ed137fc7f5fb29d80046bb4f
4,754
cpp
C++
SCRIPTER CODE -- VB6/VB6/VB-NT/00_Send_To/Send To Text List of Files/aw-source/gen_activewa.cpp
Matthew-Lancaster/matthew-lancaster
c36ccdb6b3a482fcbfcad1f3b8b1b7db6ad5a311
[ "Unlicense" ]
null
null
null
SCRIPTER CODE -- VB6/VB6/VB-NT/00_Send_To/Send To Text List of Files/aw-source/gen_activewa.cpp
Matthew-Lancaster/matthew-lancaster
c36ccdb6b3a482fcbfcad1f3b8b1b7db6ad5a311
[ "Unlicense" ]
null
null
null
SCRIPTER CODE -- VB6/VB6/VB-NT/00_Send_To/Send To Text List of Files/aw-source/gen_activewa.cpp
Matthew-Lancaster/matthew-lancaster
c36ccdb6b3a482fcbfcad1f3b8b1b7db6ad5a311
[ "Unlicense" ]
null
null
null
/************************************************************************* * * ActiveWinamp * * An automation plugin for Winamp. This exposes a lot of winamp functionality * through COM / ActiveX. You may use this to write VB or .NET or any other * applications which interact with Winamp. * * You can automate Winamp internally or externally. Write scripts that can * be executed from the playlist, "Send To" menu or hot keys, or from external * scripts and programs. * * Official Website: https://sourceforge.net/projects/activewinamp/ * Winamp Plugin Site: http://www.winamp.com/plugins/details.php?id=143299 * *------------------------------------------------------------------------- * * Name : gen_activewa.cpp * * Purpose : Implementation of DLL Exports and object registration * * Author : Shane Hird * * License : GNU Library or Lesser General Public License (LGPL) * ************************************************************************/ #include "stdafx.h" #include "resource.h" #include "gen_activewa.h" #include "globals.h" #include "ipc_pe.h" #include "RunningList.h" #include "ScriptManager.h" #include "Application.h" CScriptManager glbScriptManager; CApplication *pApplication; CComObject<CApplication> *pApp; class Cgen_activewaModule : public CAtlDllModuleT< Cgen_activewaModule > { public : DECLARE_LIBID(LIBID_ActiveWinamp) }; Cgen_activewaModule _AtlModule; // DLL Entry Point extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { mhin = hInstance; //return _AtlModule.DllMain(dwReason, lpReserved); return 1; } CRunningList rl; void config() { rl.Create(plugin.hwndParent); rl.ShowWindow(SW_SHOW); } void quit() { glbScriptManager.stopall(); SetWindowLong(HwndPl, GWL_WNDPROC, (LONG)lpPlWndProcOld); SetWindowLong(plugin.hwndParent, GWL_WNDPROC, (LONG)lpWndProcOld); } void quitML() { mlplugin.hDllInstance = NULL; } //Assumes you are running regsvr32 from the plugins directory. void RegisterAdditionalResource(UINT ResId) { USES_CONVERSION; HRESULT hRes = S_OK; CComPtr<IRegistrar> p; hRes = CoCreateInstance(CLSID_Registrar, NULL, CLSCTX_INPROC_SERVER, IID_IRegistrar, (void**)&p); if (SUCCEEDED(hRes)) { //HINSTANCE hWinamp = (HINSTANCE)GetWindowLong(plugin.hwndParent, GWL_HINSTANCE); TCHAR szModule[_MAX_PATH]; GetModuleFileName(mhin, szModule, _MAX_PATH); LPOLESTR pszModuleAW = T2OLE(szModule); int fnl = lstrlen(szModule); int pc = 2; for(int prf = fnl; prf > 0 && pc > 0; prf--) { if (szModule[prf] == '\\') { szModule[prf] = '\0'; pc--; } } wsprintf(szModule, "%s%s", szModule, "\\winamp.exe"); LPOLESTR pszModule = T2OLE(szModule); p->AddReplacement(OLESTR("Module"), pszModule); LPOLESTR szType = OLESTR("REGISTRY"); hRes = p->ResourceRegister(pszModuleAW, ResId, szType); } } int init() { _AtlModule.m_libid = LIBID_ActiveWinamp; HwndPl=(HWND)SendMessage(plugin.hwndParent,WM_WA_IPC,IPC_GETWND_PE,IPC_GETWND); lpPlWndProcOld = (WNDPROC)SetWindowLong(HwndPl, GWL_WNDPROC, (LONG)PlWndProc); lpWndProcOld = (WNDPROC)SetWindowLong(plugin.hwndParent, GWL_WNDPROC, (LONG)MWndProc); quit_ipc=SendMessage(plugin.hwndParent,WM_WA_IPC,(WPARAM)"ScriptQuitIPC",IPC_REGISTER_WINAMP_IPCMESSAGE); hotkey_ipc=SendMessage(plugin.hwndParent,WM_WA_IPC,(WPARAM)"ScriptHotKey",IPC_REGISTER_WINAMP_IPCMESSAGE); init_ipc=SendMessage(plugin.hwndParent,WM_WA_IPC,(WPARAM)"ScriptInit",IPC_REGISTER_WINAMP_IPCMESSAGE); //pApp = new CComObject<CApplication>; //pApplication = pApp; //IApplication* ppv2; //CoCreateInstance(CLSID_Application,NULL,CLSCTX_INPROC_SERVER,IID_IApplication,(LPVOID*)&ppv2); //pApplication = (CApplication*)ppv2; AtlComModuleRegisterClassObjects(&ATL::_AtlComModule, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE); IApplication* ppv2; CoCreateInstance(CLSID_Application,NULL,CLSCTX_INPROC_SERVER,IID_IApplication,(LPVOID*)&ppv2); pApplication = (CApplication*)ppv2; IGlobalInterfaceTable *gpGIT; CoCreateInstance(CLSID_StdGlobalInterfaceTable, NULL, CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable,(void **)&gpGIT); gpGIT->RegisterInterfaceInGlobal(pApplication->GetUnknown(), IID_IApplication, &pappCookie); gpGIT->Release(); glbScriptManager.init1(); //Post a message to init after gen_globalhk and gen_ml has started PostMessage(plugin.hwndParent, init_ipc, 0, 0); return 0; } STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib HRESULT hr = _AtlModule.RegisterServer(true, &CLSID_Application); RegisterAdditionalResource(IDR_APPLICATION); return hr; } extern "C" { __declspec(dllexport) winampGeneralPurposePlugin * winampGetGeneralPurposePlugin() { return &plugin; } }
28.297619
120
0.725705
[ "object" ]
17b5e933fd0c29d46110b872e9be66bf2de1bccd
4,172
cpp
C++
lib/cpp-core/src/sceneManager.cpp
PixDay/Merline-Engine
3e7e83bee307a702b686c5d83b0288a4b663760f
[ "MIT" ]
null
null
null
lib/cpp-core/src/sceneManager.cpp
PixDay/Merline-Engine
3e7e83bee307a702b686c5d83b0288a4b663760f
[ "MIT" ]
null
null
null
lib/cpp-core/src/sceneManager.cpp
PixDay/Merline-Engine
3e7e83bee307a702b686c5d83b0288a4b663760f
[ "MIT" ]
1
2022-02-04T21:05:15.000Z
2022-02-04T21:05:15.000Z
/* ** File name : ** sceneManager.cpp ** File creator : ** Adrien Colombier */ #include <iostream> #include "sceneManager.hpp" SceneManager::SceneManager(): _currentScene(0) { this->addScene("default"); } void SceneManager::clearSceneContent(std::string const &name) { size_t index = getScene(name); while (!_scenes[index]->getGameObjects().empty()) { _scenes[index]->deleteObject(0); } } /* ADDERS */ void SceneManager::addScene(std::string const &name) { Scene *scene = new Scene(name); _scenes.emplace_back(scene); } void SceneManager::addObject(GameObject *object) { _scenes[_currentScene]->addObject(object); } void SceneManager::addObjectTo(GameObject *object, std::string const &name) { _scenes[this->getScene(name)]->addObject(object); } void SceneManager::addCollisionPair(std::string const &tag1, std::string const &tag2) { Pair pair(tag1, tag2); _collisionPair.push_back(pair); } /* DELETERS */ void SceneManager::deleteScene(std::string const &name) { size_t iterator = 0; for (auto scene : _scenes) { if (scene->getName() == name) { _scenes.erase(_scenes.begin() + iterator); delete scene; break; } iterator++; } } void SceneManager::deleteCollisionPair(std::string const &tag1, std::string const &tag2) { size_t iterator = 0; for (auto collision : _collisionPair) { if (collision.getFirst() == tag1 && collision.getSecond() == tag2) { _collisionPair.erase(_collisionPair.begin() + iterator); break; } iterator++; } } /* SETTERS */ void SceneManager::setCurrentScene(size_t const &scene) { _currentScene = scene; } void SceneManager::setCurrentScene(std::string const &name) { size_t iterator = 0; for (auto scene : _scenes) { if (scene->getName() == name) { _currentScene = iterator; break; } iterator++; } } /* GETTERS */ std::vector<Scene *> SceneManager::getScenes() const { return _scenes; } size_t SceneManager::getCurrentScene() const { return _currentScene; } size_t SceneManager::getScene(std::string const &name) const { size_t iterator = 0; for (auto scene : _scenes) { if (scene->getName() == name) return iterator; iterator++; } return _currentScene; } GameObject *SceneManager::getGameObject(std::string const &tag) const { for (auto gameObject : _scenes[_currentScene]->getGameObjects()) { if (gameObject->getTag() == tag) return gameObject; } return nullptr; } void SceneManager::onCollideTrigger(void) { GameObject *collidedObject; for (auto pair : _collisionPair) { if (collidedObject = collide(pair.getFirst(), pair.getSecond())) { GameObject *object = getGameObject(pair.getFirst()); object->onCollide(collidedObject); } } } GameObject *SceneManager::collide(std::string const &tag1, std::string const &tag2) const { DisplayableObject *object1 = nullptr; DisplayableObject *object2 = nullptr; for (auto object : _scenes[_currentScene]->getGameObjects()) { if (object->getTag() == tag1) object1 = static_cast<DisplayableObject *>(object); if (object->getTag() == tag2) object2 = static_cast<DisplayableObject *>(object); if (object1 != nullptr && object2 != nullptr) { sf::Rect<float> obj1( object1->getPosition(), {(float)object1->getSprite()->getTexture()->getSize().x * object1->getScale().x, (float)object1->getSprite()->getTexture()->getSize().y * object1->getScale().y} ); sf::Rect<float> obj2( object2->getPosition(), {(float)object2->getSprite()->getTexture()->getSize().x * object2->getScale().x, (float)object2->getSprite()->getTexture()->getSize().y * object2->getScale().y} ); if (obj1.intersects(obj2)) { return object2; } } } return nullptr; }
23.977011
97
0.605225
[ "object", "vector" ]
17b6b9c2fe017b416b12b1e87ecc32c25595e02e
1,598
cpp
C++
Libs/Library/Source/GameObjects/DefaultGameComponent/ChaseComponent.cpp
butibuti/ButiEngine
0d5b68461060fdcf9049a4afd51211c84f3472d1
[ "MIT" ]
null
null
null
Libs/Library/Source/GameObjects/DefaultGameComponent/ChaseComponent.cpp
butibuti/ButiEngine
0d5b68461060fdcf9049a4afd51211c84f3472d1
[ "MIT" ]
null
null
null
Libs/Library/Source/GameObjects/DefaultGameComponent/ChaseComponent.cpp
butibuti/ButiEngine
0d5b68461060fdcf9049a4afd51211c84f3472d1
[ "MIT" ]
null
null
null
#include "stdafx.h" ButiEngine::ChaseComponent::ChaseComponent(std::shared_ptr<Transform> arg_shp_target, const float arg_speed) { shp_target = arg_shp_target; speed = arg_speed; } void ButiEngine::ChaseComponent::OnUpdate() { if (!shp_target) { return; } auto velocity = Vector3(shp_target->GetWorldPosition() - gameObject.lock()->transform->GetWorldPosition()); gameObject.lock()->Translate (velocity.GetNormalize() * (velocity.GetLength() * velocity.GetLength() )*speed*0.01f); } void ButiEngine::ChaseComponent::OnSet() { } void ButiEngine::ChaseComponent::OnShowUI() { GUI::DragFloat("speed", &speed,0.01f, 0.0f, 100.0f, "%.3f"); std::string target = "ChaseTransform:"; if (shp_target) { target += "Existence"; } else { target += "nullptr"; } GUI::BeginChild("##BaseTransform", Vector2((GUI::GetFontSize()) * (target.size() + 2), GUI::GetFontSize() * 2), true); GUI::BulletText((target).c_str()); if (shp_target) { GUI::SameLine(); if (GUI::Button("Detach")) { shp_target = nullptr; } } GUI::SameLine(); if (GUI::Button("Attach New")) { if (!shp_target) shp_target=ObjectFactory::Create<Transform>(); else { shp_target = shp_target->GetBaseTransform()->Clone(); } } if (GUI::IsWindowHovered()) { auto obj = GUI::GetDraggingObject(); if (obj && obj->IsThis<GameObject>()) { auto trans = obj->GetThis<GameObject>()->transform; shp_target = trans; } } GUI::EndChild(); } std::shared_ptr<ButiEngine::GameComponent> ButiEngine::ChaseComponent::Clone() { return ObjectFactory::Create<ChaseComponent>(shp_target, speed); }
21.890411
119
0.678974
[ "transform" ]
17b86fab841a4619b3c5f960b2cfe1157b333731
2,667
cpp
C++
source/assets/image.cpp
xeek-pro/isometric
6f7d05ce597683552d5dc3078a1634fddd41092b
[ "MIT" ]
1
2021-08-02T04:49:44.000Z
2021-08-02T04:49:44.000Z
source/assets/image.cpp
xeek-pro/isometric
6f7d05ce597683552d5dc3078a1634fddd41092b
[ "MIT" ]
null
null
null
source/assets/image.cpp
xeek-pro/isometric
6f7d05ce597683552d5dc3078a1634fddd41092b
[ "MIT" ]
1
2021-09-09T16:49:53.000Z
2021-09-09T16:49:53.000Z
#include <SDL.h> #include <SDL_image.h> #include <format> #include "image.h" #include "../source/application/application.h" using namespace isometric::assets; image::image(const std::string& name, const std::string& path) : asset(name) { if (!application::get_app() || !application::get_app()->is_initialized()) { auto error_msg = std::string("Attempted to load image before an application object has been created and initialized"); throw std::exception(error_msg.c_str()); } SDL_Surface* surface = IMG_Load(path.c_str()); if (surface == NULL) { auto error_msg = std::format("Failed to load surface for image [{}] from '{}'", name, path); throw std::exception(error_msg.c_str()); } SDL_Texture* texture = SDL_CreateTextureFromSurface( application::get_app()->get_graphics()->get_renderer(), surface ); if (texture == NULL) { SDL_FreeSurface(surface); surface = nullptr; auto error_msg = std::format("Failed to create texture for image [{}] from '{}'", name, path); throw std::exception(error_msg.c_str()); } this->texture = texture; this->surface = surface; } image::~image() { clear(); } void isometric::assets::image::clear() { if (surface) { SDL_FreeSurface(surface); surface = nullptr; } if (texture) { SDL_DestroyTexture(texture); texture = nullptr; } } std::unique_ptr<image> image::load(const std::string& name, const std::string& path) { try { return std::move(std::unique_ptr<image>(new image(name, path))); } catch (std::exception ex) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, ex.what()); return nullptr; } } SDL_Texture* image::get_texture() const { return texture; } SDL_Surface* image::get_surface() const { return surface; } unsigned image::get_width() const { SDL_Rect rect = get_rect(); return rect.w; } unsigned image::get_height() const { SDL_Rect rect = get_rect(); return rect.h; } SDL_Rect image::get_rect() const { if (texture) { int width = 0, height = 0; SDL_QueryTexture(texture, nullptr, nullptr, &width, &height); return SDL_Rect(0, 0, width, height); } else if (surface) { return SDL_Rect(0, 0, surface->w, surface->h); } return SDL_Rect(); } SDL_FRect image::get_frect() const { SDL_Rect rect = get_rect(); return SDL_FRect( static_cast<float>(rect.x), static_cast<float>(rect.y), static_cast<float>(rect.w), static_cast<float>(rect.h) ); }
21.508065
126
0.612298
[ "object" ]
17bd6774abe266c0f86d0d020772df752f7fc63d
728
cpp
C++
Spoj/CRDS_Cards.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
Spoj/CRDS_Cards.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
Spoj/CRDS_Cards.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #define vi vector<int> #define all(v) v.begin(),v.end() #define pii pair<int,int> #define mp make_pair const long long MOD = 1000007; using namespace std; long long arr[1000007]; int main() { // #ifndef ONLINE_JUDGE // freopen("/home/shiva/Learning/1.txt", "r", stdin); // freopen("/home/shiva/Learning/2.txt", "w", stdout); // #endif arr[1] = 2; // for (int i = 2; i < 1000007; i++) arr[i] = (arr[i - 1] % MOD + ((3 * i) - 1) % MOD) % MOD; // for (int i = 1; i < 1000007; i++) printf("%lld\n", arr[i]); int t; long long a = 2, d = 3; long long n; scanf("%d", &t); while (t--) { scanf("%lld", &n); n = (n*(2*a+(n-1)*d))/2; n%=MOD; printf("%lld\n",n); // printf("%lld\n", arr[n]); } }
22.75
94
0.550824
[ "vector" ]
17beaf97cf35dcc1844ecb81852214c2bfe54657
5,129
cpp
C++
framework/source/wrap/pipeline_g_info.cpp
wobakj/VulkanFramework
960628dbc9743f0d74bc13b7d990d0795e32a542
[ "MIT" ]
null
null
null
framework/source/wrap/pipeline_g_info.cpp
wobakj/VulkanFramework
960628dbc9743f0d74bc13b7d990d0795e32a542
[ "MIT" ]
null
null
null
framework/source/wrap/pipeline_g_info.cpp
wobakj/VulkanFramework
960628dbc9743f0d74bc13b7d990d0795e32a542
[ "MIT" ]
null
null
null
#include "wrap/pipeline_g_info.hpp" #include "wrap/shader.hpp" #include "geometry.hpp" #include "geometry_lod.hpp" GraphicsPipelineInfo::GraphicsPipelineInfo() :PipelineInfo{} ,info_vert{} ,info_assembly{} ,info_viewports{} ,info_ms{} ,info_ds{} ,info_raster{} ,info_blending{} ,info_dynamic{} ,info_viewport{} ,info_scissor{} { info.pVertexInputState = &info_vert.get(); info.pInputAssemblyState = &info_assembly; info.pViewportState = &info_viewports; info.pMultisampleState = &info_ms; info.pRasterizationState = &info_raster; info.pDepthStencilState = &info_ds; info.pColorBlendState = &info_blending; info_viewport.minDepth = 0.0f; info_viewport.maxDepth = 1.0f; info_viewports.viewportCount = 1; info_viewports.pViewports = &info_viewport; info_viewports.scissorCount = 1; info_viewports.pScissors = &info_scissor; info_raster.lineWidth = 1.0f; info_raster.cullMode = vk::CullModeFlagBits::eBack; // VkDynamicState dynamicStates[] = { // VK_DYNAMIC_STATE_VIEWPORT, // VK_DYNAMIC_STATE_LINE_WIDTH // }; info.pDynamicState = nullptr; // Optional // info.flags = vk::PipelineCreateFlagBits::eAllowDerivatives; // info.basePipelineIndex = -1; // Optional } GraphicsPipelineInfo::GraphicsPipelineInfo(GraphicsPipelineInfo const& rhs) :GraphicsPipelineInfo{} { *this = rhs; } GraphicsPipelineInfo::GraphicsPipelineInfo(GraphicsPipelineInfo&& rhs) :GraphicsPipelineInfo{} { *this = rhs; } GraphicsPipelineInfo& GraphicsPipelineInfo::operator=(GraphicsPipelineInfo const& rhs) { info.layout = rhs.info.layout; // copy spec infos before stages are updated // because stage update sets pointer to spec infos m_spec_infos = rhs.m_spec_infos; setShaderStages(rhs.info_stages); setVertexInput(rhs.info_vert); setTopology(rhs.info_assembly.topology); setResolution(rhs.info_scissor.extent); setDepthStencil(rhs.info_ds); setRasterizer(rhs.info_raster); for (uint32_t i = 0; i < rhs.attachment_blendings.size(); ++i) { setAttachmentBlending(rhs.attachment_blendings[i], i); } for (auto const& state : rhs.info_dynamics) { addDynamic(state); } setPass(rhs.info.renderPass, rhs.info.subpass); if (rhs.info.basePipelineHandle) { setRoot(rhs.info.basePipelineHandle); } return *this; } GraphicsPipelineInfo& GraphicsPipelineInfo::operator=(GraphicsPipelineInfo&& rhs) { return operator=(rhs); } void GraphicsPipelineInfo::setShader(Shader const& shader) { info.layout = shader.get(); setShaderStages(shader.shaderStages()); for(auto& info_stage : info_stages) { auto iter = m_spec_infos.find(info_stage.stage); if (iter == m_spec_infos.end()) { m_spec_infos.emplace(info_stage.stage, SpecInfo{}); } info_stage.pSpecializationInfo = &m_spec_infos.at(info_stage.stage).get(); } for (auto const& stage_spec : m_spec_infos) { bool found = false; for(auto const& info_stage : info_stages) { if (info_stage.stage == stage_spec.first) { found = true; break; } } if (!found) { throw std::runtime_error{"spec constant exists for missing shader stage '" + to_string(stage_spec.first) + "'"}; } } } void GraphicsPipelineInfo::setVertexInput(VertexInfo const& input) { info_vert = input; info.pVertexInputState = &(info_vert.get()); } void GraphicsPipelineInfo::setShaderStages(std::vector<vk::PipelineShaderStageCreateInfo> const& stages) { info_stages = stages; info.stageCount = uint32_t(info_stages.size()); info.pStages = info_stages.data(); } void GraphicsPipelineInfo::setTopology(vk::PrimitiveTopology const& topo) { info_assembly.topology = topo; } void GraphicsPipelineInfo::setResolution(vk::Extent2D const& res) { info_viewport.width = float(res.width); info_viewport.height = float(res.height); info_scissor.extent = res; } void GraphicsPipelineInfo::setDepthStencil(vk::PipelineDepthStencilStateCreateInfo const& ds) { info_ds = ds; } void GraphicsPipelineInfo::setRasterizer(vk::PipelineRasterizationStateCreateInfo const& raster) { info_raster = raster; } void GraphicsPipelineInfo::setAttachmentBlending(vk::PipelineColorBlendAttachmentState const& attachment, uint32_t i) { if (i >= attachment_blendings.size()) { attachment_blendings.resize(i + 1); } attachment_blendings[i] = attachment; info_blending.attachmentCount = uint32_t(attachment_blendings.size()); info_blending.pAttachments = attachment_blendings.data(); } void GraphicsPipelineInfo::setPass(vk::RenderPass const& pass, uint32_t subpass) { info.renderPass = pass; info.subpass = subpass; } void GraphicsPipelineInfo::addDynamic(vk::DynamicState const& state) { info.pDynamicState = &info_dynamic; info_dynamics.emplace_back(state); info_dynamic.dynamicStateCount = uint32_t(info_dynamics.size()); info_dynamic.pDynamicStates = info_dynamics.data(); } vk::PipelineRasterizationStateCreateInfo const& GraphicsPipelineInfo::rasterizer() const { return info_raster; } vk::PipelineDepthStencilStateCreateInfo const& GraphicsPipelineInfo::depthStencil() const { return info_ds; }
28.337017
119
0.74342
[ "geometry", "vector" ]
17c6302a8e2e0efd1ba2bcbd22f2a4c942a183a0
9,750
cpp
C++
util/ezh5.cpp
ClarkResearchGroup/tensor-tools
25fe4553991d2680b43301aef1960e4c20f1e146
[ "Apache-2.0" ]
8
2020-07-14T01:55:51.000Z
2022-02-12T14:06:59.000Z
util/ezh5.cpp
ClarkResearchGroup/tensor-tools
25fe4553991d2680b43301aef1960e4c20f1e146
[ "Apache-2.0" ]
1
2020-07-31T02:43:25.000Z
2020-08-08T16:18:36.000Z
util/ezh5.cpp
ClarkResearchGroup/tensor-tools
25fe4553991d2680b43301aef1960e4c20f1e146
[ "Apache-2.0" ]
1
2020-12-01T03:40:26.000Z
2020-12-01T03:40:26.000Z
/* * Copyright 2020 Ryan Levy, Xiongjie Yu, and Bryan K. Clark * * 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 EZH5 #define EZH5 #include "ezh5.h" namespace ezh5{ //Define Data Types template<typename T> struct DataType{ static hid_t id; }; // complex number datatype template<typename T> struct DataType<std::complex<T> >{ static hid_t id; DataType(){ H5Tinsert(id, "r", 0, DataType<T>::id); // the name 'r' is to be compatible with h5py H5Tinsert(id, "i", sizeof(T), DataType<T>::id); } }; template<> hid_t DataType<bool>::id = H5T_NATIVE_HBOOL; template<> hid_t DataType<char>::id = H5T_NATIVE_CHAR; template<> hid_t DataType<double>::id = H5T_NATIVE_DOUBLE; template<> hid_t DataType<float>::id = H5T_NATIVE_FLOAT; template<> hid_t DataType<int>::id = H5T_NATIVE_INT; template<> hid_t DataType<long>::id = H5T_NATIVE_LONG; template<> hid_t DataType<unsigned int>::id = H5T_NATIVE_UINT; template<> hid_t DataType<unsigned long>::id = H5T_NATIVE_ULONG; template<> hid_t DataType<std::complex<int> >::id = H5Tcreate(H5T_COMPOUND, sizeof(std::complex<int>)); template<> hid_t DataType<std::complex<float> >::id = H5Tcreate(H5T_COMPOUND, sizeof(std::complex<float>)); template<> hid_t DataType<std::complex<double> >::id = H5Tcreate(H5T_COMPOUND, sizeof(std::complex<double>)); DataType<std::complex<float> > obj_to_run_constructor_float; DataType<std::complex<double> > obj_to_run_constructor_double; } namespace ezh5{ /////////////////////////// Node Node::operator[] (const std::string& path_more){ if(this->id==-1){ htri_t is_exist = H5Lexists(pid, path.c_str(), H5P_DEFAULT); if (is_exist<0){ assert(false); }else if (is_exist==false){ this->id = H5Gcreate2(pid, path.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); }else{ this->id = H5Gopen(pid, path.c_str(), H5P_DEFAULT); } } assert(this->id>0); return Node(this->id, path_more, verbose_); } //////// template<typename T> Node& Node::operator = (T val){ if(id==-1){ hid_t dataspace_id = H5Screate(H5S_SCALAR); this->id = H5Dcreate(pid, path.c_str(), DataType<T>::id, dataspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } hid_t error_id = H5Dwrite(id, DataType<T>::id, H5S_ALL, H5S_ALL, H5P_DEFAULT, &val); H5Dclose(this->id); this->id = -1; return *this; } template Node& Node::operator = (bool val); template Node& Node::operator = (int val); template Node& Node::operator = (unsigned val); template Node& Node::operator = (unsigned long val); template Node& Node::operator = (long val); template Node& Node::operator = (float val); template Node& Node::operator = (double val); template Node& Node::operator = (char val); template Node& Node::operator = (std::complex<int> val); template Node& Node::operator = (std::complex<float> val); template Node& Node::operator = (std::complex<double> val); //////// template<typename T> Node& Node::operator >> (T& val){ hid_t dataset_id = H5Dopen(pid, this->path.c_str(), H5P_DEFAULT); hid_t datatype_id = H5Dget_type(dataset_id); hid_t error_id = H5Dread(dataset_id, datatype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, &val); H5Dclose(dataset_id); return *this; } template Node& Node::operator >> (bool& val); template Node& Node::operator >> (int& val); template Node& Node::operator >> (long& val); template Node& Node::operator >> (unsigned& val); template Node& Node::operator >> (unsigned long& val); template Node& Node::operator >> (float& val); template Node& Node::operator >> (double& val); template Node& Node::operator >> (char& val); template Node& Node::operator >> (std::complex<int>& val); template Node& Node::operator >> (std::complex<float>& val); template Node& Node::operator >> (std::complex<double>& val); //////// template<typename T> Node& Node::operator = (std::vector<T>& vec){ hid_t dataspace_id = -1; if(this->id == -1){ hsize_t dims[1]; dims[0] = vec.size(); dataspace_id = H5Screate_simple(1, dims, NULL); assert(dataspace_id>=0); this->id = H5Dcreate(pid, path.c_str(), DataType<T>::id, dataspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } hid_t error_id = H5Dwrite(id, DataType<T>::id, H5S_ALL, H5S_ALL, H5P_DEFAULT, &vec[0]); H5Dclose(this->id); this->id = -1; if (dataspace_id != -1) {H5Sclose(dataspace_id);} return *this; } template Node& Node::operator = (std::vector<int>& vec); template Node& Node::operator = (std::vector<long>& vec); template Node& Node::operator = (std::vector<unsigned>& vec); template Node& Node::operator = (std::vector<unsigned long>& vec); template Node& Node::operator = (std::vector<float>& vec); template Node& Node::operator = (std::vector<double>& vec); template Node& Node::operator = (std::vector<char>& vec); template Node& Node::operator = (std::vector<std::complex<int> >& vec); template Node& Node::operator = (std::vector<std::complex<float> >& vec); template Node& Node::operator = (std::vector<std::complex<double> >& vec); //////// template<typename T> Node& Node::operator >> (std::vector<T>& vec){ hid_t dataset_id = H5Dopen2(pid, this->path.c_str(), H5P_DEFAULT); hid_t datatype_id = H5Dget_type(dataset_id); hid_t dataspace_id = H5Dget_space(dataset_id); hsize_t dims[1]; int err = H5Sget_simple_extent_dims(dataspace_id,dims,NULL); assert(err>=0); if (dims[0]>0) { vec.resize(dims[0]); hid_t error_id = H5Dread(dataset_id, datatype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, &vec[0]); H5Dclose(dataset_id); } return *this; } template Node& Node::operator >> (std::vector<int>& vec); template Node& Node::operator >> (std::vector<long>& vec); template Node& Node::operator >> (std::vector<unsigned>& vec); template Node& Node::operator >> (std::vector<unsigned long>& vec); template Node& Node::operator >> (std::vector<float>& vec); template Node& Node::operator >> (std::vector<double>& vec); template Node& Node::operator >> (std::vector<char>& vec); template Node& Node::operator >> (std::vector<std::complex<int> >& vec); template Node& Node::operator >> (std::vector<std::complex<float> >& vec); template Node& Node::operator >> (std::vector<std::complex<double> >& vec); //////// template<typename T> Node& Node::operator = (Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m){ hsize_t dims[2]; dims[0] = m.rows(); dims[1] = m.cols(); if(id==-1){ hid_t dataspace_id = H5Screate_simple(2, dims, NULL); assert(dataspace_id>=0); this->id = H5Dcreate(pid, path.c_str(), DataType<T>::id, dataspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); assert(this->id>=0); } hid_t error_id = H5Dwrite(id, DataType<T>::id, H5S_ALL, H5S_ALL, H5P_DEFAULT, m.data()); H5Dclose(this->id); this->id = -1; return *this; } template Node& Node::operator = (Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator = (Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator = (Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator = (Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator = (Eigen::Matrix<std::complex<int>, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator = (Eigen::Matrix<std::complex<float>, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator = (Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic>& m); //////// template<typename T> Node& Node::operator >> (Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m){ hid_t dataset_id = H5Dopen(pid, this->path.c_str(), H5P_DEFAULT); hid_t datatype_id = H5Dget_type(dataset_id); hid_t dataspace_id = H5Dget_space(dataset_id); hsize_t rank = H5Sget_simple_extent_ndims(dataspace_id); assert(rank==2); hsize_t dims[2]; H5Sget_simple_extent_dims(dataspace_id, dims, NULL); m.setZero(dims[0],dims[1]); hid_t error_id = H5Dread(dataset_id, datatype_id, H5S_ALL, dataspace_id, H5P_DEFAULT, m.data()); H5Dclose(dataset_id); return *this; } template Node& Node::operator >> (Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator >> (Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator >> (Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator >> (Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator >> (Eigen::Matrix<std::complex<int>, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator >> (Eigen::Matrix<std::complex<float>, Eigen::Dynamic, Eigen::Dynamic>& m); template Node& Node::operator >> (Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic>& m); /////////////////////////// File::File(const std::string& path, unsigned flags, bool verbose){ verbose_ = verbose; if(flags==H5F_ACC_RDWR || flags==H5F_ACC_RDONLY){ this->id = H5Fopen(path.c_str(), flags, H5P_DEFAULT); }else if (flags==H5F_ACC_TRUNC || flags==H5F_ACC_EXCL){ this->id = H5Fcreate(path.c_str(), flags, H5P_DEFAULT, H5P_DEFAULT); }else{ assert(false && "unknow file access mode"); } } /////////////////////////// } #endif
44.117647
113
0.680718
[ "vector" ]
17cfa52727b37cba1f33f22124bf66a8df85ab30
3,297
cpp
C++
src/utility/exporter.cpp
AlterB/chronovise
5c5fac329b143f3e62ebbc8523d7e205835dd4cb
[ "Apache-2.0" ]
2
2021-02-04T18:22:41.000Z
2021-12-08T10:57:00.000Z
src/utility/exporter.cpp
AlterB/chronovise
5c5fac329b143f3e62ebbc8523d7e205835dd4cb
[ "Apache-2.0" ]
9
2018-03-20T10:24:22.000Z
2018-08-27T21:53:56.000Z
src/utility/exporter.cpp
AlterB/chronovise
5c5fac329b143f3e62ebbc8523d7e205835dd4cb
[ "Apache-2.0" ]
4
2018-05-16T14:27:55.000Z
2022-01-28T17:18:24.000Z
#include "utility/exporter.hpp" #include "statistical/distribution_uniform.hpp" #include "evt/gev_distribution.hpp" #include "evt/gpd_distribution.hpp" #include "global.hpp" #include <iostream> namespace chronovise { template<typename T_INPUT, typename T_TIME> std::unique_ptr<std::ofstream> Exporter<T_INPUT,T_TIME>::open_stream(const std::string& filename) { std::unique_ptr<std::ofstream> file = std::make_unique<std::ofstream>(); // Throw exception if opening file is a failure file->exceptions(std::ofstream::failbit | std::ofstream::badbit); // Trying to open it file->open(filename); return file; } template<typename T_INPUT, typename T_TIME> void Exporter<T_INPUT,T_TIME>::save_time_samples(const std::string& filename) const { auto file = open_stream(filename); *file << "INPUT,TIME" << std::endl; const auto &measures = aec.get_measures(); for (const auto &m : measures) { *file << m.first << ',' << m.second << std::endl; } } template<typename T_INPUT, typename T_TIME> void Exporter<T_INPUT,T_TIME>::save_wcots(const std::string& filename) const { auto file = open_stream(filename); *file << "INPUT,WCOT" << std::endl; const auto &measures = aec.get_wcots(); for (const auto &m : measures) { *file << m.first << ',' << m.second << std::endl; } } template<typename T_INPUT, typename T_TIME> void Exporter<T_INPUT,T_TIME>::save_estimated_distributions(const std::string& filename) const { auto file = open_stream(filename); *file << "TYPE,LOCATION,SCALE,SHAPE" << std::endl; const auto &distributions = aec.get_estimated_distributions(); for (const auto d : distributions) { switch (d->get_type()) { case distribution_t::EVT_GEV: { auto new_d = std::dynamic_pointer_cast<GEV_Distribution>(d); *file << "GEV," << new_d->get_location() << ',' << new_d->get_scale() << ',' << new_d->get_shape() << std::endl; } break; case distribution_t::EVT_GPD: { auto new_d = std::dynamic_pointer_cast<GPD_Distribution>(d); *file << "GPD," << new_d->get_location() << ',' << new_d->get_scale() << ',' << new_d->get_shape() << std::endl; } break; case distribution_t::UNIFORM: { auto new_d = std::dynamic_pointer_cast<DistributionUniform>(d); auto ab_pair = new_d->get_parameters(); *file << "UNI," << (ab_pair.first + ab_pair.second)/2 << ',' << (ab_pair.second - ab_pair.first)/2 << ',' << '0' << std::endl; } break; case distribution_t::UNKNOWN: default: *file << "UNK,0,0,0" << std::endl; break; } } } TEMPLATE_CLASS_IMPLEMENTATION(Exporter); } // namespace chronovise
35.074468
103
0.531695
[ "shape" ]
17d4ca00ce3080036dc7f9a9c2423e6329e68033
6,198
cpp
C++
Programs/ResourceEditor/Classes/Qt/Tools/ExportSceneDialog/ExportSceneDialog.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
5
2020-02-11T12:04:17.000Z
2022-01-30T10:18:29.000Z
Programs/ResourceEditor/Classes/Qt/Tools/ExportSceneDialog/ExportSceneDialog.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
null
null
null
Programs/ResourceEditor/Classes/Qt/Tools/ExportSceneDialog/ExportSceneDialog.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
4
2019-11-28T19:24:34.000Z
2021-08-24T19:12:50.000Z
#include "Tools/ExportSceneDialog/ExportSceneDialog.h" #include "Tools/Widgets/FilePathBrowser.h" #include "Classes/Application/REGlobal.h" #include "Classes/Project/ProjectManagerData.h" #include "Settings/SettingsManager.h" #include <Tools/TextureCompression/TextureConverter.h> #include "Base/GlobalEnum.h" #include "Debug/DVAssert.h" #include "TArc/DataProcessing/DataContext.h" #include <QCheckBox> #include <QComboBox> #include <QGridLayout> #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> ExportSceneDialog::ExportSceneDialog(QWidget* parent) : QDialog(parent) { SetupUI(); InitializeValues(); } ExportSceneDialog::~ExportSceneDialog() = default; void ExportSceneDialog::SetupUI() { setModal(true); static const int UI_WIDTH = 160; static const int UI_HEIGHT = 20; setWindowTitle("Export scene"); QGridLayout* dialogLayout = new QGridLayout(); dialogLayout->setColumnStretch(0, 1); dialogLayout->setColumnStretch(1, 1); DVASSERT(projectPathBrowser == nullptr); // to prevent several calls of this functions projectPathBrowser = new FilePathBrowser(this); projectPathBrowser->SetType(FilePathBrowser::Folder); projectPathBrowser->AllowInvalidPath(true); projectPathBrowser->setMinimumWidth(UI_WIDTH * 3); dialogLayout->addWidget(projectPathBrowser, 0, 0, 1, 0); { //GPU QVBoxLayout* gpuLayout = new QVBoxLayout(); QLabel* gpuLabel = new QLabel(this); gpuLabel->setText("Select GPU:"); gpuLabel->setMinimumSize(UI_WIDTH, UI_HEIGHT); gpuLayout->addWidget(gpuLabel); for (DAVA::int32 gpu = DAVA::GPU_POWERVR_IOS; gpu < DAVA::GPU_FAMILY_COUNT; ++gpu) { QString gpuText = GlobalEnumMap<DAVA::eGPUFamily>::Instance()->ToString(static_cast<DAVA::eGPUFamily>(gpu)); gpuSelector[gpu] = new QCheckBox(gpuText, this); gpuSelector[gpu]->setMinimumSize(UI_WIDTH, UI_HEIGHT); gpuLayout->addWidget(gpuSelector[gpu]); connect(gpuSelector[gpu], &QCheckBox::toggled, this, &ExportSceneDialog::SetExportEnabled); } gpuLayout->addStretch(); dialogLayout->addLayout(gpuLayout, 1, 0); } { // options QVBoxLayout* optionsLayout = new QVBoxLayout(); QLabel* qualityLabel = new QLabel(this); qualityLabel->setText("Select Quality:"); qualityLabel->setMinimumSize(UI_WIDTH, UI_HEIGHT); optionsLayout->addWidget(qualityLabel); qualitySelector = new QComboBox(this); qualitySelector->setMinimumSize(UI_WIDTH, UI_HEIGHT); optionsLayout->addWidget(qualitySelector); const auto& qualityMap = GlobalEnumMap<DAVA::TextureConverter::eConvertQuality>::Instance(); for (size_t i = 0; i < qualityMap->GetCount(); ++i) { int value; bool ok = qualityMap->GetValue(i, value); if (ok) { qualitySelector->addItem(qualityMap->ToString(value), value); } } optimizeOnExport = new QCheckBox("Optimize on export", this); optimizeOnExport->setMinimumSize(UI_WIDTH, UI_HEIGHT); optionsLayout->addWidget(optimizeOnExport); useHDtextures = new QCheckBox("Use HD Textures", this); useHDtextures->setMinimumSize(UI_WIDTH, UI_HEIGHT); optionsLayout->addWidget(useHDtextures); optionsLayout->addStretch(); dialogLayout->addLayout(optionsLayout, 1, 1); } { //buttons QPushButton* cancelButton = new QPushButton("Cancel", this); cancelButton->setMinimumSize(UI_WIDTH, UI_HEIGHT); cancelButton->setFixedHeight(UI_HEIGHT); connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject); exportButton = new QPushButton("Export", this); exportButton->setMinimumSize(UI_WIDTH, UI_HEIGHT); exportButton->setFixedHeight(UI_HEIGHT); connect(exportButton, &QPushButton::clicked, this, &QDialog::accept); dialogLayout->addWidget(exportButton, 2, 0); dialogLayout->addWidget(cancelButton, 2, 1); } setLayout(dialogLayout); setFixedHeight(sizeHint().height()); } void ExportSceneDialog::InitializeValues() { ProjectManagerData* data = REGlobal::GetDataNode<ProjectManagerData>(); DVASSERT(data != nullptr); DAVA::String path = data->GetProjectPath().GetAbsolutePathname(); projectPathBrowser->SetPath(QString::fromStdString(path + "Data/3d/")); for (DAVA::int32 gpu = DAVA::GPU_POWERVR_IOS; gpu < DAVA::GPU_FAMILY_COUNT; ++gpu) { gpuSelector[gpu]->setCheckState(Qt::Unchecked); } DAVA::VariantType quality = SettingsManager::Instance()->GetValue(Settings::General_CompressionQuality); qualitySelector->setCurrentIndex(quality.AsInt32()); optimizeOnExport->setCheckState(Qt::Checked); useHDtextures->setCheckState(Qt::Unchecked); SetExportEnabled(); } void ExportSceneDialog::SetExportEnabled() { bool gpuChecked = false; for (QCheckBox* gpuBox : gpuSelector) { if (gpuBox->isChecked()) { gpuChecked = true; break; } } exportButton->setEnabled(gpuChecked); } DAVA::FilePath ExportSceneDialog::GetDataFolder() const { DAVA::FilePath path = projectPathBrowser->GetPath().toStdString(); path.MakeDirectoryPathname(); return path; } DAVA::Vector<DAVA::eGPUFamily> ExportSceneDialog::GetGPUs() const { DAVA::Vector<DAVA::eGPUFamily> gpus; for (DAVA::int32 gpu = DAVA::GPU_POWERVR_IOS; gpu < DAVA::GPU_FAMILY_COUNT; ++gpu) { if (gpuSelector[gpu]->checkState() == Qt::Checked) { gpus.push_back(static_cast<DAVA::eGPUFamily>(gpu)); } } return gpus; } DAVA::TextureConverter::eConvertQuality ExportSceneDialog::GetQuality() const { return static_cast<DAVA::TextureConverter::eConvertQuality>(qualitySelector->currentIndex()); } bool ExportSceneDialog::GetOptimizeOnExport() const { return optimizeOnExport->checkState() == Qt::Checked; } bool ExportSceneDialog::GetUseHDTextures() const { return useHDtextures->checkState() == Qt::Checked; }
30.53202
120
0.680703
[ "vector", "3d" ]
17d70ebcdecb1781249c25a6cb2dd5374fc1a277
513
cpp
C++
P11650.cpp
daily-boj/SkyLightQP
5038819b6ad31f94d84a66c7679c746a870bb857
[ "Unlicense" ]
6
2020-04-08T09:05:38.000Z
2022-01-20T08:09:48.000Z
P11650.cpp
daily-boj/SkyLightQP
5038819b6ad31f94d84a66c7679c746a870bb857
[ "Unlicense" ]
null
null
null
P11650.cpp
daily-boj/SkyLightQP
5038819b6ad31f94d84a66c7679c746a870bb857
[ "Unlicense" ]
1
2020-05-23T21:17:10.000Z
2020-05-23T21:17:10.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef pair<int, int> pii; vector<pii> arr; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int N; cin >> N; for (int i = 0; i < N; i++) { int a, b; cin >> a >> b; arr.emplace_back(a, b); } sort(arr.begin(), arr.end()); for (int i = 0; i < N; i++) { cout << arr[i].first << " " << arr[i].second << "\n"; } return 0; }
16.03125
61
0.497076
[ "vector" ]
17d8bf58830d8c53aca011870628b07361dded62
1,593
cpp
C++
912.Sort an Array/main.cpp
Kingpie/leetcode
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
[ "Apache-2.0" ]
null
null
null
912.Sort an Array/main.cpp
Kingpie/leetcode
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
[ "Apache-2.0" ]
null
null
null
912.Sort an Array/main.cpp
Kingpie/leetcode
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
[ "Apache-2.0" ]
null
null
null
/*Given an array of integers nums, sort the array in ascending order.   Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5]   Constraints: 1 <= nums.length <= 50000 -50000 <= nums[i] <= 50000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ //quick sort class Solution { public: int partition(vector<int>& nums,int start,int end){ int pivot = nums[start]; while(start<end){ while(start<end && nums[end]>pivot){ end--; } nums[start] = nums[end]; while(start<end && nums[start]<=pivot){ start++; } nums[end] = nums[start]; } nums[end] = pivot; return end; } void quickSort(vector<int>& nums,int start,int end){ if(start < end){ int pivot = partition(nums,start,end); quickSort(nums,start,pivot-1); quickSort(nums,pivot+1,end); } } vector<int> sortArray(vector<int>& nums) { quickSort(nums,0,nums.size()-1); return nums; } }; //bucket class Solution { public: vector<int> sortArray(vector<int>& nums) { vector<int> arr(100001,0); for(int i = 0; i < nums.size();++i){ arr[nums[i]+50000]++; } vector<int> result; for(int i = 0; i < arr.size();++i){ while(arr[i]--){ result.push_back(i-50000); } } return result; } };
20.960526
69
0.516635
[ "vector" ]
17e05c0458ad402fff5da9afca6882551dd04284
4,859
cpp
C++
client/moc_texttool.cpp
vorushin/moodbox_aka_risovaska
5943452e4c7fc9e3c828f62f565cd2da9a040e92
[ "MIT" ]
1
2015-08-23T11:03:58.000Z
2015-08-23T11:03:58.000Z
client/moc_texttool.cpp
vorushin/moodbox_aka_risovaska
5943452e4c7fc9e3c828f62f565cd2da9a040e92
[ "MIT" ]
null
null
null
client/moc_texttool.cpp
vorushin/moodbox_aka_risovaska
5943452e4c7fc9e3c828f62f565cd2da9a040e92
[ "MIT" ]
3
2016-12-05T02:43:52.000Z
2021-06-30T21:35:46.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'texttool.h' ** ** Created: Wed Jun 24 21:01:26 2009 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Velasquez/Qt/texttool.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'texttool.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_Velasquez__TextTool[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 8, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // slots: signature, parameters, type, tag, flags 29, 21, 20, 20, 0x09, 60, 21, 20, 20, 0x09, 92, 21, 20, 20, 0x09, 120, 21, 20, 20, 0x09, 150, 21, 20, 20, 0x08, 186, 20, 20, 20, 0x08, 221, 213, 20, 20, 0x08, 252, 244, 20, 20, 0x08, 0 // eod }; static const char qt_meta_stringdata_Velasquez__TextTool[] = { "Velasquez::TextTool\0\0element\0" "onEditingStarted(TextElement*)\0" "onEditingFinished(TextElement*)\0" "onTextChanged(TextElement*)\0" "onTextUndoAdded(TextElement*)\0" "onEditingElementDestroyed(QObject*)\0" "onCursorPointerDestroyed()\0canUndo\0" "onCanUndoChanged(bool)\0canRedo\0" "onCanRedoChanged(bool)\0" }; const QMetaObject Velasquez::TextTool::staticMetaObject = { { &TransformableTool::staticMetaObject, qt_meta_stringdata_Velasquez__TextTool, qt_meta_data_Velasquez__TextTool, 0 } }; const QMetaObject *Velasquez::TextTool::metaObject() const { return &staticMetaObject; } void *Velasquez::TextTool::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Velasquez__TextTool)) return static_cast<void*>(const_cast< TextTool*>(this)); return TransformableTool::qt_metacast(_clname); } int Velasquez::TextTool::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = TransformableTool::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: onEditingStarted((*reinterpret_cast< TextElement*(*)>(_a[1]))); break; case 1: onEditingFinished((*reinterpret_cast< TextElement*(*)>(_a[1]))); break; case 2: onTextChanged((*reinterpret_cast< TextElement*(*)>(_a[1]))); break; case 3: onTextUndoAdded((*reinterpret_cast< TextElement*(*)>(_a[1]))); break; case 4: onEditingElementDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break; case 5: onCursorPointerDestroyed(); break; case 6: onCanUndoChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: onCanRedoChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; default: ; } _id -= 8; } return _id; } static const uint qt_meta_data_Velasquez__EmptyElementRemover[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 1, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // slots: signature, parameters, type, tag, flags 32, 31, 31, 31, 0x08, 0 // eod }; static const char qt_meta_stringdata_Velasquez__EmptyElementRemover[] = { "Velasquez::EmptyElementRemover\0\0" "onDestroyed()\0" }; const QMetaObject Velasquez::EmptyElementRemover::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_Velasquez__EmptyElementRemover, qt_meta_data_Velasquez__EmptyElementRemover, 0 } }; const QMetaObject *Velasquez::EmptyElementRemover::metaObject() const { return &staticMetaObject; } void *Velasquez::EmptyElementRemover::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Velasquez__EmptyElementRemover)) return static_cast<void*>(const_cast< EmptyElementRemover*>(this)); return QObject::qt_metacast(_clname); } int Velasquez::EmptyElementRemover::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: onDestroyed(); break; default: ; } _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
32.393333
91
0.620704
[ "object" ]
17e11f73cb19d79ef28d291737b30c5efeeb29af
4,669
cpp
C++
1743.RestoreTheArrayFromAdjacentPairs.cpp
mrdrivingduck/leet-code
fee008f3a62849a21ca703e05f755378996a1ff5
[ "MIT" ]
null
null
null
1743.RestoreTheArrayFromAdjacentPairs.cpp
mrdrivingduck/leet-code
fee008f3a62849a21ca703e05f755378996a1ff5
[ "MIT" ]
null
null
null
1743.RestoreTheArrayFromAdjacentPairs.cpp
mrdrivingduck/leet-code
fee008f3a62849a21ca703e05f755378996a1ff5
[ "MIT" ]
null
null
null
/** * @author Mr Dk. * @version 2021/07/25 */ /* There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them. Example 1: Input: adjacentPairs = [[2,1],[3,4],[3,2]] Output: [1,2,3,4] Explanation: This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs[i] may not be in left-to-right order. Example 2: Input: adjacentPairs = [[4,-2],[1,4],[-3,1]] Output: [-2,4,1,-3] Explanation: There can be negative numbers. Another solution is [-3,1,4,-2], which would also be accepted. Example 3: Input: adjacentPairs = [[100000,-100000]] Output: [100000,-100000] Constraints: nums.length == n adjacentPairs.length == n - 1 adjacentPairs[i].length == 2 2 <= n <= 105 -105 <= nums[i], ui, vi <= 105 There exists some nums that has adjacentPairs as its pairs. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/restore-the-array-from-adjacent-pairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 遍历 pairs,找到只出现过一次的元素,该元素一定是序列的两端。然后通过 这个元素依次找出与其相邻的元素。为了快速查找一个元素的相邻元素,可以 遍历一次 pairs,构造出一个 hash table,降低时间复杂度。 */ #include <cassert> #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <set> using std::cout; using std::endl; using std::vector; using std::unordered_map; using std::unordered_set; class Solution { public: vector<int> restoreArray(vector<vector<int>>& adjacentPairs) { unordered_map<int, vector<int>> adjacents; unordered_map<int, vector<int>>::iterator iter; unordered_set<int> dup; for (size_t i = 0; i < adjacentPairs.size(); i++) { int e1 = adjacentPairs[i][0]; int e2 = adjacentPairs[i][1]; // build a hash table to store adjacents of each element if ((iter = adjacents.find(e1)) != adjacents.end()) { iter->second.push_back(e2); } else { adjacents.insert(std::make_pair(e1, vector<int>(1, e2))); } if ((iter = adjacents.find(e2)) != adjacents.end()) { iter->second.push_back(e1); } else { adjacents.insert(std::make_pair(e2, vector<int>(1, e1))); } // to find the end point element if (dup.find(e1) != dup.end()) { dup.erase(e1); } else { dup.insert(e1); } if (dup.find(e2) != dup.end()) { dup.erase(e2); } else { dup.insert(e2); } } // end point element as current one int element = *(dup.begin()); vector<int> result(1, element); dup.clear(); dup.insert(element); for (size_t i = 1; i < adjacentPairs.size() + 1; i++) { // to find adjacent element of current element // meanwhile, avoid using duplicated element iter = adjacents.find(element); if (dup.find(iter->second[0]) != dup.end()) { element = iter->second[1]; } else { element = iter->second[0]; } result.push_back(element); dup.insert(element); } return result; } }; int main() { Solution s; vector<vector<int>> pairs; vector<int> output; pairs = { {-3,-9},{-5,3},{2,-9},{6,-3},{6,1},{5,3},{8,5},{-5,1},{7,2} }; output = { 7,2,-9,-3,6,1,-5,3,5,8 }; assert(output == s.restoreArray(pairs)); pairs = { { 2,1 }, { 3,4 }, { 3,2 } }; output = { 4,3,2,1 }; assert(output == s.restoreArray(pairs)); pairs = { { 4,-2 }, { 1,4 }, { -3,1 } }; output = { -3,1,4,-2 }; assert(output == s.restoreArray(pairs)); pairs = { { 10000,-10000 } }; output = { -10000,10000 }; assert(output == s.restoreArray(pairs)); return 0; }
28.29697
77
0.53973
[ "vector" ]
17e29847e9380292fffe28429b911c851a509531
7,105
cpp
C++
pywinrt/winsdk/src/py.Windows.System.Inventory.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
3
2022-02-14T14:53:08.000Z
2022-03-29T20:48:54.000Z
pywinrt/winsdk/src/py.Windows.System.Inventory.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
4
2022-01-28T02:53:52.000Z
2022-02-26T18:10:05.000Z
pywinrt/winsdk/src/py.Windows.System.Inventory.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
null
null
null
// WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4 #include "pybase.h" #include "py.Windows.System.Inventory.h" PyTypeObject* py::winrt_type<winrt::Windows::System::Inventory::InstalledDesktopApp>::python_type; namespace py::cpp::Windows::System::Inventory { // ----- InstalledDesktopApp class -------------------- constexpr const char* const _type_name_InstalledDesktopApp = "InstalledDesktopApp"; static PyObject* _new_InstalledDesktopApp(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_InstalledDesktopApp); return nullptr; } static void _dealloc_InstalledDesktopApp(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* InstalledDesktopApp_GetInventoryAsync(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::System::Inventory::InstalledDesktopApp::GetInventoryAsync()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* InstalledDesktopApp_ToString(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.ToString()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* InstalledDesktopApp_get_DisplayName(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DisplayName()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* InstalledDesktopApp_get_DisplayVersion(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DisplayVersion()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* InstalledDesktopApp_get_Id(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Id()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* InstalledDesktopApp_get_Publisher(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Publisher()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_InstalledDesktopApp(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::System::Inventory::InstalledDesktopApp>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _str_InstalledDesktopApp(py::wrapper::Windows::System::Inventory::InstalledDesktopApp* self) noexcept { try { return py::convert(self->obj.ToString()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_InstalledDesktopApp[] = { { "get_inventory_async", reinterpret_cast<PyCFunction>(InstalledDesktopApp_GetInventoryAsync), METH_VARARGS | METH_STATIC, nullptr }, { "to_string", reinterpret_cast<PyCFunction>(InstalledDesktopApp_ToString), METH_VARARGS, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_InstalledDesktopApp), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_InstalledDesktopApp[] = { { "display_name", reinterpret_cast<getter>(InstalledDesktopApp_get_DisplayName), nullptr, nullptr, nullptr }, { "display_version", reinterpret_cast<getter>(InstalledDesktopApp_get_DisplayVersion), nullptr, nullptr, nullptr }, { "id", reinterpret_cast<getter>(InstalledDesktopApp_get_Id), nullptr, nullptr, nullptr }, { "publisher", reinterpret_cast<getter>(InstalledDesktopApp_get_Publisher), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_InstalledDesktopApp[] = { { Py_tp_new, _new_InstalledDesktopApp }, { Py_tp_dealloc, _dealloc_InstalledDesktopApp }, { Py_tp_methods, _methods_InstalledDesktopApp }, { Py_tp_getset, _getset_InstalledDesktopApp }, { Py_tp_str, _str_InstalledDesktopApp }, { }, }; static PyType_Spec _type_spec_InstalledDesktopApp = { "_winsdk_Windows_System_Inventory.InstalledDesktopApp", sizeof(py::wrapper::Windows::System::Inventory::InstalledDesktopApp), 0, Py_TPFLAGS_DEFAULT, _type_slots_InstalledDesktopApp }; // ----- Windows.System.Inventory Initialization -------------------- static int module_exec(PyObject* module) noexcept { try { py::pyobj_handle bases { PyTuple_Pack(1, py::winrt_type<py::Object>::python_type) }; py::winrt_type<winrt::Windows::System::Inventory::InstalledDesktopApp>::python_type = py::register_python_type(module, _type_name_InstalledDesktopApp, &_type_spec_InstalledDesktopApp, bases.get()); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyModuleDef_Slot module_slots[] = {{Py_mod_exec, module_exec}, {}}; PyDoc_STRVAR(module_doc, "Windows.System.Inventory"); static PyModuleDef module_def = {PyModuleDef_HEAD_INIT, "_winsdk_Windows_System_Inventory", module_doc, 0, nullptr, module_slots, nullptr, nullptr, nullptr}; } // py::cpp::Windows::System::Inventory PyMODINIT_FUNC PyInit__winsdk_Windows_System_Inventory (void) noexcept { return PyModuleDef_Init(&py::cpp::Windows::System::Inventory::module_def); }
31.71875
209
0.599015
[ "object" ]
17e642674246648ad380db549224dd50d45cd330
4,658
cpp
C++
src/s2mGroupeMusculaire.cpp
CamWilhelm/biorbd
67d36e77d90cc09aa748c3acf2c2bdff5065d3c9
[ "MIT" ]
null
null
null
src/s2mGroupeMusculaire.cpp
CamWilhelm/biorbd
67d36e77d90cc09aa748c3acf2c2bdff5065d3c9
[ "MIT" ]
null
null
null
src/s2mGroupeMusculaire.cpp
CamWilhelm/biorbd
67d36e77d90cc09aa748c3acf2c2bdff5065d3c9
[ "MIT" ]
null
null
null
#define BIORBD_API_EXPORTS #include "../include/s2mGroupeMusculaire.h" s2mGroupeMusculaire::s2mGroupeMusculaire(const s2mString &name, const s2mString &o, const s2mString &i) : m_name(name), m_originName(o), m_insertName(i) { } s2mGroupeMusculaire::~s2mGroupeMusculaire() { } std::shared_ptr<s2mMuscle> s2mGroupeMusculaire::muscle(const unsigned int &idx){ s2mError::s2mAssert(idx<nbMuscles(), "Idx asked is higher than number of muscles"); return *(m_mus.begin() + idx); } void s2mGroupeMusculaire::addHillMuscle(const s2mString& name, const s2mString& s, const s2mMuscleGeometry& g, const s2mMuscleCaracteristics& c, const s2mMusclePathChangers& w, const s2mString& stateType){ s2mMuscleStateActual * st; if (!stateType.tolower().compare("default")) st = new s2mMuscleStateActual; else if (!stateType.tolower().compare("buchanan")) st = new s2mMuscleStateActualBuchanan; else { st = new s2mMuscleStateActual; // remove the warning undeclared s2mError::s2mAssert(false, "Wrong state type"); } if (!s.tolower().compare("hill")){ s2mMuscleHillType m(name,g,c,w,*st); addMuscle(m); } else if (!s.tolower().compare("hillmax")){ s2mMuscleHillTypeMaxime m(name,g,c,w,*st); addMuscle(m); } else if (!s.tolower().compare("hillchadwick")){ s2mMuscleHillTypeChadwick m(name,g,c,w,*st); addMuscle(m); } else if (!s.tolower().compare("hillthelen") || !s.tolower().compare("thelen")){ s2mMuscleHillTypeThelen m(name,g,c,w,*st); addMuscle(m); } else if (!s.tolower().compare("hillschutte") || !s.tolower().compare("schutte")){ s2mMuscleHillTypeSchutte m(name,g,c,w,*st); addMuscle(m); } else if (!s.tolower().compare("hillsimple") || !s.tolower().compare("simple")){ s2mMuscleHillTypeSimple m(name,g,c,w,*st); addMuscle(m); } else s2mError::s2mAssert(0, "Wrong muscle type"); } void s2mGroupeMusculaire::addMuscle(s2mMuscle &val){ s2mError::s2mAssert(muscleID(val.name()) == -1, "This muscle name was already defined for this muscle group"); // Ajouter un muscle au pool de muscle selon son type if (dynamic_cast<s2mMuscleHillTypeMaxime*> (&val)){ m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleHillTypeMaxime(dynamic_cast <s2mMuscleHillTypeMaxime&> (val)))); return; } else if (dynamic_cast<s2mMuscleHillTypeSimple*> (&val)){ m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleHillTypeSimple(dynamic_cast <s2mMuscleHillTypeSimple&> (val)))); return; } else if (dynamic_cast<s2mMuscleHillTypeChadwick*> (&val)){ m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleHillTypeChadwick(dynamic_cast <s2mMuscleHillTypeChadwick&> (val)))); return; } else if (dynamic_cast<s2mMuscleHillTypeThelen*> (&val)){ m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleHillTypeThelen(dynamic_cast <s2mMuscleHillTypeThelen&> (val)))); return; } else if (dynamic_cast<s2mMuscleHillTypeSchutte*> (&val)){ m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleHillTypeSchutte(dynamic_cast <s2mMuscleHillTypeSchutte&> (val)))); return; } else if (dynamic_cast<s2mMuscleMeshTransverse*> (&val)){ //m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleMeshTransverse(dynamic_cast <s2mMuscleMeshTransverse&> (val)))); return; } else if (dynamic_cast<s2mMuscleHillType*> (&val)){ m_mus.push_back(std::shared_ptr<s2mMuscle> (new s2mMuscleHillType(dynamic_cast <s2mMuscleHillType&> (val)))); return; } else s2mError::s2mAssert(0, "Muscle type not found"); } unsigned int s2mGroupeMusculaire::nbMuscles() const { return m_mus.size(); } int s2mGroupeMusculaire::muscleID(const s2mString& nameToFind){ std::vector<std::shared_ptr<s2mMuscle> >::iterator musIT=m_mus.begin(); for (unsigned int i=0; i<m_mus.size(); ++i){ if (!nameToFind.compare((*(musIT+i))->name()) ) return i; } // Si on se rend ici, c'est qu'il n'y a pas de muscle de ce nom dans le groupe return -1; } void s2mGroupeMusculaire::setName(s2mString name) {m_name = name;} void s2mGroupeMusculaire::setOrigin(s2mString name) {m_originName = name;} void s2mGroupeMusculaire::setInsertion(s2mString name) {m_insertName = name;} s2mString s2mGroupeMusculaire::name() const { return m_name;} s2mString s2mGroupeMusculaire::origin() const {return m_originName;} s2mString s2mGroupeMusculaire::insertion() const {return m_insertName;}
37.564516
205
0.684629
[ "vector" ]
17e7ba0e46611a1bd0a824f688bdf8c0d9a63ea4
4,921
cc
C++
src/opt_validate.cc
PixelToast/bfvm
7fe23332661ee6ca93ff91dca9d2fc646c101d52
[ "BSD-3-Clause" ]
2
2020-09-05T04:35:28.000Z
2021-11-10T17:21:06.000Z
src/opt_validate.cc
PixelToast/stackvm
34557926c80969cb8cba67b3fa58e1452cb17b46
[ "BSD-3-Clause" ]
null
null
null
src/opt_validate.cc
PixelToast/stackvm
34557926c80969cb8cba67b3fa58e1452cb17b46
[ "BSD-3-Clause" ]
null
null
null
#include <unordered_set> #include <algorithm> #include <cassert> #include "opt.h" using namespace IR; void Opt::validate(Graph &graph) { #ifdef NDEBUG return; #else std::unordered_set<int> instIds; for (Block *block : graph.blocks) { // Make sure our block id hasn't been clobbered assert(block->id < graph.nextBlockId); // Make sure our successors have higher block ids, except loops for (Block *successor : block->successors) { if (successor->id <= block->id) { // If the successor has a lower block id, make sure it's a back-branch assert(successor->reaches(block)); } } // If builtDominators is true, the dominator tree should be valid if (graph.builtDominators) { // Dominator should always reach us assert(block->alwaysReachedBy(block->dominator)); } // Build list of instructions std::vector<Inst*> insts; Inst *cur = block->first; while (cur != nullptr) { insts.push_back(cur); // Make sure instruction is in current block assert(cur->block == block); // Make sure there are no duplicates assert(!instIds.count(cur->id)); instIds.insert(cur->id); // Make sure instruction id hasn't been clobbered assert(cur->id < graph.nextInstId); cur = cur->next; } // Make sure reverse list matches forward list cur = block->last; for (size_t i = insts.size(); i > 0; i--) { assert(cur == insts[i - 1]); cur = cur->prev; } } bool first = true; for (Block *block : graph.blocks) { // Make sure entry has no predecessor if (first) { assert(block->predecessors.empty()); first = false; } // Make sure we are a successor of our predecessors for (Block *predecessor : block->predecessors) { auto &v = predecessor->successors; assert(std::find(v.begin(), v.end(), block) != v.end()); } // Make sure we are a predecessor of our successors for (Block *successor : block->successors) { auto &v = successor->predecessors; assert(std::find(v.begin(), v.end(), block) != v.end()); } std::unordered_set<Inst*> visited; Inst *cur = block->first; while (cur != nullptr) { assert(cur->mounted); switch (cur->kind) { case I_NOP: assert(cur->inputs.empty()); assert(cur->outputs.empty()); break; case I_REG: case I_IMM: case I_GETCHAR: assert(cur->inputs.empty()); break; case I_GEP: assert(resolveType(cur->inputs[0]) == T_PTR); assert(resolveType(cur->inputs[1]) == T_SIZE); assert(cur->inputs.size() == 2); break; case I_SUB: case I_ADD: case I_STR: assert(cur->inputs.size() == 2); break; case I_SETREG: case I_LD: case I_PUTCHAR: assert(cur->inputs.size() == 1); break; case I_PHI: assert(cur->inputs.size() == block->predecessors.size()); break; case I_IF: assert(cur->inputs.size() == 1); assert(cur->next == nullptr); break; case I_GOTO: assert(cur->inputs.empty()); assert(cur->next == nullptr); assert(block->successors.size() == 1); break; case I_RET: assert(cur->inputs.size() == 1); assert(cur->next == nullptr); assert(block->successors.empty()); break; } for (size_t i = 0; i < cur->inputs.size(); i++) { Inst *input = cur->inputs[i]; assert(input != nullptr); // Make sure input exists in graph assert(instIds.count(input->id)); assert(input->mounted); // Make sure we are an output of our inputs auto &v = input->outputs; assert(std::find(v.begin(), v.end(), cur) != v.end()); if (cur->kind == I_PHI) { // Make sure phi input dominates predecessor assert(block->predecessors[i]->alwaysReachedBy(input->block)); } else { if (block == input->block) { // Make sure input is before its use in same block assert(visited.count(input)); } else { // Make sure input dominates uses assert(block->alwaysReachedBy(input->block)); } } } for (Inst *output : cur->outputs) { // Make sure output exists in graph assert(instIds.count(output->id)); // Make sure we are an input of our outputs auto &v = output->inputs; assert(std::find(v.begin(), v.end(), cur) != v.end()); } visited.insert(cur); cur = cur->next; } } #endif }
30.006098
79
0.53668
[ "vector" ]
17e893daa9bdbcf837bfd4c0c1f47b4a8637dd1b
8,710
cpp
C++
DicomTest/dicom_test/data/UCTest.cpp
drleq/CppDicom
e320fad8414fabfb51c5eb80964f8b6def578247
[ "MIT" ]
null
null
null
DicomTest/dicom_test/data/UCTest.cpp
drleq/CppDicom
e320fad8414fabfb51c5eb80964f8b6def578247
[ "MIT" ]
null
null
null
DicomTest/dicom_test/data/UCTest.cpp
drleq/CppDicom
e320fad8414fabfb51c5eb80964f8b6def578247
[ "MIT" ]
null
null
null
#include "dicomtest_pch.h" #include "CppUnitTestFramework.hpp" #include "dicom/data/UC.h" #include "dicom_test/data/detail/constants.h" using namespace dicom; using namespace dicom::data; namespace { struct UCTest {}; } namespace dicom_test::data { TEST_CASE(UCTest, Constructors) { // UC() UC uc0; CHECK_EQUAL(uc0.Validity(), ValidityType::Valid); CHECK(uc0.Value().Empty()); CHECK(uc0.Parsed().empty()); CHECK_THROW(value_empty_error, UNUSED_RETURN(uc0.First())); CHECK_THROW(value_empty_error, UNUSED_RETURN(uc0.At(0))); // UC(encoded_string&&) UC uc1("Valid value"); CHECK_EQUAL(uc1.Validity(), ValidityType::Valid); CHECK_EQUAL(uc1.Value().Parsed(), "Valid value"); CHECK_EQUAL(uc1.Parsed().size(), 1u); CHECK_EQUAL(uc1.Parsed()[0], "Valid value"); CHECK_EQUAL(uc1.First(), "Valid value"); CHECK_EQUAL(uc1.At(0), "Valid value"); // UC(const encoded_string&) encoded_string value("Valid value"); UC uc2(value); CHECK_EQUAL(uc2.Validity(), ValidityType::Valid); CHECK_EQUAL(uc2.Value().Parsed(), "Valid value"); CHECK_EQUAL(uc2.Parsed().size(), 1u); CHECK_EQUAL(uc2.Parsed()[0], "Valid value"); CHECK_EQUAL(uc2.First(), "Valid value"); CHECK_EQUAL(uc2.At(0), "Valid value"); // UC(const vector<encoded_string>&) std::vector<encoded_string> values; values.push_back(value); values.push_back("Another"); UC uc3(values); CHECK_EQUAL(uc3.Validity(), ValidityType::Valid); CHECK_EQUAL(uc3.Value().Parsed(), "Valid value\\Another"); CHECK_EQUAL(uc3.Parsed().size(), 2u); CHECK_EQUAL(uc3.Parsed()[0], "Valid value"); CHECK_EQUAL(uc3.Parsed()[1], "Another"); CHECK_EQUAL(uc3.First(), "Valid value"); CHECK_EQUAL(uc3.At(0), "Valid value"); CHECK_EQUAL(uc3.At(1), "Another"); // UC(initializer_list<encoded_string>) UC uc4({ value, "Another" }); CHECK_EQUAL(uc4.Validity(), ValidityType::Valid); CHECK_EQUAL(uc4.Value().Parsed(), "Valid value\\Another"); CHECK_EQUAL(uc4.Parsed().size(), 2u); CHECK_EQUAL(uc4.Parsed()[0], "Valid value"); CHECK_EQUAL(uc4.Parsed()[1], "Another"); CHECK_EQUAL(uc4.First(), "Valid value"); CHECK_EQUAL(uc4.At(0), "Valid value"); CHECK_EQUAL(uc4.At(1), "Another"); // UC(const UC&) UC uc5(uc1); CHECK_EQUAL(uc5.Validity(), ValidityType::Valid); CHECK_EQUAL(uc5.Value().Parsed(), "Valid value"); CHECK_EQUAL(uc5.Parsed().size(), 1u); CHECK_EQUAL(uc5.Parsed()[0], "Valid value"); CHECK_EQUAL(uc5.First(), "Valid value"); CHECK_EQUAL(uc5.At(0), "Valid value"); CHECK_EQUAL(uc1.Validity(), ValidityType::Valid); CHECK_EQUAL(uc1.Value().Parsed(), "Valid value"); CHECK_EQUAL(uc1.Parsed().size(), 1u); CHECK_EQUAL(uc1.Parsed()[0], "Valid value"); CHECK_EQUAL(uc1.First(), "Valid value"); CHECK_EQUAL(uc1.At(0), "Valid value"); // UC(UC&&) UC uc6(std::move(uc2)); CHECK_EQUAL(uc6.Validity(), ValidityType::Valid); CHECK_EQUAL(uc6.Value(), "Valid value"); CHECK_EQUAL(uc6.Parsed().size(), 1u); CHECK_EQUAL(uc6.Parsed()[0], "Valid value"); CHECK_EQUAL(uc6.First(), "Valid value"); CHECK_EQUAL(uc6.At(0), "Valid value"); CHECK_EQUAL(uc2.Validity(), ValidityType::Deinitialized); CHECK(uc2.Value().Empty()); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc2.Parsed())); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc2.First())); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc2.At(0))); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Construction_Valid) { UC uc_single("Valid value 1"); CHECK_EQUAL(uc_single.Value(), "Valid value 1"); CHECK_EQUAL(uc_single.Validity(), ValidityType::Valid); CHECK_EQUAL(uc_single.Parsed().size(), 1u); CHECK_EQUAL(uc_single.Parsed()[0], "Valid value 1"); CHECK_EQUAL(uc_single.First(), "Valid value 1"); UC uc_multiple("Value 1\\2nd Value"); CHECK_EQUAL(uc_multiple.Value(), "Value 1\\2nd Value"); CHECK_EQUAL(uc_multiple.Validity(), ValidityType::Valid); CHECK_EQUAL(uc_multiple.Parsed().size(), 2u); CHECK_EQUAL(uc_multiple.Parsed()[0], "Value 1"); CHECK_EQUAL(uc_multiple.Parsed()[1], "2nd Value"); CHECK_EQUAL(uc_multiple.First(), "Value 1"); UC uc_empty1(" "); CHECK_EQUAL(uc_empty1.Value(), " "); CHECK_EQUAL(uc_empty1.Validity(), ValidityType::Valid); CHECK_EQUAL(uc_empty1.Parsed().size(), 1u); CHECK_EQUAL(uc_empty1.Parsed()[0], ""); CHECK_EQUAL(uc_empty1.First(), ""); UC uc_empty2(""); CHECK_EQUAL(uc_empty2.Value(), ""); CHECK_EQUAL(uc_empty2.Validity(), ValidityType::Valid); CHECK(uc_empty2.Parsed().empty()); CHECK_THROW(value_empty_error, UNUSED_RETURN(uc_empty2.First())); CHECK_THROW(value_empty_error, UNUSED_RETURN(uc_empty2.At(0))); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Construction_InvalidCharacters) { UC uc_newline("\x0A"); CHECK_EQUAL(uc_newline.Validity(), ValidityType::Invalid); CHECK_EQUAL(uc_newline.Value(), encoded_string("\x0A")); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc_newline.Parsed())); UC uc_newpage("\x0C"); CHECK_EQUAL(uc_newpage.Validity(), ValidityType::Invalid); CHECK_EQUAL(uc_newpage.Value(), encoded_string("\x0C")); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc_newpage.Parsed())); UC uc_carriagereturn("\x0D"); CHECK_EQUAL(uc_carriagereturn.Validity(), ValidityType::Invalid); CHECK_EQUAL(uc_carriagereturn.Value(), encoded_string("\x0D")); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc_carriagereturn.Parsed())); UC uc_multiple("Valid\\\x0A"); CHECK_EQUAL(uc_multiple.Validity(), ValidityType::Invalid); CHECK_EQUAL(uc_multiple.Value(), encoded_string("Valid\\\x0A")); CHECK_THROW(value_invalid_error, UNUSED_RETURN(uc_multiple.Parsed())); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Equality_SingleValue) { UC uc1("Valid 1"); UC uc2("Valid 2"); CHECK(uc1 == &uc1); CHECK(uc1 != &uc2); CHECK(uc2 != &uc1); CHECK(uc1 < &uc2); CHECK(uc1 <= &uc2); CHECK(uc2 > &uc1); CHECK(uc2 >= &uc1); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Equality_MultipleValue) { UC uc1("Identical\\Valid 1"); UC uc2("Identical\\Valid 2"); CHECK(uc1 == &uc1); CHECK(uc1 != &uc2); CHECK(uc2 != &uc1); CHECK(uc1 < &uc2); CHECK(uc1 <= &uc2); CHECK(uc2 > &uc1); CHECK(uc2 >= &uc1); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Equality_DifferentMultiplicity) { UC uc1("Identical"); UC uc2("Identical\\Valid"); CHECK(uc1 == &uc1); CHECK(uc1 != &uc2); CHECK(uc2 != &uc1); CHECK(uc1 < &uc2); CHECK(uc1 <= &uc2); CHECK(uc2 > &uc1); CHECK(uc2 >= &uc1); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Empty) { UC uc1; CHECK(uc1.Empty()); UC uc2("Valid"); CHECK(!uc2.Empty()); UC uc3(""); CHECK(uc3.Empty()); UC uc4(" "); CHECK(!uc4.Empty()); UC uc5("\\"); CHECK(!uc5.Empty()); } //------------------------------------------------------------------------------------------------------------ TEST_CASE(UCTest, Copy) { UC uc_orig("Valid\\Values"); std::unique_ptr<VR> vr_copy(uc_orig.Copy()); CHECK(static_cast<bool>(vr_copy)); auto uc_copy = dynamic_cast<UC*>(vr_copy.get()); CHECK(uc_copy != nullptr); CHECK(uc_orig.Value() == uc_copy->Value()); CHECK(uc_orig == uc_copy); } }
36.751055
114
0.539954
[ "vector" ]
17ea35c700c938bf2ae47e0ce8e75e969366d4ae
21,668
cpp
C++
src/game_api/render_api.cpp
spelunky-fyi/rust-injector
45ba8acbb6c8505ace288640e764e8557c6f298f
[ "MIT" ]
null
null
null
src/game_api/render_api.cpp
spelunky-fyi/rust-injector
45ba8acbb6c8505ace288640e764e8557c6f298f
[ "MIT" ]
null
null
null
src/game_api/render_api.cpp
spelunky-fyi/rust-injector
45ba8acbb6c8505ace288640e764e8557c6f298f
[ "MIT" ]
1
2020-11-15T05:43:12.000Z
2020-11-15T05:43:12.000Z
#include "render_api.hpp" #include <cstddef> #include <detours.h> #include <string> #include "entity.hpp" #include "level_api.hpp" #include "memory.hpp" #include "script/events.hpp" #include "state.hpp" #include "texture.hpp" RenderAPI& RenderAPI::get() { static RenderAPI render_api = []() { return RenderAPI{(size_t*)get_address("render_api_callback"sv), get_address("render_api_offset"sv)}; }(); return render_api; } size_t RenderAPI::renderer() const { return read_u64(*api + 0x10); } size_t RenderAPI::swap_chain() const { return read_u64(renderer() + swap_chain_off); } std::optional<TEXTURE> g_forced_lut_textures[2]{}; using RenderLayer = void(const std::vector<Illumination*>&, uint8_t, const Camera&, const char**, const char**); RenderLayer* g_render_layer = nullptr; void render_layer(const std::vector<Illumination*>& lightsources, uint8_t layer, const Camera& camera, const char** lut_lhs, const char** lut_rhs) { // The lhs and rhs LUTs are blended in the shader, but we don't know where that value is CPU side so we can only override // with a single LUT for now if (g_forced_lut_textures[layer]) { if (Texture* lut = get_texture(g_forced_lut_textures[layer].value())) { g_render_layer(lightsources, layer, camera, lut->name, lut->name); return; } } g_render_layer(lightsources, layer, camera, lut_lhs, lut_rhs); } void RenderAPI::set_lut(TEXTURE texture_id, uint8_t layer) { g_forced_lut_textures[layer] = texture_id; } void RenderAPI::reset_lut(uint8_t layer) { g_forced_lut_textures[layer] = std::nullopt; } using VanillaRenderHudFun = void(size_t, float, float, size_t); VanillaRenderHudFun* g_render_hud_trampoline{nullptr}; void render_hud(size_t hud_data, float y, float opacity, size_t hud_data2) { // hud_data and hud_data2 are the same pointer, but the second one is actually used (displays garbage if not passed) trigger_vanilla_render_callbacks(ON::RENDER_PRE_HUD); g_render_hud_trampoline(hud_data, y, opacity, hud_data2); trigger_vanilla_render_callbacks(ON::RENDER_POST_HUD); } using VanillaRenderPauseMenuFun = void(float*); VanillaRenderPauseMenuFun* g_render_pause_menu_trampoline{nullptr}; void render_pause_menu(float* drawing_info) { trigger_vanilla_render_callbacks(ON::RENDER_PRE_PAUSE_MENU); g_render_pause_menu_trampoline(drawing_info); trigger_vanilla_render_callbacks(ON::RENDER_POST_PAUSE_MENU); } using VanillaRenderDrawDepthFun = void(Layer*, uint8_t, float, float, float, float); VanillaRenderDrawDepthFun* g_render_draw_depth_trampoline{nullptr}; void render_draw_depth(Layer* layer, uint8_t draw_depth, float bbox_left, float bbox_bottom, float bbox_right, float bbox_top) { trigger_vanilla_render_draw_depth_callbacks(ON::RENDER_PRE_DRAW_DEPTH, draw_depth, {bbox_left, bbox_top, bbox_right, bbox_bottom}); g_render_draw_depth_trampoline(layer, draw_depth, bbox_left, bbox_bottom, bbox_right, bbox_top); trigger_vanilla_render_draw_depth_callbacks(ON::RENDER_POST_DRAW_DEPTH, draw_depth, {bbox_left, bbox_top, bbox_right, bbox_bottom}); } using VanillaRenderJournalPageFun = void(JournalPage*); VanillaRenderJournalPageFun* g_render_journal_page_journalmenu_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_progress_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_place_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_people_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_bestiary_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_items_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_traps_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_story_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_feats_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_deathcause_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_deathmenu_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_recap_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_player_profile_trampoline{nullptr}; VanillaRenderJournalPageFun* g_render_journal_page_last_game_played_trampoline{nullptr}; void render_journal_page_journalmenu(JournalPage* page) { g_render_journal_page_journalmenu_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::JournalMenu, page); } void render_journal_page_progress(JournalPage* page) { g_render_journal_page_progress_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Progress, page); } void render_journal_page_place(JournalPage* page) { g_render_journal_page_place_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Places, page); } void render_journal_page_people(JournalPage* page) { g_render_journal_page_people_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::People, page); } void render_journal_page_bestiary(JournalPage* page) { g_render_journal_page_bestiary_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Bestiary, page); } void render_journal_page_items(JournalPage* page) { g_render_journal_page_items_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Items, page); } void render_journal_page_traps(JournalPage* page) { g_render_journal_page_traps_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Traps, page); } void render_journal_page_story(JournalPage* page) { g_render_journal_page_story_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Story, page); } void render_journal_page_feats(JournalPage* page) { g_render_journal_page_feats_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Feats, page); } void render_journal_page_deathcause(JournalPage* page) { g_render_journal_page_deathcause_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::DeathCause, page); } void render_journal_page_deathmenu(JournalPage* page) { g_render_journal_page_deathmenu_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::DeathMenu, page); } void render_journal_page_recap(JournalPage* page) { g_render_journal_page_recap_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::Recap, page); } void render_journal_page_player_profile(JournalPage* page) { g_render_journal_page_player_profile_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::PlayerProfile, page); } void render_journal_page_last_game_played(JournalPage* page) { g_render_journal_page_last_game_played_trampoline(page); trigger_vanilla_render_journal_page_callbacks(ON::RENDER_POST_JOURNAL_PAGE, JournalPageType::LastGamePlayed, page); } bool prepare_text_for_rendering(TextRenderingInfo* info, const std::string& text, float x, float y, float scale_x, float scale_y, uint32_t alignment, uint32_t fontstyle) { static size_t text_rendering_func1_offset = 0; if (text_rendering_func1_offset == 0) { text_rendering_func1_offset = get_address("prepare_text_for_rendering"sv); } if (text_rendering_func1_offset != 0) { auto convert_result = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0); if (convert_result <= 0) { return false; } std::wstring wide_text; wide_text.resize(convert_result + 10); convert_result = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), &wide_text[0], static_cast<int>(wide_text.size())); typedef void func1(uint32_t fontstyle, void* text_to_draw, uint32_t, float x, float y, TextRenderingInfo*, float scale_x, float scale_y, uint32_t alignment, uint32_t unknown_baseline_shift, int8_t); static func1* f1 = (func1*)(text_rendering_func1_offset); f1(fontstyle, wide_text.data(), 2, x, y, info, scale_x, scale_y, alignment, 2, 0); return true; } return false; } void RenderAPI::draw_text(const std::string& text, float x, float y, float scale_x, float scale_y, Color color, uint32_t alignment, uint32_t fontstyle) { TextRenderingInfo tri = {0}; if (!prepare_text_for_rendering(&tri, text, x, y, scale_x, scale_y, alignment, fontstyle)) { return; } static size_t text_rendering_func2_offset = 0; if (text_rendering_func2_offset == 0) { text_rendering_func2_offset = get_address("draw_text"sv); } if (text_rendering_func2_offset != 0) { typedef void func2(TextRenderingInfo*, Color * color); static func2* f2 = (func2*)(text_rendering_func2_offset); f2(&tri, &color); } } std::pair<float, float> RenderAPI::draw_text_size(const std::string& text, float scale_x, float scale_y, uint32_t fontstyle) { TextRenderingInfo tri = {0}; if (!prepare_text_for_rendering(&tri, text, 0, 0, scale_x, scale_y, 1 /*center*/, fontstyle)) { return std::make_pair(0.0f, 0.0f); } return std::make_pair(tri.width, tri.height); } void RenderAPI::draw_screen_texture(Texture* texture, Quad source, Quad dest, Color color) { static size_t offset = get_address("draw_screen_texture"); constexpr uint8_t shader = 0x29; if (offset != 0) { TextureRenderingInfo tri = { 0, 0, // DESTINATION dest.bottom_left_x, dest.bottom_left_y, dest.bottom_right_x, dest.bottom_right_y, dest.top_left_x, dest.top_left_y, dest.top_right_x, dest.top_right_y, // SOURCE source.bottom_left_x, source.bottom_left_y, source.bottom_right_x, source.bottom_right_y, source.top_left_x, source.top_left_y, source.top_right_x, source.top_right_y, }; typedef void render_func(TextureRenderingInfo*, uint8_t, const char**, Color*); static render_func* rf = (render_func*)(offset); rf(&tri, shader, texture->name, &color); } } void RenderAPI::draw_world_texture(Texture* texture, Quad source, Quad dest, Color color, WorldShader shader) { static size_t func_offset = 0; static size_t param_7 = 0; if (func_offset == 0) { func_offset = get_address("draw_world_texture"sv); param_7 = get_address("draw_world_texture_param_7"sv); } if (func_offset != 0) { // destination and source float arrays are the same as in RenderInfo const float unknown = 21; // this is also Quad, but some special one float destination[12] = { // bottom left: dest.bottom_left_x, dest.bottom_left_y, unknown, // bottom right: dest.bottom_right_x, dest.bottom_right_y, unknown, // top right: dest.top_right_x, dest.top_right_y, unknown, // top left: dest.top_left_x, dest.top_left_y, unknown}; typedef void render_func(size_t, WorldShader, const char*** texture_name, uint32_t render_as_non_liquid, float* destination, Quad* source, void*, Color*, float*); static render_func* rf = (render_func*)(func_offset); auto texture_name = texture->name; rf(renderer(), shader, &texture_name, 1, destination, &source, (void*)param_7, &color, nullptr); } } void fetch_texture(Entity* entity, int32_t texture_id) { entity->texture = nullptr; auto* textures = get_textures(); if (texture_id >= static_cast<int64_t>(textures->texture_map.size())) { auto& render_api = RenderAPI::get(); std::lock_guard lock{render_api.custom_textures_lock}; auto& custom_textures = render_api.custom_textures; auto it = custom_textures.find(texture_id); if (it != custom_textures.end()) { entity->texture = &it->second; } } if (entity->texture == nullptr) { if (texture_id < -3) { texture_id = State::get().ptr_local()->current_theme->get_dynamic_texture(texture_id); } entity->texture = get_textures()->texture_map[texture_id]; } if (entity->texture != nullptr) { entity->animation_frame = static_cast<uint16_t>(entity->type->tile_y * entity->texture->num_tiles_width + entity->type->tile_x); } else { entity->animation_frame = 0; } } void init_render_api_hooks() { // Fix the texture fetching in spawn_entity if (const size_t fetch_texture_begin = get_address("fetch_texture_begin")) { const size_t fetch_texture_end = get_address("fetch_texture_end"); const size_t fetch_texture_addr = (size_t)&fetch_texture; // Manually assembled code, let's hope it won't have to change ever std::string code = fmt::format( "\x48\x89\xf1" // mov rcx, rax "\x48\x89\xc2" // mov rdx, rsi "\x48\xb8{}" // mov rax, 0x0 "\xff\xd0" // call rax "\x48\x31\xc0"sv, // xor rax, rax to_le_bytes(fetch_texture_addr)); // Fill with nop, code is not performance-critical either way const size_t original_code_size = fetch_texture_end - fetch_texture_begin; code.resize(original_code_size, '\x90'); write_mem_prot(fetch_texture_begin, code, true); } g_render_layer = (RenderLayer*)get_address("render_layer"sv); g_render_hud_trampoline = (VanillaRenderHudFun*)get_address("render_hud"sv); g_render_pause_menu_trampoline = (VanillaRenderPauseMenuFun*)get_address("render_pause_menu"sv); g_render_draw_depth_trampoline = (VanillaRenderDrawDepthFun*)get_address("render_draw_depth"sv); const size_t fourth_virt = 4 * sizeof(size_t); const size_t journal_vftable = get_address("vftable_JournalPages"sv); size_t* render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::MENU + fourth_virt); g_render_journal_page_journalmenu_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::PROGRESS + fourth_virt); g_render_journal_page_progress_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::PLACES + fourth_virt); g_render_journal_page_place_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::PEOPLE + fourth_virt); g_render_journal_page_people_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::BESTIARY + fourth_virt); g_render_journal_page_bestiary_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::ITEMS + fourth_virt); g_render_journal_page_items_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::TRAPS + fourth_virt); g_render_journal_page_traps_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::STORY + fourth_virt); g_render_journal_page_story_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::FEATS + fourth_virt); g_render_journal_page_feats_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::DEATH_CAUSE + fourth_virt); g_render_journal_page_deathcause_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::DEATH_MENU + fourth_virt); g_render_journal_page_deathmenu_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::RECAP + fourth_virt); g_render_journal_page_recap_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::PLAYER_PROFILE + fourth_virt); g_render_journal_page_player_profile_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); render_virt = (size_t*)(journal_vftable + JOURNAL_VFTABLE::LAST_GAME_PLAYED + fourth_virt); g_render_journal_page_last_game_played_trampoline = (VanillaRenderJournalPageFun*)(*render_virt); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((void**)&g_render_layer, render_layer); DetourAttach((void**)&g_render_hud_trampoline, &render_hud); DetourAttach((void**)&g_render_pause_menu_trampoline, &render_pause_menu); DetourAttach((void**)&g_render_draw_depth_trampoline, &render_draw_depth); DetourAttach((void**)&g_render_journal_page_journalmenu_trampoline, &render_journal_page_journalmenu); DetourAttach((void**)&g_render_journal_page_progress_trampoline, &render_journal_page_progress); DetourAttach((void**)&g_render_journal_page_place_trampoline, &render_journal_page_place); DetourAttach((void**)&g_render_journal_page_people_trampoline, &render_journal_page_people); DetourAttach((void**)&g_render_journal_page_bestiary_trampoline, &render_journal_page_bestiary); DetourAttach((void**)&g_render_journal_page_items_trampoline, &render_journal_page_items); DetourAttach((void**)&g_render_journal_page_traps_trampoline, &render_journal_page_traps); DetourAttach((void**)&g_render_journal_page_story_trampoline, &render_journal_page_story); DetourAttach((void**)&g_render_journal_page_feats_trampoline, &render_journal_page_feats); DetourAttach((void**)&g_render_journal_page_deathcause_trampoline, &render_journal_page_deathcause); DetourAttach((void**)&g_render_journal_page_deathmenu_trampoline, &render_journal_page_deathmenu); DetourAttach((void**)&g_render_journal_page_recap_trampoline, &render_journal_page_recap); DetourAttach((void**)&g_render_journal_page_player_profile_trampoline, &render_journal_page_player_profile); DetourAttach((void**)&g_render_journal_page_last_game_played_trampoline, &render_journal_page_last_game_played); const LONG error = DetourTransactionCommit(); if (error != NO_ERROR) { DEBUG("Failed hooking render_api: {}\n", error); } } void TextureRenderingInfo::set_destination(const AABB& bbox) { auto w = bbox.width(); auto h = bbox.bottom - bbox.top; auto half_w = w / 2.0f; auto half_h = h / 2.0f; x = bbox.left + half_w; y = bbox.top + half_h; destination_top_left_x = -half_w; destination_top_left_y = half_h; destination_top_right_x = half_w; destination_top_right_y = half_h; destination_bottom_left_x = -half_w; destination_bottom_left_y = -half_h; destination_bottom_right_x = half_w; destination_bottom_right_y = -half_h; } Quad TextureRenderingInfo::dest_get_quad() { return Quad{destination_bottom_left_x, destination_bottom_left_y, destination_bottom_right_x, destination_bottom_right_y, destination_top_right_x, destination_top_right_y, destination_top_left_x, destination_top_left_y}; } void TextureRenderingInfo::dest_set_quad(const Quad& quad) { destination_bottom_left_x = quad.bottom_left_x; destination_bottom_left_y = quad.bottom_left_y; destination_bottom_right_x = quad.bottom_right_x; destination_bottom_right_y = quad.bottom_right_y; destination_top_right_x = quad.top_right_x; destination_top_right_y = quad.top_right_y; destination_top_left_x = quad.top_left_x; destination_top_left_y = quad.top_left_y; } Quad TextureRenderingInfo::source_get_quad() { return Quad{source_bottom_left_x, source_bottom_left_y, source_bottom_right_x, source_bottom_right_y, source_top_right_x, source_top_right_y, source_top_left_x, source_top_left_y}; } void TextureRenderingInfo::source_set_quad(const Quad& quad) { source_bottom_left_x = quad.bottom_left_x; source_bottom_left_y = quad.bottom_left_y; source_bottom_right_x = quad.bottom_right_x; source_bottom_right_y = quad.bottom_right_y; source_top_right_x = quad.top_right_x; source_top_right_y = quad.top_right_y; source_top_left_x = quad.top_left_x; source_top_left_y = quad.top_left_y; }
44.401639
225
0.731955
[ "vector" ]
17f7fd23ce1e98504a5d7acb4b034ef6cf329f1d
8,761
cpp
C++
source/opengl/state_tracking.cpp
Not-Smelly-Garbage/reshade
6c25ad402169521b646b1d7a66ae9345aa39a735
[ "BSD-3-Clause" ]
58
2020-12-16T01:43:41.000Z
2022-03-28T07:49:20.000Z
source/opengl/state_tracking.cpp
FransBouma/reshade
61fe2486d02179907e51b70c7df82a6b1a78cbe1
[ "BSD-3-Clause" ]
null
null
null
source/opengl/state_tracking.cpp
FransBouma/reshade
61fe2486d02179907e51b70c7df82a6b1a78cbe1
[ "BSD-3-Clause" ]
9
2020-12-22T13:28:02.000Z
2022-03-27T08:21:29.000Z
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "state_tracking.hpp" #include <cmath> #include <cassert> void reshade::opengl::state_tracking::reset(GLuint default_width, GLuint default_height, GLenum default_format) { // Reset statistics for next frame _stats = { 0, 0 }; #if RESHADE_DEPTH _best_copy_stats = { 0, 0 }; _depth_source_table.clear(); // Initialize information for the default depth buffer _depth_source_table[0] = { 0, default_width, default_height, 0, 0, GL_FRAMEBUFFER_DEFAULT, default_format }; #else UNREFERENCED_PARAMETER(default_width); UNREFERENCED_PARAMETER(default_height); UNREFERENCED_PARAMETER(default_format); #endif } void reshade::opengl::state_tracking::release() { #if RESHADE_DEPTH glDeleteTextures(1, &_clear_texture); _clear_texture = 0; glDeleteFramebuffers(1, &_copy_fbo); _copy_fbo = 0; #endif } #if RESHADE_DEPTH static bool current_depth_source(GLint &object, GLint &target) { target = GL_FRAMEBUFFER_DEFAULT; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &object); // Zero is valid too, in which case the default depth buffer is referenced, instead of a FBO if (object != 0) { glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &target); if (target == GL_NONE) return false; // FBO does not have a depth attachment glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &object); } return true; } #endif void reshade::opengl::state_tracking::on_draw(GLsizei vertices) { vertices += _current_vertex_count; _current_vertex_count = 0; _stats.vertices += vertices; _stats.drawcalls += 1; #if RESHADE_DEPTH if (GLint object = 0, target; current_depth_source(object, target)) { auto &counters = _depth_source_table[object | (target == GL_RENDERBUFFER ? 0x80000000 : 0)]; counters.total_stats.vertices += vertices; counters.total_stats.drawcalls += 1; counters.current_stats.vertices += vertices; counters.current_stats.drawcalls += 1; } #endif } #if RESHADE_DEPTH static void get_rbo_param(GLuint id, GLenum param, GLuint &value) { if (gl3wProcs.gl.GetNamedRenderbufferParameteriv != nullptr) { glGetNamedRenderbufferParameteriv(id, param, reinterpret_cast<GLint *>(&value)); } else { GLint prev_binding = 0; glGetIntegerv(GL_RENDERBUFFER_BINDING, &prev_binding); glBindRenderbuffer(GL_RENDERBUFFER, id); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, reinterpret_cast<GLint *>(&value)); glBindRenderbuffer(GL_RENDERBUFFER, prev_binding); } } static void get_tex_param(GLuint id, GLenum param, GLuint &value) { if (gl3wProcs.gl.GetTextureParameteriv != nullptr) { glGetTextureParameteriv(id, param, reinterpret_cast<GLint *>(&value)); } else { GLint prev_binding = 0; glGetIntegerv(GL_TEXTURE_BINDING_2D, &prev_binding); glBindTexture(GL_TEXTURE_2D, id); glGetTexParameteriv(GL_TEXTURE_2D, param, reinterpret_cast<GLint *>(&value)); glBindTexture(GL_TEXTURE_2D, prev_binding); } } static void get_tex_level_param(GLuint id, GLuint level, GLenum param, GLuint &value) { if (gl3wProcs.gl.GetTextureLevelParameteriv != nullptr) { glGetTextureLevelParameteriv(id, level, param, reinterpret_cast<GLint *>(&value)); } else { GLint prev_binding = 0; glGetIntegerv(GL_TEXTURE_BINDING_2D, &prev_binding); glBindTexture(GL_TEXTURE_2D, id); glGetTexLevelParameteriv(GL_TEXTURE_2D, level, param, reinterpret_cast<GLint *>(&value)); glBindTexture(GL_TEXTURE_2D, prev_binding); } } void reshade::opengl::state_tracking::on_bind_draw_fbo() { GLint object = 0, target; if (!current_depth_source(object, target)) return; depthstencil_info &info = _depth_source_table[object | (target == GL_RENDERBUFFER ? 0x80000000 : 0)]; info.obj = object; info.target = target; switch (target) { case GL_TEXTURE: glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, reinterpret_cast<GLint *>(&info.level)); glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, reinterpret_cast<GLint *>(&info.layer)); get_tex_param(object, GL_TEXTURE_TARGET, info.target); get_tex_level_param(object, info.level, GL_TEXTURE_WIDTH, info.width); get_tex_level_param(object, info.level, GL_TEXTURE_HEIGHT, info.height); get_tex_level_param(object, info.level, GL_TEXTURE_INTERNAL_FORMAT, info.format); break; case GL_RENDERBUFFER: get_rbo_param(object, GL_RENDERBUFFER_WIDTH, info.width); get_rbo_param(object, GL_RENDERBUFFER_HEIGHT, info.height); get_rbo_param(object, GL_RENDERBUFFER_INTERNAL_FORMAT, info.format); break; case GL_FRAMEBUFFER_DEFAULT: break; } } void reshade::opengl::state_tracking::on_clear_attachments(GLbitfield mask) { if ((mask & GL_DEPTH_BUFFER_BIT) == 0) return; GLint object = 0, target; if (!current_depth_source(object, target)) return; const GLuint id = object | (target == GL_RENDERBUFFER ? 0x80000000 : 0); if (id != depthstencil_clear_index.first) return; auto &counters = _depth_source_table[id]; // Ignore clears when there was no meaningful workload if (counters.current_stats.drawcalls == 0) return; counters.clears.push_back(counters.current_stats); // Make a backup copy of the depth texture before it is cleared if (depthstencil_clear_index.second == 0 ? // If clear index override is set to zero, always copy any suitable buffers counters.current_stats.vertices > _best_copy_stats.vertices : counters.clears.size() == depthstencil_clear_index.second) { _best_copy_stats = counters.current_stats; GLint read_fbo = 0; GLint draw_fbo = 0; glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_fbo); glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_fbo); if (_copy_fbo == 0) { glGenFramebuffers(1, &_copy_fbo); } if (_clear_texture == 0) { glGenTextures(1, &_clear_texture); glBindTexture(GL_TEXTURE_2D, _clear_texture); glTexStorage2D(GL_TEXTURE_2D, 1, counters.format, counters.width, counters.height); glBindFramebuffer(GL_FRAMEBUFFER, _copy_fbo); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _clear_texture, 0); assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); } glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _copy_fbo); glBlitFramebuffer(0, 0, counters.width, counters.height, 0, 0, counters.width, counters.height, GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, read_fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw_fbo); } // Reset draw call stats for clears counters.current_stats = { 0, 0 }; } reshade::opengl::state_tracking::depthstencil_info reshade::opengl::state_tracking::find_best_depth_texture(GLuint width, GLuint height, GLuint override) { depthstencil_info best_snapshot = _depth_source_table.at(0); // Always fall back to default depth buffer if no better match is found if (override != std::numeric_limits<GLuint>::max()) { const auto source_it = _depth_source_table.find(override); if (source_it != _depth_source_table.end()) return source_it->second; else return best_snapshot; } for (const auto &[image, snapshot] : _depth_source_table) { if (snapshot.total_stats.drawcalls == 0) continue; // Skip unused if (use_aspect_ratio_heuristics) { assert(width != 0 && height != 0); const float w = static_cast<float>(width); const float w_ratio = w / snapshot.width; const float h = static_cast<float>(height); const float h_ratio = h / snapshot.height; const float aspect_ratio = (w / h) - (static_cast<float>(snapshot.width) / snapshot.height); if (std::fabs(aspect_ratio) > 0.1f || w_ratio > 1.85f || h_ratio > 1.85f || w_ratio < 0.5f || h_ratio < 0.5f) continue; // Not a good fit } const auto curr_weight = snapshot.total_stats.vertices * (1.2f - static_cast<float>(snapshot.total_stats.drawcalls) / _stats.drawcalls); const auto best_weight = best_snapshot.total_stats.vertices * (1.2f - static_cast<float>(best_snapshot.total_stats.drawcalls) / _stats.vertices); if (curr_weight >= best_weight) { best_snapshot = snapshot; } } const GLuint id = best_snapshot.obj | (best_snapshot.target == GL_RENDERBUFFER ? 0x80000000 : 0); if (depthstencil_clear_index.first != id) release(); depthstencil_clear_index.first = id; if (preserve_depth_buffers && _clear_texture != 0) { best_snapshot.obj = _clear_texture; best_snapshot.level = 0; best_snapshot.target = GL_TEXTURE_2D; } return best_snapshot; } #endif
32.568773
163
0.763497
[ "object" ]
17faf9f017942bd18d421fb7cebd3834608c4a76
535
hpp
C++
libs/core/render/include/bksge/core/render/vulkan/detail/fwd/device_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/include/bksge/core/render/vulkan/detail/fwd/device_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/include/bksge/core/render/vulkan/detail/fwd/device_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file device_fwd.hpp * * @brief Device クラスの前方宣言 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_VULKAN_DETAIL_FWD_DEVICE_FWD_HPP #define BKSGE_CORE_RENDER_VULKAN_DETAIL_FWD_DEVICE_FWD_HPP #include <bksge/fnd/memory/shared_ptr.hpp> namespace bksge { namespace render { namespace vulkan { class Device; using DeviceSharedPtr = bksge::shared_ptr<Device>; } // namespace vulkan } // namespace render } // namespace bksge #endif // BKSGE_CORE_RENDER_VULKAN_DETAIL_FWD_DEVICE_FWD_HPP
16.212121
61
0.730841
[ "render" ]
aa04218a9b99df6c538fd846bec9b04e2da369d1
3,214
cpp
C++
geometry/MultiVolumeGrid.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
57
2015-05-07T18:07:11.000Z
2022-03-18T18:44:39.000Z
geometry/MultiVolumeGrid.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
7
2018-12-10T21:46:52.000Z
2022-01-20T19:49:11.000Z
geometry/MultiVolumeGrid.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
36
2015-01-10T18:36:45.000Z
2022-01-20T19:49:24.000Z
#include "MultiVolumeGrid.h" #include <algorithm> using namespace std; using namespace Meshing; using namespace Geometry; MultiVolumeGrid::MultiVolumeGrid() { channelNames.push_back("value"); channels.resize(1); } void MultiVolumeGrid::AddChannel(const std::string& name) { channelNames.push_back(name); channels.resize(channels.size()+1); if(channels.size() > 1) channels.back().MakeSimilar(channels[0]); } void MultiVolumeGrid::SetChannelName(int channel,const std::string& name) { channelNames[channel] = name; } int MultiVolumeGrid::GetChannel(const std::string& name) const { auto i=find(channelNames.begin(),channelNames.end(),name); if(i==channelNames.end()) return -1; return i-channelNames.begin(); } void MultiVolumeGrid::Resize(int m,int n,int p) { for(size_t i=0;i<channels.size();i++) channels[i].Resize(m,n,p); } void MultiVolumeGrid::ResizeByResolution(const Vector3& res) { for(size_t i=0;i<channels.size();i++) channels[i].ResizeByResolution(res); } void MultiVolumeGrid::MakeSimilar(const MultiVolumeGrid& grid) { channelNames = grid.channelNames; channels.resize(grid.channels.size()); for(size_t i=0;i<channels.size();i++) channels[i].MakeSimilar(grid.channels[i]); } bool MultiVolumeGrid::IsSimilar(const MultiVolumeGrid& grid) const { if(channels.size() != grid.channels.size()) return false; for(size_t i=0;i<channels.size();i++) if(!channels[i].IsSimilar(grid.channels[i])) return false; return true; } void MultiVolumeGrid::GetValue(const IntTriple& index,Vector& values) const { ///TODO: make this a little faster by precomputing array offset? values.resize(channels.size()); for(size_t i=0;i<channels.size();i++) values[i] = channels[i].value(index); } void MultiVolumeGrid::GetValue(const Vector3& pt,Vector& values) const { IntTriple index; channels[0].GetIndex(pt,index); GetValue(index,values); } void MultiVolumeGrid::SetValue(const IntTriple& index,const Vector& values) { Assert(values.size()==(int)channels.size()); for(size_t i=0;i<channels.size();i++) channels[i].value(index) = values[i]; } void MultiVolumeGrid::SetValue(const Vector3& pt,const Vector& values) { IntTriple index; channels[0].GetIndex(pt,index); SetValue(index,values); } void MultiVolumeGrid::TrilinearInterpolate(const Vector3& pt,Vector& values) const { ///TODO: make this a little faster by precomputing interpolation parameters? values.resize(channels.size()); for(size_t i=0;i<channels.size();i++) values[i] = channels[i].TrilinearInterpolate(pt); } void MultiVolumeGrid::ResampleTrilinear(const MultiVolumeGrid& grid) { channelNames = grid.channelNames; channels.resize(grid.channels.size()); for(size_t i=1;i<channels.size();i++) channels[i].MakeSimilar(channels[0]); for(size_t i=0;i<channels.size();i++) channels[i].ResampleTrilinear(grid.channels[i]); } void MultiVolumeGrid::ResampleAverage(const MultiVolumeGrid& grid) { channelNames = grid.channelNames; channels.resize(grid.channels.size()); for(size_t i=1;i<channels.size();i++) channels[i].MakeSimilar(channels[0]); for(size_t i=0;i<channels.size();i++) channels[i].ResampleAverage(grid.channels[i]); }
27.947826
82
0.724642
[ "geometry", "vector" ]
aa05163d029d9bf9cec70014076844eb69326ef3
1,750
cpp
C++
C++/1561. MaximumNumberOfCoinsYouCanGet.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
263
2020-10-05T18:47:29.000Z
2022-03-31T19:44:46.000Z
C++/1561. MaximumNumberOfCoinsYouCanGet.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
1,264
2020-10-05T18:13:05.000Z
2022-03-31T23:16:35.000Z
C++/1561. MaximumNumberOfCoinsYouCanGet.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
760
2020-10-05T18:22:51.000Z
2022-03-29T06:06:20.000Z
/* PROBLEM - 1561. Maximum Number of Coins You Can Get DESCRIPTION - There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: == In each step, you will choose any 3 piles of coins (not necessarily consecutive). == Of your choice, Alice will pick the pile with the maximum number of coins. == You will pick the next pile with maximum number of coins. == Your friend Bob will pick the last pile. == Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins which you can have. CONSTRAINTS- 3 <= piles.length <= 10^5 piles.length % 3 == 0 1 <= piles[i] <= 10^4 APPROACH- -- We first sort the piles array as we are greedily going to assign piles. -- Then we maintain a cnt, to track the number of piles each one will get. -- Then from max end of array, we start assigning the piles. -- At every odd chance we will be adding the pile to our ans so as to maximize output. TIME COMPLEXITY- TC of solution O(n.log.n) where n is size of piles array. (Due to sorting) */ class Solution { public: int maxCoins(vector<int>& piles) { sort(piles.begin(), piles.end()); // Sort the piles array int cnt = piles.size() / 3; // 3n piles hence everyone will get (3n)/3 piles int ans(0), curr(0); for (int i = piles.size() - 1; i >= 0; i--) // Start from max end { if (!cnt) break; if (curr & 1) // If the current counter is odd { ans += piles[i]; cnt--; // 1 pile is done. curr++; } else curr++; } return ans; } };
31.25
86
0.625714
[ "vector" ]
aa070f11550395277a35ce76b22c019615c6ce1e
2,915
cpp
C++
TheLargeMonProject/largeMon.cpp
Eromonsele/TheLargeMonProject
883735e54f17fd278fc4de3efa6ae8a77858e6fc
[ "MIT" ]
null
null
null
TheLargeMonProject/largeMon.cpp
Eromonsele/TheLargeMonProject
883735e54f17fd278fc4de3efa6ae8a77858e6fc
[ "MIT" ]
null
null
null
TheLargeMonProject/largeMon.cpp
Eromonsele/TheLargeMonProject
883735e54f17fd278fc4de3efa6ae8a77858e6fc
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "largeMon.h" #include <map> #include <utility> /** * The largemon objects, holds the largemon healthpoints, attackpoints * name, description,size and weakness * * Author: Eromosele Okhilua * */ // constructor LargeMon::LargeMon(string type, string name, string lsize, string description, int attackpoints, int healthPoints) :ltype_(std::move(type)), lname_(std::move(name)), lsize_(std::move(lsize)), ldescription_(std::move(description)), lattack_points_(attackpoints), lhealth_points_(healthPoints) { //empty body }// end Largemon constructor // set LargeMon type void LargeMon::set_type(const string &type) { ltype_ = type; }// end function // set LargeMon name void LargeMon::set_name(const string &name) { lname_ = name; }// end function // set LargeMon Size void LargeMon::set_size(const string &size) { lsize_ = size; }// end function // set LargeMon Description void LargeMon::set_description(const string &description) { ldescription_ = description; }// end function // set LargeMon AttackPoints void LargeMon::set_attack_points(int attackpoints) { lattack_points_ = attackpoints; }// end function // set LargeMon HealthPoints void LargeMon::set_health_points(int healthPoints) { lhealth_points_ = healthPoints; }// end function setHealthPoints // set LargeMon antagonist or weakness void LargeMon::set_antagonist(const string &s) { map<string, vector<string>> const m{ { "Fire",{ "Water","Rock","Ground" } }, { "Water",{ "Grass","Electric" } }, { "Normal",{ "Fighting" } }, { "Grass",{ "Fire","Ice" } }, { "Electric",{ "Ground" } }, { "Psychic",{ "Ghost" } }, { "Fighting",{ "Psychic" } }, { "Ghost",{ "Ghost" } }, { "Rock",{ "Water","Grass", "Fighting", "Ground" } }, { "Ground",{ "Water","Grass","Ice" } }, { "Ice",{ "Fire","Fighting","Rock" } }, { "Poison",{ "Psychic","Ground" } }, { "Dragon",{ "Ice","Dragon" } } }; for (auto const& x : m) { if (s == x.first) { for (auto const& y : x.second) { l_weakness_.push_back(y); } } else { } } } // end function setAntagonist // return largemon type string LargeMon::get_type() const { return ltype_; }// end function getType // return largemon name string LargeMon::get_name() const { return lname_; }// end function getName // return largemon size string LargeMon::get_size() const { return lsize_; }// end function getSize // return largemon description string LargeMon::get_description() const { return ldescription_; }// end function getDescription // return largemon attackpoints int LargeMon::get_attack_points() const { return lattack_points_; }// end function getAttackPoints // return largemon health points int LargeMon::get_health_points() const { return lhealth_points_; }// end function getHealthPoints // return largemon weakness vector<string> LargeMon::getLWeakness() const { return l_weakness_; }// end function getWeakness
22.251908
177
0.69331
[ "vector" ]
aa0a441cfb8f77964439c7362df4fcf887de8f43
1,433
cpp
C++
c-bindings/integration/utilities/internal/colored_printing.cpp
nabarunnag/geode-native
4ccd5f7d5f37728b83798b4ec2b5e7532bafc7b0
[ "Apache-2.0" ]
null
null
null
c-bindings/integration/utilities/internal/colored_printing.cpp
nabarunnag/geode-native
4ccd5f7d5f37728b83798b4ec2b5e7532bafc7b0
[ "Apache-2.0" ]
19
2020-10-30T00:31:27.000Z
2022-03-11T20:02:19.000Z
c_bindings/integration/utilities/internal/colored_printing.cpp
moleske/geode-native
5ef2c7850c5d1359991f326defe6aff493be364e
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "colored_printing.hpp" namespace util { /* This is explicit template instantiation. This translation unit will compile these template instances here, and we can extern them everywhere they are in use to reduce object bloat and compile time. */ template void print_message<::testing::internal::COLOR_DEFAULT>( const char* fmt...); template void print_message<::testing::internal::COLOR_GREEN>( const char* fmt...); template void print_message<::testing::internal::COLOR_YELLOW>( const char* fmt...); template void print_message<::testing::internal::COLOR_RED>(const char* fmt...); } // namespace util
44.78125
80
0.750872
[ "object" ]
aa0d6b3d5b49751140975f40ba03e6e31b47e8fe
20,192
cxx
C++
rdpfuzz-winafl/cmake-3.16.0/Source/cmWorkerPool.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
rdpfuzz-winafl/cmake-3.16.0/Source/cmWorkerPool.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
null
null
null
rdpfuzz-winafl/cmake-3.16.0/Source/cmWorkerPool.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmWorkerPool.h" #include <algorithm> #include <array> #include <condition_variable> #include <cstddef> #include <deque> #include <functional> #include <mutex> #include <thread> #include <cm/memory> #include "cm_uv.h" #include "cmRange.h" #include "cmStringAlgorithms.h" #include "cmUVHandlePtr.h" #include "cmUVSignalHackRAII.h" // IWYU pragma: keep /** * @brief libuv pipe buffer class */ class cmUVPipeBuffer { public: using DataRange = cmRange<const char*>; using DataFunction = std::function<void(DataRange)>; /// On error the ssize_t argument is a non zero libuv error code using EndFunction = std::function<void(ssize_t)>; public: /** * Reset to construction state */ void reset(); /** * Initializes uv_pipe(), uv_stream() and uv_handle() * @return true on success */ bool init(uv_loop_t* uv_loop); /** * Start reading * @return true on success */ bool startRead(DataFunction dataFunction, EndFunction endFunction); //! libuv pipe uv_pipe_t* uv_pipe() const { return UVPipe_.get(); } //! uv_pipe() casted to libuv stream uv_stream_t* uv_stream() const { return static_cast<uv_stream_t*>(UVPipe_); } //! uv_pipe() casted to libuv handle uv_handle_t* uv_handle() { return static_cast<uv_handle_t*>(UVPipe_); } private: // -- Libuv callbacks static void UVAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf); static void UVData(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf); private: cm::uv_pipe_ptr UVPipe_; std::vector<char> Buffer_; DataFunction DataFunction_; EndFunction EndFunction_; }; void cmUVPipeBuffer::reset() { if (UVPipe_.get() != nullptr) { EndFunction_ = nullptr; DataFunction_ = nullptr; Buffer_.clear(); Buffer_.shrink_to_fit(); UVPipe_.reset(); } } bool cmUVPipeBuffer::init(uv_loop_t* uv_loop) { reset(); if (uv_loop == nullptr) { return false; } int ret = UVPipe_.init(*uv_loop, 0, this); return (ret == 0); } bool cmUVPipeBuffer::startRead(DataFunction dataFunction, EndFunction endFunction) { if (UVPipe_.get() == nullptr) { return false; } if (!dataFunction || !endFunction) { return false; } DataFunction_ = std::move(dataFunction); EndFunction_ = std::move(endFunction); int ret = uv_read_start(uv_stream(), &cmUVPipeBuffer::UVAlloc, &cmUVPipeBuffer::UVData); return (ret == 0); } void cmUVPipeBuffer::UVAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf) { auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(handle->data); pipe.Buffer_.resize(suggestedSize); buf->base = pipe.Buffer_.data(); buf->len = static_cast<unsigned long>(pipe.Buffer_.size()); } void cmUVPipeBuffer::UVData(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(stream->data); if (nread > 0) { if (buf->base != nullptr) { // Call data function pipe.DataFunction_(DataRange(buf->base, buf->base + nread)); } } else if (nread < 0) { // Save the end function on the stack before resetting the pipe EndFunction efunc; efunc.swap(pipe.EndFunction_); // Reset pipe before calling the end function pipe.reset(); // Call end function efunc((nread == UV_EOF) ? 0 : nread); } } /** * @brief External process management class */ class cmUVReadOnlyProcess { public: // -- Types //! @brief Process settings struct SetupT { std::string WorkingDirectory; std::vector<std::string> Command; cmWorkerPool::ProcessResultT* Result = nullptr; bool MergedOutput = false; }; public: // -- Const accessors SetupT const& Setup() const { return Setup_; } cmWorkerPool::ProcessResultT* Result() const { return Setup_.Result; } bool IsStarted() const { return IsStarted_; } bool IsFinished() const { return IsFinished_; } // -- Runtime void setup(cmWorkerPool::ProcessResultT* result, bool mergedOutput, std::vector<std::string> const& command, std::string const& workingDirectory = std::string()); bool start(uv_loop_t* uv_loop, std::function<void()> finishedCallback); private: // -- Libuv callbacks static void UVExit(uv_process_t* handle, int64_t exitStatus, int termSignal); void UVPipeOutData(cmUVPipeBuffer::DataRange data); void UVPipeOutEnd(ssize_t error); void UVPipeErrData(cmUVPipeBuffer::DataRange data); void UVPipeErrEnd(ssize_t error); void UVTryFinish(); private: // -- Setup SetupT Setup_; // -- Runtime bool IsStarted_ = false; bool IsFinished_ = false; std::function<void()> FinishedCallback_; std::vector<const char*> CommandPtr_; std::array<uv_stdio_container_t, 3> UVOptionsStdIO_; uv_process_options_t UVOptions_; cm::uv_process_ptr UVProcess_; cmUVPipeBuffer UVPipeOut_; cmUVPipeBuffer UVPipeErr_; }; void cmUVReadOnlyProcess::setup(cmWorkerPool::ProcessResultT* result, bool mergedOutput, std::vector<std::string> const& command, std::string const& workingDirectory) { Setup_.WorkingDirectory = workingDirectory; Setup_.Command = command; Setup_.Result = result; Setup_.MergedOutput = mergedOutput; } bool cmUVReadOnlyProcess::start(uv_loop_t* uv_loop, std::function<void()> finishedCallback) { if (IsStarted() || (Result() == nullptr)) { return false; } // Reset result before the start Result()->reset(); // Fill command string pointers if (!Setup().Command.empty()) { CommandPtr_.reserve(Setup().Command.size() + 1); for (std::string const& arg : Setup().Command) { CommandPtr_.push_back(arg.c_str()); } CommandPtr_.push_back(nullptr); } else { Result()->ErrorMessage = "Empty command"; } if (!Result()->error()) { if (!UVPipeOut_.init(uv_loop)) { Result()->ErrorMessage = "libuv stdout pipe initialization failed"; } } if (!Result()->error()) { if (!UVPipeErr_.init(uv_loop)) { Result()->ErrorMessage = "libuv stderr pipe initialization failed"; } } if (!Result()->error()) { // -- Setup process stdio options // stdin UVOptionsStdIO_[0].flags = UV_IGNORE; UVOptionsStdIO_[0].data.stream = nullptr; // stdout UVOptionsStdIO_[1].flags = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); UVOptionsStdIO_[1].data.stream = UVPipeOut_.uv_stream(); // stderr UVOptionsStdIO_[2].flags = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); UVOptionsStdIO_[2].data.stream = UVPipeErr_.uv_stream(); // -- Setup process options std::fill_n(reinterpret_cast<char*>(&UVOptions_), sizeof(UVOptions_), 0); UVOptions_.exit_cb = &cmUVReadOnlyProcess::UVExit; UVOptions_.file = CommandPtr_[0]; UVOptions_.args = const_cast<char**>(CommandPtr_.data()); UVOptions_.cwd = Setup_.WorkingDirectory.c_str(); UVOptions_.flags = UV_PROCESS_WINDOWS_HIDE; UVOptions_.stdio_count = static_cast<int>(UVOptionsStdIO_.size()); UVOptions_.stdio = UVOptionsStdIO_.data(); // -- Spawn process int uvErrorCode = UVProcess_.spawn(*uv_loop, UVOptions_, this); if (uvErrorCode != 0) { Result()->ErrorMessage = "libuv process spawn failed"; if (const char* uvErr = uv_strerror(uvErrorCode)) { Result()->ErrorMessage += ": "; Result()->ErrorMessage += uvErr; } } } // -- Start reading from stdio streams if (!Result()->error()) { if (!UVPipeOut_.startRead( [this](cmUVPipeBuffer::DataRange range) { this->UVPipeOutData(range); }, [this](ssize_t error) { this->UVPipeOutEnd(error); })) { Result()->ErrorMessage = "libuv start reading from stdout pipe failed"; } } if (!Result()->error()) { if (!UVPipeErr_.startRead( [this](cmUVPipeBuffer::DataRange range) { this->UVPipeErrData(range); }, [this](ssize_t error) { this->UVPipeErrEnd(error); })) { Result()->ErrorMessage = "libuv start reading from stderr pipe failed"; } } if (!Result()->error()) { IsStarted_ = true; FinishedCallback_ = std::move(finishedCallback); } else { // Clear libuv handles and finish UVProcess_.reset(); UVPipeOut_.reset(); UVPipeErr_.reset(); CommandPtr_.clear(); } return IsStarted(); } void cmUVReadOnlyProcess::UVExit(uv_process_t* handle, int64_t exitStatus, int termSignal) { auto& proc = *reinterpret_cast<cmUVReadOnlyProcess*>(handle->data); if (proc.IsStarted() && !proc.IsFinished()) { // Set error message on demand proc.Result()->ExitStatus = exitStatus; proc.Result()->TermSignal = termSignal; if (!proc.Result()->error()) { if (termSignal != 0) { proc.Result()->ErrorMessage = cmStrCat( "Process was terminated by signal ", proc.Result()->TermSignal); } else if (exitStatus != 0) { proc.Result()->ErrorMessage = cmStrCat( "Process failed with return value ", proc.Result()->ExitStatus); } } // Reset process handle proc.UVProcess_.reset(); // Try finish proc.UVTryFinish(); } } void cmUVReadOnlyProcess::UVPipeOutData(cmUVPipeBuffer::DataRange data) { Result()->StdOut.append(data.begin(), data.end()); } void cmUVReadOnlyProcess::UVPipeOutEnd(ssize_t error) { // Process pipe error if ((error != 0) && !Result()->error()) { Result()->ErrorMessage = cmStrCat( "Reading from stdout pipe failed with libuv error code ", error); } // Try finish UVTryFinish(); } void cmUVReadOnlyProcess::UVPipeErrData(cmUVPipeBuffer::DataRange data) { std::string* str = Setup_.MergedOutput ? &Result()->StdOut : &Result()->StdErr; str->append(data.begin(), data.end()); } void cmUVReadOnlyProcess::UVPipeErrEnd(ssize_t error) { // Process pipe error if ((error != 0) && !Result()->error()) { Result()->ErrorMessage = cmStrCat( "Reading from stderr pipe failed with libuv error code ", error); } // Try finish UVTryFinish(); } void cmUVReadOnlyProcess::UVTryFinish() { // There still might be data in the pipes after the process has finished. // Therefore check if the process is finished AND all pipes are closed // before signaling the worker thread to continue. if ((UVProcess_.get() != nullptr) || (UVPipeOut_.uv_pipe() != nullptr) || (UVPipeErr_.uv_pipe() != nullptr)) { return; } IsFinished_ = true; FinishedCallback_(); } /** * @brief Worker pool worker thread */ class cmWorkerPoolWorker { public: cmWorkerPoolWorker(uv_loop_t& uvLoop); ~cmWorkerPoolWorker(); cmWorkerPoolWorker(cmWorkerPoolWorker const&) = delete; cmWorkerPoolWorker& operator=(cmWorkerPoolWorker const&) = delete; /** * Set the internal thread */ void SetThread(std::thread&& aThread) { Thread_ = std::move(aThread); } /** * Run an external process */ bool RunProcess(cmWorkerPool::ProcessResultT& result, std::vector<std::string> const& command, std::string const& workingDirectory); private: // -- Libuv callbacks static void UVProcessStart(uv_async_t* handle); void UVProcessFinished(); private: // -- Process management struct { std::mutex Mutex; cm::uv_async_ptr Request; std::condition_variable Condition; std::unique_ptr<cmUVReadOnlyProcess> ROP; } Proc_; // -- System thread std::thread Thread_; }; cmWorkerPoolWorker::cmWorkerPoolWorker(uv_loop_t& uvLoop) { Proc_.Request.init(uvLoop, &cmWorkerPoolWorker::UVProcessStart, this); } cmWorkerPoolWorker::~cmWorkerPoolWorker() { if (Thread_.joinable()) { Thread_.join(); } } bool cmWorkerPoolWorker::RunProcess(cmWorkerPool::ProcessResultT& result, std::vector<std::string> const& command, std::string const& workingDirectory) { if (command.empty()) { return false; } // Create process instance { std::lock_guard<std::mutex> lock(Proc_.Mutex); Proc_.ROP = cm::make_unique<cmUVReadOnlyProcess>(); Proc_.ROP->setup(&result, true, command, workingDirectory); } // Send asynchronous process start request to libuv loop Proc_.Request.send(); // Wait until the process has been finished and destroyed { std::unique_lock<std::mutex> ulock(Proc_.Mutex); while (Proc_.ROP) { Proc_.Condition.wait(ulock); } } return !result.error(); } void cmWorkerPoolWorker::UVProcessStart(uv_async_t* handle) { auto* wrk = reinterpret_cast<cmWorkerPoolWorker*>(handle->data); bool startFailed = false; { auto& Proc = wrk->Proc_; std::lock_guard<std::mutex> lock(Proc.Mutex); if (Proc.ROP && !Proc.ROP->IsStarted()) { startFailed = !Proc.ROP->start(handle->loop, [wrk] { wrk->UVProcessFinished(); }); } } // Clean up if starting of the process failed if (startFailed) { wrk->UVProcessFinished(); } } void cmWorkerPoolWorker::UVProcessFinished() { { std::lock_guard<std::mutex> lock(Proc_.Mutex); if (Proc_.ROP && (Proc_.ROP->IsFinished() || !Proc_.ROP->IsStarted())) { Proc_.ROP.reset(); } } // Notify idling thread Proc_.Condition.notify_one(); } /** * @brief Private worker pool internals */ class cmWorkerPoolInternal { public: // -- Constructors cmWorkerPoolInternal(cmWorkerPool* pool); ~cmWorkerPoolInternal(); /** * Runs the libuv loop. */ bool Process(); /** * Clear queue and abort threads. */ void Abort(); /** * Push a job to the queue and notify a worker. */ bool PushJob(cmWorkerPool::JobHandleT&& jobHandle); /** * Worker thread main loop method. */ void Work(unsigned int workerIndex); // -- Request slots static void UVSlotBegin(uv_async_t* handle); static void UVSlotEnd(uv_async_t* handle); public: // -- UV loop #ifdef CMAKE_UV_SIGNAL_HACK std::unique_ptr<cmUVSignalHackRAII> UVHackRAII; #endif std::unique_ptr<uv_loop_t> UVLoop; cm::uv_async_ptr UVRequestBegin; cm::uv_async_ptr UVRequestEnd; // -- Thread pool and job queue std::mutex Mutex; bool Processing = false; bool Aborting = false; bool FenceProcessing = false; unsigned int WorkersRunning = 0; unsigned int WorkersIdle = 0; unsigned int JobsProcessing = 0; std::deque<cmWorkerPool::JobHandleT> Queue; std::condition_variable Condition; std::vector<std::unique_ptr<cmWorkerPoolWorker>> Workers; // -- References cmWorkerPool* Pool = nullptr; }; void cmWorkerPool::ProcessResultT::reset() { ExitStatus = 0; TermSignal = 0; if (!StdOut.empty()) { StdOut.clear(); StdOut.shrink_to_fit(); } if (!StdErr.empty()) { StdErr.clear(); StdErr.shrink_to_fit(); } if (!ErrorMessage.empty()) { ErrorMessage.clear(); ErrorMessage.shrink_to_fit(); } } cmWorkerPoolInternal::cmWorkerPoolInternal(cmWorkerPool* pool) : Pool(pool) { // Initialize libuv loop uv_disable_stdio_inheritance(); #ifdef CMAKE_UV_SIGNAL_HACK UVHackRAII = cm::make_unique<cmUVSignalHackRAII>(); #endif UVLoop = cm::make_unique<uv_loop_t>(); uv_loop_init(UVLoop.get()); } cmWorkerPoolInternal::~cmWorkerPoolInternal() { uv_loop_close(UVLoop.get()); } bool cmWorkerPoolInternal::Process() { // Reset state flags Processing = true; Aborting = false; // Initialize libuv asynchronous request UVRequestBegin.init(*UVLoop, &cmWorkerPoolInternal::UVSlotBegin, this); UVRequestEnd.init(*UVLoop, &cmWorkerPoolInternal::UVSlotEnd, this); // Send begin request UVRequestBegin.send(); // Run libuv loop bool success = (uv_run(UVLoop.get(), UV_RUN_DEFAULT) == 0); // Update state flags Processing = false; Aborting = false; return success; } void cmWorkerPoolInternal::Abort() { bool notifyThreads = false; // Clear all jobs and set abort flag { std::lock_guard<std::mutex> guard(Mutex); if (Processing && !Aborting) { // Register abort and clear queue Aborting = true; Queue.clear(); notifyThreads = true; } } if (notifyThreads) { // Wake threads Condition.notify_all(); } } inline bool cmWorkerPoolInternal::PushJob(cmWorkerPool::JobHandleT&& jobHandle) { std::lock_guard<std::mutex> guard(Mutex); if (Aborting) { return false; } // Append the job to the queue Queue.emplace_back(std::move(jobHandle)); // Notify an idle worker if there's one if (WorkersIdle != 0) { Condition.notify_one(); } // Return success return true; } void cmWorkerPoolInternal::UVSlotBegin(uv_async_t* handle) { auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data); // Create worker threads { unsigned int const num = gint.Pool->ThreadCount(); // Create workers gint.Workers.reserve(num); for (unsigned int ii = 0; ii != num; ++ii) { gint.Workers.emplace_back( cm::make_unique<cmWorkerPoolWorker>(*gint.UVLoop)); } // Start worker threads for (unsigned int ii = 0; ii != num; ++ii) { gint.Workers[ii]->SetThread( std::thread(&cmWorkerPoolInternal::Work, &gint, ii)); } } // Destroy begin request gint.UVRequestBegin.reset(); } void cmWorkerPoolInternal::UVSlotEnd(uv_async_t* handle) { auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data); // Join and destroy worker threads gint.Workers.clear(); // Destroy end request gint.UVRequestEnd.reset(); } void cmWorkerPoolInternal::Work(unsigned int workerIndex) { cmWorkerPool::JobHandleT jobHandle; std::unique_lock<std::mutex> uLock(Mutex); // Increment running workers count ++WorkersRunning; // Enter worker main loop while (true) { // Abort on request if (Aborting) { break; } // Wait for new jobs if (Queue.empty()) { ++WorkersIdle; Condition.wait(uLock); --WorkersIdle; continue; } // Check for fence jobs if (FenceProcessing || Queue.front()->IsFence()) { if (JobsProcessing != 0) { Condition.wait(uLock); continue; } // No jobs get processed. Set the fence job processing flag. FenceProcessing = true; } // Pop next job from queue jobHandle = std::move(Queue.front()); Queue.pop_front(); // Unlocked scope for job processing ++JobsProcessing; { uLock.unlock(); jobHandle->Work(Pool, workerIndex); // Process job jobHandle.reset(); // Destroy job uLock.lock(); } --JobsProcessing; // Was this a fence job? if (FenceProcessing) { FenceProcessing = false; Condition.notify_all(); } } // Decrement running workers count if (--WorkersRunning == 0) { // Last worker thread about to finish. Send libuv event. UVRequestEnd.send(); } } cmWorkerPool::JobT::~JobT() = default; bool cmWorkerPool::JobT::RunProcess(ProcessResultT& result, std::vector<std::string> const& command, std::string const& workingDirectory) { // Get worker by index auto* wrk = Pool_->Int_->Workers.at(WorkerIndex_).get(); return wrk->RunProcess(result, command, workingDirectory); } cmWorkerPool::cmWorkerPool() : Int_(cm::make_unique<cmWorkerPoolInternal>(this)) { } cmWorkerPool::~cmWorkerPool() = default; void cmWorkerPool::SetThreadCount(unsigned int threadCount) { if (!Int_->Processing) { ThreadCount_ = (threadCount > 0) ? threadCount : 1u; } } bool cmWorkerPool::Process(void* userData) { // Setup user data UserData_ = userData; // Run libuv loop bool success = Int_->Process(); // Clear user data UserData_ = nullptr; // Return return success; } bool cmWorkerPool::PushJob(JobHandleT&& jobHandle) { return Int_->PushJob(std::move(jobHandle)); } void cmWorkerPool::Abort() { Int_->Abort(); }
26.429319
79
0.657934
[ "vector" ]
aa10112442e2008248bc541ac4010ccdef3f62a1
2,999
cpp
C++
src/oneDPL/complex_sum_soa.cpp
UoB-HPC/everythingsreduced
72e69dafdf0d155c35df38bfda7786d9f88c641a
[ "MIT" ]
null
null
null
src/oneDPL/complex_sum_soa.cpp
UoB-HPC/everythingsreduced
72e69dafdf0d155c35df38bfda7786d9f88c641a
[ "MIT" ]
5
2021-08-18T10:12:33.000Z
2021-09-10T13:21:18.000Z
src/oneDPL/complex_sum_soa.cpp
UoB-HPC/everythingsreduced
72e69dafdf0d155c35df38bfda7786d9f88c641a
[ "MIT" ]
1
2021-08-03T16:08:39.000Z
2021-08-03T16:08:39.000Z
// Copyright (c) 2021 Everything's Reduced authors // SPDX-License-Identifier: MIT #include <iostream> #include "../complex_sum_soa.hpp" #include "../sycl/common.hpp" #include <oneapi/dpl/algorithm> #include <oneapi/dpl/execution> template <typename T> struct complex_sum_soa<T>::data { data(long N) : real(N), imag(N), q(sycl::default_selector()) {} sycl::buffer<T> real; sycl::buffer<T> imag; sycl::queue q; }; template <typename T> complex_sum_soa<T>::complex_sum_soa(long N_) : N(N_), pdata{std::make_unique<data>(N)} { std::cout << config_string("Complex Sum SoA", pdata->q) << std::endl; } #define FUSE_KERNELS template <typename T> complex_sum_soa<T>::~complex_sum_soa() {} template <typename T> void complex_sum_soa<T>::setup() { auto exec_p = oneapi::dpl::execution::make_device_policy(pdata->q); const T val = 2.0 * 1024.0 / static_cast<T>(N); #ifdef FUSE_KERNELS #ifdef ZIP_FILL auto output = oneapi::dpl::make_zip_iterator(oneapi::dpl::begin(pdata->real), oneapi::dpl::begin(pdata->imag)); oneapi::dpl::fill(exec_p, output, output + N, std::make_tuple(val, val)); #else auto output = oneapi::dpl::make_zip_iterator(oneapi::dpl::begin(pdata->real), oneapi::dpl::begin(pdata->imag)); oneapi::dpl::transform(exec_p, oneapi::dpl::counting_iterator(0L), oneapi::dpl::counting_iterator(N), output, [=](const auto &) { return std::make_tuple(val, val); }); #endif // ZIP_FILL #else oneapi::dpl::fill(exec_p, oneapi::dpl::begin(pdata->real), oneapi::dpl::end(pdata->real), 2.0 * 1024.0 / static_cast<T>(N)); oneapi::dpl::fill(exec_p, oneapi::dpl::begin(pdata->imag), oneapi::dpl::end(pdata->imag), 2.0 * 1024.0 / static_cast<T>(N)); #endif // FUSE_KERNELS } template <typename T> void complex_sum_soa<T>::teardown() { pdata.reset(); // NOTE: All the data has been destroyed! } template <typename T> std::tuple<T, T> complex_sum_soa<T>::run() { auto exec_p = oneapi::dpl::execution::make_device_policy(pdata->q); #ifdef FUSE_KERNELS auto input = oneapi::dpl::make_zip_iterator(oneapi::dpl::begin(pdata->real), oneapi::dpl::begin(pdata->imag)); return oneapi::dpl::reduce(exec_p, input, input + N, std::make_tuple(T(), T()), [=](const auto &l, const auto &r) { return std::make_tuple(std::get<0>(l) + std::get<0>(r), std::get<1>(l) + std::get<1>(r)); }); #else return { oneapi::dpl::reduce(exec_p, oneapi::dpl::begin(pdata->real), oneapi::dpl::end(pdata->real)), oneapi::dpl::reduce(exec_p, oneapi::dpl::begin(pdata->imag), oneapi::dpl::end(pdata->imag)), }; #endif // FUSE_KERNELS } template struct complex_sum_soa<double>; template struct complex_sum_soa<float>;
34.471264
122
0.603868
[ "transform" ]
aa17c39b86fc2fb0140459e93d3e593e2fb7c5a8
1,907
cpp
C++
src/common.cpp
Izumemori/muscord-cpp
49cb50dc5ed17023b0c91f1699a9e9832b591bb5
[ "MIT" ]
2
2019-06-08T14:02:06.000Z
2019-06-22T12:55:34.000Z
src/common.cpp
Izumemori/muscord-cpp
49cb50dc5ed17023b0c91f1699a9e9832b591bb5
[ "MIT" ]
2
2020-04-02T04:31:15.000Z
2021-11-11T04:37:40.000Z
src/common.cpp
Izumemori/muscord-cpp
49cb50dc5ed17023b0c91f1699a9e9832b591bb5
[ "MIT" ]
null
null
null
#include "common.h" #include <cstdlib> #include <string> #include <sstream> #include <vector> #include <iterator> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> void muscord::replace(std::string& str, const std::string& from, const std::string& to) { size_t start_pos = str.find(from); if (start_pos == std::string::npos) return; str.replace(start_pos, from.length(), to); } template<typename Tout> void muscord::split(const std::string& s, char delimiter, Tout result) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delimiter)) { if (item.empty()) continue; *(result++) = item; } } std::string muscord::get_config_dir() { std::string config_home; char* xdg_config_home = std::getenv("XDG_CONFIG_HOME"); if (xdg_config_home) { config_home = xdg_config_home; delete xdg_config_home; return config_home; } char* user_home = std::getenv("HOME"); if (!user_home) throw std::runtime_error("Could not determine config location, ensure $HOME or $XDG_CONFIG_HOME are set"); return std::string(user_home) + "/.config"; } void muscord::ensure_config_dir_created(std::string& path) { DIR* dir = opendir(path.c_str()); if (dir) { closedir(dir); return; } const int dir_err = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (dir_err != 0) { std::cout << "Failed to create directory!" << std::endl; exit(1); } } std::string muscord::to_title_case(const std::string& input) { std::vector<std::string> words; split(input, ' ', std::back_inserter(words)); std::stringstream ss; for (auto& word : words) { word[0] = std::toupper(word[0]); ss << word; if (&word != &words.back()) ss << " "; } return ss.str(); }
24.766234
126
0.608285
[ "vector" ]
aa1997eb35d61725240408765112363de8ab20d7
12,651
cpp
C++
DivisionCore/Tile.cpp
Papishushi/Gametility
4220f89dbaa911422f9b96d70069e360c3748cc2
[ "MIT" ]
null
null
null
DivisionCore/Tile.cpp
Papishushi/Gametility
4220f89dbaa911422f9b96d70069e360c3748cc2
[ "MIT" ]
null
null
null
DivisionCore/Tile.cpp
Papishushi/Gametility
4220f89dbaa911422f9b96d70069e360c3748cc2
[ "MIT" ]
null
null
null
/** * @file Tile.cpp * @author Daniel Molinero Lucas (Papishushi) * @section Copyright © <2021+> <Daniel Molinero Lucas (Papishushi)> MIT LICENSE * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #include "ObjectMacros.h" #include "Tile.h" #include "Tilemap.h" #include "Dictionary.h" INCLUDE_OBJECT_STATIC namespace DivisionCore { namespace Core { namespace Tilemaps { Tile::Tile(const Tile &clone) { if (&clone != this) { state = clone.state; if (clone.tilemap->lenght == 0) { tilemap->lenght = 1.; } else { tilemap->lenght = clone.tilemap->lenght; } tilemap.reset(clone.tilemap.get()); for (unsigned x = 0; x < 3; x++) { for (unsigned y = 0; y < 3; y++) { neighbours(x, y) = clone.neighbours(x, y); } } position = clone.position; worldPosition = clone.worldPosition; } else { if (tilemap->lenght == 0) { tilemap->lenght = 1.; } position = Vectors::Vector2Int::Zero(); worldPosition = Vector2(position.coords[0] * tilemap->lenght, position.coords[0] * tilemap->lenght); state = 0; tilemap->grid.Add(VectorKeyValuePair<Vector, Tile *, 2, int>(position, this)); } UpdateCycle(); } Tile::Tile(const Tile *clone) { if (clone != this) { state = clone->state; if (clone->tilemap->lenght == 0) { tilemap->lenght = 1.; } else { tilemap->lenght = clone->tilemap->lenght; } tilemap.reset(clone->tilemap.get()); for (unsigned x = 0; x < 3; x++) { for (unsigned y = 0; y < 3; y++) { neighbours(x, y) = clone->neighbours(x, y); } } position = clone->position; worldPosition = clone->worldPosition; } else { if (tilemap->lenght == 0) { tilemap->lenght = 1.; } position = Vectors::Vector2Int::Zero(); worldPosition = Vector2(position.coords[0] * tilemap->lenght, position.coords[0] * tilemap->lenght); state = 0; tilemap->grid.Add(VectorKeyValuePair<Vector, Tile *, 2, int>(position, this)); } UpdateCycle(); } Tile::Tile(const Vector2Int &_position, Tilemap &_tilemap) { if (tilemap->lenght == 0) { tilemap->lenght = 1.; } position = _position; worldPosition = Vector2(_position.coords[0] * tilemap->lenght, _position.coords[0] * tilemap->lenght); state = 0; tilemap.reset(&_tilemap); tilemap->grid.Add(VectorKeyValuePair<Vector, Tile *, 2, int>(position, this)); UpdateCycle(); } Tile::Tile(const unique_ptr<Vector2Int> _position, Tilemap &_tilemap) { if (tilemap->lenght == 0) { tilemap->lenght = 1.; } #pragma warning (disable : 4068 ) /* Disable unknown pragma warnings */ #pragma clang diagnostic push /* Disable CLANG ide LocalValueEscapesScope warning */ #pragma ide diagnostic ignored "LocalValueEscapesScope" position = *_position; #pragma clang diagnostic pop worldPosition = Vector2(_position->coords[0] * tilemap->lenght, _position->coords[0] * tilemap->lenght); state = 0; tilemap.reset(&_tilemap); tilemap->grid.Add(VectorKeyValuePair<Vector, Tile *, 2, int>(position, this)); UpdateCycle(); } Tile::Tile(initializer_list<int> list, Tilemap &_tilemap) { if (tilemap->lenght == 0) { tilemap->lenght = 1.; } initializer_list<int>::iterator it; unsigned counter = 0; for (it = list.begin(); it < list.end(); ++it) { position.coords[counter] = *it; counter++; } worldPosition = Vector2(position.coords[0] * tilemap->lenght, position.coords[1] * tilemap->lenght); state = 0; tilemap.reset(&_tilemap); tilemap->grid.Add(VectorKeyValuePair<Vector, Tile *, 2, int>(position, this)); UpdateCycle(); } Tile::~Tile() { tilemap->grid.Remove(position); UpdateNeighbours(neighbours); } Tile &Tile::operator()(const int row, const int column) { return *(tilemap->GetTileAs(Vectors::Vector2Int(row, column))); } Tile *Tile::operator()(const int row, const int column) const { return tilemap->GetTileAs(Vectors::Vector2Int(row, column)); } bool Tile::GetNeighbours() { if (!tilemap->grid.empty()) { //Up-Midle neighbours.GetTop().reset(tilemap->GetTileAs(position + Vector2Int::Up())); //Down-Midle neighbours.GetDown().reset(tilemap->GetTileAs(position + Vector2Int::Down())); //Left-Midle neighbours.GetLeft().reset(tilemap->GetTileAs(position + Vector2Int::Left())); //Right-Midle neighbours.GetRight().reset(tilemap->GetTileAs(position + Vector2Int::Right())); //Right-up neighbours.GetRightTopCorner().reset( tilemap->GetTileAs(position + Vector2Int::Up() + Vector2Int::Right())); //Left-Up neighbours.GetLeftTopCorner().reset( tilemap->GetTileAs(position + Vector2Int::Up() + Vector2Int::Left())); //Right-Down neighbours.GetRightDownCorner().reset( tilemap->GetTileAs(position + Vector2Int::Down() + Vector2Int::Right())); //Left-Down neighbours.GetLeftDownCorner().reset(tilemap->GetTileAs(position + Vector2Int::Left())); //Center neighbours.GetCenter().reset(std::make_shared<Tile>(this).get()); return true; } else { return false; } /*1 2 3 4 0 5 6 7 8*/ } bool Tile::UpdateNeighbours(const NeighbourTemplate<Tile> &filteredNeighbours) { /*1 2 3 4 0 5 6 7 8*/ bool returnValue = true; //Up-Midle if (filteredNeighbours.GetTop()) { if (!filteredNeighbours.GetTop()->UpdateCycle(neighbours)) { returnValue = false; } } //Down-Midle if (filteredNeighbours.GetDown()) { if (!filteredNeighbours.GetDown()->UpdateCycle(neighbours)) { returnValue = false; } } //Left-Midle if (!filteredNeighbours.GetLeft() || !filteredNeighbours.GetLeft()->UpdateCycle(neighbours)) { returnValue = false; } //Right-Midle if (!filteredNeighbours.GetRight() || !filteredNeighbours.GetRight()->UpdateCycle(neighbours)) { returnValue = false; } //Right-up if (!filteredNeighbours.GetRightTopCorner() || !filteredNeighbours.GetRightTopCorner()->UpdateCycle(neighbours)) { returnValue = false; } //Left-Up if (!filteredNeighbours.GetLeftTopCorner() || !filteredNeighbours.GetLeftTopCorner()->UpdateCycle(neighbours)) { returnValue = false; } //Right-Down if (!filteredNeighbours.GetRightDownCorner() || !filteredNeighbours.GetRightDownCorner()->UpdateCycle(neighbours)) { returnValue = false; } //Left-Down if (!filteredNeighbours.GetLeftDownCorner() || !filteredNeighbours.GetLeftDownCorner()->UpdateCycle(neighbours)) { returnValue = false; } return returnValue; } NeighbourTemplate<Tile> Tile::FilterNeighboursToUpdate(const NeighbourTemplate<Tile> &other) const { NeighbourTemplate<Tile> filteredNeighbours; for (unsigned x = 0; x < 3; x++) { for (unsigned y = 0; y < 3; y++) { auto temp = neighbours(x, y).lock() == other(x, y).lock() ? std::make_shared<Tile>(nullptr) : neighbours(x, y); filteredNeighbours(x, y) = temp; } } return filteredNeighbours; } unsigned Tile::FindTileState() const { unsigned tempState = 0; if (IsCenter()) { tempState = 1; } else { if (IsIsolated()) { tempState = 2; } else { if (IsDownEnd()) { } else if (IsUpEnd()) { } else if (IsLeftEnd()) { } else if (IsRightEnd()) { } else { } } } return tempState; } bool Tile::UpdateCycle() { /*1 2 3 4 0 5 6 7 8*/ if (GetNeighbours()) { if (UpdateNeighbours(neighbours)) { state = FindTileState(); return true; } else { return false; } } else { return false; } } bool Tile::UpdateCycle(const NeighbourTemplate<Tile> &_neighbours) { /*1 2 3 4 0 5 6 7 8*/ if (GetNeighbours()) { if (UpdateNeighbours(FilterNeighboursToUpdate(_neighbours))) { state = FindTileState(); return true; } else { return false; } } else { return false; } } } } }
36.776163
161
0.460991
[ "vector" ]
aa1a405eca8ba9744728a33ff5171f1fbcc7cbfe
23,147
hpp
C++
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/distributions_R.hpp
rebeccagb/gtsummary
04996e385acab0b76a9938378e8af87526117aef
[ "MIT" ]
null
null
null
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/distributions_R.hpp
rebeccagb/gtsummary
04996e385acab0b76a9938378e8af87526117aef
[ "MIT" ]
null
null
null
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/distributions_R.hpp
rebeccagb/gtsummary
04996e385acab0b76a9938378e8af87526117aef
[ "MIT" ]
null
null
null
// Copyright (C) 2013-2015 Kasper Kristensen // License: GPL-2 /** \file \brief Probability distribution functions. */ /** \brief Distribution function of the normal distribution (following R argument convention). \ingroup R_style_distribution */ template<class Type> Type pnorm(Type q, Type mean = 0., Type sd = 1.){ CppAD::vector<Type> tx(1); tx[0] = (q - mean) / sd; return atomic::pnorm1(tx)[0]; } VECTORIZE3_ttt(pnorm) VECTORIZE1_t(pnorm) /** \brief Quantile function of the normal distribution (following R argument convention). \ingroup R_style_distribution */ template<class Type> Type qnorm(Type p, Type mean = 0., Type sd = 1.){ CppAD::vector<Type> tx(1); tx[0] = p; return sd*atomic::qnorm1(tx)[0] + mean; } VECTORIZE3_ttt(qnorm) VECTORIZE1_t(qnorm) /** \brief Distribution function of the gamma distribution (following R argument convention). \ingroup R_style_distribution */ template<class Type> Type pgamma(Type q, Type shape, Type scale = 1.){ CppAD::vector<Type> tx(4); tx[0] = q/scale; tx[1] = shape; tx[2] = Type(0); // 0'order deriv tx[3] = -lgamma(shape); // normalize return atomic::D_incpl_gamma_shape(tx)[0]; } VECTORIZE3_ttt(pgamma) /** \brief Quantile function of the gamma distribution (following R argument convention). \ingroup R_style_distribution */ template<class Type> Type qgamma(Type q, Type shape, Type scale = 1.){ CppAD::vector<Type> tx(3); tx[0] = q; tx[1] = shape; tx[2] = -lgamma(shape); // normalize return atomic::inv_incpl_gamma(tx)[0] * scale; } VECTORIZE3_ttt(qgamma) /** \brief Distribution function of the poisson distribution (following R argument convention). \ingroup R_style_distribution */ template<class Type> Type ppois(Type q, Type lambda){ CppAD::vector<Type> tx(2); tx[0] = q; tx[1] = lambda; return atomic::ppois(tx)[0]; } VECTORIZE2_tt(ppois) /** @name Exponential distribution. Functions relative to the exponential distribution. */ /**@{*/ /** \brief Cumulative distribution function of the exponential distribution. \ingroup R_style_distribution \param rate Rate parameter. Must be strictly positive. */ template<class Type> Type pexp(Type x, Type rate) { return CppAD::CondExpGe(x,Type(0),1-exp(-rate*x),Type(0)); } // Vectorize pexp VECTORIZE2_tt(pexp) /** \brief Probability density function of the exponential distribution. \ingroup R_style_distribution \param rate Rate parameter. Must be strictly positive. \param give_log true if one wants the log-probability, false otherwise. */ template<class Type> Type dexp(Type x, Type rate, int give_log=0) { if(!give_log) return CppAD::CondExpGe(x,Type(0),rate*exp(-rate*x),Type(0)); else return CppAD::CondExpGe(x,Type(0),log(rate)-rate*x,Type(-INFINITY)); } // Vectorize dexp VECTORIZE3_tti(dexp) /** \brief Inverse cumulative distribution function of the exponential distribution. \ingroup R_style_distribution \param rate Rate parameter. Must be strictly positive. */ template <class Type> Type qexp(Type p, Type rate) { return -log(1-p)/rate; } // Vectorize qexp. VECTORIZE2_tt(qexp) /**@}*/ /** @name Weibull distribution. Functions relative to the Weibull distribution. */ /**@{*/ /** \brief Cumulative distribution function of the Weibull distribution. \ingroup R_style_distribution \param shape Shape parameter. Must be strictly positive. \param scale Scale parameter. Must be strictly positive. */ template<class Type> Type pweibull(Type x, Type shape, Type scale) { return CppAD::CondExpGe(x,Type(0),1-exp(-pow(x/scale,shape)),Type(0)); } // Vectorize pweibull VECTORIZE3_ttt(pweibull) /** \brief Probability density function of the Weibull distribution. \ingroup R_style_distribution \param shape Shape parameter. Must be strictly positive. \param scale Scale parameter. Must be strictly positive. \param give_log true if one wants the log-probability, false otherwise. */ template<class Type> Type dweibull(Type x, Type shape, Type scale, int give_log=0) { if(!give_log) return CppAD::CondExpGe(x,Type(0),shape/scale * pow(x/scale,shape-1) * exp(-pow(x/scale,shape)),Type(0)); else return CppAD::CondExpGe(x,Type(0),log(shape) - log(scale) + (shape-1)*(log(x)-log(scale)) - pow(x/scale,shape),Type(-INFINITY)); } // Vectorize dweibull VECTORIZE4_ttti(dweibull) /** \brief Inverse cumulative distribution function of the Weibull distribution. \ingroup R_style_distribution \param p Probability ; must be between 0 and 1. \param shape Shape parameter. Must be strictly positive. \param scale Scale parameter. Must be strictly positive. */ template<class Type> Type qweibull(Type p, Type shape, Type scale) { Type res = scale * pow( (-log(1-p)) , 1/shape ); res = CppAD::CondExpLt(p,Type(0),Type(0),res); res = CppAD::CondExpGt(p,Type(1),Type(0),res); return res; } // Vectorize qweibull VECTORIZE3_ttt(qweibull) /**@}*/ /** \brief Probability mass function of the binomial distribution. \ingroup R_style_distribution \param k Number of successes. \param size Number of trials. \param prob Probability of success. \param give_log true if one wants the log-probability, false otherwise. */ template<class Type> Type dbinom(Type k, Type size, Type prob, int give_log=0) { Type logres = lgamma(size + 1) - lgamma(k + 1) - lgamma(size - k + 1); // Add 'k * log(prob)' only if k > 0 logres += CppAD::CondExpGt(k, Type(0), k * log(prob), Type(0) ); // Add '(size - k) * log(1 - prob)' only if size > k logres += CppAD::CondExpGt(size, k, (size - k) * log(1 - prob), Type(0) ); if (!give_log) return exp(logres); else return logres; } // Vectorize dbinom VECTORIZE4_ttti(dbinom) /** \brief Density of binomial distribution parameterized via logit(prob) This version should be preferred when working on the logit scale as it is numerically stable for probabilities close to 0 or 1. \ingroup R_style_distribution */ template<class Type> Type dbinom_robust(Type k, Type size, Type logit_p, int give_log=0) { CppAD::vector<Type> tx(4); tx[0] = k; tx[1] = size; tx[2] = logit_p; tx[3] = 0; Type ans = atomic::log_dbinom_robust(tx)[0]; /* without norm. constant */ if (size > 1) { ans += lgamma(size+1.) - lgamma(k+1.) - lgamma(size-k+1.); } return ( give_log ? ans : exp(ans) ); } VECTORIZE4_ttti(dbinom_robust) /** \brief Probability density function of the beta distribution. \ingroup R_style_distribution \param shape1 First shape parameter. Must be strictly positive. \param shape2 Second shape parameter. Must be strictly positive. \param give_log true if one wants the log-probability, false otherwise. */ template <class Type> Type dbeta(Type x, Type shape1, Type shape2, int give_log) { Type res = exp(lgamma(shape1+shape2) - lgamma(shape1) - lgamma(shape2)) * pow(x,shape1-1) * pow(1-x,shape2-1); if(!give_log) return res; else return CppAD::CondExpEq(x,Type(0),log(res),lgamma(shape1+shape2) - lgamma(shape1) - lgamma(shape2) + (shape1-1)*log(x) + (shape2-1)*log(1-x)); } // Vectorize dbeta VECTORIZE4_ttti(dbeta) /** \brief Probability density function of the Fisher distribution. \ingroup R_style_distribution \param df1 Degrees of freedom 1. \param df2 Degrees of freedom 2. \param give_log true if one wants the log-probability, false otherwise. */ template <class Type> Type df(Type x, Type df1, Type df2, int give_log) { Type logres = lgamma((df1+df2)/2.) - lgamma(df1/2.) - lgamma(df2/2.) + df1/2.*log(Type(df1)/df2) + (df1/2.-1)*log(x) - (df1+df2)/2.*log(1+Type(df1)/df2*x); if(!give_log) return exp(logres); else return logres; } //Vectorize df VECTORIZE4_ttti(df) /** \brief Probability density function of the logistic distribution. \ingroup R_style_distribution \param location Location parameter. \param scale Scale parameter. Must be strictly positive. \param give_log true if one wants the log-probability, false otherwise. */ template <class Type> Type dlogis(Type x, Type location, Type scale, int give_log) { Type logres = -(x-location)/scale - log(scale) - 2*log(1+exp(-(x-location)/scale)); if(!give_log) return exp(logres); else return logres; } // Vectorize dlogis VECTORIZE4_ttti(dlogis) /** \brief Probability density function of the skew-normal distribution. \ingroup R_style_distribution \param alpha Slant parameter. \param give_log true if one wants the log-probability, false otherwise. */ template <class Type> Type dsn(Type x, Type alpha, int give_log=0) { if(!give_log) return 2 * dnorm(x,Type(0),Type(1),0) * pnorm(alpha*x); else return log(2.0) + log(dnorm(x,Type(0),Type(1),0)) + log(pnorm(alpha*x)); } // Vectorize dsn VECTORIZE3_tti(dsn) /** \brief Probability density function of the Student t-distribution. \ingroup R_style_distribution \param df Degree of freedom. \param give_log true if one wants the log-probability, false otherwise. */ template <class Type> Type dt(Type x, Type df, int give_log) { Type logres = lgamma((df+1)/2) - Type(1)/2*log(df*M_PI) -lgamma(df/2) - (df+1)/2*log(1+x*x/df); if(!give_log) return exp(logres); else return logres; } // Vectorize dt VECTORIZE3_tti(dt) /** \brief Probability mass function of the multinomial distribution. \ingroup R_style_distribution \param x Vector of length K of integers. \param p Vector of length K, specifying the probability for the K classes (note, unlike in R these must sum to 1). \param give_log true if one wants the log-probability, false otherwise. */ template <class Type> Type dmultinom(vector<Type> x, vector<Type> p, int give_log=0) { vector<Type> xp1 = x+Type(1); Type logres = lgamma(x.sum() + Type(1)) - lgamma(xp1).sum() + (x*log(p)).sum(); if(give_log) return logres; else return exp(logres); } /** @name Sinh-asinh distribution. Functions relative to the sinh-asinh distribution. */ /**@{*/ /** \brief Probability density function of the sinh-asinh distribution. \ingroup R_style_distribution \param mu Location. \param sigma Scale. \param nu Skewness. \param tau Kurtosis. \param give_log true if one wants the log-probability, false otherwise. Notation adopted from R package "gamlss.dist". Probability density given in (2) in __Jones and Pewsey (2009) Biometrika (2009) 96 (4): 761-780__. It is not possible to call this function with nu a vector or tau a vector. */ template <class Type> Type dSHASHo(Type x, Type mu, Type sigma, Type nu, Type tau, int give_log = 0) { // TODO : Replace log(x+sqrt(x^2+1)) by a better approximation for asinh(x). Type z = (x-mu)/sigma; Type c = cosh(tau*log(z+sqrt(z*z+1))-nu); Type r = sinh(tau*log(z+sqrt(z*z+1))-nu); Type logres = -log(sigma) + log(tau) -0.5*log(2*M_PI) -0.5*log(1+(z*z)) +log(c) -0.5*(r*r); if(!give_log) return exp(logres); else return logres; } // Vectorize dSHASHo VECTORIZE6_ttttti(dSHASHo) /** \brief Cumulative distribution function of the sinh-asinh distribution. \ingroup R_style_distribution \param mu Location. \param sigma Scale. \param nu Skewness. \param tau Kurtosis. \param give_log true if one wants the log-probability, false otherwise. Notation adopted from R package "gamlss.dist". It is not possible to call this function with nu a vector or tau a vector. */ template <class Type> Type pSHASHo(Type q,Type mu,Type sigma,Type nu,Type tau,int give_log=0) { // TODO : Replace log(x+sqrt(x^2+1)) by a better approximation for asinh(x). Type z = (q-mu)/sigma; Type r = sinh(tau * log(z+sqrt(z*z+1)) - nu); Type p = pnorm(r); if (!give_log) return p; else return log(p); } // Vectorize pSHASHo VECTORIZE6_ttttti(pSHASHo) /** \brief Quantile function of the sinh-asinh distribution. \ingroup R_style_distribution \param mu Location. \param sigma Scale. \param nu Skewness. \param tau Kurtosis. \param log_p true if p is log-probability, false otherwise. Notation adopted from R package "gamlss.dist". It is not possible to call this function with nu a vector or tau a vector. */ template <class Type> Type qSHASHo(Type p, Type mu, Type sigma, Type nu, Type tau, int log_p = 0) { // TODO : Replace log(x+sqrt(x^2+1)) by a better approximation for asinh(x). if(!log_p) return mu + sigma*sinh((1/tau)* log(qnorm(p)+sqrt(qnorm(p)*qnorm(p)+1)) + (nu/tau)); else return mu + sigma*sinh((1/tau)*log(qnorm(exp(p))+sqrt(qnorm(exp(p))*qnorm(exp(p))+1))+(nu/tau)); } // Vectorize qSHASHo VECTORIZE6_ttttti(qSHASHo) /** \brief Transforms a normal variable into a sinh-asinh variable. \param mu Location parameter of the result sinh-asinh distribution. \param sigma Scale parameter of the result sinh-asinh distribution. \param nu Skewness parameter of the result sinh-asinh distribution. \param tau Kurtosis parameter of the result sinh-asinh distribution. \param log_p true if p is log-probability, false otherwise. It is not possible to call this function with nu a vector or tau a vector. */ template <class Type> Type norm2SHASHo(Type x, Type mu, Type sigma, Type nu, Type tau, int log_p = 0) { return qSHASHo(pnorm(x),mu,sigma,nu,tau,log_p); } // Vectorize norm2SHASHo VECTORIZE6_ttttti(norm2SHASHo) /**@}*/ /** \brief Distribution function of the beta distribution (following R argument convention). \note Non-centrality parameter (ncp) not implemented. \ingroup R_style_distribution */ template<class Type> Type pbeta(Type q, Type shape1, Type shape2){ CppAD::vector<Type> tx(4); tx[0] = q; tx[1] = shape1; tx[2] = shape2; tx[3] = 0; // order Type ans = atomic::pbeta(tx)[0]; return ans; } VECTORIZE3_ttt(pbeta) /** \brief Quantile function of the beta distribution (following R argument convention). \note Non-centrality parameter (ncp) not implemented. \ingroup R_style_distribution */ template<class Type> Type qbeta(Type p, Type shape1, Type shape2){ CppAD::vector<Type> tx(3); tx[0] = p; tx[1] = shape1; tx[2] = shape2; Type ans = atomic::qbeta(tx)[0]; return ans; } VECTORIZE3_ttt(qbeta) /** \brief besselK function (same as besselK from R). \note Derivatives wrt. both arguments are implemented \ingroup special_functions */ template<class Type> Type besselK(Type x, Type nu){ Type ans; if(CppAD::Variable(nu)) { CppAD::vector<Type> tx(3); tx[0] = x; tx[1] = nu; tx[2] = 0; ans = atomic::bessel_k(tx)[0]; } else { CppAD::vector<Type> tx(2); tx[0] = x; tx[1] = nu; ans = atomic::bessel_k_10(tx)[0]; } return ans; } VECTORIZE2_tt(besselK) /** \brief besselI function (same as besselI from R). \note Derivatives wrt. both arguments are implemented \ingroup special_functions */ template<class Type> Type besselI(Type x, Type nu){ Type ans; if(CppAD::Variable(nu)) { CppAD::vector<Type> tx(3); tx[0] = x; tx[1] = nu; tx[2] = 0; ans = atomic::bessel_i(tx)[0]; } else { CppAD::vector<Type> tx(2); tx[0] = x; tx[1] = nu; ans = atomic::bessel_i_10(tx)[0]; } return ans; } VECTORIZE2_tt(besselI) /** \brief besselJ function (same as besselJ from R). \note Derivatives wrt. both arguments are implemented \ingroup special_functions */ template<class Type> Type besselJ(Type x, Type nu){ CppAD::vector<Type> tx(3); tx[0] = x; tx[1] = nu; tx[2] = 0; Type ans = atomic::bessel_j(tx)[0]; return ans; } VECTORIZE2_tt(besselJ) /** \brief besselY function (same as besselY from R). \note Derivatives wrt. both arguments are implemented \ingroup special_functions */ template<class Type> Type besselY(Type x, Type nu){ CppAD::vector<Type> tx(3); tx[0] = x; tx[1] = nu; tx[2] = 0; Type ans = atomic::bessel_y(tx)[0]; return ans; } VECTORIZE2_tt(besselY) /** \brief dtweedie function (same as dtweedie.series from R package 'tweedie'). Silently returns NaN if not within the valid parameter range: \f[ (0 \leq y) \land (0 < \mu) \land (0 < \phi) \land (1 < p) \land (p < 2) \f] . \note Parameter order differs from the R version. \warning The derivative wrt. the y argument is disabled (zero). Hence the tweedie distribution can only be used for *data* (not random effects). \ingroup R_style_distribution */ template<class Type> Type dtweedie(Type y, Type mu, Type phi, Type p, int give_log = 0) { Type p1 = p - 1.0, p2 = 2.0 - p; Type ans = -pow(mu, p2) / (phi * p2); // log(prob(y=0)) if (y > 0) { CppAD::vector<Type> tx(4); tx[0] = y; tx[1] = phi; tx[2] = p; tx[3] = 0; ans += atomic::tweedie_logW(tx)[0]; ans += -y / (phi * p1 * pow(mu, p1)) - log(y); } return ( give_log ? ans : exp(ans) ); } VECTORIZE5_tttti(dtweedie) /** \brief Conway-Maxwell-Poisson log normalizing constant. \f[ Z(\lambda, \nu) = \sum_{i=0}^{\infty} \frac{\lambda^i}{(i!)^\nu} \f] . \param loglambda \f$ \log(\lambda) \f$ \param nu \f$ \nu \f$ \return \f$ \log Z(\lambda, \nu) \f$ */ template<class Type> Type compois_calc_logZ(Type loglambda, Type nu) { CppAD::vector<Type> tx(3); tx[0] = loglambda; tx[1] = nu; tx[2] = 0; return atomic::compois_calc_logZ(tx)[0]; } VECTORIZE2_tt(compois_calc_logZ) /** \brief Conway-Maxwell-Poisson. Calculate log(lambda) from log(mean). \param logmean \f$ \log(E[X]) \f$ \param nu \f$ \nu \f$ \return \f$ \log \lambda \f$ */ template<class Type> Type compois_calc_loglambda(Type logmean, Type nu) { CppAD::vector<Type> tx(3); tx[0] = logmean; tx[1] = nu; tx[2] = 0; return atomic::compois_calc_loglambda(tx)[0]; } VECTORIZE2_tt(compois_calc_loglambda) /** \brief Conway-Maxwell-Poisson. Calculate density. \f[ P(X=x) \propto \frac{\lambda^x}{(x!)^\nu}\:,x=0,1,\ldots \f] Silently returns NaN if not within the valid parameter range: \f[ (0 \leq x) \land (0 < \lambda) \land (0 < \nu) \f] . \param x Observation \param mode Approximate mode \f$ \lambda^\frac{1}{\nu} \f$ \param nu \f$ \nu \f$ \ingroup R_style_distribution */ template<class T1, class T2, class T3> T1 dcompois(T1 x, T2 mode, T3 nu, int give_log = 0) { T2 loglambda = nu * log(mode); T1 ans = x * loglambda - nu * lfactorial(x); ans -= compois_calc_logZ(loglambda, nu); return ( give_log ? ans : exp(ans) ); } /** \brief Conway-Maxwell-Poisson. Calculate density parameterized via the mean. Silently returns NaN if not within the valid parameter range: \f[ (0 \leq x) \land (0 < E[X]) \land (0 < \nu) \f] . \param x Observation \param mean \f$ E[X] \f$ \param nu \f$ \nu \f$ \ingroup R_style_distribution */ template<class T1, class T2, class T3> T1 dcompois2(T1 x, T2 mean, T3 nu, int give_log = 0) { T2 logmean = log(mean); T2 loglambda = compois_calc_loglambda(logmean, nu); T1 ans = x * loglambda - nu * lfactorial(x); ans -= compois_calc_logZ(loglambda, nu); return ( give_log ? ans : exp(ans) ); } /********************************************************************/ /* SIMULATON CODE */ /********************************************************************/ extern "C" { double Rf_rnorm(double mu, double sigma); } /** \brief Simulate from a normal distribution */ template<class Type> Type rnorm(Type mu, Type sigma) { return Rf_rnorm(asDouble(mu), asDouble(sigma)); } VECTORIZE2_tt(rnorm) VECTORIZE2_n(rnorm) extern "C" { double Rf_rpois(double mu); } /** \brief Simulate from a Poisson distribution */ template<class Type> Type rpois(Type mu) { return Rf_rpois(asDouble(mu)); } VECTORIZE1_t(rpois) VECTORIZE1_n(rpois) extern "C" { double Rf_runif(double a, double b); } /** \brief Simulate from a uniform distribution */ template<class Type> Type runif(Type a, Type b) { return Rf_runif(asDouble(a), asDouble(b)); } VECTORIZE2_tt(runif) VECTORIZE2_n(runif) extern "C" { double Rf_rbinom(double size, double prob); } /** \brief Simulate from a binomial distribution */ template<class Type> Type rbinom(Type size, Type prob) { return Rf_rbinom(asDouble(size), asDouble(prob)); } VECTORIZE2_tt(rbinom) VECTORIZE2_n(rbinom) extern "C" { double Rf_rgamma(double shape, double scale); } /** \brief Simulate from a gamma distribution */ template<class Type> Type rgamma(Type shape, Type scale) { return Rf_rgamma(asDouble(shape), asDouble(scale)); } VECTORIZE2_tt(rgamma) VECTORIZE2_n(rgamma) extern "C" { double Rf_rexp(double rate); } /** \brief Simulate from an exponential distribution */ template<class Type> Type rexp(Type rate) { return Rf_rexp(asDouble(rate)); } VECTORIZE1_t(rexp) VECTORIZE1_n(rexp) extern "C" { double Rf_rbeta(double shape1, double shape2); } /** \brief Simulate from a beta distribution */ template<class Type> Type rbeta(Type shape1, Type shape2) { return Rf_rbeta(asDouble(shape1), asDouble(shape2)); } VECTORIZE2_tt(rbeta) VECTORIZE2_n(rbeta) extern "C" { double Rf_rf(double df1, double df2); } /** \brief Simulate from an F distribution */ template<class Type> Type rf(Type df1, Type df2) { return Rf_rf(asDouble(df1), asDouble(df2)); } VECTORIZE2_tt(rf) VECTORIZE2_n(rf) extern "C" { double Rf_rlogis(double location, double scale); } /** \brief Simulate from a logistic distribution */ template<class Type> Type rlogis(Type location, Type scale) { return Rf_rlogis(asDouble(location), asDouble(scale)); } VECTORIZE2_tt(rlogis) VECTORIZE2_n(rlogis) extern "C" { double Rf_rt(double df); } /** \brief Simulate from a Student's t distribution */ template<class Type> Type rt(Type df) { return Rf_rt(asDouble(df)); } VECTORIZE1_t(rt) VECTORIZE1_n(rt) extern "C" { double Rf_rweibull(double shape, double scale); } /** \brief Simulate from a Weibull distribution */ template<class Type> Type rweibull(Type shape, Type scale) { return Rf_rweibull(asDouble(shape), asDouble(scale)); } VECTORIZE2_tt(rweibull) VECTORIZE2_n(rweibull) /** \brief Simulate from a Conway-Maxwell-Poisson distribution */ template<class Type> Type rcompois(Type mode, Type nu) { Type loglambda = nu * log(mode); return atomic::compois_utils::simulate(asDouble(loglambda), asDouble(nu)); } VECTORIZE2_tt(rcompois) VECTORIZE2_n(rcompois) /** \brief Simulate from a Conway-Maxwell-Poisson distribution */ template<class Type> Type rcompois2(Type mean, Type nu) { Type logmean = log(mean); Type loglambda = compois_calc_loglambda(logmean, nu); return atomic::compois_utils::simulate(asDouble(loglambda), asDouble(nu)); } VECTORIZE2_tt(rcompois2) // Note: Vectorize manually to avoid many identical calls to // 'calc_loglambda'. template<class Type> vector<Type> rcompois2(int n, Type mean, Type nu) { Type logmean = log(mean); Type loglambda = compois_calc_loglambda(logmean, nu); Type mode = exp(loglambda / nu); return rcompois(n, mode, nu); } /** \brief Simulate from tweedie distribution */ template<class Type> Type rtweedie(Type mu, Type phi, Type p) { // Copied from R function tweedie::rtweedie Type lambda = pow(mu, 2. - p) / (phi * (2. - p)); Type alpha = (2. - p) / (1. - p); Type gam = phi * (p - 1.) * pow(mu, p - 1.); Type N = rpois(lambda); Type ans = rgamma( -alpha * N /* shape */, gam /* scale */); return ans; } VECTORIZE3_ttt(rtweedie) VECTORIZE3_n(rtweedie)
27.787515
156
0.687476
[ "shape", "vector" ]
aa1b9ea83312974d24a32022ad3e7073f8564436
541
hpp
C++
taskflow/sanitizer/nonreachable_sanitizer.hpp
junlinmessi/taskflow
9339b395742e63b0937760cff434f21f19d6ff53
[ "MIT" ]
318
2021-08-20T10:16:12.000Z
2022-03-24T03:08:16.000Z
Source/IntegratedExternals/taskflow/sanitizer/nonreachable_sanitizer.hpp
s-nase/XeGTAO
11e439c33e3dd7c1e4ea0fc73733ca840bc95bec
[ "MIT" ]
5
2021-09-03T11:40:54.000Z
2022-02-09T12:37:12.000Z
Source/IntegratedExternals/taskflow/sanitizer/nonreachable_sanitizer.hpp
s-nase/XeGTAO
11e439c33e3dd7c1e4ea0fc73733ca840bc95bec
[ "MIT" ]
22
2021-09-02T03:33:18.000Z
2022-02-23T06:36:39.000Z
#pragma once #include "../core/taskflow.hpp" namespace tf { class NonReachableSanitizer { struct nrsNode { bool reachable {false}; Node* node {nullptr}; }; struct nrsGraph { std::vector<nrsNode> nodes; }; public: NonReachableSanitizer(const Taskflow& taskflow) : _taskflow {taskflow} { } std::vector<Task> operator ()(std::ostream& ) { // copy _taskflow to _graph return {}; } private: const Taskflow& _taskflow; nrsGraph _graph; }; } // end of namespace tf
14.236842
76
0.613678
[ "vector" ]
aa260b38f76cea65d50eec4ad9a9ba9b2632b055
13,828
cpp
C++
third_party/WebKit/Source/bindings/core/v8/ScriptCustomElementDefinition.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/core/v8/ScriptCustomElementDefinition.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/core/v8/ScriptCustomElementDefinition.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "bindings/core/v8/ScriptCustomElementDefinition.h" #include "bindings/core/v8/V8BindingForCore.h" #include "bindings/core/v8/V8CustomElementRegistry.h" #include "bindings/core/v8/V8Element.h" #include "bindings/core/v8/V8ErrorHandler.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "bindings/core/v8/V8ThrowDOMException.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/events/ErrorEvent.h" #include "core/html/HTMLElement.h" #include "core/html/custom/CustomElement.h" #include "core/html/imports/HTMLImportsController.h" #include "platform/bindings/ScriptState.h" #include "platform/bindings/V8BindingMacros.h" #include "platform/bindings/V8PrivateProperty.h" #include "platform/wtf/Allocator.h" #include "v8.h" namespace blink { ScriptCustomElementDefinition* ScriptCustomElementDefinition::ForConstructor( ScriptState* script_state, CustomElementRegistry* registry, const v8::Local<v8::Value>& constructor) { V8PerContextData* per_context_data = script_state->PerContextData(); // TODO(yukishiino): Remove this check when crbug.com/583429 is fixed. if (UNLIKELY(!per_context_data)) return nullptr; auto private_id = per_context_data->GetPrivateCustomElementDefinitionId(); v8::Local<v8::Value> id_value; if (!constructor.As<v8::Object>() ->GetPrivate(script_state->GetContext(), private_id) .ToLocal(&id_value)) return nullptr; if (!id_value->IsUint32()) return nullptr; uint32_t id = id_value.As<v8::Uint32>()->Value(); // This downcast is safe because only ScriptCustomElementDefinitions // have an ID associated with them. This relies on three things: // // 1. Only ScriptCustomElementDefinition::Create sets the private // property on a constructor. // // 2. CustomElementRegistry adds ScriptCustomElementDefinitions // assigned an ID to the list of definitions without fail. // // 3. The relationship between the CustomElementRegistry and its // private property is never mixed up; this is guaranteed by the // bindings system because the registry is associated with its // context. // // At a meta-level, this downcast is safe because there is // currently only one implementation of CustomElementDefinition in // product code and that is ScriptCustomElementDefinition. But // that may change in the future. CustomElementDefinition* definition = registry->DefinitionForId(id); CHECK(definition); return static_cast<ScriptCustomElementDefinition*>(definition); } ScriptCustomElementDefinition* ScriptCustomElementDefinition::Create( ScriptState* script_state, CustomElementRegistry* registry, const CustomElementDescriptor& descriptor, CustomElementDefinition::Id id, const v8::Local<v8::Object>& constructor, const v8::Local<v8::Function>& connected_callback, const v8::Local<v8::Function>& disconnected_callback, const v8::Local<v8::Function>& adopted_callback, const v8::Local<v8::Function>& attribute_changed_callback, HashSet<AtomicString>&& observed_attributes) { ScriptCustomElementDefinition* definition = new ScriptCustomElementDefinition( script_state, descriptor, constructor, connected_callback, disconnected_callback, adopted_callback, attribute_changed_callback, std::move(observed_attributes)); // Tag the JavaScript constructor object with its ID. v8::Local<v8::Value> id_value = v8::Integer::NewFromUnsigned(script_state->GetIsolate(), id); auto private_id = script_state->PerContextData()->GetPrivateCustomElementDefinitionId(); CHECK( constructor->SetPrivate(script_state->GetContext(), private_id, id_value) .ToChecked()); return definition; } ScriptCustomElementDefinition::ScriptCustomElementDefinition( ScriptState* script_state, const CustomElementDescriptor& descriptor, const v8::Local<v8::Object>& constructor, const v8::Local<v8::Function>& connected_callback, const v8::Local<v8::Function>& disconnected_callback, const v8::Local<v8::Function>& adopted_callback, const v8::Local<v8::Function>& attribute_changed_callback, HashSet<AtomicString>&& observed_attributes) : CustomElementDefinition(descriptor, std::move(observed_attributes)), script_state_(script_state), constructor_(script_state->GetIsolate(), this, constructor), connected_callback_(this), disconnected_callback_(this), adopted_callback_(this), attribute_changed_callback_(this) { v8::Isolate* isolate = script_state->GetIsolate(); if (!connected_callback.IsEmpty()) connected_callback_.Set(isolate, connected_callback); if (!disconnected_callback.IsEmpty()) disconnected_callback_.Set(isolate, disconnected_callback); if (!adopted_callback.IsEmpty()) adopted_callback_.Set(isolate, adopted_callback); if (!attribute_changed_callback.IsEmpty()) attribute_changed_callback_.Set(isolate, attribute_changed_callback); } DEFINE_TRACE_WRAPPERS(ScriptCustomElementDefinition) { visitor->TraceWrappers(constructor_.Cast<v8::Value>()); visitor->TraceWrappers(connected_callback_.Cast<v8::Value>()); visitor->TraceWrappers(disconnected_callback_.Cast<v8::Value>()); visitor->TraceWrappers(adopted_callback_.Cast<v8::Value>()); visitor->TraceWrappers(attribute_changed_callback_.Cast<v8::Value>()); } static void DispatchErrorEvent(v8::Isolate* isolate, v8::Local<v8::Value> exception, v8::Local<v8::Object> constructor) { v8::TryCatch try_catch(isolate); try_catch.SetVerbose(true); V8ScriptRunner::ThrowException( isolate, exception, constructor.As<v8::Function>()->GetScriptOrigin()); } HTMLElement* ScriptCustomElementDefinition::HandleCreateElementSyncException( Document& document, const QualifiedName& tag_name, v8::Isolate* isolate, ExceptionState& exception_state) { DCHECK(exception_state.HadException()); // 6.1."If any of these subsubsteps threw an exception".1 // Report the exception. DispatchErrorEvent(isolate, exception_state.GetException(), Constructor()); exception_state.ClearException(); // ... .2 Return HTMLUnknownElement. return CustomElement::CreateFailedElement(document, tag_name); } HTMLElement* ScriptCustomElementDefinition::CreateElementSync( Document& document, const QualifiedName& tag_name) { if (!script_state_->ContextIsValid()) return CustomElement::CreateFailedElement(document, tag_name); ScriptState::Scope scope(script_state_.Get()); v8::Isolate* isolate = script_state_->GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kConstructionContext, "CustomElement"); // Create an element with the synchronous custom elements flag set. // https://dom.spec.whatwg.org/#concept-create-element // TODO(dominicc): Implement step 5 which constructs customized // built-in elements. Element* element = nullptr; { v8::TryCatch try_catch(script_state_->GetIsolate()); bool is_import_document = document.ImportsController() && document.ImportsController()->Master() != document; if (is_import_document) { // V8HTMLElement::constructorCustom() can only refer to // window.document() which is not the import document. Create // elements in import documents ahead of time so they end up in // the right document. This subtly violates recursive // construction semantics, but only in import documents. element = CreateElementForConstructor(document); DCHECK(!try_catch.HasCaught()); ConstructionStackScope construction_stack_scope(this, element); element = CallConstructor(); } else { element = CallConstructor(); } if (try_catch.HasCaught()) { exception_state.RethrowV8Exception(try_catch.Exception()); return HandleCreateElementSyncException(document, tag_name, isolate, exception_state); } } // 6.1.3. through 6.1.9. CheckConstructorResult(element, document, tag_name, exception_state); if (exception_state.HadException()) { return HandleCreateElementSyncException(document, tag_name, isolate, exception_state); } DCHECK_EQ(element->GetCustomElementState(), CustomElementState::kCustom); return ToHTMLElement(element); } // https://html.spec.whatwg.org/multipage/scripting.html#upgrades bool ScriptCustomElementDefinition::RunConstructor(Element* element) { if (!script_state_->ContextIsValid()) return false; ScriptState::Scope scope(script_state_.Get()); v8::Isolate* isolate = script_state_->GetIsolate(); // Step 5 says to rethrow the exception; but there is no one to // catch it. The side effect is to report the error. v8::TryCatch try_catch(isolate); try_catch.SetVerbose(true); Element* result = CallConstructor(); // To report exception thrown from callConstructor() if (try_catch.HasCaught()) return false; // To report InvalidStateError Exception, when the constructor returns some // different object if (result != element) { const String& message = "custom element constructors must call super() first and must " "not return a different object"; v8::Local<v8::Value> exception = V8ThrowDOMException::CreateDOMException( script_state_->GetIsolate(), kInvalidStateError, message); DispatchErrorEvent(isolate, exception, Constructor()); return false; } return true; } Element* ScriptCustomElementDefinition::CallConstructor() { v8::Isolate* isolate = script_state_->GetIsolate(); DCHECK(ScriptState::Current(isolate) == script_state_); ExecutionContext* execution_context = ExecutionContext::From(script_state_.Get()); v8::Local<v8::Value> result; if (!V8ScriptRunner::CallAsConstructor(isolate, Constructor(), execution_context, 0, nullptr) .ToLocal(&result)) { return nullptr; } return V8Element::toImplWithTypeCheck(isolate, result); } v8::Local<v8::Object> ScriptCustomElementDefinition::Constructor() const { DCHECK(!constructor_.IsEmpty()); return constructor_.NewLocal(script_state_->GetIsolate()); } // CustomElementDefinition ScriptValue ScriptCustomElementDefinition::GetConstructorForScript() { return ScriptValue(script_state_.Get(), Constructor()); } bool ScriptCustomElementDefinition::HasConnectedCallback() const { return !connected_callback_.IsEmpty(); } bool ScriptCustomElementDefinition::HasDisconnectedCallback() const { return !disconnected_callback_.IsEmpty(); } bool ScriptCustomElementDefinition::HasAdoptedCallback() const { return !adopted_callback_.IsEmpty(); } void ScriptCustomElementDefinition::RunCallback( v8::Local<v8::Function> callback, Element* element, int argc, v8::Local<v8::Value> argv[]) { DCHECK(ScriptState::Current(script_state_->GetIsolate()) == script_state_); v8::Isolate* isolate = script_state_->GetIsolate(); // Invoke custom element reactions // https://html.spec.whatwg.org/multipage/scripting.html#invoke-custom-element-reactions // If this throws any exception, then report the exception. v8::TryCatch try_catch(isolate); try_catch.SetVerbose(true); ExecutionContext* execution_context = ExecutionContext::From(script_state_.Get()); v8::Local<v8::Value> element_handle = ToV8(element, script_state_->GetContext()->Global(), isolate); V8ScriptRunner::CallFunction(callback, execution_context, element_handle, argc, argv, isolate); } void ScriptCustomElementDefinition::RunConnectedCallback(Element* element) { if (!script_state_->ContextIsValid()) return; ScriptState::Scope scope(script_state_.Get()); v8::Isolate* isolate = script_state_->GetIsolate(); RunCallback(connected_callback_.NewLocal(isolate), element); } void ScriptCustomElementDefinition::RunDisconnectedCallback(Element* element) { if (!script_state_->ContextIsValid()) return; ScriptState::Scope scope(script_state_.Get()); v8::Isolate* isolate = script_state_->GetIsolate(); RunCallback(disconnected_callback_.NewLocal(isolate), element); } void ScriptCustomElementDefinition::RunAdoptedCallback(Element* element, Document* old_owner, Document* new_owner) { if (!script_state_->ContextIsValid()) return; ScriptState::Scope scope(script_state_.Get()); v8::Isolate* isolate = script_state_->GetIsolate(); v8::Local<v8::Value> argv[] = { ToV8(old_owner, script_state_->GetContext()->Global(), isolate), ToV8(new_owner, script_state_->GetContext()->Global(), isolate)}; RunCallback(adopted_callback_.NewLocal(isolate), element, WTF_ARRAY_LENGTH(argv), argv); } void ScriptCustomElementDefinition::RunAttributeChangedCallback( Element* element, const QualifiedName& name, const AtomicString& old_value, const AtomicString& new_value) { if (!script_state_->ContextIsValid()) return; ScriptState::Scope scope(script_state_.Get()); v8::Isolate* isolate = script_state_->GetIsolate(); v8::Local<v8::Value> argv[] = { V8String(isolate, name.LocalName()), V8StringOrNull(isolate, old_value), V8StringOrNull(isolate, new_value), V8StringOrNull(isolate, name.NamespaceURI()), }; RunCallback(attribute_changed_callback_.NewLocal(isolate), element, WTF_ARRAY_LENGTH(argv), argv); } } // namespace blink
39.508571
90
0.728956
[ "object" ]
aa2877e656631a937dc08aaccc512b79e4ebdbcf
5,576
cpp
C++
VkRenderer/Source/VkCore/VkCorePhysicalDevice.cpp
JanVijfhuizen/VkRenderer
5f5848f637dcf587b55ff8bd52bdb56fcf9caab4
[ "MIT" ]
null
null
null
VkRenderer/Source/VkCore/VkCorePhysicalDevice.cpp
JanVijfhuizen/VkRenderer
5f5848f637dcf587b55ff8bd52bdb56fcf9caab4
[ "MIT" ]
null
null
null
VkRenderer/Source/VkCore/VkCorePhysicalDevice.cpp
JanVijfhuizen/VkRenderer
5f5848f637dcf587b55ff8bd52bdb56fcf9caab4
[ "MIT" ]
null
null
null
#include "pch.h" #include "VkCore/VkCorePhysicalDevice.h" #include "VkCore/VkCoreInstance.h" #include "VkCore/VkCoreInfo.h" #include "VkCore/VkCoreSwapchain.h" namespace vi { VkCorePhysicalDevice::QueueFamilies::operator bool() const { for (const auto& family : values) if (family == UINT32_MAX) return false; return true; } void VkCorePhysicalDevice::Setup( const VkCoreInfo& info, const VkCoreInstance& instance, const VkSurfaceKHR& surface) { uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); assert(deviceCount); ArrayPtr<VkPhysicalDevice> devices{ deviceCount, GMEM_TEMP }; vkEnumeratePhysicalDevices(instance, &deviceCount, devices.GetData()); BinTree<VkPhysicalDevice> candidates{ deviceCount, GMEM_TEMP }; // Add all potential candidates in a sorted way. for (const auto& device : devices) { VkPhysicalDeviceProperties deviceProperties; VkPhysicalDeviceFeatures deviceFeatures; deviceFeatures.samplerAnisotropy = VK_TRUE; vkGetPhysicalDeviceProperties(device, &deviceProperties); vkGetPhysicalDeviceFeatures(device, &deviceFeatures); // If families are not all present, continue. const auto families = GetQueueFamilies(surface, device); if (!families) continue; // If extensions are not supported, continue. if (!CheckDeviceExtensionSupport(device, info.deviceExtensions)) continue; const DeviceInfo deviceInfo { device, deviceProperties, deviceFeatures }; // If the device does not support the chosen features, continue. if (!IsDeviceSuitable(surface, deviceInfo)) continue; // Assign hardware score and add it to the potential candidates. const int32_t score = RateDevice(deviceInfo); candidates.Push({ score, device }); } // Assign the chosen hardware. assert(!candidates.IsEmpty()); _value = candidates.Peek(); } VkCorePhysicalDevice::operator VkPhysicalDevice_T* () const { return _value; } VkCorePhysicalDevice::QueueFamilies VkCorePhysicalDevice::GetQueueFamilies( const VkSurfaceKHR surface, const VkPhysicalDevice physicalDevice) { QueueFamilies families{}; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); ArrayPtr<VkQueueFamilyProperties> queueFamilies{ queueFamilyCount, GMEM_TEMP }; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.GetData()); // Check for hardware capabilities. uint32_t i = 0; for (const auto& queueFamily : queueFamilies) { // If the graphics family is present. if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) families.graphics = i; VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); // Since this is a renderer made for games, we need to be able to render to the screen. if (presentSupport) families.present = i; // If all families have been found. if (families) break; i++; } return families; } bool VkCorePhysicalDevice::IsDeviceSuitable( const VkSurfaceKHR surface, const DeviceInfo& deviceInfo) { const auto swapChainSupport = VkCoreSwapchain::QuerySwapChainSupport(surface, deviceInfo.device); if (!swapChainSupport) return false; if (!deviceInfo.features.samplerAnisotropy) return false; if (!deviceInfo.features.geometryShader) return false; return true; } uint32_t VkCorePhysicalDevice::RateDevice(const DeviceInfo& deviceInfo) { uint32_t score = 0; auto& properties = deviceInfo.properties; // Arbitrary increase in score, not sure what to look for to be honest. if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) score += 1000; // Increase the score based on the maximum resolution supported. score += properties.limits.maxImageDimension2D; return score; } bool VkCorePhysicalDevice::CheckDeviceExtensionSupport( const VkPhysicalDevice device, const ArrayPtr<const char*>& extensions) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); ArrayPtr<VkExtensionProperties> availableExtensions{ extensionCount, GMEM_TEMP }; vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.GetData()); // Check if every required extension is available. HashMap<CStrRef> hashMap{ extensionCount, GMEM_TEMP }; for (auto& extension : extensions) hashMap.Insert(extension); // Remove all the available extensions and check if the hashmap is now empty (which would suggest that all the extensions are supported). for (const auto& extension : availableExtensions) hashMap.Remove(extension.extensionName); return hashMap.IsEmpty(); } VkSampleCountFlagBits VkCorePhysicalDevice::GetMaxUsableSampleCount(const VkPhysicalDevice device) { VkPhysicalDeviceProperties physicalDeviceProperties; vkGetPhysicalDeviceProperties(device, &physicalDeviceProperties); const VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts; // Iterate over all the sample count enums and return the highest supported one. VkSampleCountFlagBits ret = VK_SAMPLE_COUNT_1_BIT; for (int32_t i = VK_SAMPLE_COUNT_2_BIT; i != VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM; i++) { const auto flags = static_cast<VkSampleCountFlagBits>(i); if (counts & flags) { ret = flags; continue; } break; } return ret; } }
29.978495
139
0.761657
[ "render" ]
a8f85c89e42fd3d50f271df50568d687868e76da
981
cpp
C++
hotel-rsvp/cpp/HotelTest.cpp
naomijub/tw-old-challenges
1214793e2269a2e589fcdca53a1e32f4336fb10e
[ "Unlicense" ]
1
2021-06-15T20:34:14.000Z
2021-06-15T20:34:14.000Z
hotel-rsvp/cpp/HotelTest.cpp
naomijub/tw-old-challenges
1214793e2269a2e589fcdca53a1e32f4336fb10e
[ "Unlicense" ]
null
null
null
hotel-rsvp/cpp/HotelTest.cpp
naomijub/tw-old-challenges
1214793e2269a2e589fcdca53a1e32f4336fb10e
[ "Unlicense" ]
null
null
null
#include "gtest/gtest.h" #include "Hotel.h" #include "Client.h" #include "gmock/gmock.h" using namespace ::testing; class AHotelRsvp: public Test { public: Hotel* hotel; void SetUp() override { std::string* name = new std::string("lakewood"); hotel = new Hotel( 3, name, 11, 17, 3, 7 ); } const Client regular_client() { std::vector<Days> days{ Days::Sun, Days::Mon, Days::Tues}; Client rc(ClientType::Regular, days); return rc; } const Client rewards_client() { std::vector<Days> days{ Days::Sun, Days::Mon, Days::Tues}; Client wc(ClientType::Rewards, days); return wc; } }; TEST_F(AHotelRsvp, HasCorrectPriceForRegulars) { const Client reg_client = regular_client(); ASSERT_EQ(hotel->price(reg_client), 39); } TEST_F(AHotelRsvp, HasCorrectPriceForRewards) { const Client rew_client = rewards_client(); ASSERT_EQ(hotel->price(rew_client), 13); }
24.525
66
0.627931
[ "vector" ]
a8f9d9b6b735863040a71ab0d359f8fc5e2196aa
23,389
cxx
C++
source/OOSQL/Compiler/compiler/OOSQL_Compiler.cxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
6
2016-08-29T08:03:21.000Z
2022-03-25T09:56:23.000Z
source/OOSQL/Compiler/compiler/OOSQL_Compiler.cxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
null
null
null
source/OOSQL/Compiler/compiler/OOSQL_Compiler.cxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************/ /* */ /* Copyright (c) 1990-2016, KAIST */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* */ /* 3. Neither the name of the copyright holder nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /******************************************************************************/ /******************************************************************************/ /* */ /* ODYSSEUS/OOSQL DB-IR-Spatial Tightly-Integrated DBMS */ /* Version 5.0 */ /* */ /* Developed by Professor Kyu-Young Whang et al. */ /* */ /* Advanced Information Technology Research Center (AITrc) */ /* Korea Advanced Institute of Science and Technology (KAIST) */ /* */ /* e-mail: odysseus.oosql@gmail.com */ /* */ /* Bibliography: */ /* [1] Whang, K., Lee, J., Lee, M., Han, W., Kim, M., and Kim, J., "DB-IR */ /* Integration Using Tight-Coupling in the Odysseus DBMS," World Wide */ /* Web, Vol. 18, No. 3, pp. 491-520, May 2015. */ /* [2] Whang, K., Lee, M., Lee, J., Kim, M., and Han, W., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with IR Features," In Proc. */ /* IEEE 21st Int'l Conf. on Data Engineering (ICDE), pp. 1104-1105 */ /* (demo), Tokyo, Japan, April 5-8, 2005. This paper received the Best */ /* Demonstration Award. */ /* [3] Whang, K., Park, B., Han, W., and Lee, Y., "An Inverted Index */ /* Storage Structure Using Subindexes and Large Objects for Tight */ /* Coupling of Information Retrieval with Database Management */ /* Systems," U.S. Patent No.6,349,308 (2002) (Appl. No. 09/250,487 */ /* (1999)). */ /* [4] Whang, K., Lee, J., Kim, M., Lee, M., Lee, K., Han, W., and Kim, */ /* J., "Tightly-Coupled Spatial Database Features in the */ /* Odysseus/OpenGIS DBMS for High-Performance," GeoInformatica, */ /* Vol. 14, No. 4, pp. 425-446, Oct. 2010. */ /* [5] Whang, K., Lee, J., Kim, M., Lee, M., and Lee, K., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with Spatial Database */ /* Features," In Proc. 23rd IEEE Int'l Conf. on Data Engineering */ /* (ICDE), pp. 1493-1494 (demo), Istanbul, Turkey, Apr. 16-20, 2007. */ /* */ /******************************************************************************/ #include <stdio.h> #include <locale.h> #include "OQL_AST.hxx" #include "OQL_GDS.hxx" #include "OQL_ASTtoGDS.hxx" #include "OQL_AST_Util.hxx" #include "OQL_CommonAP.hxx" #include "OQL_GDStoCommonAP.hxx" #include "OOSQL_Catalog.hxx" #include "OQL_OutStream.hxx" #include "OOSQL_Compiler.hxx" #include "OOSQL_AccessPlan.hxx" // routines in c_parser extern "C" { extern int c_parser(char *str,ASTNodeIdx *node); extern int free_parser(); } /**************************************************************************** DESCRIPTION: RETURN VALUE: IMPLEMENTATION: ****************************************************************************/ OOSQL_Compiler::OOSQL_Compiler( Four volId, OOSQL_StorageManager* storageManager, OOSQL_Catalog* catalog, OOSQL_ErrorMessage* errorMessage, OOSQL_ExternalFunctionManager* externalFunctionManager) { // initialize m_status m_status = STANDBY; // initialize objects for processing AST, GDS, PLAN... m_volId = volId; m_ast = NULL; m_gds = NULL; m_pool = NULL; m_astToGds = NULL; m_astUtil = NULL; m_commonAP = NULL; m_gdsToCommonAP = NULL; m_catalog = catalog; m_storageManager = storageManager; m_nResultColumns = 0; m_resultTypes = NULL; m_resultNames = NULL; m_errorMessage = errorMessage; m_externalFunctionManager = externalFunctionManager; } /**************************************************************************** DESCRIPTION: RETURN VALUE: IMPLEMENTATION: ****************************************************************************/ OOSQL_Compiler::~OOSQL_Compiler() { destroyObjects(); } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::destroyObjects() { Four i; if(m_ast) OOSQL_DELETE(m_ast); if(m_gds) OOSQL_DELETE(m_gds); if(m_pool) OOSQL_DELETE(m_pool); if(m_astToGds) OOSQL_DELETE(m_astToGds); if(m_astUtil) OOSQL_DELETE(m_astUtil); if(m_commonAP) OOSQL_DELETE(m_commonAP); if(m_gdsToCommonAP) OOSQL_DELETE(m_gdsToCommonAP); if(m_resultTypes) pMemoryManager->Free(m_resultTypes); if(m_resultNames) { for(i = 0; i < m_nResultColumns; i++) pMemoryManager->Free(m_resultNames[i]); pMemoryManager->Free(m_resultNames); } m_ast = NULL; m_gds = NULL; m_pool = NULL; m_astToGds = NULL; m_astUtil = NULL; m_commonAP = NULL; m_gdsToCommonAP = NULL; m_nResultColumns = 0; m_resultTypes = NULL; m_resultNames = NULL; return eNOERROR; } // c_parser constructs int, real, string, string index m_pool, and m_ast tree extern int* *strIndex; extern int* strIdxTop; /* top of string index table */ extern char* *strPool; extern int* stringTop; /* top of string table */ extern long* *intPool; extern int* intTop; /* top of table */ extern float* *realPool; extern int* realTop; /* top of table */ extern "C" { // DEFINED IN OQL.lex.l extern int LINE_NUM; extern int COLM_NUM; extern char* yytext; } extern "C" { // DEFINED IN OQL_AST.c extern int astNodeTop; } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::parse( char* queryStr // IN ) { Four e; m_status = STR_TO_AST; // initialize pointer destroyObjects(); // parse string e = c_parser(queryStr, &m_astRoot); if(e == ePARSE_ERROR_OOSQL) { m_errorMessage->Clear(); m_errorMessage->Append("Parsing error is occurred at column "); m_errorMessage->Append((Four)COLM_NUM); m_errorMessage->Append(", line "); m_errorMessage->Append((Four)LINE_NUM); free_parser(); return e; } else { if(e < eNOERROR) { free_parser(); OOSQL_ERR(e); } } // construct obejcts OOSQL_NEW(m_ast, pMemoryManager, OQL_AST(*intPool, *intTop + 1, *realPool, *realTop + 1, *strPool, *stringTop + 1, *strIndex, *strIdxTop + 1, astNodePool, astNodeTop + 1)); OOSQL_NEW(m_gds, pMemoryManager, OQL_GDS); OOSQL_NEW(m_pool, pMemoryManager, OQL_GDSPOOL); OOSQL_NEW(m_astToGds, pMemoryManager, OQL_ASTtoGDS(*m_ast, *m_gds, *m_pool, m_volId, *m_storageManager, *m_catalog, *m_errorMessage, *m_externalFunctionManager)); OOSQL_NEW(m_astUtil, pMemoryManager, OQL_AST_Util(*m_ast, *m_pool)); OOSQL_NEW(m_commonAP, pMemoryManager, OQL_CommonAP); OOSQL_NEW(m_gdsToCommonAP, pMemoryManager, OQL_GDStoCommonAP(*m_gds, *m_pool, *m_catalog, *m_commonAP, *m_errorMessage)); free_parser(); return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::smtChkAndGenGDS() { Four e; // m_status check and transition if(m_status != STR_TO_AST) return -1; // some valid error code.... else m_status = AST_TO_GDS; // do semantic check e = m_astToGds->smtChk(m_astRoot); OOSQL_CHECK_ERR(e); return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::genAccessPlan( OOSQL_AccessPlan*& oosql_accessPlan // OUT Access Plan ) { Four e; CommonAP_PoolElements accessPlan(m_pool->commonAP_Pool); Four i; AP_ProjectionListPoolElements projList; AP_ProjectionPoolElements projection; char stringBuffer[OOSQL_EVALBUFFER_MAXSTRINGSIZE]; Four usedSize; Four lastPlanNo; // m_status check and transition if(m_status != AST_TO_GDS) return -1; // some valid error code.... else m_status = GDS_TO_PLAN; // generate access plan e = m_gdsToCommonAP->genAccessPlan(); OOSQL_CHECK_ERR(e); // get query result informations // get # of result cols, type of result cols, name of result cols // get # of resultcols lastPlanNo = m_pool->commonAP_Pool.nElements() - 1; if(lastPlanNo >= 0 && m_gds->queryType == OQL_GDS::SELECT_QUERY) { projList = m_pool->commonAP_Pool[lastPlanNo].projectionList.getElements(m_pool->projectionListPool); projection = projList[0].projectionInfo.getElements(m_pool->projectionPool); m_nResultColumns = projection.size - m_pool->targetListPool.nElements(); } else { m_nResultColumns = 0; } if(m_nResultColumns > 0) { // allocate memory m_resultTypes = (Four*)pMemoryManager->Alloc(sizeof(Four) * m_nResultColumns); if(m_resultTypes == NULL) OOSQL_ERR(eMEMORYALLOCERR_OOSQL); m_resultNames = (char**)pMemoryManager->Alloc(sizeof(char*) * m_nResultColumns); if(m_resultNames == NULL) OOSQL_ERR(eMEMORYALLOCERR_OOSQL); // get type and name information for(i = 0; i < m_nResultColumns; i++) { m_resultTypes[i] = (Four)projection[i].resultType; e = selectClause_GetIthTerm(i, sizeof(stringBuffer), stringBuffer, &usedSize); OOSQL_CHECK_ERR(e); m_resultNames[i] = (char*)pMemoryManager->Alloc(usedSize); if(m_resultNames[i] == NULL) OOSQL_ERR(eMEMORYALLOCERR_OOSQL); strcpy(m_resultNames[i], stringBuffer); } } // convert m_commonAP to oosql_accessPlan // create OOSQL_AccessPlan object accessPlan = m_commonAP->commonAP; OOSQL_NEW(oosql_accessPlan, pMemoryManager, OOSQL_AccessPlan(accessPlan, m_storageManager, m_catalog, &m_pool->ap_condListPool, m_pool->ap_condListPool.nElements(), &m_pool->ap_exprPool, m_pool->ap_exprPool.nElements(), &m_pool->subClassPool, m_pool->subClassPool.nElements(), &m_pool->ap_aggrFuncPool, m_pool->ap_aggrFuncPool.nElements(), &m_pool->colNoMapPool, m_pool->colNoMapPool.nElements(), &m_pool->usedColPool, m_pool->usedColPool.nElements(), &m_pool->methodNoMapPool, m_pool->methodNoMapPool.nElements(), &m_pool->usedMethodPool, m_pool->usedMethodPool.nElements(), &m_pool->projectionListPool, m_pool->projectionListPool.nElements(), &m_pool->projectionPool, m_pool->projectionPool.nElements(), &m_pool->ap_argumentPool, m_pool->ap_argumentPool.nElements(), &m_pool->valuePool, m_pool->valuePool.nElements(), &m_pool->intPool, m_pool->intPool.nElements(), &m_pool->realPool, m_pool->realPool.nElements(), &m_pool->stringPool, m_pool->stringPool.nElements(), &m_pool->funcPool, m_pool->funcPool.nElements(), &m_pool->collectionPool, m_pool->collectionPool.nElements(), &m_pool->domainPool, m_pool->domainPool.nElements(), &m_pool->mbrPool, m_pool->mbrPool.nElements(), &m_pool->memberPool, m_pool->memberPool.nElements(), &m_pool->indexInfoPool, m_pool->indexInfoPool.nElements(), &m_pool->textIndexCondPool, m_pool->textIndexCondPool.nElements(), &m_pool->datePool, m_pool->datePool.nElements(), &m_pool->timePool, m_pool->timePool.nElements(), &m_pool->timestampPool, m_pool->timestampPool.nElements(), &m_pool->intervalPool, m_pool->intervalPool.nElements(), &m_pool->ap_insertValuePool, m_pool->ap_insertValuePool.nElements(), &m_pool->ap_updateValuePool, m_pool->ap_updateValuePool.nElements() )); return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::selectClause_GetN_Terms() { if(m_gds->queryType == OQL_GDS::SELECT_QUERY && m_pool->selectQueryPool[0].selListType & STAR_BIT) { return m_pool->selectQueryPool[0].selList.size; } else return m_astUtil->select_GetN_Terms(m_astRoot); } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::selectClause_GetIthTerm( Four ith, // IN Four stringBufferSize, // IN char* stringBuffer, // OUT string buffer Four* usedStringBufferSize // OUT ) { Four e; SelListPoolElements selList(m_pool->selListPool); PathExprPoolElements pathExpr(m_pool->pathExprPool); char attributeName[255]; if(m_pool->selectQueryPool[0].selListType & STAR_BIT) { selList = m_pool->selectQueryPool[0].selList; pathExpr = selList[ith].pathExpr; e = m_catalog->attr_CataAttrInfo_to_AttrName(pathExpr[1].classInfo, pathExpr[1].attr.attrInfo, attributeName); OOSQL_CHECK_ERR(e); if(strlen(attributeName) + 1 < stringBufferSize) strcpy(stringBuffer, attributeName); else { memcpy(stringBuffer, attributeName, stringBufferSize); stringBuffer[stringBufferSize - 1] = '\0'; } *usedStringBufferSize = strlen(stringBuffer) + 1; return eNOERROR; } else { e = m_astUtil->select_GetIthTerm(m_astRoot, ith, stringBufferSize, stringBuffer); if(e == eNOERROR) { *usedStringBufferSize = strlen(stringBuffer) + 1; return eNOERROR; } else if(e == eSTRINGBUFFER_OVERFLOW_OOSQL) { return eINSUFFICIENT_BUFSIZE_OOSQL; } else return e; } } /**************************************************************************** DESCRIPTION: RETURN VALUE: OOSQL_UNKNOWN_QUERY < eNOERROR IMPLEMENTATION: ****************************************************************************/ OOSQL_QueryType OOSQL_Compiler::GetQueryType() { Four i; if(m_pool->dbCommandPool.nElements() > 0) { switch(m_pool->dbCommandPool[0].command) { case DBCOMMAND_ALTER_TABLE: return OOSQL_ALTER_TABLE_QUERY; case DBCOMMAND_CREATE_SEQUENCE: return OOSQL_CREATE_SEQUENCE_QUERY; case DBCOMMAND_DROP_SEQUENCE: return OOSQL_DROP_SEQUENCE_QUERY; case DBCOMMAND_CREATE_TABLE: return OOSQL_CREATE_TABLE_QUERY; case DBCOMMAND_CREATE_INDEX: return OOSQL_CREATE_INDEX_QUERY; case DBCOMMAND_DROP_TABLE: return OOSQL_DROP_TABLE_QUERY; case DBCOMMAND_DROP_INDEX: return OOSQL_DROP_INDEX_QUERY; case DBCOMMAND_CREATE_FUNCTION: return OOSQL_CREATE_FUNCTION_QUERY; case DBCOMMAND_DROP_FUNCTION: return OOSQL_DROP_FUNCTION_QUERY; case DBCOMMAND_CREATE_PROCEDURE: return OOSQL_CREATE_PROCEDURE_QUERY; case DBCOMMAND_DROP_PROCEDURE: return OOSQL_DROP_PROCEDURE_QUERY; case DBCOMMAND_CALL_PROCEDURE: return OOSQL_CALL_PROCEDURE_QUERY; default: return OOSQL_UNKNOWN_QUERY; } } else { switch(m_gds->queryType) { case OQL_GDS::SELECT_QUERY: return OOSQL_SELECT_QUERY; case OQL_GDS::UPDATE_QUERY: for(i = 0; i < m_pool->updateValuePool.nElements(); i++) if(m_pool->updateValuePool[i].isParam == SM_TRUE) return OOSQL_UPDATE_QUERY_WITH_PARAM; return OOSQL_UPDATE_QUERY; case OQL_GDS::INSERT_QUERY: for(i = 0; i < m_pool->insertValuePool.nElements(); i++) if(m_pool->insertValuePool[i].isParam == SM_TRUE) return OOSQL_INSERT_QUERY_WITH_PARAM; return OOSQL_INSERT_QUERY; case OQL_GDS::DELETE_QUERY: return OOSQL_DELETE_QUERY; default: return OOSQL_UNKNOWN_QUERY; } } return OOSQL_UNKNOWN_QUERY; } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::ReInit() { destroyObjects(); m_status = STANDBY; return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: eBADPARAMETER_OOSQL < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::GetResultColName( Two columnNumber, // IN char* columnName, // OUT Four bufferLength // IN ) { if(columnNumber >= m_nResultColumns) { m_errorMessage->Clear(); m_errorMessage->Append("The number of results of this query is "); m_errorMessage->Append(m_nResultColumns); m_errorMessage->Append(" but the user requests to get "); m_errorMessage->Append(columnNumber); m_errorMessage->Append("th column's name."); OOSQL_ERR(eBADPARAMETER_OOSQL); } if(bufferLength > strlen(m_resultNames[columnNumber]) + 1) strcpy(columnName, m_resultNames[columnNumber]); else { memcpy(columnName, m_resultNames[columnNumber], bufferLength); columnName[bufferLength - 1] = '\0'; } return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: eBADPARAMETER_OOSQL < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::GetResultColType( Two columnNumber, // IN Four* type // OUT ) { if(columnNumber >= m_nResultColumns) { m_errorMessage->Clear(); m_errorMessage->Append("The number of results of this query is "); m_errorMessage->Append(m_nResultColumns); m_errorMessage->Append(" but the user requests to get "); m_errorMessage->Append(columnNumber); m_errorMessage->Append("th column's type."); OOSQL_ERR(eBADPARAMETER_OOSQL); } *type = m_resultTypes[columnNumber]; return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ Four OOSQL_Compiler::GetNumResultCols( Two* nCols // OUT ) { *nCols = (Two)m_nResultColumns; return eNOERROR; } /**************************************************************************** DESCRIPTION: RETURN VALUE: < eNOERROR IMPLEMENTATION: ****************************************************************************/ OQL_OutStream& operator<<( OQL_OutStream& os, // IN OOSQL_Compiler& object // IN ) { os << *object.m_pool; return os; } Four OOSQL_Compiler::GetClassName(Two targetNo, char* className, Four bufferLength) { Four e; TargetListPoolElements targetList(m_pool->targetListPool); PathExprPoolElements pathExpr(m_pool->pathExprPool); char classNameBuffer[255]; if(m_pool->selectQueryPool[0].selListType) { targetList = m_pool->selectQueryPool[0].targetList; e = m_catalog->class_CataClassInfo_to_ClassName(targetList[targetNo].collectionInfo.classInfo, classNameBuffer); OOSQL_CHECK_ERR(e); memcpy(className, classNameBuffer, bufferLength); className[bufferLength - 1] = '\0'; } return eNOERROR; }
33.701729
163
0.544658
[ "object" ]
a8fc2626cd8be60ff980fc565c5a52b4d326b582
28,013
cpp
C++
src/ACAN2515.cpp
Arjan-Woltjer/acan2515
4e95abcc438e9216fd34708be700de2b296d9635
[ "MIT" ]
null
null
null
src/ACAN2515.cpp
Arjan-Woltjer/acan2515
4e95abcc438e9216fd34708be700de2b296d9635
[ "MIT" ]
null
null
null
src/ACAN2515.cpp
Arjan-Woltjer/acan2515
4e95abcc438e9216fd34708be700de2b296d9635
[ "MIT" ]
null
null
null
//—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // A CAN driver for MCP2515 // by Pierre Molinaro // https://github.com/pierremolinaro/acan2515 // //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— #include <ACAN2515.h> //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // MCP2515 COMMANDS //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— static const uint8_t RESET_COMMAND = 0xC0 ; static const uint8_t WRITE_COMMAND = 0x02 ; static const uint8_t READ_COMMAND = 0x03 ; static const uint8_t BIT_MODIFY_COMMAND = 0x05 ; static const uint8_t LOAD_TX_BUFFER_COMMAND = 0x40 ; static const uint8_t REQUEST_TO_SEND_COMMAND = 0x80 ; static const uint8_t READ_FROM_RXB0SIDH_COMMAND = 0x90 ; static const uint8_t READ_FROM_RXB1SIDH_COMMAND = 0x94 ; static const uint8_t READ_STATUS_COMMAND = 0xA0 ; static const uint8_t RX_STATUS_COMMAND = 0xB0 ; //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // MCP2515 REGISTERS //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— static const uint8_t BFPCTRL_REGISTER = 0x0C ; static const uint8_t TXRTSCTRL_REGISTER = 0x0D ; static const uint8_t CANSTAT_REGISTER = 0x0E ; static const uint8_t CANCTRL_REGISTER = 0x0F ; static const uint8_t TEC_REGISTER = 0x1C ; static const uint8_t REC_REGISTER = 0x1D ; static const uint8_t RXM0SIDH_REGISTER = 0x20 ; static const uint8_t RXM1SIDH_REGISTER = 0x24 ; static const uint8_t CNF3_REGISTER = 0x28 ; static const uint8_t CNF2_REGISTER = 0x29 ; static const uint8_t CNF1_REGISTER = 0x2A ; static const uint8_t CANINTF_REGISTER = 0x2C ; static const uint8_t TXB0CTRL_REGISTER = 0x30 ; static const uint8_t TXB1CTRL_REGISTER = 0x40 ; static const uint8_t TXB2CTRL_REGISTER = 0x50 ; static const uint8_t RXB0CTRL_REGISTER = 0x60 ; static const uint8_t RXB1CTRL_REGISTER = 0x70 ; static const uint8_t RXFSIDH_REGISTER [6] = {0x00, 0x04, 0x08, 0x10, 0x14, 0x18} ; //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // CONSTRUCTOR, HARDWARE SPI //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— ACAN2515::ACAN2515 (const uint8_t inCS, // CS input of MCP2515 SPIClass & inSPI, // Hardware SPI object const uint8_t inINT) : // INT output of MCP2515 mSPI (inSPI), mSPISettings (10UL * 1000UL * 1000UL, MSBFIRST, SPI_MODE0), // 10 MHz, UL suffix is required for Arduino Uno mCS (inCS), mINT (inINT), mReceiveBuffer (), mCallBackFunctionArray (), mTransmitBuffer (), mTXBIsFree () { for (uint32_t i=0 ; i<6 ; i++) { mCallBackFunctionArray [i] = NULL ; } } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // BEGIN //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint32_t ACAN2515::begin (const ACAN2515Settings & inSettings, void (* inInterruptServiceRoutine) (void)) { return beginWithoutFilterCheck (inSettings, inInterruptServiceRoutine, ACAN2515Mask (), ACAN2515Mask (), NULL, 0) ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint32_t ACAN2515::begin (const ACAN2515Settings & inSettings, void (* inInterruptServiceRoutine) (void), const ACAN2515Mask inRXM0, const ACAN2515AcceptanceFilter inAcceptanceFilters [], const uint32_t inAcceptanceFilterCount) { uint32_t errorCode = 0 ; if (inAcceptanceFilterCount == 0) { errorCode = kOneFilterMaskRequiresOneOrTwoAcceptanceFilters ; }else if (inAcceptanceFilterCount > 2) { errorCode = kOneFilterMaskRequiresOneOrTwoAcceptanceFilters ; }else if (inAcceptanceFilters == NULL) { errorCode = kAcceptanceFilterArrayIsNULL ; }else{ errorCode = beginWithoutFilterCheck (inSettings, inInterruptServiceRoutine, inRXM0, inRXM0, inAcceptanceFilters, inAcceptanceFilterCount) ; } return errorCode ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint32_t ACAN2515::begin (const ACAN2515Settings & inSettings, void (* inInterruptServiceRoutine) (void), const ACAN2515Mask inRXM0, const ACAN2515Mask inRXM1, const ACAN2515AcceptanceFilter inAcceptanceFilters [], const uint32_t inAcceptanceFilterCount) { uint32_t errorCode = 0 ; if (inAcceptanceFilterCount < 3) { errorCode = kTwoFilterMasksRequireThreeToSixAcceptanceFilters ; }else if (inAcceptanceFilterCount > 6) { errorCode = kTwoFilterMasksRequireThreeToSixAcceptanceFilters ; }else if (inAcceptanceFilters == NULL) { errorCode = kAcceptanceFilterArrayIsNULL ; }else{ errorCode = beginWithoutFilterCheck (inSettings, inInterruptServiceRoutine, inRXM0, inRXM1, inAcceptanceFilters, inAcceptanceFilterCount) ; } return errorCode ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint32_t ACAN2515::beginWithoutFilterCheck (const ACAN2515Settings & inSettings, void (* inInterruptServiceRoutine) (void), const ACAN2515Mask inRXM0, const ACAN2515Mask inRXM1, const ACAN2515AcceptanceFilter inAcceptanceFilters [], const uint32_t inAcceptanceFilterCount) { uint32_t errorCode = 0 ; // Means no error //----------------------------------- check mINT has interrupt capability const int8_t itPin = digitalPinToInterrupt (mINT) ; if (itPin == NOT_AN_INTERRUPT) { errorCode = kINTPinIsNotAnInterrupt ; } //----------------------------------- Check isr is not NULL if (inInterruptServiceRoutine == NULL) { errorCode |= kISRIsNull ; } //----------------------------------- if no error, configure port and MCP2515 if (errorCode == 0) { //--- Configure ports pinMode (mCS, OUTPUT) ; digitalWrite (mCS, HIGH) ; // CS is high outside a command //--- Send software reset to MCP2515 mSPI.beginTransaction (mSPISettings) ; select () ; mSPI.transfer (RESET_COMMAND) ; unselect () ; mSPI.endTransaction () ; //--- delayMicroseconds (10) ; //--- Configure MCP2515_IRQ as external interrupt pinMode (mINT, INPUT_PULLUP) ; attachInterrupt (itPin, inInterruptServiceRoutine, LOW) ; mSPI.usingInterrupt (itPin) ; //--- Internal begin errorCode = internalBeginOperation (inSettings, inRXM0, inRXM1, inAcceptanceFilters, inAcceptanceFilterCount) ; } //----------------------------------- Return return errorCode ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // MESSAGE EMISSION //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— bool ACAN2515::tryToSend (const CANMessage & inMessage) { //--- Find send buffer index uint8_t idx = inMessage.idx ; if (idx > 2) { idx = 0 ; } //--- Workaround: the Teensy 3.5 / 3.6 "SPI.usingInterrupt" bug // https://github.com/PaulStoffregen/SPI/issues/35 #if (defined (__MK64FX512__) || defined (__MK66FX1M0__)) noInterrupts () ; #endif //--- mSPI.beginTransaction (mSPISettings) ; bool ok = mTXBIsFree [idx] ; if (ok) { // Transmit buffer and TXB are both free: transmit immediatly mTXBIsFree [idx] = false ; internalSendMessage (inMessage, idx) ; }else{ // Enter in transmit buffer, if not full ok = mTransmitBuffer [idx].append (inMessage) ; } mSPI.endTransaction () ; #if (defined (__MK64FX512__) || defined (__MK66FX1M0__)) interrupts () ; #endif return ok ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // MESSAGE RECEPTION //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— bool ACAN2515::available (void) { noInterrupts () ; const bool hasReceivedMessage = mReceiveBuffer.count () > 0 ; interrupts () ; return hasReceivedMessage ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— bool ACAN2515::receive (CANMessage & outMessage) { noInterrupts () ; const bool hasReceivedMessage = mReceiveBuffer.remove (outMessage) ; interrupts () ; //--- return hasReceivedMessage ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— bool ACAN2515::dispatchReceivedMessage (const tFilterMatchCallBack inFilterMatchCallBack) { CANMessage receivedMessage ; const bool hasReceived = receive (receivedMessage) ; if (hasReceived) { const uint32_t filterIndex = receivedMessage.idx ; if (NULL != inFilterMatchCallBack) { inFilterMatchCallBack (filterIndex) ; } ACANCallBackRoutine callBackFunction = mCallBackFunctionArray [filterIndex] ; if (NULL != callBackFunction) { callBackFunction (receivedMessage) ; } } return hasReceived ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // INTERRUPTS ARE DISABLED WHEN THESE FUNCTIONS ARE EXECUTED //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint32_t ACAN2515::internalBeginOperation (const ACAN2515Settings & inSettings, const ACAN2515Mask inRXM0, const ACAN2515Mask inRXM1, const ACAN2515AcceptanceFilter inAcceptanceFilters [], const uint32_t inAcceptanceFilterCount) { uint32_t errorCode = 0 ; // Ok be default //----------------------------------- Check if MCP2515 is accessible mSPI.beginTransaction (mSPISettings) ; write2515Register (CNF1_REGISTER, 0x55) ; bool ok = read2515Register (CNF1_REGISTER) == 0x55 ; if (ok) { write2515Register (CNF1_REGISTER, 0xAA) ; ok = read2515Register (CNF1_REGISTER) == 0xAA ; } if (!ok) { errorCode = kNoMCP2515 ; } mSPI.endTransaction () ; //----------------------------------- If ok, check if settings are correct if (!inSettings.mBitRateClosedToDesiredRate) { errorCode |= kTooFarFromDesiredBitRate ; } if (inSettings.CANBitSettingConsistency () != 0) { errorCode |= kInconsistentBitRateSettings ; } //----------------------------------- If ok, perform configuration if (errorCode == 0) { mSPI.beginTransaction (mSPISettings) ; //----------------------------------- Allocate receive buffer mReceiveBuffer.initWithSize (inSettings.mReceiveBufferSize) ; //----------------------------------- Allocate transmit buffers mTransmitBuffer [0].initWithSize (inSettings.mTransmitBuffer0Size) ; mTransmitBuffer [1].initWithSize (inSettings.mTransmitBuffer1Size) ; mTransmitBuffer [2].initWithSize (inSettings.mTransmitBuffer1Size) ; mTXBIsFree [0] = true ; mTXBIsFree [1] = true ; mTXBIsFree [2] = true ; //----------------------------------- Set CNF3, CNF2, CNF1 and CANINTE registers select () ; mSPI.transfer (WRITE_COMMAND) ; mSPI.transfer (CNF3_REGISTER) ; //--- Register CNF3: // Bit 7: SOF // bit 6 --> 0: No Wake-up Filter bit // Bit 5-3: - // Bit 2-0: PHSEG2 - 1 const uint8_t cnf3 = ((inSettings.mCLKOUT_SOF_pin == ACAN2515CLKOUT_SOF::SOF) << 6) /* SOF */ | ((inSettings.mPhaseSegment2 - 1) << 0) /* PHSEG2 */ ; mSPI.transfer (cnf3) ; //--- Register CNF2: // Bit 7 --> 1: BLTMODE // bit 6: SAM // Bit 5-3: PHSEG1 - 1 // Bit 2-0: PRSEG - 1 const uint8_t cnf2 = 0x80 /* BLTMODE */ | (inSettings.mTripleSampling << 6) /* SAM */ | ((inSettings.mPhaseSegment1 - 1) << 3) /* PHSEG1 */ | ((inSettings.mPropagationSegment - 1) << 0) /* PRSEG */ ; mSPI.transfer (cnf2) ; //--- Register CNF1: // Bit 7-6: SJW - 1 // Bit 5-0: BRP - 1 const uint8_t cnf1 = (inSettings.mSJW << 6) /* SJW */ | ((inSettings.mBitRatePrescaler - 1) << 0) /* BRP */ ; mSPI.transfer (cnf1) ; //--- Register CANINTE: activate interrupts // Bit 7 --> 0: MERRE // Bit 6 --> 0: WAKIE // Bit 5 --> 0: ERRIE // Bit 4 --> 1: TX2IE // Bit 3 --> 1: TX1IE // Bit 2 --> 1: TX0IE // Bit 1 --> 1: RX1IE // Bit 0 --> 1: RX0IE mSPI.transfer (0x1F) ; unselect () ; //----------------------------------- Deactivate the RXnBF Pins (High Impedance State) write2515Register (BFPCTRL_REGISTER, 0) ; //----------------------------------- Set TXnRTS as inputs write2515Register (TXRTSCTRL_REGISTER, 0); //----------------------------------- RXBnCTRL write2515Register (RXB0CTRL_REGISTER, ((uint8_t) inSettings.mRolloverEnable) << 2) ; write2515Register (RXB1CTRL_REGISTER, 0x00) ; //----------------------------------- Setup mask registers setupMaskRegister (inRXM0, RXM0SIDH_REGISTER) ; setupMaskRegister (inRXM1, RXM1SIDH_REGISTER) ; if (inAcceptanceFilterCount > 0) { uint32_t idx = 0 ; while (idx < inAcceptanceFilterCount) { setupMaskRegister (inAcceptanceFilters [idx].mMask, RXFSIDH_REGISTER [idx]) ; mCallBackFunctionArray [idx] = inAcceptanceFilters [idx].mCallBack ; idx += 1 ; } while (idx < 6) { setupMaskRegister (inAcceptanceFilters [inAcceptanceFilterCount-1].mMask, RXFSIDH_REGISTER [idx]) ; mCallBackFunctionArray [idx] = inAcceptanceFilters [inAcceptanceFilterCount-1].mCallBack ; idx += 1 ; } } //----------------------------------- Set TXBi priorities write2515Register (TXB0CTRL_REGISTER, inSettings.mTXBPriority & 3) ; write2515Register (TXB1CTRL_REGISTER, (inSettings.mTXBPriority >> 2) & 3) ; write2515Register (TXB2CTRL_REGISTER, (inSettings.mTXBPriority >> 4) & 3) ; //----------------------------------- Reset device to requested mode uint8_t canctrl = inSettings.mOneShotModeEnabled ? (1 << 3) : 0 ; switch (inSettings.mCLKOUT_SOF_pin) { case ACAN2515CLKOUT_SOF::CLOCK : canctrl = 0x04 | 0x00 ; break ; case ACAN2515CLKOUT_SOF::CLOCK2 : canctrl |= 0x04 | 0x01 ; break ; case ACAN2515CLKOUT_SOF::CLOCK4 : canctrl |= 0x04 | 0x02 ; break ; case ACAN2515CLKOUT_SOF::CLOCK8 : canctrl |= 0x04 | 0x03 ; break ; case ACAN2515CLKOUT_SOF::SOF : canctrl |= 0x04 ; break ; case ACAN2515CLKOUT_SOF::HiZ : break ; } //--- Requested mode uint8_t requestedMode = 0 ; switch (inSettings.mRequestedMode) { case ACAN2515RequestedMode::NormalMode : break ; case ACAN2515RequestedMode::ListenOnlyMode : requestedMode = 0x03 << 5 ; break ; case ACAN2515RequestedMode::LoopBackMode : requestedMode = 0x02 << 5 ; break ; } //--- Request mode write2515Register (CANCTRL_REGISTER, canctrl | requestedMode) ; mSPI.endTransaction () ; //--- Wait until requested mode is reached (during 1 or 2 ms) bool wait = true ; const uint32_t deadline = millis () + 2 ; while (wait) { mSPI.beginTransaction (mSPISettings) ; const uint8_t actualMode = read2515Register (CANSTAT_REGISTER) & 0xE0 ; mSPI.endTransaction () ; wait = actualMode != requestedMode ; if (wait && (millis () >= deadline)) { errorCode |= kRequestedModeTimeOut ; wait = false ; } } } //----------------------------------- return errorCode ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— void ACAN2515::isr (void) { mSPI.beginTransaction (mSPISettings) ; uint8_t itStatus = read2515Register (CANSTAT_REGISTER) & 0x0E ; while (itStatus != 0) { switch (itStatus) { case 0 : // No interrupt break ; case 1 << 1 : // Error interrupt break ; case 2 << 1 : // Wake-up interrupt break ; case 3 << 1 : // TXB0 interrupt handleTXBInterrupt (0) ; break ; case 4 << 1 : // TXB1 interrupt handleTXBInterrupt (1) ; break ; case 5 << 1 : // TXB2 interrupt handleTXBInterrupt (2) ; break ; case 6 << 1 : // RXB0 interrupt case 7 << 1 : // RXB1 interrupt handleRXBInterrupt () ; break ; } itStatus = read2515Register (CANSTAT_REGISTER) & 0x0E ; } mSPI.endTransaction () ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // This function is called by ISR when a MCP2515 receive buffer becomes full void ACAN2515::handleRXBInterrupt (void) { const uint8_t rxStatus = read2515RxStatus () ; // Bit 6: message in RXB0, bit 7: message in RXB1 const bool received = (rxStatus & 0xC0) != 0 ; if (received) { // Message in RXB0 and / or RXB1 const bool accessRXB0 = (rxStatus & 0x40) != 0 ; CANMessage message ; message.rtr = (rxStatus & 0x10) != 0 ; message.ext = (rxStatus & 0x08) != 0 ; //--- Set idx field to matching receive filter message.idx = rxStatus & 0x07 ; if (message.idx > 5) { message.idx -= 6 ; } //--- select () ; mSPI.transfer (accessRXB0 ? READ_FROM_RXB0SIDH_COMMAND : READ_FROM_RXB1SIDH_COMMAND) ; //--- SIDH message.id = mSPI.transfer (0) ; //--- SIDL const uint32_t sidl = mSPI.transfer (0) ; message.id <<= 3 ; message.id |= sidl >> 5 ; //--- EID8 const uint32_t eid8 = mSPI.transfer (0) ; if (message.ext) { message.id <<= 2 ; message.id |= (sidl & 0x03) ; message.id <<= 8 ; message.id |= eid8 ; } //--- EID0 const uint32_t eid0 = mSPI.transfer (0) ; if (message.ext) { message.id <<= 8 ; message.id |= eid0 ; } //--- DLC const uint8_t dlc = mSPI.transfer (0) ; message.len = dlc & 0x0F ; //--- Read data for (int i=0 ; i<message.len ; i++) { message.data [i] = mSPI.transfer (0) ; } //--- unselect () ; //--- Free receive buffer command bitModify2515Register (CANINTF_REGISTER, accessRXB0 ? 0x01 : 0x02, 0) ; //--- Enter received message in receive buffer (if not full) mReceiveBuffer.append (message) ; } } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // This function is called by ISR when a MCP2515 transmit buffer becomes empty void ACAN2515::handleTXBInterrupt (const uint8_t inTXB) { // inTXB value is 0, 1 or 2 //--- Acknowledge interrupt bitModify2515Register (CANINTF_REGISTER, 0x04 << inTXB, 0) ; //--- Send an other message ? CANMessage message ; const bool ok = mTransmitBuffer [inTXB].remove (message) ; if (ok) { internalSendMessage (message, inTXB) ; }else{ mTXBIsFree [inTXB] = true ; } } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— void ACAN2515::internalSendMessage (const CANMessage & inFrame, const uint8_t inTXB) { // inTXB is 0, 1 or 2 //--- Send command // send via TXB0: 0x81 // send via TXB1: 0x82 // send via TXB2: 0x84 const uint8_t sendCommand = REQUEST_TO_SEND_COMMAND | (1 << inTXB) ; //--- Load TX buffer command // Load TXB0, start at TXB0SIDH: 0x40 // Load TXB1, start at TXB1SIDH: 0x42 // Load TXB2, start at TXB2SIDH: 0x44 const uint8_t loadTxBufferCommand = LOAD_TX_BUFFER_COMMAND | (inTXB << 1) ; //--- Send message select () ; mSPI.transfer (loadTxBufferCommand) ; if (inFrame.ext) { // Extended frame uint32_t v = inFrame.id >> 21 ; mSPI.transfer ((uint8_t) v) ; // ID28 ... ID21 --> SIDH v = (inFrame.id >> 13) & 0xE0 ; // ID20, ID19, ID18 in bits 7, 6, 5 v |= (inFrame.id >> 16) & 0x03 ; // ID17, ID16 in bits 1, 0 v |= 0x08 ; // Extended bit mSPI.transfer ((uint8_t) v) ; // ID20, ID19, ID18, -, 1, -, ID17, ID16 --> SIDL v = (inFrame.id >> 8) & 0xFF ; // ID15, ..., ID8 mSPI.transfer ((uint8_t) v) ; // ID15, ID14, ID13, ID12, ID11, ID10, ID9, ID8 --> EID8 v = inFrame.id & 0xFF ; // ID7, ..., ID0 mSPI.transfer ((uint8_t) v) ; // ID7, ID6, ID5, ID4, ID3, ID2, ID1, ID0 --> EID0 }else{ // Standard frame uint32_t v = inFrame.id >> 3 ; mSPI.transfer ((uint8_t) v) ; // ID10 ... ID3 --> SIDH v = (inFrame.id << 5) & 0xE0 ; // ID2, ID1, ID0 in bits 7, 6, 5 mSPI.transfer ((uint8_t) v) ; // ID2, ID1, ID0, -, 0, -, 0, 0 --> SIDL mSPI.transfer (0x00) ; // any value --> EID8 mSPI.transfer (0x00) ; // any value --> EID0 } //--- DLC uint8_t v = inFrame.len ; if (v > 8) { v = 8 ; } if (inFrame.rtr) { v |= 0x40 ; } mSPI.transfer (v) ; //--- Send data if (!inFrame.rtr) { for (unsigned i=0 ; i<inFrame.len ; i++) { mSPI.transfer (inFrame.data [i]) ; } } unselect () ; //--- Write send command select () ; mSPI.transfer (sendCommand) ; unselect () ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // INTERNAL SPI FUNCTIONS //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— void ACAN2515::write2515Register (const uint8_t inRegister, const uint8_t inValue) { select () ; mSPI.transfer (WRITE_COMMAND) ; mSPI.transfer (inRegister) ; mSPI.transfer (inValue) ; unselect () ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint8_t ACAN2515::read2515Register (const uint8_t inRegister) { select () ; mSPI.transfer (READ_COMMAND) ; mSPI.transfer (inRegister) ; const uint8_t readValue = mSPI.transfer (0) ; unselect () ; return readValue ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint8_t ACAN2515::read2515Status (void) { select () ; mSPI.transfer (READ_STATUS_COMMAND) ; const uint8_t readValue = mSPI.transfer (0) ; unselect () ; return readValue ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint8_t ACAN2515::read2515RxStatus (void) { select () ; mSPI.transfer (RX_STATUS_COMMAND) ; const uint8_t readValue = mSPI.transfer (0) ; unselect () ; return readValue ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— void ACAN2515::bitModify2515Register (const uint8_t inRegister, const uint8_t inMask, const uint8_t inData) { select () ; mSPI.transfer (BIT_MODIFY_COMMAND) ; mSPI.transfer (inRegister) ; mSPI.transfer (inMask) ; mSPI.transfer (inData) ; unselect () ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— void ACAN2515::setupMaskRegister (const ACAN2515Mask inMask, const uint8_t inRegister) { select () ; mSPI.transfer (WRITE_COMMAND) ; mSPI.transfer (inRegister) ; mSPI.transfer (inMask.mSIDH) ; mSPI.transfer (inMask.mSIDL) ; mSPI.transfer (inMask.mEID8) ; mSPI.transfer (inMask.mEID0) ; unselect () ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // MCP2515 controller state //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint8_t ACAN2515::transmitErrorCounter (void) { mSPI.beginTransaction (mSPISettings) ; const uint8_t result = read2515Register (TEC_REGISTER) ; mSPI.endTransaction () ; return result ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— uint8_t ACAN2515::receiveErrorCounter (void) { mSPI.beginTransaction (mSPISettings) ; const uint8_t result = read2515Register (REC_REGISTER) ; mSPI.endTransaction () ; return result ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— // FILTER HELPER FUNCTIONS //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— ACAN2515Mask standard2515Mask (const uint16_t inIdentifier, const uint8_t inByte0, const uint8_t inByte1) { ACAN2515Mask result ; result.mSIDH = (uint8_t) (inIdentifier >> 3) ; result.mSIDL = (uint8_t) (inIdentifier << 5) ; result.mEID8 = inByte0 ; result.mEID0 = inByte1 ; return result ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— ACAN2515Mask extended2515Mask (const uint32_t inIdentifier) { ACAN2515Mask result ; result.mSIDH = (uint8_t) (inIdentifier >> 21) ; result.mSIDL = (uint8_t) (((inIdentifier >> 16) & 0x03) | ((inIdentifier >> 13) & 0xE0)) ; result.mEID8 = (uint8_t) (inIdentifier >> 8) ; result.mEID0 = (uint8_t) inIdentifier ; // Serial.print ("Mask ") ; // Serial.print (result.mSIDH, HEX) ; // Serial.print (" ") ; // Serial.print (result.mSIDL, HEX) ; // Serial.print (" ") ; // Serial.print (result.mEID8, HEX) ; // Serial.print (" ") ; // Serial.println (result.mEID0, HEX) ; return result ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— ACAN2515Mask standard2515Filter (const uint16_t inIdentifier, const uint8_t inByte0, const uint8_t inByte1) { ACAN2515Mask result ; result.mSIDH = (uint8_t) (inIdentifier >> 3) ; result.mSIDL = (uint8_t) (inIdentifier << 5) ; result.mEID8 = inByte0 ; result.mEID0 = inByte1 ; return result ; } //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— ACAN2515Mask extended2515Filter (const uint32_t inIdentifier) { ACAN2515Mask result ; result.mSIDH = (uint8_t) (inIdentifier >> 21) ; result.mSIDL = (uint8_t) (((inIdentifier >> 16) & 0x03) | ((inIdentifier >> 13) & 0xE0)) | 0x08 ; result.mEID8 = (uint8_t) (inIdentifier >> 8) ; result.mEID0 = (uint8_t) inIdentifier ; // Serial.print ("Acceptance ") ; // Serial.print (result.mSIDH, HEX) ; // Serial.print (" ") ; // Serial.print (result.mSIDL, HEX) ; // Serial.print (" ") ; // Serial.print (result.mEID8, HEX) ; // Serial.print (" ") ; // Serial.println (result.mEID0, HEX) ; return result ; } //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
39.069735
120
0.509192
[ "object" ]
d10174740f3a696399a621d3eb95dbf904c4de8a
3,481
hpp
C++
include/rcpputils/split.hpp
pal-robotics-forks/rcpputils
4e2b95cde54d559d546e9382f89a368fca701fd3
[ "Apache-2.0" ]
null
null
null
include/rcpputils/split.hpp
pal-robotics-forks/rcpputils
4e2b95cde54d559d546e9382f89a368fca701fd3
[ "Apache-2.0" ]
null
null
null
include/rcpputils/split.hpp
pal-robotics-forks/rcpputils
4e2b95cde54d559d546e9382f89a368fca701fd3
[ "Apache-2.0" ]
2
2020-06-04T23:55:02.000Z
2020-11-12T21:37:29.000Z
// Copyright (c) 2019, Open Source Robotics Foundation, Inc. // All rights reserved. // // Software License Agreement (BSD License 2.0) // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // This file is originally from: // https://github.com/ros/pluginlib/blob/1a4de29fa55173e9b897ca8ff57ebc88c047e0b3/pluginlib/include/pluginlib/impl/split.hpp /*! \file split.hpp * \brief Split string by provided delimiter. */ #ifndef RCPPUTILS__SPLIT_HPP_ #define RCPPUTILS__SPLIT_HPP_ #include <iterator> #include <sstream> #include <string> #include <vector> namespace rcpputils { /// Split a specified input into tokens using a delimiter and a type erased insert iterator. /** * The returned vector will contain the tokens split from the input * * \param[in] input the input string to be split * \param[in] delim the delimiter used to split the input string * \param[in] insert iterator pointing to a storage container */ template< class InsertIterator, typename std::enable_if< std::is_same< InsertIterator &, decltype(std::declval<InsertIterator>().operator=(std::declval<std::string>()))>::value >::type * = nullptr> void split(const std::string & input, char delim, InsertIterator & it, bool skip_empty = false) { std::stringstream ss; ss.str(input); std::string item; while (std::getline(ss, item, delim)) { if (skip_empty && item == "") { continue; } it = item; } } /// Split a specified input into tokens using a delimiter. /** * The returned vector will contain the tokens split from the input * * \param[in] input the input string to be split * \param[in] delim the delimiter used to split the input string * \return A vector of tokens. */ inline std::vector<std::string> split(const std::string & input, char delim, bool skip_empty = false) { std::vector<std::string> result; auto it = std::back_inserter(result); split(input, delim, it, skip_empty); return result; } } // namespace rcpputils #endif // RCPPUTILS__SPLIT_HPP_
35.161616
124
0.734846
[ "vector" ]
d10ce52e786b0766e6cfa163e184b2d5fab572d0
3,828
cpp
C++
fbpcs/data_processing/id_combiner/test/GroupByTest.cpp
adshastri/fbpcs
81d816ee56ea36f8f58dca6ae803fa50138cb91e
[ "MIT" ]
null
null
null
fbpcs/data_processing/id_combiner/test/GroupByTest.cpp
adshastri/fbpcs
81d816ee56ea36f8f58dca6ae803fa50138cb91e
[ "MIT" ]
null
null
null
fbpcs/data_processing/id_combiner/test/GroupByTest.cpp
adshastri/fbpcs
81d816ee56ea36f8f58dca6ae803fa50138cb91e
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "../GroupBy.h" #include <chrono> #include <cstdlib> #include <filesystem> #include <fstream> #include <gflags/gflags.h> #include <gtest/gtest.h> class GroupByTest : public testing::Test { public: void vectorStringToStream( std::vector<std::string>& input, std::stringstream& out) { for (auto const& row : input) { out << row << '\n'; } } void validateOutputFile(std::vector<std::string>& expectedOutput) { // Validate the output with what is expected uint64_t lineIndex = 0; std::string outputString; while (getline(outputStream_, outputString)) { EXPECT_EQ(outputString, expectedOutput.at(lineIndex)); ++lineIndex; } // Should not be any extra entries any side EXPECT_EQ(lineIndex, expectedOutput.size()); } void runTest( std::vector<std::string>& dataContent, std::string groupByCol, std::vector<std::string> columnsToAggregate, std::vector<std::string>& expectedOutput) { vectorStringToStream(dataContent, dataStream_); pid::combiner::groupBy( dataStream_, groupByCol, columnsToAggregate, outputStream_); validateOutputFile(expectedOutput); } protected: std::stringstream dataStream_; std::stringstream outputStream_; }; // testing group by first col over all other columns TEST_F(GroupByTest, TestGroupingOverAllCols) { std::vector<std::string> dataInput = { "id_,event_timestamp,value", "AAA,125,102", "AAA,126,103", "AAA,127,104", "AAA,128,105", "AAA,129,106", "BBB,200,200", "CCC,375,300", "DDD,400,400"}; std::vector<std::string> expectedOutput = { "id_,event_timestamp,value", "AAA,[125,126,127,128,129],[102,103,104,105,106]", "BBB,[200],[200]", "CCC,[375],[300]", "DDD,[400],[400]"}; runTest(dataInput, "id_", {"event_timestamp", "value"}, expectedOutput); } // testing group by first col over 1 other col TEST_F(GroupByTest, TestGroupingOverSomeCols) { std::vector<std::string> dataInput = { "id_,event_timestamp,value", "id_1,125,a", "id_1,126,a", "id_2,200,c", "id_3,375,d", "id_1,390,a", "id_4,400,d"}; std::vector<std::string> expectedOutput = { "id_,event_timestamp,value", "id_1,[125,126,390],a", "id_2,[200],c", "id_3,[375],d", "id_4,[400],d"}; runTest(dataInput, "id_", {"event_timestamp"}, expectedOutput); } // testing group by second col over 1 other col TEST_F(GroupByTest, TestGroupingBySecondColOverSomeCols) { std::vector<std::string> dataInput = { "event_timestamp,id_,value", "125,id_1,a", "126,id_1,a", "200,id_2,c", "375,id_3,d", "390,id_1,a", "400,id_4,d"}; std::vector<std::string> expectedOutput = { "event_timestamp,id_,value", "[125,126,390],id_1,a", "[200],id_2,c", "[375],id_3,d", "[400],id_4,d"}; runTest(dataInput, "id_", {"event_timestamp"}, expectedOutput); } // testing group by second col over 1 other col TEST_F(GroupByTest, TestGroupingTraversedOrder) { std::vector<std::string> dataInput = { "id_,event_timestamp,value", "BBB,200,200", "AAA,125,102", "AAA,126,103", "AAA,127,104", "AAA,128,105", "AAA,129,106", "DDD,400,400", "CCC,375,300", }; std::vector<std::string> expectedOutput = { "id_,event_timestamp,value", "BBB,[200],[200]", "AAA,[125,126,127,128,129],[102,103,104,105,106]", "DDD,[400],[400]", "CCC,[375],[300]", }; runTest(dataInput, "id_", {"event_timestamp", "value"}, expectedOutput); }
27.539568
74
0.621996
[ "vector" ]
d116842563f635d13730a7e0783f4f3986707d08
3,808
hpp
C++
openstudiocore/src/analysis/SequentialSearchOptions.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/analysis/SequentialSearchOptions.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/analysis/SequentialSearchOptions.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * 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 ANALYSIS_SEQUENTIALSEARCHOPTIONS_HPP #define ANALYSIS_SEQUENTIALSEARCHOPTIONS_HPP #include "AnalysisAPI.hpp" #include "AlgorithmOptions.hpp" namespace openstudio { namespace analysis { namespace detail { class SequentialSearchOptions_Impl; } // detail /** SequentialSearchOptions is an options class for SequentialSearch, derived from * AlgorithmOptions. \relates SequentialSearch */ class ANALYSIS_API SequentialSearchOptions : public AlgorithmOptions { public: /** @name Constructors and Destructors */ //@{ /** Constructor. Required argument objectiveToMinimizeFirst is the index of the objective * function (0 or 1) for which the minimum curve will be constructed. This means that the * SequentialSearch algorithm will first work towards locating the point that minimizes this * objective function, in the direction of also minimizing the other objective function. After * achieving this minimum point, objectiveToMinimizeFirst will be allowed to increase, while * the other objective function continues to be driven towards its minimum. The final * MinimumCurve(objectiveToMinimizeFirst) will contain the convex hull of the overall * ParetoFront; the values of objectiveToMinimizeFirst will first decrease, then increase; and * the other objective function will monotonically decrease. * * In NREL analyses, objectiveToMinimizeFirst typically refers to an economic objective, and * the other objective function is typically an energy metric. In this way the final curve * traces out minimum cost designs for each level of energy use that improves on the baseline * (existing building or code minimum). */ explicit SequentialSearchOptions(int objectiveToMinimizeFirst); /** Constructor provided for deserialization; not for general use. */ explicit SequentialSearchOptions(const std::vector<Attribute>& options); virtual ~SequentialSearchOptions() {} //@} /** @name Getters and Queries */ //@{ int objectiveToMinimizeFirst() const; //@} protected: /// @cond typedef detail::SequentialSearchOptions_Impl ImplType; explicit SequentialSearchOptions(std::shared_ptr<detail::SequentialSearchOptions_Impl> impl); friend class detail::SequentialSearchOptions_Impl; friend class AlgorithmOptions; /// @endcond private: REGISTER_LOGGER("openstudio.analysis.SequentialSearchOptions"); }; /** \relates SequentialSearchOptions*/ typedef boost::optional<SequentialSearchOptions> OptionalSequentialSearchOptions; /** \relates SequentialSearchOptions*/ typedef std::vector<SequentialSearchOptions> SequentialSearchOptionsVector; } // analysis } // openstudio #endif // ANALYSIS_SEQUENTIALSEARCHOPTIONS_HPP
40.510638
99
0.722426
[ "vector" ]
d11dda215410b3d6e50df888c2e2673630c20d1a
1,491
cpp
C++
KiteOpenGLDriverCore/KiteDriverFbxVisitor.cpp
awyhhwxz/KiteOpenGLDriver
cce0a67b93431d3958a485d0cc9420ecb6295d42
[ "BSD-3-Clause" ]
2
2018-08-19T04:08:00.000Z
2018-08-19T04:08:44.000Z
KiteOpenGLDriverCore/KiteDriverFbxVisitor.cpp
awyhhwxz/KiteOpenGLDriver
cce0a67b93431d3958a485d0cc9420ecb6295d42
[ "BSD-3-Clause" ]
null
null
null
KiteOpenGLDriverCore/KiteDriverFbxVisitor.cpp
awyhhwxz/KiteOpenGLDriver
cce0a67b93431d3958a485d0cc9420ecb6295d42
[ "BSD-3-Clause" ]
null
null
null
#include "stdafx.h" #include "KiteDriverFbxVisitor.h" namespace kite_driver { KiteDriverFbxVisitor::KiteDriverFbxVisitor() { } KiteDriverFbxVisitor::~KiteDriverFbxVisitor() { } void KiteDriverFbxVisitor::LoadFbx(const tchar* fbx_path) { kite_fbx::FbxParser fbx_parser; auto node_parser = fbx_parser.LoadFbx(fbx_path); _meshes.clear(); auto meshes = node_parser->get_meshes(); std::for_each(meshes.begin(), meshes.end(), [this](const auto& mesh) { _meshes.push_back(ParseFbxMesh(mesh.get())); }); } KiteDriverMeshPtr KiteDriverFbxVisitor::ParseFbxMesh(kite_fbx::IFbxMesh* fbx_mesh) { KiteDriverMeshPtr mesh = std::make_shared<KiteDriverMesh>(); const auto& fbx_mesh_data = fbx_mesh->get_mesh_data(); mesh->SetVertices(const_cast<kite_math::Vector3f*>(fbx_mesh_data.Vertices.data()), fbx_mesh_data.Vertices.size()); const auto& fbx_mesh_uvs = fbx_mesh_data.UVs; std::for_each(fbx_mesh_uvs.begin(), fbx_mesh_uvs.end(), [&mesh](const auto& uv_pair) { mesh->SetUVs(uv_pair.first, const_cast<kite_math::Vector2f*>(uv_pair.second.data()), uv_pair.second.size()); }); const auto& fbx_normals = fbx_mesh_data.Normals; if (fbx_normals.size() != 0) { const auto& normal = (*fbx_normals.begin()).second; mesh->SetNormals(const_cast<kite_math::Vector3f*>(normal.data()), normal.size()); } const auto& indices = fbx_mesh->get_indexes(); mesh->SetIndices(const_cast<uint16*>(indices.data()), indices.size()); return mesh; } }
28.673077
116
0.722334
[ "mesh" ]
d1231476fd644517816d8009d2edf301accc191e
12,867
cpp
C++
src/EulerianUnsplitAdvectionAllLevels.cpp
gdeskos/amr-offshore-utils
9876c15c89327cf0847ac7d3a0d8a8448560e920
[ "Apache-2.0" ]
null
null
null
src/EulerianUnsplitAdvectionAllLevels.cpp
gdeskos/amr-offshore-utils
9876c15c89327cf0847ac7d3a0d8a8448560e920
[ "Apache-2.0" ]
null
null
null
src/EulerianUnsplitAdvectionAllLevels.cpp
gdeskos/amr-offshore-utils
9876c15c89327cf0847ac7d3a0d8a8448560e920
[ "Apache-2.0" ]
null
null
null
#include "AmrGVOF.H" #include "Kernels.H" #include <AMReX_MultiFabUtil.H> using namespace amrex; // advance all levels for a single time step void AmrGVOF::EulerianUnsplitAdvectionAllLevels (Real time, Real dt_lev, int iteration) { constexpr int num_grow = 3; Vector< Array<MultiFab,AMREX_SPACEDIM> > fluxes(finest_level+1); for (int lev = 0; lev <= finest_level; lev++) { for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { BoxArray ba = grids[lev]; ba.surroundingNodes(idim); fluxes[lev][idim] = MultiFab(ba, dmap[lev], 1, 0); } } for (int lev = 0; lev <= finest_level; lev++) { std::swap(phi_old[lev], phi_new[lev]); t_old[lev] = t_new[lev]; t_new[lev] += dt_lev; const Real old_time = t_old[lev]; const Real new_time = t_new[lev]; const Real ctr_time = 0.5*(old_time+new_time); const auto dx = geom[lev].CellSizeArray(); GpuArray<Real, AMREX_SPACEDIM> dtdx; for (int i=0; i<AMREX_SPACEDIM; ++i) dtdx[i] = dt_lev/(dx[i]); const Real* prob_lo = geom[lev].ProbLo(); // State with ghost cells MultiFab Sborder(grids[lev], dmap[lev], phi_new[lev].nComp(), num_grow); FillPatch(lev, time, Sborder, 0, Sborder.nComp()); #ifdef _OPENMP #pragma omp parallel if (Gpu::notInLaunchRegion()) #endif { for (MFIter mfi(phi_new[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi) { GpuArray<Array4<Real>, AMREX_SPACEDIM> vel{ AMREX_D_DECL( facevel[lev][0].array(mfi), facevel[lev][1].array(mfi), facevel[lev][2].array(mfi)) }; const Box& bx = mfi.tilebox(); const Box& gbx = amrex::grow(bx, 1); Array4<Real> statein = Sborder.array(mfi); Array4<Real> stateout = phi_new[lev].array(mfi); GpuArray<Array4<Real>, AMREX_SPACEDIM> flux{ AMREX_D_DECL(fluxes[lev][0].array(mfi), fluxes[lev][1].array(mfi), fluxes[lev][2].array(mfi)) }; AMREX_D_TERM(const Box& dqbxx = amrex::grow(bx, IntVect{AMREX_D_DECL(2, 1, 1)});, const Box& dqbxy = amrex::grow(bx, IntVect{AMREX_D_DECL(1, 2, 1)});, const Box& dqbxz = amrex::grow(bx, IntVect{AMREX_D_DECL(1, 1, 2)});); FArrayBox slope2fab (amrex::grow(bx, 2), 1); Elixir slope2eli = slope2fab.elixir(); Array4<Real> slope2 = slope2fab.array(); FArrayBox slope4fab (amrex::grow(bx, 1), 1); Elixir slope4eli = slope4fab.elixir(); Array4<Real> slope4 = slope4fab.array(); // compute longitudinal fluxes // =========================== // x ------------------------- FArrayBox phixfab (gbx, 1); Elixir phixeli = phixfab.elixir(); Array4<Real> phix = phixfab.array(); amrex::launch(dqbxx, [=] AMREX_GPU_DEVICE (const Box& tbx) { slopex2(tbx, statein, slope2); }); amrex::launch(gbx, [=] AMREX_GPU_DEVICE (const Box& tbx) { slopex4(tbx, statein, slope2, slope4); }); amrex::ParallelFor(amrex::growLo(gbx, 0, -1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_x(i, j, k, statein, vel[0], phix, slope4, dtdx); }); // y ------------------------- FArrayBox phiyfab (gbx, 1); Elixir phiyeli = phiyfab.elixir(); Array4<Real> phiy = phiyfab.array(); amrex::launch(dqbxy, [=] AMREX_GPU_DEVICE (const Box& tbx) { slopey2(tbx, statein, slope2); }); amrex::launch(gbx, [=] AMREX_GPU_DEVICE (const Box& tbx) { slopey4(tbx, statein, slope2, slope4); }); amrex::ParallelFor(amrex::growLo(gbx, 1, -1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_y(i, j, k, statein, vel[1], phiy, slope4, dtdx); }); #if (AMREX_SPACEDIM > 2) // z ------------------------- FArrayBox phizfab (gbx, 1); Elixir phizeli = phizfab.elixir(); Array4<Real> phiz = phizfab.array(); amrex::launch(dqbxz, [=] AMREX_GPU_DEVICE (const Box& tbx) { slopez2(tbx, statein, slope2); }); amrex::launch(gbx, [=] AMREX_GPU_DEVICE (const Box& tbx) { slopez4(tbx, statein, slope2, slope4); }); amrex::ParallelFor(amrex::growLo(gbx, 2, -1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_z(i, j, k, statein, vel[2], phiz, slope4, dtdx); }); // compute transverse fluxes (3D only) // =================================== AMREX_D_TERM(const Box& gbxx = amrex::grow(bx, 0, 1);, const Box& gbxy = amrex::grow(bx, 1, 1);, const Box& gbxz = amrex::grow(bx, 2, 1);); // xy -------------------- FArrayBox phix_yfab (gbx, 1); Elixir phix_yeli = phix_yfab.elixir(); Array4<Real> phix_y = phix_yfab.array(); amrex::ParallelFor(amrex::growHi(gbxz, 0, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_xy(i, j, k, AMREX_D_DECL(vel[0], vel[1], vel[2]), AMREX_D_DECL(phix, phiy, phiz), phix_y, dtdx); }); // xz -------------------- FArrayBox phix_zfab (gbx, 1); Elixir phix_zeli = phix_zfab.elixir(); Array4<Real> phix_z = phix_zfab.array(); amrex::ParallelFor(amrex::growHi(gbxy, 0, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_xz(i, j, k, AMREX_D_DECL(vel[0], vel[1], vel[2]), AMREX_D_DECL(phix, phiy, phiz), phix_z, dtdx); }); // yx -------------------- FArrayBox phiy_xfab (gbx, 1); FArrayBox phiy_zfab (gbx, 1); Elixir phiy_xeli = phiy_xfab.elixir(); Elixir phiy_zeli = phiy_zfab.elixir(); Array4<Real> phiy_x = phiy_xfab.array(); Array4<Real> phiy_z = phiy_zfab.array(); amrex::ParallelFor(amrex::growHi(gbxz, 1, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_yx(i, j, k, AMREX_D_DECL(vel[0], vel[1], vel[2]), AMREX_D_DECL(phix, phiy, phiz), phiy_x, dtdx); }); // yz -------------------- amrex::ParallelFor(amrex::growHi(gbxx, 1, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_yz(i, j, k, AMREX_D_DECL(vel[0], vel[1], vel[2]), AMREX_D_DECL(phix, phiy, phiz), phiy_z, dtdx); }); // zx & zy -------------------- FArrayBox phiz_xfab (gbx, 1); FArrayBox phiz_yfab (gbx, 1); Elixir phiz_xeli = phiz_xfab.elixir(); Elixir phiz_yeli = phiz_yfab.elixir(); Array4<Real> phiz_x = phiz_xfab.array(); Array4<Real> phiz_y = phiz_yfab.array(); amrex::ParallelFor(amrex::growHi(gbxy, 2, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_zx(i, j, k, AMREX_D_DECL(vel[0], vel[1], vel[2]), AMREX_D_DECL(phix, phiy, phiz), phiz_x, dtdx); }); amrex::ParallelFor(amrex::growHi(gbxx, 2, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { flux_zy(i, j, k, AMREX_D_DECL(vel[0], vel[1], vel[2]), AMREX_D_DECL(phix, phiy, phiz), phiz_y, dtdx); }); #endif // final edge states // =========================== amrex::ParallelFor(amrex::growHi(bx, 0, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { create_flux_x(i, j, k, vel[0], vel[1], #if (AMREX_SPACEDIM > 2) vel[2], #endif #if (AMREX_SPACEDIM > 2) phix, phiy_z, phiz_y, #else phix, phiy, #endif flux[0], dtdx); }); amrex::ParallelFor(amrex::growHi(bx, 1, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { create_flux_y(i, j, k, vel[0], vel[1], #if (AMREX_SPACEDIM > 2) vel[2], #endif #if (AMREX_SPACEDIM > 2) phiy, phix_z, phiz_x, #else phiy, phix, #endif flux[1], dtdx); }); #if (AMREX_SPACEDIM > 2) amrex::ParallelFor(amrex::growHi(bx, 2, 1), [=] AMREX_GPU_DEVICE (int i, int j, int k) { create_flux_z(i, j, k, vel[0], vel[1], vel[2], phiz, phix_y, phiy_x, flux[2], dtdx); }); #endif } // end mfi } // end omp } // end lev // ======================================================= // Average down the fluxes before using them to update phi // ======================================================= for (int lev = finest_level; lev > 0; lev--) { average_down_faces(amrex::GetArrOfConstPtrs(fluxes[lev ]), amrex::GetArrOfPtrs (fluxes[lev-1]), refRatio(lev-1), Geom(lev-1)); } for (int lev = 0; lev <= finest_level; lev++) { #ifdef _OPENMP #pragma omp parallel if (Gpu::notInLaunchRegion()) #endif { const auto dx = geom[lev].CellSizeArray(); GpuArray<Real, AMREX_SPACEDIM> dtdx; for (int i=0; i<AMREX_SPACEDIM; ++i) dtdx[i] = dt_lev/(dx[i]); // =========================================== // Compute phi_new using a conservative update // =========================================== for (MFIter mfi(phi_new[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi) { Array4<Real> statein = phi_old[lev].array(mfi); Array4<Real> stateout = phi_new[lev].array(mfi); GpuArray<Array4<Real>, AMREX_SPACEDIM> flux{ AMREX_D_DECL(fluxes[lev][0].array(mfi), fluxes[lev][1].array(mfi), fluxes[lev][2].array(mfi)) }; const Box& bx = mfi.tilebox(); amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k) { conservative(i, j, k, statein, stateout, AMREX_D_DECL(flux[0], flux[1], flux[2]), dtdx); // Do clipping stateout(i, j, k) = std::max(0.0, std::min(1.0, stateout(i, j, k))); }); } // end mfi } // end omp } // end lev }
37.955752
104
0.404756
[ "vector", "3d" ]
d123f72363e60dd84187afd03c7bb7db8aed4d5d
27,352
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/vtf/ReaderWriterVTF.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/vtf/ReaderWriterVTF.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/vtf/ReaderWriterVTF.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/********************************************************************** * * FILE: ReaderWriterVTF.cpp * * DESCRIPTION: Class for reading a Valve Texture Format (VTF) file * into an osg::Image. * * Borrows heavily from the DDS plugin for OSG, as well * as the Valve Source SDK * * CREATED BY: Jason Daly (jdaly@ist.ucf.edu) * * HISTORY: Created 27.10.2008 * **********************************************************************/ #include <osg/Texture> #include <osg/Notify> #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <iomanip> #include <stdio.h> enum VTFFlags { VTF_FLAGS_POINTSAMPLE = 0x00000001, VTF_FLAGS_TRILINEAR = 0x00000002, VTF_FLAGS_CLAMP_S = 0x00000004, VTF_FLAGS_CLAMP_T = 0x00000008, VTF_FLAGS_ANISOTROPIC = 0x00000010, VTF_FLAGS_HINT_DXT5 = 0x00000020, VTF_FLAGS_NOCOMPRESS = 0x00000040, VTF_FLAGS_NORMAL = 0x00000080, VTF_FLAGS_NOMIP = 0x00000100, VTF_FLAGS_NOLOD = 0x00000200, VTF_FLAGS_MINMIP = 0x00000400, VTF_FLAGS_PROCEDURAL = 0x00000800, VTF_FLAGS_ONEBITALPHA = 0x00001000, VTF_FLAGS_EIGHTBITALPHA = 0x00002000, VTF_FLAGS_ENVMAP = 0x00004000, VTF_FLAGS_RENDERTARGET = 0x00008000, VTF_FLAGS_DEPTHRENDERTARGET = 0x00010000, VTF_FLAGS_NODEBUGOVERRIDE = 0x00020000, VTF_FLAGS_SINGLECOPY = 0x00040000, VTF_FLAGS_ONEOVERMIPLEVELINALPHA = 0x00080000, VTF_FLAGS_PREMULTCOLORBYONEOVERMIPLEVEL = 0x00100000, VTF_FLAGS_NORMALTODUDV = 0x00200000, VTF_FLAGS_ALPHATESTMIPGENERATION = 0x00400000, VTF_FLAGS_NODEPTHBUFFER = 0x00800000, VTF_FLAGS_NICEFILTERED = 0x01000000, VTF_FLAGS_CLAMP_U = 0x02000000, VTF_FLAGS_PRESWIZZLED = 0x04000000, VTF_FLAGS_CACHEABLE = 0x08000000, VTF_FLAGS_UNFILTERABLE_OK = 0x10000000, VTF_FLAGS_LASTFLAG = 0x10000000 }; enum VTFCubeMapFaceIndex { VTF_CUBEMAP_FACE_RIGHT = 0, VTF_CUBEMAP_FACE_LEFT, VTF_CUBEMAP_FACE_BACK, VTF_CUBEMAP_FACE_FRONT, VTF_CUBEMAP_FACE_UP, VTF_CUBEMAP_FACE_DOWN, VTF_CUBEMAP_FACE_SPHEREMAP, VTF_CUBEMAP_FACE_COUNT }; enum VTFLookDir { VTF_LOOK_DOWN_X = 0, VTF_LOOK_DOWN_NEGX, VTF_LOOK_DOWN_Y = 0, VTF_LOOK_DOWN_NEGY, VTF_LOOK_DOWN_Z = 0, VTF_LOOK_DOWN_NEGZ }; enum VTFImageFormat { VTF_FORMAT_UNKNOWN = -1, VTF_FORMAT_RGBA8888 = 0, VTF_FORMAT_ABGR8888, VTF_FORMAT_RGB888, VTF_FORMAT_BGR888, VTF_FORMAT_RGB565, VTF_FORMAT_I8, VTF_FORMAT_IA88, VTF_FORMAT_P8, VTF_FORMAT_A8, VTF_FORMAT_RGB888_BLUESCREEN, VTF_FORMAT_BGR888_BLUESCREEN, VTF_FORMAT_ARGB8888, VTF_FORMAT_BGRA8888, VTF_FORMAT_DXT1, VTF_FORMAT_DXT3, VTF_FORMAT_DXT5, VTF_FORMAT_BGRX8888, VTF_FORMAT_BGR565, VTF_FORMAT_BGRX5551, VTF_FORMAT_BGRA4444, VTF_FORMAT_DXT1_ONEBITALPHA, VTF_FORMAT_BGRA5551, VTF_FORMAT_UV88, VTF_FORMAT_UVWQ8888, VTF_FORMAT_RGBA16161616F, VTF_FORMAT_RGBA16161616, VTF_FORMAT_UVLX8888, VTF_FORMAT_R32F, VTF_FORMAT_RGB323232F, VTF_FORMAT_RGBA32323232F, VTF_NUM_IMAGE_FORMATS }; #define VTF_FORMAT_DEFAULT ((VTFImageFormat)-2) struct VTFFileHeader { char magic_number[4]; unsigned int file_version[2]; unsigned int header_size; unsigned short image_width; unsigned short image_height; unsigned int image_flags; unsigned short num_frames; unsigned short start_frame; unsigned char padding_0[4]; osg::Vec3f reflectivity_value; unsigned char padding_1[4]; float bump_scale; unsigned int image_format; unsigned char num_mip_levels; unsigned char low_res_image_format; unsigned char padding_2[3]; unsigned char low_res_image_width; unsigned char low_res_image_height; unsigned short image_depth; }; // // Structure of a DXT-1 compressed texture block // see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/directx9_c/Opaque_and_1_Bit_Alpha_Textures.asp // struct DXT1TexelsBlock { unsigned short color_0; // colors at their unsigned short color_1; // extreme unsigned int texels4x4; // interpolated colors (2 bits per texel) }; bool ConvertImageFormat(unsigned int vtfFormat, int& internalFormat, int& pixelFormat, int& dataType) { bool supported; // Assume a supported format to start supported = true; // Decode the format switch (vtfFormat) { case VTF_FORMAT_DEFAULT: supported = false; break; case VTF_FORMAT_UNKNOWN: supported = false; break; case VTF_FORMAT_RGBA8888: internalFormat = GL_RGBA; pixelFormat = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_ABGR8888: internalFormat = GL_RGBA; pixelFormat = GL_ABGR_EXT; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_RGB888: internalFormat = GL_RGB; pixelFormat = GL_RGB; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_BGR888: internalFormat = GL_RGB; pixelFormat = GL_BGR; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_RGB565: internalFormat = GL_RGB; pixelFormat = GL_RGB; dataType = GL_UNSIGNED_SHORT_5_6_5; break; case VTF_FORMAT_I8: internalFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_IA88: internalFormat = GL_LUMINANCE_ALPHA; pixelFormat = GL_LUMINANCE_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_P8: // 8-bit paletted image, not supported supported = false; break; case VTF_FORMAT_A8: internalFormat = GL_ALPHA; pixelFormat = GL_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_RGB888_BLUESCREEN: // Ignore the "bluescreen" specification for now internalFormat = GL_RGB; pixelFormat = GL_RGB; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_BGR888_BLUESCREEN: // Ignore the "bluescreen" specification for now internalFormat = GL_RGB; pixelFormat = GL_BGR; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_ARGB8888: // ARGB not supported supported = false; break; case VTF_FORMAT_BGRA8888: internalFormat = GL_RGBA; pixelFormat = GL_BGRA; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_DXT1: internalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; pixelFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_DXT3: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; pixelFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_DXT5: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; pixelFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_BGRX8888: internalFormat = GL_RGB; pixelFormat = GL_BGRA; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_BGR565: internalFormat = GL_RGB; pixelFormat = GL_BGR; dataType = GL_UNSIGNED_SHORT_5_6_5_REV; break; case VTF_FORMAT_BGRX5551: internalFormat = GL_RGB; pixelFormat = GL_BGRA; dataType = GL_UNSIGNED_SHORT_5_5_5_1; break; case VTF_FORMAT_BGRA4444: internalFormat = GL_RGBA; pixelFormat = GL_BGRA; dataType = GL_UNSIGNED_SHORT_4_4_4_4; break; case VTF_FORMAT_DXT1_ONEBITALPHA: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; pixelFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; dataType = GL_UNSIGNED_BYTE; break; case VTF_FORMAT_BGRA5551: internalFormat = GL_RGBA; pixelFormat = GL_BGRA; dataType = GL_UNSIGNED_SHORT_5_5_5_1; break; case VTF_FORMAT_UV88: supported = false; break; case VTF_FORMAT_UVWQ8888: supported = false; break; case VTF_FORMAT_RGBA16161616F: internalFormat = GL_RGBA; pixelFormat = GL_RGBA; dataType = GL_HALF_FLOAT_NV; break; case VTF_FORMAT_RGBA16161616: internalFormat = GL_RGBA; pixelFormat = GL_RGBA; dataType = GL_UNSIGNED_SHORT; break; case VTF_FORMAT_UVLX8888: supported = false; break; default: supported = false; break; } // Return whether or not the format is supported return supported; } osg::Image* ReadVTFFile(std::istream& _istream) { VTFFileHeader vtf_header; bool supported; int internalFormat; int pixelFormat; int dataType; int s, t, r; unsigned int lrSize; unsigned char * imageData; unsigned int base; unsigned int size; int mip; int mipSize; int mipOffset; // Validate the file with the 'VTF\0' magic number _istream.read(&vtf_header.magic_number[0], 4); if ((vtf_header.magic_number[0] != 'V') || (vtf_header.magic_number[1] != 'T') || (vtf_header.magic_number[2] != 'F') || (vtf_header.magic_number[3] != 0)) { // Not a VTF file, so bail osg::notify(osg::WARN) << "VTF file is invalid" << std::endl; return NULL; } // Now, read the rest of the header _istream.read((char *)&vtf_header.file_version[0], 8); _istream.read((char *)&vtf_header.header_size, 4); _istream.read((char *)&vtf_header.image_width, 2); _istream.read((char *)&vtf_header.image_height, 2); _istream.read((char *)&vtf_header.image_flags, 4); _istream.read((char *)&vtf_header.num_frames, 2); _istream.read((char *)&vtf_header.start_frame, 2); _istream.ignore(4); _istream.read((char *)&vtf_header.reflectivity_value, 12); _istream.ignore(4); _istream.read((char *)&vtf_header.bump_scale, 4); _istream.read((char *)&vtf_header.image_format, 4); _istream.read((char *)&vtf_header.num_mip_levels, 1); _istream.read((char *)&vtf_header.low_res_image_format, 4); _istream.read((char *)&vtf_header.low_res_image_width, 1); _istream.read((char *)&vtf_header.low_res_image_height, 1); // No depth in textures earlier than version 7.2 if ((vtf_header.file_version[0] < 7) || ((vtf_header.file_version[0] == 7) && (vtf_header.file_version[1] < 2))) { // No depth in header, set it to 1 vtf_header.image_depth = 1; } else { // Read the image depth _istream.read((char *)&vtf_header.image_depth, 2); } // Skip past the rest of the header's space std::streampos filePos = _istream.tellg(); _istream.ignore(vtf_header.header_size - filePos); // Environment maps not supported if (vtf_header.image_flags & VTF_FLAGS_ENVMAP) { osg::notify(osg::WARN) << "VTF Environment maps not supported"; osg::notify(osg::WARN) << std::endl; return NULL; } osg::notify(osg::INFO) << "VTF Header: (" << sizeof(VTFFileHeader); osg::notify(osg::INFO) << " bytes)" << std::endl; osg::notify(osg::INFO) << " magic_number = "; osg::notify(osg::INFO) << vtf_header.magic_number[0]; osg::notify(osg::INFO) << vtf_header.magic_number[1]; osg::notify(osg::INFO) << vtf_header.magic_number[2]; osg::notify(osg::INFO) << vtf_header.magic_number[3] << std:: endl; osg::notify(osg::INFO) << " file_version = "; osg::notify(osg::INFO) << vtf_header.file_version[0] << "."; osg::notify(osg::INFO) << vtf_header.file_version[1] << std:: endl; osg::notify(osg::INFO) << " header_size = "; osg::notify(osg::INFO) << vtf_header.header_size << std::endl; osg::notify(osg::INFO) << " image_width = "; osg::notify(osg::INFO) << vtf_header.image_width << std::endl; osg::notify(osg::INFO) << " image_height = "; osg::notify(osg::INFO) << vtf_header.image_height << std::endl; osg::notify(osg::INFO) << " num_frames = "; osg::notify(osg::INFO) << vtf_header.num_frames << std::endl; osg::notify(osg::INFO) << " start_frame = "; osg::notify(osg::INFO) << vtf_header.start_frame << std::endl; osg::notify(osg::INFO) << " reflectivity = "; osg::notify(osg::INFO) << vtf_header.reflectivity_value.x() << ", "; osg::notify(osg::INFO) << vtf_header.reflectivity_value.y() << ", "; osg::notify(osg::INFO) << vtf_header.reflectivity_value.z() << std::endl; osg::notify(osg::INFO) << " bump_scale = "; osg::notify(osg::INFO) << vtf_header.bump_scale << std::endl; osg::notify(osg::INFO) << " image_format = "; osg::notify(osg::INFO) << vtf_header.image_format << std::endl; osg::notify(osg::INFO) << " num_mip_lvls = "; osg::notify(osg::INFO) << (int)vtf_header.num_mip_levels << std::endl; osg::notify(osg::INFO) << " lr_image_fmt = "; osg::notify(osg::INFO) << (int)vtf_header.low_res_image_format << std::endl; osg::notify(osg::INFO) << " lr_width = "; osg::notify(osg::INFO) << (int)vtf_header.low_res_image_width << std::endl; osg::notify(osg::INFO) << " lr_height = "; osg::notify(osg::INFO) << (int)vtf_header.low_res_image_height << std::endl; osg::notify(osg::INFO) << " image_depth = "; osg::notify(osg::INFO) << (int)vtf_header.image_depth << std::endl; // Before we get to the real image, we need to skip over the "low res" // image that's often stored along with VTF textures, so get the // low-res image dimensions s = vtf_header.low_res_image_width; t = vtf_header.low_res_image_height; r = 1; osg::notify(osg::INFO) << "Low-res s = " << s << std::endl; osg::notify(osg::INFO) << "Low-res t = " << t << std::endl; // See if the low-res image is there lrSize = 0; if ((s > 0) && (t > 0)) { supported = ConvertImageFormat(vtf_header.low_res_image_format, internalFormat, pixelFormat, dataType); // If we don't recognize the format, we can't locate the real image // in the file, so we have to bail if (!supported) { osg::notify(osg::WARN) << "Low-res image format is not supported"; osg::notify(osg::WARN) << " (" << vtf_header.low_res_image_format; osg::notify(osg::WARN) << ")" << std::endl; return NULL; } // Allocate an osg::Image for the lo-res image metadata osg::ref_ptr<osg::Image> loResImage = new osg::Image(); // Set the image metadata, and figure out how many bytes to read loResImage->setImage(s, t, r, internalFormat, pixelFormat, dataType, 0, osg::Image::USE_NEW_DELETE); lrSize = loResImage->getTotalSizeInBytes(); // Skip over the low-res image data osg::notify(osg::INFO) << "Low-res size = " << lrSize << std::endl; _istream.ignore(lrSize); } // Compute the base position of the high-res image data base = vtf_header.header_size + lrSize; // Now, get the internal format, pixel format, and data type from the // full-size image format, and check whether the format is supported supported = ConvertImageFormat(vtf_header.image_format, internalFormat, pixelFormat, dataType); // Bail if the format isn't supported if (!supported) { osg::notify(osg::WARN) << "Image format is not supported ("; osg::notify(osg::WARN) << vtf_header.image_format << ")"; osg::notify(osg::WARN) << std::endl; return NULL; } // Get the dimensions of the image s = vtf_header.image_width; t = vtf_header.image_height; r = vtf_header.image_depth; // VTF allows either 0 or 1 for 2D images if (r == 0) r = 1; // NOTE: VTF supports animated textures and cube maps. Currently, we // only handle a single frame of data, so multiple frames // are ignored. Same for cube maps (only one face is loaded). // Create the mipmap offsets vector osg::Image::MipmapDataType mipmaps; // Deal with mipmaps, if necessary if (vtf_header.num_mip_levels > 1) { // Set up the offsets vector float power2_s = logf((float)s)/logf((float)2); float power2_t = logf((float)t)/logf((float)2); mipmaps.resize((unsigned int)osg::maximum(power2_s,power2_t),0); // Calculate the dimensions of each mipmap if ((vtf_header.image_format == VTF_FORMAT_DXT1) || (vtf_header.image_format == VTF_FORMAT_DXT1_ONEBITALPHA) || (vtf_header.image_format == VTF_FORMAT_DXT3) || (vtf_header.image_format == VTF_FORMAT_DXT5)) { // Handle S3TC compressed mipmaps int width = vtf_header.image_width; int height = vtf_header.image_height; int blockSize; if ((vtf_header.image_format == VTF_FORMAT_DXT1) || (vtf_header.image_format == VTF_FORMAT_DXT1_ONEBITALPHA)) blockSize = 8; else blockSize = 16; int offset = 0; for (unsigned int k = 1; (k < vtf_header.num_mip_levels) && (width || height); ++k) { // Clamp dimensions to 1 if (width == 0) width = 1; if (height == 0) height = 1; // Compute and store the offset into the final image data offset += (((width+3)/4) * ((height+3)/4) * blockSize); mipmaps[k-1] = offset; // Get the next level's dimensions width >>= 1; height >>= 1; } } else { // Handle uncompressed mipmaps int offset = 0; int width = vtf_header.image_width; int height = vtf_header.image_height; int depth = vtf_header.image_depth; for (unsigned int k = 1; (k < vtf_header.num_mip_levels) && (width || height || depth); ++k) { if (width == 0) width = 1; if (height == 0) height = 1; if (depth == 0) depth = 1; // Compute and store the offset into the final image data offset += depth * height * osg::Image::computeRowWidthInBytes(width, pixelFormat, dataType, 1 ); mipmaps[k-1] = offset; // Get the next level's dimensions width >>= 1; height >>= 1; depth >>= 1; } } } // Allocate the resulting osg::Image osg::ref_ptr<osg::Image> osgImage = new osg::Image(); // Set the image meta-data, including dimensions, format, data type, // and mipmap levels. Everything but the image data itself. We'll use // this to compute the total image size, so we know how much data to read // from the file osgImage->setImage(s, t, r, internalFormat, pixelFormat, dataType, 0, osg::Image::USE_NEW_DELETE); if (mipmaps.size() > 0) osgImage->setMipmapLevels(mipmaps); // Compute the total image size size = osgImage->getTotalSizeInBytesIncludingMipmaps(); osg::notify(osg::INFO) << "ReadVTFFile info : size = " << size << std::endl; if(size <= 0) { osg::notify(osg::WARN) << "ReadVTFFile warning: size <= 0" << std::endl; return NULL; } // Prepare to read the image data imageData = new unsigned char [size]; if(!imageData) { osg::notify(osg::WARN) << "ReadVTFFile warning: imageData == NULL"; osg::notify(osg::WARN) << std::endl; return NULL; } // See if we have mipmaps if (vtf_header.num_mip_levels > 1) { // VTF stores the mipmaps in reverse order from what OpenGL expects, so // we need to read them from the file and store them in order in the // image data array for (mip = vtf_header.num_mip_levels - 2; mip >= 0; mip--) { // Look up the offset for this mip level mipOffset = mipmaps[mip]; // Calculate the size of the mipmap if (mip == vtf_header.num_mip_levels-2) mipSize = size - mipOffset; else mipSize = mipmaps[mip+1] - mipOffset; // Read the image data _istream.read((char*)&imageData[mipOffset], mipSize); } // We've read all of the mipmaps except the largest (the original // image), so do that now mipSize = mipmaps[0]; _istream.read((char*)imageData, mipSize); } else { // Just read the image data _istream.read((char*)imageData, size); } /* // Check if alpha information embedded in the 8-byte encoding blocks if (checkIfUsingOneBitAlpha) { const DXT1TexelsBlock *texelsBlock = reinterpret_cast<const DXT1TexelsBlock*>(imageData); // Only do the check on the first mipmap level unsigned int numBlocks = mipmaps.size()>0 ? mipmaps[0] / 8 : size / 8; for (int i=numBlocks; i>0; --i, ++texelsBlock) { if (texelsBlock->color_0<=texelsBlock->color_1) { // Texture is using the 1-bit alpha encoding, so we need to // update the assumed pixel format internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; pixelFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; } } } */ // Now, set the actual image data and mipmap levels osgImage->setImage(s,t,r, internalFormat, pixelFormat, dataType, imageData, osg::Image::USE_NEW_DELETE); if (mipmaps.size()>0) osgImage->setMipmapLevels(mipmaps); // Finally, return the image return osgImage.release(); } bool WriteVTFFile(const osg::Image *img, std::ostream& fout) { // Not supported return false; } class ReaderWriterVTF : public osgDB::ReaderWriter { public: virtual const char* className() const { return "VTF Image Reader/Writer"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension, "vtf"); } virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const { return readImage(file,options); } virtual ReadResult readObject(std::istream& fin, const Options* options) const { return readImage(fin,options); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; std::ifstream stream(fileName.c_str(), std::ios::in | std::ios::binary); if(!stream) return ReadResult::FILE_NOT_HANDLED; ReadResult rr = readImage(stream, options); if(rr.validImage()) rr.getImage()->setFileName(file); return rr; } virtual ReadResult readImage(std::istream& fin, const Options* options) const { osg::Image* osgImage = ReadVTFFile(fin); if (osgImage==NULL) return ReadResult::FILE_NOT_HANDLED; if (options && options->getOptionString().find("vtf_flip")!=std::string::npos) { osgImage->flipVertical(); } return osgImage; } virtual WriteResult writeObject(const osg::Object& object,const std::string& file, const osgDB::ReaderWriter::Options* options) const { const osg::Image* image = dynamic_cast<const osg::Image*>(&object); if (!image) return WriteResult::FILE_NOT_HANDLED; return writeImage(*image,file,options); } virtual WriteResult writeObject(const osg::Object& object,std::ostream& fout,const Options* options) const { const osg::Image* image = dynamic_cast<const osg::Image*>(&object); if (!image) return WriteResult::FILE_NOT_HANDLED; return writeImage(*image,fout,options); } virtual WriteResult writeImage(const osg::Image &image,const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getFileExtension(file); if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; std::ofstream fout(file.c_str(), std::ios::out | std::ios::binary); if(!fout) return WriteResult::ERROR_IN_WRITING_FILE; return writeImage(image,fout,options); } virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const Options*) const { bool success = WriteVTFFile(&image, fout); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } }; // now register with Registry to instantiate the above // reader/writer. REGISTER_OSGPLUGIN(vtf, ReaderWriterVTF)
33.893432
137
0.582078
[ "object", "vector" ]
d1241c2354bc9ebf3c1b29021dfa41eb5813ef5d
10,105
cpp
C++
test/libpldmresponder_platform_test.cpp
mine260309/pldm
ac3c45aebd29a8e1d9ec36e3a9c33773dec1cbb3
[ "Apache-2.0" ]
null
null
null
test/libpldmresponder_platform_test.cpp
mine260309/pldm
ac3c45aebd29a8e1d9ec36e3a9c33773dec1cbb3
[ "Apache-2.0" ]
null
null
null
test/libpldmresponder_platform_test.cpp
mine260309/pldm
ac3c45aebd29a8e1d9ec36e3a9c33773dec1cbb3
[ "Apache-2.0" ]
null
null
null
#include "libpldmresponder/pdr.hpp" #include "libpldmresponder/pdr_utils.hpp" #include "libpldmresponder/platform.hpp" #include <iostream> #include <gmock/gmock-matchers.h> #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace pldm::responder; using namespace pldm::responder::platform; using namespace pldm::responder::pdr; using namespace pldm::responder::pdr_utils; TEST(getPDR, testGoodPath) { std::array<uint8_t, sizeof(pldm_msg_hdr) + PLDM_GET_PDR_REQ_BYTES> requestPayload{}; auto req = reinterpret_cast<pldm_msg*>(requestPayload.data()); size_t requestPayloadLength = requestPayload.size() - sizeof(pldm_msg_hdr); struct pldm_get_pdr_req* request = reinterpret_cast<struct pldm_get_pdr_req*>(req->payload); request->request_count = 100; auto pdrRepo = pldm_pdr_init(); Handler handler("./pdr_jsons/state_effecter/good", pdrRepo); Repo repo(pdrRepo); ASSERT_EQ(repo.empty(), false); auto response = handler.getPDR(req, requestPayloadLength); auto responsePtr = reinterpret_cast<pldm_msg*>(response.data()); struct pldm_get_pdr_resp* resp = reinterpret_cast<struct pldm_get_pdr_resp*>(responsePtr->payload); ASSERT_EQ(PLDM_SUCCESS, resp->completion_code); ASSERT_EQ(2, resp->next_record_handle); ASSERT_EQ(true, resp->response_count != 0); pldm_pdr_hdr* hdr = reinterpret_cast<pldm_pdr_hdr*>(resp->record_data); ASSERT_EQ(hdr->record_handle, 1); ASSERT_EQ(hdr->version, 1); pldm_pdr_destroy(pdrRepo); } TEST(getPDR, testShortRead) { std::array<uint8_t, sizeof(pldm_msg_hdr) + PLDM_GET_PDR_REQ_BYTES> requestPayload{}; auto req = reinterpret_cast<pldm_msg*>(requestPayload.data()); size_t requestPayloadLength = requestPayload.size() - sizeof(pldm_msg_hdr); struct pldm_get_pdr_req* request = reinterpret_cast<struct pldm_get_pdr_req*>(req->payload); request->request_count = 1; auto pdrRepo = pldm_pdr_init(); Handler handler("./pdr_jsons/state_effecter/good", pdrRepo); Repo repo(pdrRepo); ASSERT_EQ(repo.empty(), false); auto response = handler.getPDR(req, requestPayloadLength); auto responsePtr = reinterpret_cast<pldm_msg*>(response.data()); struct pldm_get_pdr_resp* resp = reinterpret_cast<struct pldm_get_pdr_resp*>(responsePtr->payload); ASSERT_EQ(PLDM_SUCCESS, resp->completion_code); ASSERT_EQ(1, resp->response_count); pldm_pdr_destroy(pdrRepo); } TEST(getPDR, testBadRecordHandle) { std::array<uint8_t, sizeof(pldm_msg_hdr) + PLDM_GET_PDR_REQ_BYTES> requestPayload{}; auto req = reinterpret_cast<pldm_msg*>(requestPayload.data()); size_t requestPayloadLength = requestPayload.size() - sizeof(pldm_msg_hdr); struct pldm_get_pdr_req* request = reinterpret_cast<struct pldm_get_pdr_req*>(req->payload); request->record_handle = 100000; request->request_count = 1; auto pdrRepo = pldm_pdr_init(); Handler handler("./pdr_jsons/state_effecter/good", pdrRepo); Repo repo(pdrRepo); ASSERT_EQ(repo.empty(), false); auto response = handler.getPDR(req, requestPayloadLength); auto responsePtr = reinterpret_cast<pldm_msg*>(response.data()); ASSERT_EQ(responsePtr->payload[0], PLDM_PLATFORM_INVALID_RECORD_HANDLE); pldm_pdr_destroy(pdrRepo); } TEST(getPDR, testNoNextRecord) { std::array<uint8_t, sizeof(pldm_msg_hdr) + PLDM_GET_PDR_REQ_BYTES> requestPayload{}; auto req = reinterpret_cast<pldm_msg*>(requestPayload.data()); size_t requestPayloadLength = requestPayload.size() - sizeof(pldm_msg_hdr); struct pldm_get_pdr_req* request = reinterpret_cast<struct pldm_get_pdr_req*>(req->payload); request->record_handle = 1; auto pdrRepo = pldm_pdr_init(); Handler handler("./pdr_jsons/state_effecter/good", pdrRepo); Repo repo(pdrRepo); ASSERT_EQ(repo.empty(), false); auto response = handler.getPDR(req, requestPayloadLength); auto responsePtr = reinterpret_cast<pldm_msg*>(response.data()); struct pldm_get_pdr_resp* resp = reinterpret_cast<struct pldm_get_pdr_resp*>(responsePtr->payload); ASSERT_EQ(PLDM_SUCCESS, resp->completion_code); ASSERT_EQ(2, resp->next_record_handle); pldm_pdr_destroy(pdrRepo); } TEST(getPDR, testFindPDR) { std::array<uint8_t, sizeof(pldm_msg_hdr) + PLDM_GET_PDR_REQ_BYTES> requestPayload{}; auto req = reinterpret_cast<pldm_msg*>(requestPayload.data()); size_t requestPayloadLength = requestPayload.size() - sizeof(pldm_msg_hdr); struct pldm_get_pdr_req* request = reinterpret_cast<struct pldm_get_pdr_req*>(req->payload); request->request_count = 100; auto pdrRepo = pldm_pdr_init(); Handler handler("./pdr_jsons/state_effecter/good", pdrRepo); Repo repo(pdrRepo); ASSERT_EQ(repo.empty(), false); auto response = handler.getPDR(req, requestPayloadLength); // Let's try to find a PDR of type stateEffecter (= 11) and entity type = // 100 bool found = false; uint32_t handle = 0; // start asking for PDRs from recordHandle 0 while (!found) { request->record_handle = handle; auto response = handler.getPDR(req, requestPayloadLength); auto responsePtr = reinterpret_cast<pldm_msg*>(response.data()); struct pldm_get_pdr_resp* resp = reinterpret_cast<struct pldm_get_pdr_resp*>(responsePtr->payload); ASSERT_EQ(PLDM_SUCCESS, resp->completion_code); handle = resp->next_record_handle; // point to the next pdr in case // current is not what we want pldm_pdr_hdr* hdr = reinterpret_cast<pldm_pdr_hdr*>(resp->record_data); std::cerr << "PDR next record handle " << handle << "\n"; std::cerr << "PDR type " << hdr->type << "\n"; if (hdr->type == PLDM_STATE_EFFECTER_PDR) { pldm_state_effecter_pdr* pdr = reinterpret_cast<pldm_state_effecter_pdr*>(resp->record_data); std::cerr << "PDR entity type " << pdr->entity_type << "\n"; if (pdr->entity_type == 100) { found = true; // Rest of the PDR can be accessed as need be break; } } if (!resp->next_record_handle) // no more records { break; } } ASSERT_EQ(found, true); pldm_pdr_destroy(pdrRepo); } namespace pldm { namespace responder { class MockdBusHandler { public: MOCK_CONST_METHOD4(setDbusProperty, int(const std::string&, const std::string&, const std::string&, const std::variant<std::string>&)); }; } // namespace responder } // namespace pldm using ::testing::_; using ::testing::Return; TEST(setStateEffecterStatesHandler, testGoodRequest) { auto inPDRRepo = pldm_pdr_init(); auto outPDRRepo = pldm_pdr_init(); Repo outRepo(outPDRRepo); Handler handler("./pdr_jsons/state_effecter/good", inPDRRepo); Repo inRepo(inPDRRepo); getRepoByType(inRepo, outRepo, PLDM_STATE_EFFECTER_PDR); pdr_utils::PdrEntry e; auto record1 = pdr::getRecordByHandle(outRepo, 1, e); ASSERT_NE(record1, nullptr); pldm_state_effecter_pdr* pdr = reinterpret_cast<pldm_state_effecter_pdr*>(e.data); EXPECT_EQ(pdr->hdr.type, PLDM_STATE_EFFECTER_PDR); std::vector<set_effecter_state_field> stateField; stateField.push_back({PLDM_REQUEST_SET, 1}); stateField.push_back({PLDM_REQUEST_SET, 1}); auto bootProgressInf = "xyz.openbmc_project.State.OperatingSystem.Status"; auto bootProgressProp = "OperatingSystemState"; std::string objPath = "/foo/bar"; std::variant<std::string> value{"xyz.openbmc_project.State.OperatingSystem." "Status.OSStatus.Standby"}; MockdBusHandler handlerObj; EXPECT_CALL(handlerObj, setDbusProperty(objPath, bootProgressProp, bootProgressInf, value)) .Times(2); auto rc = handler.setStateEffecterStatesHandler<MockdBusHandler>( handlerObj, 0x1, stateField); ASSERT_EQ(rc, 0); pldm_pdr_destroy(inPDRRepo); pldm_pdr_destroy(outPDRRepo); } TEST(setStateEffecterStatesHandler, testBadRequest) { auto inPDRRepo = pldm_pdr_init(); auto outPDRRepo = pldm_pdr_init(); Repo outRepo(outPDRRepo); Handler handler("./pdr_jsons/state_effecter/good", inPDRRepo); Repo inRepo(inPDRRepo); getRepoByType(inRepo, outRepo, PLDM_STATE_EFFECTER_PDR); pdr_utils::PdrEntry e; auto record1 = pdr::getRecordByHandle(outRepo, 1, e); ASSERT_NE(record1, nullptr); pldm_state_effecter_pdr* pdr = reinterpret_cast<pldm_state_effecter_pdr*>(e.data); EXPECT_EQ(pdr->hdr.type, PLDM_STATE_EFFECTER_PDR); std::vector<set_effecter_state_field> stateField; stateField.push_back({PLDM_REQUEST_SET, 3}); stateField.push_back({PLDM_REQUEST_SET, 4}); MockdBusHandler handlerObj; auto rc = handler.setStateEffecterStatesHandler<MockdBusHandler>( handlerObj, 0x1, stateField); ASSERT_EQ(rc, PLDM_PLATFORM_SET_EFFECTER_UNSUPPORTED_SENSORSTATE); rc = handler.setStateEffecterStatesHandler<MockdBusHandler>(handlerObj, 0x9, stateField); ASSERT_EQ(rc, PLDM_PLATFORM_INVALID_EFFECTER_ID); stateField.push_back({PLDM_REQUEST_SET, 4}); rc = handler.setStateEffecterStatesHandler<MockdBusHandler>(handlerObj, 0x1, stateField); ASSERT_EQ(rc, PLDM_ERROR_INVALID_DATA); std::vector<set_effecter_state_field> newStateField; newStateField.push_back({PLDM_REQUEST_SET, 1}); rc = handler.setStateEffecterStatesHandler<MockdBusHandler>(handlerObj, 0x2, newStateField); ASSERT_EQ(rc, PLDM_PLATFORM_INVALID_STATE_VALUE); pldm_pdr_destroy(inPDRRepo); pldm_pdr_destroy(outPDRRepo); }
36.348921
80
0.68481
[ "vector" ]
d124f39fddde6d7ecdb8400d5d6e6f9af5943b8d
49,793
cxx
C++
inetcore/wininet/dll/thrdinfo.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/wininet/dll/thrdinfo.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/wininet/dll/thrdinfo.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1994 Microsoft Corporation Module Name: thrdinfo.cxx Abstract: Functions to manipulate an INTERNET_THREAD_INFO Contents: InternetCreateThreadInfo InternetDestroyThreadInfo InternetTerminateThreadInfo InternetGetThreadInfo InternetSetThreadInfo InternetIndicateStatusAddress InternetIndicateStatusString InternetIndicateStatusNewHandle InternetIndicateStatus InternetSetLastError _InternetSetLastError InternetLockErrorText InternetUnlockErrorText InternetSetContext InternetSetObjectHandle InternetGetObjectHandle InternetFreeThreadInfo Author: Richard L Firth (rfirth) 16-Feb-1995 Environment: Win32 user-level DLL Revision History: 16-Feb-1995 rfirth Created --*/ #include <wininetp.h> #include <perfdiag.hxx> // // manifests // #define BAD_TLS_INDEX 0xffffffff // according to online win32 SDK documentation #ifdef SPX_SUPPORT #define GENERIC_SPX_NAME "SPX Server" #endif //SPX_SUPPORT // // macros // #ifdef ENABLE_DEBUG #define InitializeInternetThreadInfo(lpThreadInfo) \ InitializeListHead(&lpThreadInfo->List); \ lpThreadInfo->Signature = INTERNET_THREAD_INFO_SIGNATURE; \ lpThreadInfo->ThreadId = GetCurrentThreadId(); #else #define InitializeInternetThreadInfo(threadInfo) \ InitializeListHead(&lpThreadInfo->List); \ lpThreadInfo->ThreadId = GetCurrentThreadId(); #endif // ENABLE_DEBUG // // private data // PRIVATE DWORD InternetTlsIndex = BAD_TLS_INDEX; PRIVATE SERIALIZED_LIST ThreadInfoList; INTERNETAPI_(BOOL) ResumeSuspendedDownload( IN HINTERNET hRequest, IN DWORD dwResultCode ) /*++ Routine Description: Attempts to restart a stalled FSM that is blocked on UI interaction, Arguments: hRequest - handle to open HTTP request dwResultCode - the result of InternetErrorDlg, passed back into Wininet via this API Return Value: DWORD Success - ERROR_SUCCESS ERROR_IO_PENDING Failure - --*/ { HINTERNET hRequestMapped = NULL; BOOL fResumed = FALSE; DWORD error; // // map the handle // error = MapHandleToAddress(hRequest, (LPVOID *)&hRequestMapped, FALSE); if ((error != ERROR_SUCCESS) && (hRequestMapped == NULL)) { goto quit; } // // Call internal to do the work // error = ResumeAfterUserInput( hRequestMapped, dwResultCode, &fResumed ); if ( error != ERROR_SUCCESS) { goto quit; } if ( error == ERROR_SUCCESS ) { error = ERROR_IO_PENDING; // remap to pending } // // If we failed to resume, the handle must have been canceled // if (!fResumed) { error = ERROR_INTERNET_OPERATION_CANCELLED; goto quit; } quit: if (hRequestMapped != NULL) { DereferenceObject((LPVOID)hRequestMapped); } SetLastError(error); return (error == ERROR_SUCCESS) ? TRUE : FALSE; } // // functions // DWORD ResumeAfterUserInput( IN HINTERNET hRequestMapped, IN DWORD dwResultCode, OUT LPBOOL pfItemResumed ) /*++ Routine Description: Internal version of Resume API that unblocks an FSM after the UI has been shown, user prompted, and the FSM should now continue. Arguments: hRequestMapped - dwResultCode - pfItemResumed - Return Value: DWORD Success - ERROR_SUCCESS Failure - --*/ { HTTP_REQUEST_HANDLE_OBJECT *pRequest; INTERNET_CONNECT_HANDLE_OBJECT * pConnect; INTERNET_HANDLE_OBJECT * pInternet; DWORD error = ERROR_SUCCESS; DEBUG_ENTER((DBG_THRDINFO, Dword, "ResumeAfterUserInput", "%x, %u, %x", hRequestMapped, dwResultCode, pfItemResumed )); *pfItemResumed = FALSE; // // Now round up the objects that are involved // pRequest = (HTTP_REQUEST_HANDLE_OBJECT *) hRequestMapped; pConnect = (INTERNET_CONNECT_HANDLE_OBJECT *)pRequest->GetParent(); INET_ASSERT(pConnect != NULL); INET_ASSERT(pConnect->IsValid(TypeHttpConnectHandle) == ERROR_SUCCESS); pInternet = (INTERNET_HANDLE_OBJECT *)pConnect->GetParent(); INET_ASSERT(pInternet != NULL); INET_ASSERT(pInternet->IsValid(TypeInternetHandle) == ERROR_SUCCESS); // // Lock us while we attempt to unblock the FSM // pInternet->LockPopupInfo(); // // Can only resume if we're blocked on both request and internet handles // if ( pInternet->IsBlockedOnUserInput() && pRequest->IsBlockedOnUserInput() ) { DWORD dwCntUnBlocked; INET_ASSERT(pInternet->GetBlockId() == pRequest->GetBlockId()); dwCntUnBlocked = UnblockWorkItems( pInternet->GetBlockedUiCount(), pRequest->GetBlockId(), // blocked on FSM ERROR_SUCCESS, TP_NO_PRIORITY_CHANGE ); if ( dwCntUnBlocked > 0 ) { *pfItemResumed = TRUE; pInternet->SetBlockedResultCode(dwResultCode); } } INET_ASSERT( ! (pRequest->IsBlockedOnUserInput() && !pInternet->IsBlockedOnUserInput()) ); //quit: -- not used pInternet->UnlockPopupInfo(); DEBUG_LEAVE(error); return error; } DWORD ChangeUIBlockingState( IN HINTERNET hRequestMapped, IN DWORD dwError, OUT LPDWORD lpdwActionTaken, OUT LPDWORD lpdwResultCode, IN OUT LPVOID * lplpResultData ) /*++ Routine Description: Attempts to determine the best way of putting up UI for a given error. This allows us to back out of the Asyncronous FSM thread while popping up UI. How it works: We attempt to prevent more than one dialog per InternetOpen handle Arguments: hRequestHandle - mapped handle to open request dwError - error code to pass back to client and ultimately to InternetErrorDlg to generate UI lpdwActionTaken - returns one of several values, used to tell caller what UI action has been taken UI_ACTION_CODE_NONE_TAKEN 0 UI_ACTION_CODE_BLOCKED_FOR_INTERNET_HANDLE 1 UI_ACTION_CODE_BLOCKED_FOR_USER_INPUT 2 UI_ACTION_CODE_USER_ACTION_COMPLETED 3 lpdwResultCode - returns the result of InternetErrorDlg, passed through ResumeSuspendedDownload lplpResultData - a void pointer allocated and owned by callee until after a thread has been resumed used to pass extra data through client to InternetErrorDlg Return Value: DWORD Success - ERROR_SUCCESS ERROR_IO_PENDING Failure - --*/ { HTTP_REQUEST_HANDLE_OBJECT *pRequest; INTERNET_CONNECT_HANDLE_OBJECT * pConnect; DEBUG_ENTER((DBG_THRDINFO, Dword, "ChangeUIBlockingState", "%x, %u, %x, %x [%x]", hRequestMapped, dwError, lpdwActionTaken, lpdwResultCode, lplpResultData, (lplpResultData ? *lplpResultData : NULL ) )); LPINTERNET_THREAD_INFO lpThreadInfo = InternetGetThreadInfo(); DWORD error = ERROR_SUCCESS; DWORD_PTR dwBlockId; BOOL fLocked = FALSE; BOOL fDoAsyncCallback = FALSE; // TRUE if we need to callback to the app LPVOID lpResultData = NULL; *lpdwActionTaken = UI_ACTION_CODE_NONE_TAKEN; if ( lplpResultData ) { lpResultData = *lplpResultData; // save off } // // Gather various sundry elements, objects, thread info, etc, // validate, and if proper continue with the process // if (lpThreadInfo != NULL) { if ( lpThreadInfo->Fsm == NULL ) { goto quit; } if ( ! lpThreadInfo->IsAsyncWorkerThread ) { goto quit; } INET_ASSERT(lpThreadInfo->hObject != NULL); INET_ASSERT(lpThreadInfo->hObjectMapped != NULL); if ( hRequestMapped == NULL ) { hRequestMapped = lpThreadInfo->Fsm->GetMappedHandle(); } INET_ASSERT(hRequestMapped == lpThreadInfo->Fsm->GetMappedHandle()); // // if the context value in the thread info block is 0 then we use the // context from the handle object // DWORD_PTR context; context = _InternetGetContext(lpThreadInfo); if (context == INTERNET_NO_CALLBACK) { context = ((INTERNET_HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->GetContext(); } INTERNET_STATUS_CALLBACK appCallback; appCallback = ((INTERNET_HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->GetStatusCallback(); // // No callback, no FSM means no special UI callback can be done. // if ((appCallback == NULL) || (context == INTERNET_NO_CALLBACK)) { // // For the sync return error // error = dwError; goto quit; } } else { INET_ASSERT(FALSE); goto quit; } // // Make sure our handle isn't invalidated before proceeding // if (((HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->IsInvalidated()) { error = ERROR_INTERNET_OPERATION_CANCELLED; goto quit; } // // Now get the objects that are involved // pRequest = (HTTP_REQUEST_HANDLE_OBJECT *) hRequestMapped; pConnect = (INTERNET_CONNECT_HANDLE_OBJECT *)pRequest->GetParent(); INET_ASSERT(pConnect != NULL); INET_ASSERT(pConnect->IsValid(TypeHttpConnectHandle) == ERROR_SUCCESS); INTERNET_HANDLE_OBJECT * pInternet; pInternet = (INTERNET_HANDLE_OBJECT *)pConnect->GetParent(); INET_ASSERT(pInternet != NULL); INET_ASSERT(pInternet->IsValid(TypeInternetHandle) == ERROR_SUCCESS); pInternet->LockPopupInfo(); fLocked = TRUE; // // We check whether we're blocked on the HTTP handle and the // Internet handle. Basically we have a little matrix here // based on which one is blocked (or if neither is blocked) // // So: // InternetHandle(blocked)/RequestHandle(not-blocked) - // indicates we are not the request blocking the UI, // we will need to block the FSM until the other dialog // has completed // // InternetHandle(blocked)/RequestHandle(blocked) - // indicates that we have blocked and have now been // woken up, we need return the result of the UI // to the caller. // // InternetHandle(not-blocked)/RequestHandle(blocked) - // ASSERT, we shouldn't have this happen // // InternetHandle(not-blocked)/RequestHandle(not-blocked) - // We've just entered with no-blocking handles, // so we block both and wait till UI has completed // if (!pInternet->IsBlockedOnUserInput()) { // // Indicate to the caller via callback // that we need to generate UI, then block // DEBUG_PRINT(THRDINFO, INFO, ("Blocking on UI, notifing client via callback\n" )); fDoAsyncCallback = TRUE; INET_ASSERT(!pRequest->IsBlockedOnUserInput()); dwBlockId = (DWORD_PTR) lpThreadInfo->Fsm; pInternet->BlockOnUserInput(dwError, dwBlockId, lpResultData); // IncrementBlockedUiCount() is implied here. pRequest->BlockOnUserInput(dwBlockId); *lpdwActionTaken = UI_ACTION_CODE_BLOCKED_FOR_USER_INPUT; } else if (pRequest->IsBlockedOnUserInput() ) { DEBUG_PRINT(THRDINFO, INFO, ("UnBlocking on UI, returning UI result\n" )); INET_ASSERT(pInternet->IsBlockedOnUserInput()); // // Retrieve the result of the UI and return // to caller. // // save off block id in case need it later DWORD_PTR dwSavedBlockedId = pRequest->GetBlockId(); INET_ASSERT(pInternet->GetBlockId() == pRequest->GetBlockId()); pInternet->UnBlockOnUserInput(lpdwResultCode, &lpResultData); pRequest->UnBlockOnUserInput(); if ( lplpResultData ) { *lplpResultData = lpResultData; } *lpdwActionTaken = UI_ACTION_CODE_USER_ACTION_COMPLETED; // // If others are still blocked, then wake them up too // if (pInternet->IsBlockedOnUserInput()) { DWORD dwCntUnBlocked; dwCntUnBlocked = UnblockWorkItems( pInternet->GetBlockedUiCount(), dwSavedBlockedId, ERROR_SUCCESS, TP_NO_PRIORITY_CHANGE ); DEBUG_PRINT(THRDINFO, INFO, ("Unblocked %u work items, expected %u\n", dwCntUnBlocked, pInternet->GetBlockedUiCount() )); pInternet->ClearBlockedUiCount(); } goto quit; } else { DEBUG_PRINT(THRDINFO, INFO, ("Blocking on another FSM (that is busy doing UI) until their completeion\n" )); INET_ASSERT(pInternet->IsBlockedOnUserInput()); INET_ASSERT(!pRequest->IsBlockedOnUserInput()); // // not blocked on the request handle // but blocked on internet handle, so we need // to wait until this internet handle is ours // so we do nothing // pInternet->IncrementBlockedUiCount(); dwBlockId = pInternet->GetBlockId(); *lpdwActionTaken = UI_ACTION_CODE_BLOCKED_FOR_INTERNET_HANDLE; } // // Now do the actual blocking of the FSM here. // lpThreadInfo->Fsm->SetState(FSM_STATE_CONTINUE); lpThreadInfo->Fsm->SetNextState(FSM_STATE_CONTINUE); error = BlockWorkItem( lpThreadInfo->Fsm, dwBlockId, // block the FSM on FSM that created this INFINITE // we block foreever ); if ( error == ERROR_SUCCESS ) { error = ERROR_IO_PENDING; //goto quit; } quit: if (fLocked) { INET_ASSERT(hRequestMapped); pInternet->UnlockPopupInfo(); } if (fDoAsyncCallback) { INTERNET_ASYNC_RESULT asyncResult; // // Pass the result Data pointer back to the caller, // this is needed to pass extra info to InternetErrorDlg, // once this pointer is passed, the caller must not free, // until his/her FSM is restarted. // INET_ASSERT(*lpdwActionTaken == UI_ACTION_CODE_BLOCKED_FOR_USER_INPUT); asyncResult.dwResult = (DWORD_PTR)lpResultData; asyncResult.dwError = dwError; SetLastError(dwError); error = InternetIndicateStatus( INTERNET_STATUS_USER_INPUT_REQUIRED, (LPVOID)&asyncResult, sizeof(asyncResult) ); if ( error == ERROR_SUCCESS || error == ERROR_INTERNET_OPERATION_CANCELLED ) { error = ERROR_IO_PENDING; } else { INET_ASSERT(FALSE); } } DEBUG_LEAVE(error); return error; } LPINTERNET_THREAD_INFO InternetCreateThreadInfo( IN BOOL SetTls ) /*++ Routine Description: Creates, initializes an INTERNET_THREAD_INFO. Optionally (allocates and) sets this thread's Internet TLS Assumes: 1. The first time this function is called is in the context of the process attach library call, so we allocate the TLS index once Arguments: SetTls - TRUE if we are to set the INTERNET_THREAD_INFO TLS for this thread Return Value: LPINTERNET_THREAD_INFO Success - pointer to allocated INTERNET_THREAD_INFO structure which has been set as this threads value in its InternetTlsIndex slot Failure - NULL --*/ { LPINTERNET_THREAD_INFO lpThreadInfo = NULL; BOOL ok = FALSE; if (InDllCleanup) { goto quit; } if (InternetTlsIndex == BAD_TLS_INDEX) { // // first time through, initialize serialized list // InitializeSerializedList(&ThreadInfoList); // // we assume that if we are allocating the TLS index, then this is the // one and only thread in this process that can call into this DLL // right now - i.e. this thread is loading the DLL // InternetTlsIndex = TlsAlloc(); } if (InternetTlsIndex != BAD_TLS_INDEX) { lpThreadInfo = NEW(INTERNET_THREAD_INFO); if (lpThreadInfo != NULL) { InitializeInternetThreadInfo(lpThreadInfo); if (SetTls) { ok = TlsSetValue(InternetTlsIndex, (LPVOID)lpThreadInfo); if (!ok) { DEBUG_PUT(("InternetCreateThreadInfo(): TlsSetValue(%d, %#x) returns %d\n", InternetTlsIndex, lpThreadInfo, GetLastError() )); DEBUG_BREAK(THRDINFO); } } else { ok = TRUE; } } else { DEBUG_PUT(("InternetCreateThreadInfo(): NEW(INTERNET_THREAD_INFO) returned NULL\n")); DEBUG_BREAK(THRDINFO); } } else { DEBUG_PUT(("InternetCreateThreadInfo(): TlsAlloc() returns %#x, error %d\n", BAD_TLS_INDEX, GetLastError() )); DEBUG_BREAK(THRDINFO); } if (ok) { InsertAtHeadOfSerializedList(&ThreadInfoList, &lpThreadInfo->List); } else { if (lpThreadInfo != NULL) { DEL(lpThreadInfo); lpThreadInfo = NULL; } if (InternetTlsIndex != BAD_TLS_INDEX) { TlsFree(InternetTlsIndex); InternetTlsIndex = BAD_TLS_INDEX; } } quit: return lpThreadInfo; } VOID InternetDestroyThreadInfo( VOID ) /*++ Routine Description: Cleans up the INTERNET_THREAD_INFO - deletes any memory it owns and deletes it Arguments: None. Return Value: None. --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; IF_DEBUG(NOTHING) { DEBUG_PUT(("InternetDestroyThreadInfo(): Thread %#x: Deleting INTERNET_THREAD_INFO\n", GetCurrentThreadId() )); } // // don't call InternetGetThreadInfo() - we don't need to create the // INTERNET_THREAD_INFO if it doesn't exist in this case // lpThreadInfo = (LPINTERNET_THREAD_INFO)TlsGetValue(InternetTlsIndex); if (lpThreadInfo != NULL) { #if INET_DEBUG // // there shouldn't be anything in the debug record stack. On Win95, we // ignore this check if this is the async scheduler (nee worker) thread // AND there are entries in the debug record stack. The async thread // gets killed off before it has chance to DEBUG_LEAVE, then comes here, // causing this assert to be over-active // if (IsPlatformWin95() && lpThreadInfo->IsAsyncWorkerThread) { if (lpThreadInfo->CallDepth != 0) { DEBUG_PUT(("InternetDestroyThreadInfo(): " "Thread %#x: " "%d records in debug stack\n", lpThreadInfo->CallDepth )); } } else { INET_ASSERT(lpThreadInfo->Stack == NULL); } #endif // INET_DEBUG InternetFreeThreadInfo(lpThreadInfo); INET_ASSERT(InternetTlsIndex != BAD_TLS_INDEX); TlsSetValue(InternetTlsIndex, NULL); } else { DEBUG_PUT(("InternetDestroyThreadInfo(): Thread %#x: no INTERNET_THREAD_INFO\n", GetCurrentThreadId() )); } } VOID InternetFreeThreadInfo( IN LPINTERNET_THREAD_INFO lpThreadInfo ) /*++ Routine Description: Removes the INTERNET_THREAD_INFO from the list and frees all allocated blocks Arguments: lpThreadInfo - pointer to INTERNET_THREAD_INFO to remove and free Return Value: None. --*/ { RemoveFromSerializedList(&ThreadInfoList, &lpThreadInfo->List); if (lpThreadInfo->hErrorText != NULL) { FREE_MEMORY(lpThreadInfo->hErrorText); } //if (lpThreadInfo->lpResolverInfo != NULL) { // if (lpThreadInfo->lpResolverInfo->DnrSocketHandle != NULL) { // lpThreadInfo->lpResolverInfo->DnrSocketHandle->Dereference(); // } // DEL(lpThreadInfo->lpResolverInfo); //} DEL(lpThreadInfo); } VOID InternetTerminateThreadInfo( VOID ) /*++ Routine Description: Destroy all INTERNET_THREAD_INFO structures and terminate the serialized list. This funciton called at process detach time. At DLL_PROCESS_DETACH time, there may be other threads in the process for which we created an INTERNET_THREAD_INFO that aren't going to get the chance to delete the structure, so we do it here. Code in this module assumes that it is impossible for a new thread to enter this DLL while we are terminating in DLL_PROCESS_DETACH Arguments: None. Return Value: None. --*/ { // // get rid of this thread's info structure. No more debug output after this! // InternetDestroyThreadInfo(); // // get rid of the thread info structures left by other threads // LockSerializedList(&ThreadInfoList); LPINTERNET_THREAD_INFO lpThreadInfo; while (lpThreadInfo = (LPINTERNET_THREAD_INFO)SlDequeueHead(&ThreadInfoList)) { // // already dequeued, no need to call InternetFreeThreadInfo() // FREE_MEMORY(lpThreadInfo); } UnlockSerializedList(&ThreadInfoList); // // no more need for list // TerminateSerializedList(&ThreadInfoList); // // or TLS index // TlsFree(InternetTlsIndex); InternetTlsIndex = BAD_TLS_INDEX; } LPINTERNET_THREAD_INFO InternetGetThreadInfo( VOID ) /*++ Routine Description: Gets the pointer to the INTERNET_THREAD_INFO for this thread and checks that it still looks good. If this thread does not have an INTERNET_THREAD_INFO then we create one, presuming that this is a new thread Arguments: None. Return Value: LPINTERNET_THREAD_INFO Success - pointer to INTERNET_THREAD_INFO block Failure - NULL --*/ { LPINTERNET_THREAD_INFO lpThreadInfo = NULL; DWORD lastError; // // this is pretty bad - TlsGetValue() can destroy the per-thread last error // variable if it returns NULL (to indicate that NULL was actually set, and // that NULL does not indicate an error). So we have to read it before it is // potentially destroyed, and reset it before we quit. // // We do this here because typically, other functions will be completely // unsuspecting of this behaviour, and it is better to fix it once here, // than in several dozen other places, even though it is slightly // inefficient // lastError = GetLastError(); if (InternetTlsIndex != BAD_TLS_INDEX) { lpThreadInfo = (LPINTERNET_THREAD_INFO)TlsGetValue(InternetTlsIndex); } // // we may be in the process of creating the INTERNET_THREAD_INFO, in // which case its okay for this to be NULL. According to online SDK // documentation, a threads TLS value will be initialized to NULL // if (lpThreadInfo == NULL) { // // we presume this is a new thread. Create an INTERNET_THREAD_INFO // IF_DEBUG(NOTHING) { DEBUG_PUT(("InternetGetThreadInfo(): Thread %#x: Creating INTERNET_THREAD_INFO\n", GetCurrentThreadId() )); } lpThreadInfo = InternetCreateThreadInfo(TRUE); } if (lpThreadInfo != NULL) { INET_ASSERT(lpThreadInfo->Signature == INTERNET_THREAD_INFO_SIGNATURE); INET_ASSERT(lpThreadInfo->ThreadId == GetCurrentThreadId()); } else { DEBUG_PUT(("InternetGetThreadInfo(): Failed to get/create INTERNET_THREAD_INFO\n")); } // // as above - reset the last error variable in case TlsGetValue() trashed it // SetLastError(lastError); // // actual success/failure indicated by non-NULL/NULL pointer resp. // return lpThreadInfo; } VOID InternetSetThreadInfo( IN LPINTERNET_THREAD_INFO lpThreadInfo ) /*++ Routine Description: Sets lpThreadInfo as the current thread's INTERNET_THREAD_INFO. Used within fibers Arguments: lpThreadInfo - new INTERNET_THREAD_INFO to set Return Value: None. --*/ { if (InternetTlsIndex != BAD_TLS_INDEX) { if (!TlsSetValue(InternetTlsIndex, (LPVOID)lpThreadInfo)) { DEBUG_PUT(("InternetSetThreadInfo(): TlsSetValue(%d, %#x) returns %d\n", InternetTlsIndex, lpThreadInfo, GetLastError() )); INET_ASSERT(FALSE); } } else { DEBUG_PUT(("InternetSetThreadInfo(): InternetTlsIndex = %d\n", InternetTlsIndex )); INET_ASSERT(FALSE); } } DWORD InternetIndicateStatusAddress( IN DWORD dwInternetStatus, IN LPSOCKADDR lpSockAddr, IN DWORD dwSockAddrLength ) /*++ Routine Description: Make a status callback to the app. The data is a network address that we need to convert to a string Arguments: dwInternetStatus - INTERNET_STATUS_ value lpSockAddr - pointer to full socket address dwSockAddrLength - length of lpSockAddr in bytes Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INTERNET_OPERATION_CANCELLED The app closed the object handle during the callback --*/ { LPSTR lpAddress; INET_ASSERT(lpSockAddr != NULL); switch (lpSockAddr->sa_family) { case AF_INET: lpAddress = _I_inet_ntoa( ((struct sockaddr_in*)lpSockAddr)->sin_addr ); break; case AF_IPX: // // BUGBUG - this should be a call to WSAAddressToString, but that's not implemented yet // #ifdef SPX_SUPPORT lpAddress = GENERIC_SPX_NAME; #else lpAddress = NULL; #endif //SPX_SUPPORT break; default: lpAddress = NULL; break; } return InternetIndicateStatusString(dwInternetStatus, lpAddress); } DWORD InternetIndicateStatusString( IN DWORD dwInternetStatus, IN LPSTR lpszStatusInfo OPTIONAL ) /*++ Routine Description: Make a status callback to the app. The data is a string Arguments: dwInternetStatus - INTERNET_STATUS_ value lpszStatusInfo - string status data Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INTERNET_OPERATION_CANCELLED The app closed the object handle during the callback --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetIndicateStatusString", "%d, %q", dwInternetStatus, lpszStatusInfo )); DWORD length; if (ARGUMENT_PRESENT(lpszStatusInfo)) { length = strlen(lpszStatusInfo) + 1; } else { length = 0; } DWORD error; error = InternetIndicateStatus(dwInternetStatus, lpszStatusInfo, length); DEBUG_LEAVE(error); return error; } DWORD InternetIndicateStatusNewHandle( IN LPVOID hInternetMapped ) /*++ Routine Description: Indicates to the app a new handle Arguments: hInternetMapped - mapped address of new handle being indicated Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INTERNET_OPERATION_CANCELLED The app closed the either the new object handle or the parent object handle during the callback --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetIndicateStatusNewHandle", "%#x", hInternetMapped )); HANDLE_OBJECT * hObject = (HANDLE_OBJECT *)hInternetMapped; // // reference the new request handle, in case the app closes it in the // callback. The new handle now has a reference count of 2 // hObject->Reference(); //INET_ASSERT(hObject->ReferenceCount() == 3); // // we indicate the pseudo handle to the app // HINTERNET hInternet = hObject->GetPseudoHandle(); DWORD error = InternetIndicateStatus(INTERNET_STATUS_HANDLE_CREATED, (LPVOID)&hInternet, sizeof(hInternet) ); // // dereference the new request handle. If this returns TRUE then the new // handle has been deleted (the app called InternetCloseHandle() against // it which dereferenced it to 1, and now we've dereferenced it to zero) // if (hObject->Dereference()) { error = ERROR_INTERNET_OPERATION_CANCELLED; } else if (error == ERROR_INTERNET_OPERATION_CANCELLED) { // // the parent handle was deleted. Kill off the new handle too // BOOL ok; ok = hObject->Dereference(); INET_ASSERT(ok); } DEBUG_LEAVE(error); return error; } DWORD InternetIndicateStatus( IN DWORD dwStatus, IN LPVOID lpBuffer, IN DWORD dwLength ) /*++ Routine Description: If the app has registered a callback function for the object that this thread is operating on, call it with the arguments supplied Arguments: dwStatus - INTERNET_STATUS_ value lpBuffer - pointer to variable data buffer dwLength - length of *lpBuffer in bytes Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INTERNET_OPERATION_CANCELLED The app closed the object handle during the callback --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetIndicateStatus", "%s, %#x, %d", InternetMapStatus(dwStatus), lpBuffer, dwLength )); LPINTERNET_THREAD_INFO lpThreadInfo = InternetGetThreadInfo(); DWORD error = ERROR_SUCCESS; // // the app can affect callback operation by specifying a zero context value // meaning no callbacks will be generated for this API // if (lpThreadInfo != NULL) { INET_ASSERT(lpThreadInfo->hObject != NULL); INET_ASSERT(lpThreadInfo->hObjectMapped != NULL); // // if the context value in the thread info block is 0 then we use the // context from the handle object // DWORD_PTR context; context = _InternetGetContext(lpThreadInfo); if (context == INTERNET_NO_CALLBACK) { context = ((INTERNET_HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->GetContext(); } INTERNET_STATUS_CALLBACK appCallback; appCallback = ((INTERNET_HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->GetStatusCallback(); IF_DEBUG(THRDINFO) { if (dwStatus == INTERNET_STATUS_REQUEST_COMPLETE) { DEBUG_PRINT(THRDINFO, INFO, ("REQUEST_COMPLETE: dwResult = %#x, dwError = %d [%s]\n", ((LPINTERNET_ASYNC_RESULT)lpBuffer)->dwResult, ((LPINTERNET_ASYNC_RESULT)lpBuffer)->dwError, InternetMapError(((LPINTERNET_ASYNC_RESULT)lpBuffer)->dwError) )); } } if ((appCallback != NULL) && (context != INTERNET_NO_CALLBACK)) { LPVOID pInfo; DWORD infoLength; BOOL isAsyncWorkerThread; BYTE buffer[256]; // // we make a copy of the info to remove the app's opportunity to // change it. E.g. if we were about to resolve host name "foo" and // passed the pointer to our buffer containing "foo", the app could // change the name to "bar", changing the intended server // if (lpBuffer != NULL) { if (dwLength <= sizeof(buffer)) { pInfo = buffer; } else { pInfo = (LPVOID)ALLOCATE_FIXED_MEMORY(dwLength); } if (pInfo != NULL) { memcpy(pInfo, lpBuffer, dwLength); infoLength = dwLength; } else { infoLength = 0; DEBUG_PRINT(THRDINFO, ERROR, ("Failed to allocate %d bytes for info\n", dwLength )); } } else { pInfo = NULL; infoLength = 0; } // // we're about to call into the app. We may be in the context of an // async worker thread, and if the callback submits an async request // then we'll execute it synchronously. To avoid this, we will reset // the async worker thread indicator in the INTERNET_THREAD_INFO and // restore it when the app returns control to us. This way, if the // app makes an API request during the callback, on a handle that // has async I/O semantics, then we will simply queue it, and not // try to execute it synchronously // isAsyncWorkerThread = lpThreadInfo->IsAsyncWorkerThread; lpThreadInfo->IsAsyncWorkerThread = FALSE; BOOL bInCallback = lpThreadInfo->InCallback; lpThreadInfo->InCallback = TRUE; INET_ASSERT(!IsBadCodePtr((FARPROC)appCallback)); DEBUG_ENTER((DBG_THRDINFO, None, "(*callback)", "%#x, %#x, %s (%d), %#x [%#x], %d", lpThreadInfo->hObject, context, InternetMapStatus(dwStatus), dwStatus, pInfo, ((dwStatus == INTERNET_STATUS_HANDLE_CREATED) || (dwStatus == INTERNET_STATUS_HANDLE_CLOSING)) ? (DWORD_PTR)*(LPHINTERNET)pInfo : (((dwStatus == INTERNET_STATUS_REQUEST_SENT) || (dwStatus == INTERNET_STATUS_RESPONSE_RECEIVED) || (dwStatus == INTERNET_STATUS_INTERMEDIATE_RESPONSE) || (dwStatus == INTERNET_STATUS_STATE_CHANGE)) ? *(LPDWORD)pInfo : 0), infoLength )); PERF_LOG(PE_APP_CALLBACK_START, dwStatus, lpThreadInfo->ThreadId, lpThreadInfo->hObject ); HINTERNET hObject = lpThreadInfo->hObject; LPVOID hObjectMapped = lpThreadInfo->hObjectMapped; appCallback(lpThreadInfo->hObject, context, dwStatus, pInfo, infoLength ); lpThreadInfo->hObject = hObject; lpThreadInfo->hObjectMapped = hObjectMapped; PERF_LOG(PE_APP_CALLBACK_END, dwStatus, lpThreadInfo->ThreadId, lpThreadInfo->hObject ); DEBUG_LEAVE(0); lpThreadInfo->InCallback = bInCallback; lpThreadInfo->IsAsyncWorkerThread = isAsyncWorkerThread; // // free the buffer // if (pInfo != NULL) { if (dwLength > sizeof(buffer)) FREE_FIXED_MEMORY(pInfo); } // // if the object is now invalid then the app closed the handle in // the callback, and the entire operation is cancelled // if (((HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->IsInvalidated()) { error = ERROR_INTERNET_OPERATION_CANCELLED; } } else { DEBUG_PRINT(THRDINFO, ERROR, ("%#x: callback = %#x, context = %#x\n", lpThreadInfo->hObject, appCallback, context )); // // if we're completing a request then we shouldn't be here - it // means we lost the context or callback address somewhere along the // way // INET_ASSERT(dwStatus != INTERNET_STATUS_REQUEST_COMPLETE); #ifdef DEBUG if ( dwStatus == INTERNET_STATUS_REQUEST_COMPLETE) { INET_ASSERT(appCallback != NULL); INET_ASSERT(context != INTERNET_NO_CALLBACK); INET_ASSERT(_InternetGetContext(lpThreadInfo) != INTERNET_NO_CALLBACK); } #endif } } else { // // this is catastrophic if the indication was async request completion // DEBUG_PUT(("InternetIndicateStatus(): no INTERNET_THREAD_INFO?\n")); } DEBUG_LEAVE(error); return error; } DWORD InternetSetLastError( IN DWORD ErrorNumber, IN LPSTR ErrorText, IN DWORD ErrorTextLength, IN DWORD Flags ) /*++ Routine Description: Copies the error text to the per-thread error buffer (moveable memory) Arguments: ErrorNumber - protocol-specific error code ErrorText - protocol-specific error text (from server). The buffer is NOT zero-terminated ErrorTextLength - number of characters in ErrorText Flags - Flags that control how this function operates: SLE_APPEND TRUE if ErrorText is to be appended to the text already in the buffer SLE_ZERO_TERMINATE TRUE if ErrorText must have a '\0' appended to it Return Value: DWORD Success - ERROR_SUCCESS Failure - Win32 error --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetSetLastError", "%d, %.80q, %d, %#x", ErrorNumber, ErrorText, ErrorTextLength, Flags )); DWORD error; LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { error = _InternetSetLastError(lpThreadInfo, ErrorNumber, ErrorText, ErrorTextLength, Flags ); } else { DEBUG_PUT(("InternetSetLastError(): no INTERNET_THREAD_INFO\n")); error = ERROR_INTERNET_INTERNAL_ERROR; } DEBUG_LEAVE(error); return error; } DWORD _InternetSetLastError( IN LPINTERNET_THREAD_INFO lpThreadInfo, IN DWORD ErrorNumber, IN LPSTR ErrorText, IN DWORD ErrorTextLength, IN DWORD Flags ) /*++ Routine Description: Sets or resets the last error text in an INTERNET_THREAD_INFO block Arguments: lpThreadInfo - pointer to INTERNET_THREAD_INFO ErrorNumber - protocol-specific error code ErrorText - protocol-specific error text (from server). The buffer is NOT zero-terminated ErrorTextLength - number of characters in ErrorText Flags - Flags that control how this function operates: SLE_APPEND TRUE if ErrorText is to be appended to the text already in the buffer SLE_ZERO_TERMINATE TRUE if ErrorText must have a '\0' appended to it Return Value: DWORD Success - ERROR_SUCCESS Failure - Win32 error --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "_InternetSetLastError", "%#x, %d, %.80q, %d, %#x", lpThreadInfo, ErrorNumber, ErrorText, ErrorTextLength, Flags )); DWORD currentLength; DWORD newTextLength; DWORD error; newTextLength = ErrorTextLength; // // if we are appending text, then account for the '\0' currently at the end // of the buffer (if it exists) // if (Flags & SLE_APPEND) { currentLength = lpThreadInfo->ErrorTextLength; if (currentLength != 0) { --currentLength; } newTextLength += currentLength; } if (Flags & SLE_ZERO_TERMINATE) { ++newTextLength; } // // expect success (and why not?) // error = ERROR_SUCCESS; // // allocate, grow or shrink the buffer to fit. The buffer is moveable. If // the buffer is being shrunk to zero size then NULL will be returned as // the buffer handle from ResizeBuffer() // lpThreadInfo->hErrorText = ResizeBuffer(lpThreadInfo->hErrorText, newTextLength, FALSE ); if (lpThreadInfo->hErrorText != NULL) { LPSTR lpErrorText; lpErrorText = (LPSTR)LOCK_MEMORY(lpThreadInfo->hErrorText); INET_ASSERT(lpErrorText != NULL); if (lpErrorText != NULL) { if (Flags & SLE_APPEND) { lpErrorText += currentLength; } memcpy(lpErrorText, ErrorText, ErrorTextLength); if (Flags & SLE_ZERO_TERMINATE) { lpErrorText[ErrorTextLength++] = '\0'; } // // the text should always be zero-terminated. We expect this in // InternetGetLastResponseInfo() // INET_ASSERT(lpErrorText[ErrorTextLength - 1] == '\0'); UNLOCK_MEMORY(lpThreadInfo->hErrorText); } else { // // real error occurred - failed to lock memory? // error = GetLastError(); } } else { INET_ASSERT(newTextLength == 0); newTextLength = 0; } // // set the error code and text length // lpThreadInfo->ErrorTextLength = newTextLength; lpThreadInfo->ErrorNumber = ErrorNumber; DEBUG_LEAVE(error); return error; } LPSTR InternetLockErrorText( VOID ) /*++ Routine Description: Returns a pointer to the locked per-thread error text buffer Arguments: None. Return Value: LPSTR Success - pointer to locked buffer Failure - NULL --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { HLOCAL lpErrorText; lpErrorText = lpThreadInfo->hErrorText; if (lpErrorText != (HLOCAL)NULL) { return (LPSTR)LOCK_MEMORY(lpErrorText); } } return NULL; } // //VOID //InternetUnlockErrorText( // VOID // ) // ///*++ // //Routine Description: // // Unlocks the per-thread error text buffer locked by InternetLockErrorText() // //Arguments: // // None. // //Return Value: // // None. // //--*/ // //{ // LPINTERNET_THREAD_INFO lpThreadInfo; // // lpThreadInfo = InternetGetThreadInfo(); // // // // // assume that if we locked the error text, there must be an // // INTERNET_THREAD_INFO when we come to unlock it // // // // INET_ASSERT(lpThreadInfo != NULL); // // if (lpThreadInfo != NULL) { // // HLOCAL hErrorText; // // hErrorText = lpThreadInfo->hErrorText; // // // // // similarly, there must be a handle to the error text buffer // // // // INET_ASSERT(hErrorText != NULL); // // if (hErrorText != (HLOCAL)NULL) { // UNLOCK_MEMORY(hErrorText); // } // } //} VOID InternetSetContext( IN DWORD_PTR dwContext ) /*++ Routine Description: Sets the context value in the INTERNET_THREAD_INFO for status callbacks Arguments: dwContext - context value to remember Return Value: None. --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { _InternetSetContext(lpThreadInfo, dwContext); } } VOID InternetSetObjectHandle( IN HINTERNET hInternet, IN HINTERNET hInternetMapped ) /*++ Routine Description: Sets the hObject field in the INTERNET_THREAD_INFO structure so we can get at the handle contents, even when we're in a function that does not take the hInternet as a parameter Arguments: hInternet - handle of object we may need info from hInternetMapped - mapped handle of object we may need info from Return Value: None. --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { _InternetSetObjectHandle(lpThreadInfo, hInternet, hInternetMapped); } } HINTERNET InternetGetObjectHandle( VOID ) /*++ Routine Description: Just returns the hObject value stored in our INTERNET_THREAD_INFO Arguments: None. Return Value: HINTERNET Success - non-NULL handle value Failure - NULL object handle (may not have been set) --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; HINTERNET hInternet; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { hInternet = lpThreadInfo->hObject; } else { hInternet = NULL; } return hInternet; } HINTERNET InternetGetMappedObjectHandle( VOID ) /*++ Routine Description: Just returns the hObjectMapped value stored in our INTERNET_THREAD_INFO Arguments: None. Return Value: HINTERNET Success - non-NULL handle value Failure - NULL object handle (may not have been set) --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; HINTERNET hInternet; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { hInternet = lpThreadInfo->hObjectMapped; } else { hInternet = NULL; } return hInternet; }
24.846806
117
0.557388
[ "object" ]
d12dc54290d9110b0a4e9c3f67441e420a294795
22,922
cpp
C++
vulkan/texture.cpp
rickmarson/vulkan_experiments
c48956212edd0105007e553af1d49ff92aad6e20
[ "MIT" ]
2
2021-02-15T14:09:58.000Z
2021-11-11T22:07:23.000Z
vulkan/texture.cpp
rickmarson/vulkan_experiments
c48956212edd0105007e553af1d49ff92aad6e20
[ "MIT" ]
null
null
null
vulkan/texture.cpp
rickmarson/vulkan_experiments
c48956212edd0105007e553af1d49ff92aad6e20
[ "MIT" ]
null
null
null
/* * texture.hpp * * Copyright (C) 2020 Riccardo Marson */ #include "texture.hpp" #include "vulkan_backend.hpp" #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace { bool isFormatSupported(VkPhysicalDevice physical_device, VkFormat format, VkImageTiling tiling, VkFormatFeatureFlags features) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(physical_device, format, &props); if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features) { return true; } else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features) { return true; } return false; } } std::shared_ptr<Texture> Texture::createTexture(const std::string& name, VkDevice device, VulkanBackend* backend) { return std::make_shared<Texture>(name, device, backend); } Texture::Texture(const std::string& name, VkDevice device, VulkanBackend* backend) : name_(name), backend_(backend), device_(device) { } Texture::~Texture() { cleanup(); } void Texture::cleanup() { if (isValid()) { if (vk_sampler_ != VK_NULL_HANDLE) { vkDestroySampler(device_, vk_sampler_, nullptr); } vkDestroyImageView(device_, vk_image_view_, nullptr); if (vk_sampler_image_view_ != VK_NULL_HANDLE) { vkDestroyImageView(device_, vk_sampler_image_view_, nullptr); } vkDestroyImage(device_, vk_image_, nullptr); vkFreeMemory(device_, vk_memory_, nullptr); } } void Texture::loadImageRGBA(const std::string& src_image_path, bool genMipMaps, bool srgb) { int width, height, original_channels; stbi_uc* stb_pixels = stbi_load(src_image_path.c_str(), &width, &height, &original_channels, STBI_rgb_alpha); if (!stb_pixels) { std::cerr << "Failed to load texture image!" << std::endl; return; } uint32_t channels = STBI_rgb_alpha; size_t bytes = static_cast<size_t>(width)* height * channels; auto pixels = std::vector<stbi_uc>(stb_pixels, stb_pixels + bytes); stbi_image_free(stb_pixels); loadImageRGBA(static_cast<uint32_t>(width), static_cast<uint32_t>(height), static_cast<uint32_t>(channels), genMipMaps, pixels, srgb); } void Texture::loadImageRGBA(uint32_t width, uint32_t height, bool genMipMaps, glm::vec4 fill_colour, bool srgb) { auto pixels = std::vector<uint8_t>(width * height * 4, 0); uint8_t fill_bytes[] = { static_cast<uint8_t>(fill_colour[0] * 255), static_cast<uint8_t>(fill_colour[1] * 255), static_cast<uint8_t>(fill_colour[2] * 255), static_cast<uint8_t>(fill_colour[3] * 255)}; size_t offset = 0; for (uint32_t px = 0; px < width * height; ++px) { std::memcpy(pixels.data() + offset, fill_bytes, 4); offset += 4; } loadImageRGBA(width, height, 4, genMipMaps, pixels, srgb); } void Texture::loadImageRGBA(uint32_t width, uint32_t height, uint32_t channels, bool genMipMaps, const std::vector<unsigned char>& pixels, bool srgb) { VkFormat format = srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; if (!isFormatSupported(backend_->getPhysicalDevice(), format, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_TRANSFER_DST_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { std::cerr << "Error creating texture " << name_ << std::endl; std::cerr << (srgb ? "VK_FORMAT_R8G8B8A8_SRGB" : "VK_FORMAT_R8G8B8A8_UNORM") << " texture format is not supported on the selected device!" << std::endl; return; } width_ = width; height_ = height; channels_ = channels; mip_levels_ = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1; vk_format_ = format; vk_usage_flags_ = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; vk_tiling_ = VK_IMAGE_TILING_OPTIMAL; vk_mem_props_ = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; vk_num_samples_ = VK_SAMPLE_COUNT_1_BIT; Buffer staging_buffer = backend_->createBuffer<stbi_uc>("image_staging_buffer", pixels, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_SHARING_MODE_EXCLUSIVE, true); backend_->updateBuffer<stbi_uc>(staging_buffer, pixels); if (!createImage()) { vkDestroyBuffer(device_, staging_buffer.vk_buffer, nullptr); vkFreeMemory(device_, staging_buffer.vk_buffer_memory, nullptr); if (vk_image_ != VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); } return; } transitionImageLayout(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); copyBufferToImage(staging_buffer.vk_buffer, vk_image_, width_, height_); if (genMipMaps) { generateMipMaps(); } else { transitionImageLayout(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); } vk_image_view_ = backend_->createImageView(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT, mip_levels_); if (vk_image_view_ == VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); vkFreeMemory(device_, vk_memory_, nullptr); } vkDestroyBuffer(device_, staging_buffer.vk_buffer, nullptr); vkFreeMemory(device_, staging_buffer.vk_buffer_memory, nullptr); } void Texture::createColourAttachment(uint32_t width, uint32_t height, VkFormat format, VkSampleCountFlagBits num_samples, bool enable_sampling) { if (!isFormatSupported(backend_->getPhysicalDevice(), format, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { std::cerr << "Error loading texture " << name_ << std::endl; std::cerr << "VK_FORMAT_R8G8B8A8_SRGB texture format is not supported on the selected device!" << std::endl; return; } width_ = width; height_ = height; channels_ = 4; mip_levels_ = 1; vk_format_ = format; vk_usage_flags_ = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; vk_tiling_ = VK_IMAGE_TILING_OPTIMAL; vk_mem_props_ = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; vk_num_samples_ = num_samples; if (!createImage()) { if (vk_image_ != VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); } return; } vk_image_view_ = backend_->createImageView(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT); if (vk_image_view_ == VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); vkFreeMemory(device_, vk_memory_, nullptr); } transitionImageLayout(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); if (enable_sampling) { createSampler(); } } void Texture::createDepthStencilAttachment(uint32_t width, uint32_t height, VkSampleCountFlagBits num_samples, bool enable_sampling) { if (!isFormatSupported(backend_->getPhysicalDevice(), VK_FORMAT_D24_UNORM_S8_UINT, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { std::cerr << "Error creating depth attachment image" << std::endl; std::cerr << "VK_FORMAT_D24_UNORM_S8_UINT texture format is not supported on the selected device!" << std::endl; return; } VkImageUsageFlags usage_flags = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; if (enable_sampling) { usage_flags |= VK_IMAGE_USAGE_SAMPLED_BIT; } width_ = width; height_ = height; channels_ = 1; mip_levels_ = 1; vk_format_ = VK_FORMAT_D24_UNORM_S8_UINT; vk_usage_flags_ = usage_flags; vk_tiling_ = VK_IMAGE_TILING_OPTIMAL; vk_mem_props_ = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; vk_num_samples_ = num_samples; if (!createImage()) { if (vk_image_ != VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); } return; } vk_image_view_ = backend_->createImageView(vk_image_, vk_format_, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT); if (vk_image_view_ == VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); vkFreeMemory(device_, vk_memory_, nullptr); } transitionImageLayout(vk_image_, vk_format_, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); if (enable_sampling) { createSampler(); vk_sampler_image_view_ = backend_->createImageView(vk_image_, vk_format_, VK_IMAGE_ASPECT_DEPTH_BIT); if (vk_sampler_image_view_ == VK_NULL_HANDLE) { vkDestroyImageView(device_, vk_image_view_, nullptr); vkDestroyImage(device_, vk_image_, nullptr); vkFreeMemory(device_, vk_memory_, nullptr); } } } void Texture::createDepthStorageImage(uint32_t width, uint32_t height, bool as_rgba32) { VkFormat format = as_rgba32 ? VK_FORMAT_R32G32B32A32_SFLOAT : VK_FORMAT_R32_SFLOAT; if (!isFormatSupported(backend_->getPhysicalDevice(), format, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) { std::cerr << "Error creating depth storage image" << std::endl; std::cerr << "VK_FORMAT_R32_SFLOAT texture format is not supported as STORAGE_IMAGE on the selected device!" << std::endl; return; } width_ = width; height_ = height; channels_ = 1; mip_levels_ = 1; vk_format_ = format; vk_usage_flags_ = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT; vk_tiling_ = VK_IMAGE_TILING_OPTIMAL; vk_mem_props_ = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; vk_descriptor_type_ = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; if (!createImage()) { if (vk_image_ != VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); } return; } vk_image_view_ = backend_->createImageView(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT); if (vk_image_view_ == VK_NULL_HANDLE) { vkDestroyImage(device_, vk_image_, nullptr); vkFreeMemory(device_, vk_memory_, nullptr); } transitionImageLayout(vk_image_, vk_format_, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); auto cmd_buffer = backend_->beginSingleTimeCommands(); VkClearColorValue clear_colour{}; clear_colour.float32[0] = 1.0f; VkImageSubresourceRange range{}; range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; range.baseArrayLayer = 0; range.baseMipLevel = 0; range.layerCount = 1; range.levelCount = 1; vkCmdClearColorImage(cmd_buffer, vk_image_, VK_IMAGE_LAYOUT_GENERAL, &clear_colour, 1, &range); backend_->endSingleTimeCommands(cmd_buffer); } VkImageView Texture::getSamplerImageView() const { if (vk_sampler_image_view_ != VK_NULL_HANDLE) { return vk_sampler_image_view_; } return vk_image_view_; } bool Texture::createImage() { VkImageCreateInfo image_info{}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.extent.width = width_; image_info.extent.height = height_; image_info.extent.depth = 1; image_info.mipLevels = mip_levels_; image_info.arrayLayers = 1; image_info.format = vk_format_; image_info.tiling = vk_tiling_; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_info.usage = vk_usage_flags_; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.samples = vk_num_samples_; image_info.flags = 0; // Optional VkImageFormatProperties image_format_props{}; vkGetPhysicalDeviceImageFormatProperties(backend_->physical_device_, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TYPE_2D, vk_tiling_, vk_usage_flags_, 0, &image_format_props); if (vkCreateImage(device_, &image_info, nullptr, &vk_image_) != VK_SUCCESS) { std::cerr << "Failed to create image!" << std::endl; return false; } VkMemoryRequirements mem_reqs; vkGetImageMemoryRequirements(device_, vk_image_, &mem_reqs); vk_memory_ = backend_->allocateDeviceMemory(mem_reqs, vk_mem_props_); if (vk_memory_ == VK_NULL_HANDLE) { std::cerr << "Failed to allocate image memory!" << std::endl; return false; } vkBindImageMemory(device_, vk_image_, vk_memory_, 0); return true; } void Texture::transitionImageLayout(VkImage image, VkFormat format, VkImageAspectFlags aspect_flags, VkImageLayout old_layout, VkImageLayout new_layout) { VkCommandBuffer command_buffer = backend_->beginSingleTimeCommands(); VkImageMemoryBarrier barrier{}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = old_layout; barrier.newLayout = new_layout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; barrier.subresourceRange.aspectMask = aspect_flags; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = mip_levels_; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; VkPipelineStageFlags src_stage; VkPipelineStageFlags dst_stage; if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; src_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; dst_stage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_GENERAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else { std::cerr << "Unsupported layout transition!" << std::endl; return; } vkCmdPipelineBarrier( command_buffer, src_stage, dst_stage, 0, 0, nullptr, 0, nullptr, 1, &barrier ); backend_->endSingleTimeCommands(command_buffer); vk_layout_ = new_layout; } void Texture::copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height) { VkCommandBuffer command_buffer = backend_->beginSingleTimeCommands(); VkBufferImageCopy region{}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = { 0, 0, 0 }; region.imageExtent = { width, height, 1 }; vkCmdCopyBufferToImage( command_buffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region ); backend_->endSingleTimeCommands(command_buffer); } void Texture::generateMipMaps() { VkFormatProperties format_properties; vkGetPhysicalDeviceFormatProperties(backend_->getPhysicalDevice(), vk_format_, &format_properties); if (!(format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) { std::cerr << "Texture image format does not support linear blitting!" << std::endl; return; } VkCommandBuffer command_buffer = backend_->beginSingleTimeCommands(); VkImageMemoryBarrier barrier{}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.image = vk_image_; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; barrier.subresourceRange.levelCount = 1; int32_t mip_width = width_; int32_t mip_height = height_; for (uint32_t i = 1; i < mip_levels_; ++i) { barrier.subresourceRange.baseMipLevel = i - 1; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); VkImageBlit blit{}; blit.srcOffsets[0] = { 0, 0, 0 }; blit.srcOffsets[1] = { mip_width, mip_height, 1 }; blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit.srcSubresource.mipLevel = i - 1; blit.srcSubresource.baseArrayLayer = 0; blit.srcSubresource.layerCount = 1; blit.dstOffsets[0] = { 0, 0, 0 }; blit.dstOffsets[1] = { mip_width > 1 ? mip_width / 2 : 1, mip_height > 1 ? mip_height / 2 : 1, 1 }; blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit.dstSubresource.mipLevel = i; blit.dstSubresource.baseArrayLayer = 0; blit.dstSubresource.layerCount = 1; vkCmdBlitImage(command_buffer, vk_image_, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vk_image_, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); if (mip_width > 1) mip_width /= 2; if (mip_height > 1) mip_height /= 2; } barrier.subresourceRange.baseMipLevel = mip_levels_ - 1; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); backend_->endSingleTimeCommands(command_buffer); vk_layout_ = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } void Texture::createSampler() { VkSamplerCreateInfo sampler_info{}; sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; sampler_info.magFilter = VK_FILTER_LINEAR; sampler_info.minFilter = VK_FILTER_LINEAR; sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler_info.anisotropyEnable = VK_TRUE; sampler_info.maxAnisotropy = 16.0f; sampler_info.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; sampler_info.unnormalizedCoordinates = VK_FALSE; sampler_info.compareEnable = VK_FALSE; sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler_info.mipLodBias = 0.0f; sampler_info.minLod = 0.0f; sampler_info.maxLod = static_cast<float>(mip_levels_); if (vkCreateSampler(device_, &sampler_info, nullptr, &vk_sampler_) != VK_SUCCESS) { std::cerr << "Failed to create texture sampler!" << std::endl; } } void Texture::updateDescriptorSets(std::vector<VkDescriptorSet>& descriptor_sets, uint32_t binding_point) { VkImageView image_view; if (vk_sampler_ != VK_NULL_HANDLE && vk_sampler_image_view_ != VK_NULL_HANDLE) { image_view = vk_sampler_image_view_; } else { image_view = vk_image_view_; } for (size_t i = 0; i < descriptor_sets.size(); i++) { VkDescriptorImageInfo image_info{}; image_info.imageLayout = vk_layout_; image_info.imageView = image_view; image_info.sampler = vk_sampler_; VkWriteDescriptorSet descriptor_write{}; descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptor_write.dstSet = descriptor_sets[i]; descriptor_write.dstBinding = binding_point; descriptor_write.dstArrayElement = 0; descriptor_write.descriptorType = vk_descriptor_type_; descriptor_write.descriptorCount = 1; descriptor_write.pBufferInfo = nullptr; // Optional descriptor_write.pImageInfo = &image_info; descriptor_write.pTexelBufferView = nullptr; // Optional vkUpdateDescriptorSets(device_, 1, &descriptor_write, 0, nullptr); } }
38.076412
183
0.708446
[ "vector" ]
d132a060fa3de0dfbcc51e8e7b17c2603804f0f9
9,153
cpp
C++
test/ParserTests.cpp
guidowb/lightshow-render
32f927f399b61748ceb897639e0cda6f3ac585b7
[ "Apache-2.0" ]
null
null
null
test/ParserTests.cpp
guidowb/lightshow-render
32f927f399b61748ceb897639e0cda6f3ac585b7
[ "Apache-2.0" ]
null
null
null
test/ParserTests.cpp
guidowb/lightshow-render
32f927f399b61748ceb897639e0cda6f3ac585b7
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include <cppunit/extensions/HelperMacros.h> #include "../src/Parser.h" #include "TestHelpers.h" class ParserTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE( ParserTests ); CPPUNIT_TEST( testSimpleCommand ); CPPUNIT_TEST( testExtraArguments ); CPPUNIT_TEST( testInvalidInt ); CPPUNIT_TEST( testValidInt ); CPPUNIT_TEST( testNegativeInt ); CPPUNIT_TEST( testInvalidColor ); CPPUNIT_TEST( testInvalidColorDigit ); CPPUNIT_TEST( testInvalidColorLength ); CPPUNIT_TEST( testInvalidDuration ); CPPUNIT_TEST( testInvalidDurationUnit ); CPPUNIT_TEST( testInvalidDurationLongUnit ); CPPUNIT_TEST( testValidDurationSeconds ); CPPUNIT_TEST( testValidDurationMinutes ); CPPUNIT_TEST( testValidDurationHours ); CPPUNIT_TEST( testInvalidTime ); CPPUNIT_TEST( testValidTimeNoSeconds ); CPPUNIT_TEST( testValidTimeSeconds ); CPPUNIT_TEST( testInvalidDate ); CPPUNIT_TEST( testValidDate ); CPPUNIT_TEST( testShortRGB ); CPPUNIT_TEST( testShortRGBA ); CPPUNIT_TEST( testLongRGB ); CPPUNIT_TEST( testLongRGBA ); CPPUNIT_TEST( testTopLevelBlock ); CPPUNIT_TEST( testNestedBlock ); CPPUNIT_TEST( testUnexpectedBlock ); CPPUNIT_TEST_SUITE_END(); void testSimpleCommand() { Parser parser("ParserTests::testSimpleCommand", "solid"); CPPUNIT_ASSERT(parser.isName()); CPPUNIT_ASSERT(parser.getCommand() == "solid"); parser.endCommand(); CPPUNIT_ASSERT_EQUAL(0, parser.maxErrorLevel()); } void testExtraArguments() { Parser parser("ParserTests::testExtraArguments", "solid blah"); CPPUNIT_ASSERT(parser.getCommand() == "solid"); parser.endCommand(); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testInvalidInt() { Parser parser("ParserTests::testInvalidInt", "nonsense"); CPPUNIT_ASSERT(!parser.isInteger()); CPPUNIT_ASSERT_EQUAL(0, parser.getInteger()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testValidInt() { Parser parser("ParserTests::testValidInt", "1234"); CPPUNIT_ASSERT(parser.isInteger()); CPPUNIT_ASSERT_EQUAL(1234, parser.getInteger()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testNegativeInt() { Parser parser("ParserTests::testValidInt", "-1234"); CPPUNIT_ASSERT(parser.isInteger()); CPPUNIT_ASSERT_EQUAL(-1234, parser.getInteger()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testInvalidDuration() { Parser parser("ParserTests::testInvalidDuration", "1234"); CPPUNIT_ASSERT_EQUAL(0, (int) parser.getDuration()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testInvalidDurationUnit() { Parser parser("ParserTests::testInvalidDurationUnit", "1234x"); CPPUNIT_ASSERT_EQUAL(0, (int) parser.getDuration()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testInvalidDurationLongUnit() { Parser parser("ParserTests::testInvalidDurationLongUnit", "1234seconds"); CPPUNIT_ASSERT_EQUAL(0, (int) parser.getDuration()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testValidDurationSeconds() { Parser parser("ParserTests::testValidDurationSeconds", "1234s"); CPPUNIT_ASSERT_EQUAL(1234000, (int) parser.getDuration()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testValidDurationMinutes() { Parser parser("ParserTests::testValidDurationMinutes", "2m"); CPPUNIT_ASSERT_EQUAL(120000, (int) parser.getDuration()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testValidDurationHours() { Parser parser("ParserTests::testValidDurationHours", "3h"); CPPUNIT_ASSERT_EQUAL(3 * 60 * 60000, (int) parser.getDuration()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testInvalidTime() { Parser parser("ParserTests::testInvalidTime", "4o'clock"); CPPUNIT_ASSERT_EQUAL(0, (int) parser.getTime()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testValidTimeNoSeconds() { Parser parser("ParserTests::testValidTimeNoSeconds", "12:34"); CPPUNIT_ASSERT_EQUAL(12 * 3600 + 34 * 60, (int) parser.getTime()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testValidTimeSeconds() { Parser parser("ParserTests::testValidTimeSeconds", "12:34:56"); CPPUNIT_ASSERT_EQUAL(12 * 3600 + 34 * 60 + 56, (int) parser.getTime()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testInvalidDate() { Parser parser("ParserTests::testInvalidDate", "14/14"); CPPUNIT_ASSERT_EQUAL(0, (int) parser.getDate()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testValidDate() { Parser parser("ParserTests::testValidDate", "12/25"); CPPUNIT_ASSERT_EQUAL((12 << 8) + 25, (int) parser.getDate()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testInvalidColor() { Parser parser("ParserTests::testInvalidColor", "nonsense"); CPPUNIT_ASSERT(!parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA_NULL, parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testInvalidColorDigit() { Parser parser("ParserTests::testInvalidColorDigit", "#00zz0000"); CPPUNIT_ASSERT(!parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA_NULL, parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testInvalidColorLength() { Parser parser("ParserTests::testInvalidColorLength", "#12345"); CPPUNIT_ASSERT(!parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA_NULL, parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } void testShortRGB() { Parser parser("ParserTests::testShortRGB", "#123"); CPPUNIT_ASSERT(parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA(0x11, 0x22, 0x33, 0xFF), parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testShortRGBA() { Parser parser("ParserTests::testShortRGBA", "#abcd"); CPPUNIT_ASSERT(parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA(0xAA, 0xBB, 0xCC, 0xDD), parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testLongRGB() { Parser parser("ParserTests::testLongRGB", "#123456"); CPPUNIT_ASSERT(parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA(0x12, 0x34, 0x56, 0xFF), parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testLongRGBA() { Parser parser("ParserTests::testLongRGBA", "#09ABCDEF"); CPPUNIT_ASSERT(parser.isColor()); CPPUNIT_ASSERT_EQUAL(RGBA(0x09, 0xAB, 0xCD, 0xEF), parser.getColor()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testTopLevelBlock() { Parser parser("ParserTests::testTopLevelBlock", "command1\ncommand2\ncommand3"); Word indent = parser.startBlock(); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command1"); parser.endCommand(); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command2"); parser.endCommand(); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command3"); parser.endCommand(); CPPUNIT_ASSERT(!parser.inBlock()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testNestedBlock() { Parser parser("ParserTests::testNestedBlock", "command1\n command2\n command3\ncommand4"); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command1"); CPPUNIT_ASSERT(parser.hasBlock()); Word indent = parser.startBlock(); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command2"); parser.endCommand(); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command3"); parser.endCommand(); CPPUNIT_ASSERT(!parser.inBlock()); parser.endBlock(indent); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command4"); parser.endCommand(); CPPUNIT_ASSERT(!parser.inBlock()); CPPUNIT_ASSERT_EQUAL(LEXER_OK, parser.maxErrorLevel()); } void testUnexpectedBlock() { Parser parser("ParserTests::testUnexpectedBlock", "command1\n command2\ncommand3"); CPPUNIT_ASSERT(parser.inBlock()); CPPUNIT_ASSERT(parser.getCommand() == "command1"); parser.endCommand(); CPPUNIT_ASSERT(parser.getCommand() == "command3"); CPPUNIT_ASSERT_EQUAL(LEXER_ERROR, parser.maxErrorLevel()); } };
40.144737
100
0.678903
[ "solid" ]
d13419237fd49302a226b9b88e0e61cebb0a4e92
6,305
cpp
C++
src/GridSide.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
19
2016-06-18T02:03:56.000Z
2022-02-23T17:26:32.000Z
src/GridSide.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
43
2017-03-09T07:32:12.000Z
2022-03-23T20:18:35.000Z
src/GridSide.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
5
2019-11-14T22:24:02.000Z
2021-09-07T18:27:21.000Z
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Sun Oct 16 16:08:05 PDT 2016 // Last Modified: Sun Oct 16 16:08:08 PDT 2016 // Filename: GridSide.cpp // URL: https://github.com/craigsapp/hum2ly/blob/master/src/GridSide.cpp // Syntax: C++11; humlib // vim: ts=3 noexpandtab // // Description: GridSide is an intermediate container for converting from // MusicXML syntax into Humdrum syntax. // // #include "HumGrid.h" using namespace std; namespace hum { // START_MERGE ////////////////////////////// // // GridSide::GridSide -- Constructor. // GridSide::GridSide(void) { // do nothing } ////////////////////////////// // // GridSide::~GridSide -- Deconstructor. // GridSide::~GridSide(void) { for (int i=0; i<(int)m_verses.size(); i++) { if (m_verses[i]) { delete m_verses[i]; m_verses[i] = NULL; } } m_verses.resize(0); if (m_dynamics) { delete m_dynamics; m_dynamics = NULL; } if (m_harmony) { delete m_harmony; m_harmony = NULL; } } ////////////////////////////// // // GridSide::setVerse -- // void GridSide::setVerse(int index, HTp token) { if (token == NULL) { // null tokens are written in the transfer process when responsibility // for deleting the pointer is given to another object (HumdrumFile class). } if (index == (int)m_verses.size()) { // Append to the end of the verse list. m_verses.push_back(token); } else if (index < (int)m_verses.size()) { // Insert in a slot which might already have a verse token if ((token != NULL) && (m_verses.at(index) != NULL)) { // don't delete a previous non-NULL token if a NULL // token is being stored, as it is assumed that the // token has been transferred to a HumdrumFile object. delete m_verses[index]; } m_verses[index] = token; } else { // Add more than one verse spot and insert verse: int oldsize = (int)m_verses.size(); int newsize = index + 1; m_verses.resize(newsize); for (int i=oldsize; i<newsize; i++) { m_verses.at(i) = NULL; } m_verses.at(index) = token; } } void GridSide::setVerse(int index, const string& token) { HTp newtoken = new HumdrumToken(token); setVerse(index, newtoken); } ////////////////////////////// // // GridSide::getVerse -- // HTp GridSide::getVerse(int index) { if (index < 0 || index >= getVerseCount()) { return NULL; } return m_verses[index]; } ////////////////////////////// // // GridSide::getVerseCount -- // int GridSide::getVerseCount(void) { return (int)m_verses.size(); } ////////////////////////////// // // GridSide::getHarmonyCount -- // int GridSide::getHarmonyCount(void) { if (m_harmony == NULL) { return 0; } else { return 1; } } ////////////////////////////// // // GridSide::setHarmony -- // void GridSide::setHarmony(HTp token) { if (m_harmony) { delete m_harmony; m_harmony = NULL; } m_harmony = token; } void GridSide::setHarmony(const string& token) { HTp newtoken = new HumdrumToken(token); setHarmony(newtoken); } ////////////////////////////// // // GridSide::getXmlidCount -- // int GridSide::getXmlidCount(void) { if (m_xmlid == NULL) { return 0; } else { return 1; } } ////////////////////////////// // // GridSide::setXmlid -- // void GridSide::setXmlid(HTp token) { if (m_xmlid) { delete m_xmlid; m_xmlid = NULL; } m_xmlid = token; } void GridSide::setXmlid(const string& token) { HTp newtoken = new HumdrumToken(token); setXmlid(newtoken); } ////////////////////////////// // // GridSide::setDynamics -- // void GridSide::setDynamics(HTp token) { if (m_dynamics) { delete m_dynamics; m_dynamics = NULL; } m_dynamics = token; } void GridSide::setDynamics(const string& token) { HTp newtoken = new HumdrumToken(token); setDynamics(newtoken); } ////////////////////////////// // // GridSide::setFiguredBass -- // void GridSide::setFiguredBass(HTp token) { if (m_figured_bass) { delete m_figured_bass; m_figured_bass = NULL; } m_figured_bass = token; } void GridSide::setFiguredBass(const string& token) { HTp newtoken = new HumdrumToken(token); setFiguredBass(newtoken); } /////////////////////////// // // GridSide::detachHarmony -- // void GridSide::detachHarmony(void) { m_harmony = NULL; } /////////////////////////// // // GridSide::detachXmlid -- // void GridSide::detachXmlid(void) { m_xmlid = NULL; } /////////////////////////// // // GridSide::detachDynamics -- // void GridSide::detachDynamics(void) { m_dynamics = NULL; } /////////////////////////// // // GridSide::detachFiguredBass -- // void GridSide::detachFiguredBass(void) { m_figured_bass = NULL; } ////////////////////////////// // // GridSide::getHarmony -- // HTp GridSide::getHarmony(void) { return m_harmony; } ////////////////////////////// // // GridSide::getXmlid -- // HTp GridSide::getXmlid(void) { return m_xmlid; } ////////////////////////////// // // GridSide::getDynamics -- // HTp GridSide::getDynamics(void) { return m_dynamics; } ////////////////////////////// // // GridSide::getDynamicsCount -- // int GridSide::getDynamicsCount(void) { if (m_dynamics == NULL) { return 0; } else { return 1; } } ////////////////////////////// // // GridSide::getFiguredBass -- // HTp GridSide::getFiguredBass(void) { return m_figured_bass; } ////////////////////////////// // // GridSide::getFiguredBassCount -- // int GridSide::getFiguredBassCount(void) { if (m_figured_bass == NULL) { return 0; } else { return 1; } } ////////////////////////////// // // operator<< -- // ostream& operator<<(ostream& output, GridSide* side) { output << " ["; if (side->getXmlidCount() > 0) { output << "xmlid:" << side->getXmlid(); } if (side->getVerseCount() > 0) { output << " verse:"; } for (int i=0; i<(int)side->getVerseCount(); i++) { output << side->getVerse(i); if (i < (int)side->getVerseCount() - 1) { output << "; "; } } if (side->getDynamicsCount() > 0) { output << "dyn:" << side->getDynamics(); } if (side->getHarmonyCount() > 0) { output << "harm:" << side->getHarmony(); } if (side->getXmlidCount() > 0) { output << "xmlid:" << side->getXmlid(); } output << "] "; return output; } // END_MERGE } // end namespace hum
15.4914
82
0.569072
[ "object" ]
d1394b4e3913841b549c2294726375a53765f23a
8,652
cpp
C++
icpc/4186-LuckyCities/LuckyCities.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
icpc/4186-LuckyCities/LuckyCities.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
icpc/4186-LuckyCities/LuckyCities.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#if defined(LOCAL) #define PROBLEM_NAME "LuckyCities" const double _max_double_error = 1e-9; #include "testutils.h" #define L(x...) debug(x) #else #define L(x, ...) (x) #include <bits/stdc++.h> #endif using namespace std; using vi = vector<int>; using vvi = vector<vi>; using ii = pair<int,int>; using vii = vector<ii>; using l = long long; using vl = vector<l>; using vvl = vector<vl>; using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>; using lu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; using mll = unordered_map<l, l>; const l INF = numeric_limits<l>::max(); const double EPS = 1e-10; static constexpr auto PI = acos(-1); const l e0=1, e3=1000, e5=100000, e6=10*e5, e7=10*e6, e8=10*e7, e9=10*e8; const char lf = '\n'; #define all(x) begin(x), end(x) #define F(a,b,c) for (l a = l(b); a < l(c); a++) #define B(a,b,c) for (l a = l(c) - 1; a >= l(b); a--) #if defined(LOCAL) #define L(x...) debug(x) #else #define L(x, ...) (x) #endif struct Edge { l to; l id, from; }; struct Graph { l v_count, e_count; vector<vector<Edge>> adj; Graph(l n) { v_count = n; adj.resize(n); e_count = 0; } void add_undirected(l a, l b) { Edge ab; ab.id = e_count; ab.from = a; ab.to = b; adj[a].emplace_back(ab); Edge ba; ba.id = e_count; ba.from = b; ba.to = a; adj[b].emplace_back(ba); e_count++; } }; struct G { l size; l edge_count, time; vector<vector<Edge>> adj; vl age, lowlink; vb in_path, visited, explored_edge, cut_vertex, bridge; vl bridges; stack<Edge> edge_stack; vl value; vector<vector<Edge>> component; G(l n) { size = n; adj.resize(size); edge_count = 0; time = 0; age.resize(size, -1); lowlink.resize(size); in_path.resize(size); visited.resize(size); value.resize(size); cut_vertex.resize(size); } void add_undirected(l a, l b) { Edge ab; ab.id = edge_count; ab.from = a; ab.to = b; adj[a].emplace_back(ab); Edge ba; ba.id = edge_count; ba.from = b; ba.to = a; adj[b].emplace_back(ba); edge_count++; } // edge #id ->a void dfs_components(l a, l edge_id) { visited[a] = true; in_path[a] = true; lowlink[a] = age[a] = time; time++; l forward_count = 0; bool root = edge_id == edge_count; for (auto e : adj[a]) { if (e.id == edge_id) continue; // same edge if (not explored_edge[e.id]) { explored_edge[e.id] = true; edge_stack.push(e); } if (visited[e.to]) { if (in_path[e.to]) { // back edge lowlink[a] = min(lowlink[a], age[e.to]); } } else { // forward edge dfs_components(e.to, e.id); lowlink[a] = min(lowlink[a], lowlink[e.to]); if (root ? (++forward_count > 1) : (lowlink[e.to] >= age[a])) { // articulation point cut_vertex[a] = true; // extract component vector<Edge> c; while (1) { auto t = edge_stack.top(); edge_stack.pop(); c.emplace_back(t); if (t.id == e.id) break; } component.emplace_back(c); } } } if (root) { if (not edge_stack.empty()) { vector<Edge> c; while (not edge_stack.empty()) { auto t = edge_stack.top(); edge_stack.pop(); c.emplace_back(t); } component.emplace_back(c); } } in_path[a] = false; } void build_components() { explored_edge.clear(); explored_edge.resize(edge_count); bridge.clear(); bridge.resize(edge_count); F(i, 0, size) if (not visited[i]) dfs_components(i, edge_count); } l count_odd_cycle_vertexes() { l r = 0; F(i, 0, component.size()) { auto& c = component[i]; l s = 1; value[c.back().from] = i + 1; bool bipartite = true; B(j, 0, c.size()) { if (abs(value[c[j].to]) == i + 1) { bipartite = bipartite and (value[c[j].to] == -value[c[j].from]); } else { value[c[j].to] = -value[c[j].from]; s++; } } if (not bipartite and s > 1) r += s; } return r; } }; struct BiComponents { l time; vl age, lowlink; vb in_path, explored_edge, cut_vertex, bridge; stack<Edge> edge_stack; vector<vector<Edge>> component; // 2-vertex-connected components static BiComponents build(Graph& g) { BiComponents bc; bc.time = 0; bc.age.resize(g.v_count, -1); bc.lowlink.resize(g.v_count, -1); bc.in_path.resize(g.v_count); bc.cut_vertex.resize(g.v_count); bc.explored_edge.resize(g.e_count); bc.bridge.resize(g.e_count); F(i, 0, g.v_count) { if (bc.age[i] == 0) bc.dfs_components(i, g.e_count, g); } return bc; } // edge #id ->a void dfs_components(l a, l edge_id, Graph& g) { in_path[a] = true; lowlink[a] = age[a] = time; time++; l forward_count = 0; bool root = edge_id == g.e_count; for (auto e : g.adj[a]) { if (e.id == edge_id) continue; // same edge if (not explored_edge[e.id]) { explored_edge[e.id] = true; edge_stack.push(e); } if (age[e.to] != 0) { // visited if (in_path[e.to]) { // back edge lowlink[a] = min(lowlink[a], age[e.to]); } } else { // forward edge dfs_components(e.to, e.id, g); lowlink[a] = min(lowlink[a], lowlink[e.to]); if (root ? (++forward_count > 1) : (lowlink[e.to] >= age[a])) { // articulation point cut_vertex[a] = true; // extract component vector<Edge> c; while (1) { auto t = edge_stack.top(); edge_stack.pop(); c.emplace_back(t); if (t.id == e.id) break; } component.emplace_back(c); } } } if (root) { if (not edge_stack.empty()) { vector<Edge> c; while (not edge_stack.empty()) { auto t = edge_stack.top(); edge_stack.pop(); c.emplace_back(t); } component.emplace_back(c); } } in_path[a] = false; } }; l count_odd_cycle_vertexes(Graph& g, BiComponents& bi) { vl value(g.v_count); l r = 0; F(i, 0, bi.component.size()) { auto& c = bi.component[i]; l s = 1; value[c.back().from] = i + 1; bool bipartite = true; B(j, 0, c.size()) { if (abs(value[c[j].to]) == i + 1) { bipartite = bipartite and (value[c[j].to] == -value[c[j].from]); } else { value[c[j].to] = -value[c[j].from]; s++; } } if (not bipartite and s > 1) r += s; } return r; } void solve(istream& cin, ostream& cout) { l tcc; cin >> tcc; while (tcc--) { l n, m; cin >> n >> m; Graph g(n); F(i, 0, m) { l a, b; cin >> a >> b; a--; b--; g.add_undirected(a, b); } auto bc = BiComponents::build(g); cout << count_odd_cycle_vertexes(g, bc) << lf; } } default_random_engine source(chrono::system_clock::now().time_since_epoch().count()); // [a, b) l random_in_range(l a, l b) { return uniform_int_distribution<l>(a, b - 1)(source); } double random_double() { return uniform_real_distribution<double>(0, 1)(source); } bool random_bool() { return random_in_range(0, 2) == 1; } string random_string(int length) { string s = ""; string an = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i = 0; i < length; i++) { s += an[random_in_range(0, an.size())]; } return s; } bool generate_random(l tc, ostream& cout) { l max_cases = 10000; if (tc % (max_cases / 100) == 0) cerr << (tc * 100 / max_cases) << "%\r"; cout << 1 << lf; l n = tc / 100 + 1; l m = random_in_range(0, n * n); vll pairs; F(i, 0, m) { l a = random_in_range(0, n); l b = random_in_range(0, n); if (a == b) continue; pairs.emplace_back(a, b); } m = pairs.size(); cout << n << ' ' << m << lf; // cerr << n << ' ' << m << endl; for (auto p : pairs) { cout << p.first + 1 << ' ' << p.second + 1 << lf; // cerr << p.first + 1 << ' ' << p.second + 1 << endl; } return tc < max_cases; } bool solution_checker(istream& input, istream& /* expected */, istream& actual, ostream& out) { return true; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(15); #if defined(LOCAL) _generate_random_test = generate_random; // _solve_brute = solve_brute; // _player_b = player_b; _custom_solution_checker = solution_checker; maybe_run_tests(cin, cout); #else solve(cin, cout); #endif }
25.826866
85
0.553051
[ "vector" ]
d1397b0b320961f09ccbcf5f951b04884bdb5946
58,965
cxx
C++
STEER/STEER/AliGeomManager.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEER/AliGeomManager.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEER/AliGeomManager.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //------------------------------------------------------------------------- // Implementation of AliGeomManager, the geometry manager class // which interfaces to TGeo and the look-up table mapping unique // volume indices to symbolic volume names. For that it collects // several static methods. //------------------------------------------------------------------------- #include <TClass.h> #include <TFile.h> #include <TGeoManager.h> #include <TObjString.h> #include <TGeoPhysicalNode.h> #include <TClonesArray.h> #include <TGeoMatrix.h> #include <TGeoPhysicalNode.h> #include <TSystem.h> #include <TStopwatch.h> #include <TGeoOverlap.h> #include <TPluginManager.h> #include <TROOT.h> #include "AliGeomManager.h" #include "AliLog.h" #include "AliAlignObj.h" #include "AliAlignObjParams.h" #include "AliCDBManager.h" #include "AliCDBStorage.h" #include "AliCDBEntry.h" ClassImp(AliGeomManager) Int_t AliGeomManager::fgLayerSize[kLastLayer - kFirstLayer] = { 80, 160, // ITS SPD first and second layer 84, 176, // ITS SDD first and second layer 748, 950, // ITS SSD first and second layer 36, 36, // TPC inner and outer chambers 90, 90, 90, 90, 90, 90, // 6 TRD chambers' layers 1638, // TOF 5, 5, // PHOS,CPV 7, // HMPID ?? 1, // MUON ?? 22 // EMCAL and DCAL }; const char* AliGeomManager::fgLayerName[kLastLayer - kFirstLayer] = { "ITS inner pixels layer", "ITS outer pixels layer", "ITS inner drifts layer", "ITS outer drifts layer", "ITS inner strips layer", "ITS outer strips layer", "TPC inner chambers layer", "TPC outer chambers layer", "TRD chambers layer 1", "TRD chambers layer 2", "TRD chambers layer 3", "TRD chambers layer 4", "TRD chambers layer 5", "TRD chambers layer 6", "TOF layer", "PHOS EMC layer","PHOS CPV layer", "HMPID layer", "MUON ?", "EMCAL layer" }; TGeoPNEntry** AliGeomManager::fgPNEntry[kLastLayer - kFirstLayer] = { 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0,0x0, 0x0,0x0,0x0, 0x0, 0x0,0x0, 0x0, 0x0, 0x0 }; AliAlignObj** AliGeomManager::fgAlignObjs[kLastLayer - kFirstLayer] = { 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0, 0x0,0x0,0x0, 0x0,0x0,0x0, 0x0, 0x0,0x0, 0x0, 0x0, 0x0 }; const char* AliGeomManager::fgkDetectorName[AliGeomManager::fgkNDetectors] = {"GRP","ITS","TPC","TRD","TOF","PHOS","HMPID","EMCAL","MUON","FMD","ZDC","PMD","T0","VZERO","ACORDE","AD","MFT","FIT"}; Int_t AliGeomManager::fgNalignable[fgkNDetectors] = {0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; TGeoManager* AliGeomManager::fgGeometry = 0x0; //_____________________________________________________________________________ void AliGeomManager::Destroy() { // destroy the manager as well as gGeoManager (if it was not attached to fgGeometry) TGeoManager::UnlockGeometry(); delete gGeoManager; fgGeometry = gGeoManager = 0; ResetPNEntriesLUT(); } //_____________________________________________________________________________ void AliGeomManager::LoadGeometry(const char *geomFileName) { // initialization // Load geometry either from a file // or from the corresponding CDB entry if(fgGeometry->IsLocked()){ AliErrorClass("Cannot load a new geometry, the current one being locked. Setting internal geometry to null!!"); fgGeometry = NULL; return; } fgGeometry = NULL; if (geomFileName && (!gSystem->AccessPathName(geomFileName))) { fgGeometry = TGeoManager::Import(geomFileName); AliInfoClass(Form("From now on using geometry from custom geometry file \"%s\"",geomFileName)); } if (!fgGeometry) { AliCDBPath path("GRP","Geometry","Data"); AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath()); if(!entry) AliFatalClass("Couldn't load geometry data from CDB!"); entry->SetOwner(0); fgGeometry = (TGeoManager*) entry->GetObject(); if (!fgGeometry) AliFatalClass("Couldn't find TGeoManager in the specified CDB entry!"); AliInfoClass(Form("From now on using geometry from CDB base folder \"%s\"", AliCDBManager::Instance()->GetURI("GRP/Geometry/Data"))); } ResetPNEntriesLUT(); InitPNEntriesLUT(); InitNalignable(); } //_____________________________________________________________________________ void AliGeomManager::SetGeometry(TGeoManager * const geom) { // Load already active geometry if (!geom) AliFatalClass("Pointer to the active geometry is 0x0!"); ResetPNEntriesLUT(); fgGeometry = geom; InitPNEntriesLUT(); InitNalignable(); } //_____________________________________________________________________________ AliGeomManager::AliGeomManager(): TObject() { // default constructor } //_____________________________________________________________________________ AliGeomManager::~AliGeomManager() { // dummy destructor } //_____________________________________________________________________________ Int_t AliGeomManager::LayerSize(Int_t layerId) { // Get the layer size for layer corresponding to layerId. // Implemented only for ITS,TPC,TRD,TOF and HMPID // if (layerId < kFirstLayer || layerId >= kLastLayer) { AliErrorClass(Form("Invalid layer index %d ! Layer range is (%d -> %d) !",layerId,kFirstLayer,kLastLayer)); return 0; } else { return fgLayerSize[layerId - kFirstLayer]; } } //_____________________________________________________________________________ const char* AliGeomManager::LayerName(Int_t layerId) { // Get the layer name corresponding to layerId. // Implemented only for ITS,TPC,TRD,TOF and HMPID // if (layerId < kFirstLayer || layerId >= kLastLayer) { AliErrorClass(Form("Invalid layer index %d ! Layer range is (%d -> %d) !",layerId,kFirstLayer,kLastLayer)); return "Invalid Layer!"; } else { return fgLayerName[layerId - kFirstLayer]; } } //_____________________________________________________________________________ UShort_t AliGeomManager::LayerToVolUID(ELayerID layerId, Int_t modId) { // From detector (layer) name and module number (according to detector // internal numbering) build the unique numerical identity of that volume // inside ALICE // fVolUID is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values). // NO check for validity of given modId inside the layer for speed's sake. // return ((UShort_t(layerId) << 11) | UShort_t(modId)); } //_____________________________________________________________________________ UShort_t AliGeomManager::LayerToVolUID(Int_t layerId, Int_t modId) { // From detector (layer) name and module number (according to detector // internal numbering) build the unique numerical identity of that volume // inside ALICE // fVolUID is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values). // NO check for validity of given modId inside the layer for speed's sake. // return ((UShort_t(layerId) << 11) | UShort_t(modId)); } //_____________________________________________________________________________ UShort_t AliGeomManager::LayerToVolUIDSafe(ELayerID layerId, Int_t modId) { // From detector (layer) name and module number (according to detector // internal numbering) build the unique numerical identity of that volume // inside ALICE // fVolUID is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values). // Check validity of given modId inside the layer. // if(modId < 0 || modId >= LayerSize(layerId)){ AliErrorClass(Form("Invalid volume id %d ! Range of valid ids for layer \"%s\" is [0, %d] !",modId,LayerName(layerId),LayerSize(layerId)-1)); return 0; } return ((UShort_t(layerId) << 11) | UShort_t(modId)); } //_____________________________________________________________________________ UShort_t AliGeomManager::LayerToVolUIDSafe(Int_t layerId, Int_t modId) { // From detector (layer) name and module number (according to detector // internal numbering) build the unique numerical identity of that volume // inside ALICE // fVolUID is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values). // Check validity of given modId inside the layer. // if(modId < 0 || modId >= LayerSize(layerId)){ AliErrorClass(Form("Invalid volume id %d ! Range of valid ids for layer \"%s\" is [0, %d] !",modId,LayerName(layerId),LayerSize(layerId)-1)); return 0; } return ((UShort_t(layerId) << 11) | UShort_t(modId)); } //_____________________________________________________________________________ AliGeomManager::ELayerID AliGeomManager::VolUIDToLayer(UShort_t voluid, Int_t &modId) { // From voluid, unique numerical identity of that volume inside ALICE, // (voluid is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values)), return // the identity of the layer to which that volume belongs and sets the // argument modId to the identity of that volume internally to the layer. // NO check for validity of given voluid for speed's sake. // modId = voluid & 0x7ff; return VolUIDToLayer(voluid); } //_____________________________________________________________________________ AliGeomManager::ELayerID AliGeomManager::VolUIDToLayer(UShort_t voluid) { // From voluid, unique numerical identity of that volume inside ALICE, // (voluid is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values)), return // the identity of the layer to which that volume belongs // NO check for validity of given voluid for speed's sake. // return ELayerID(voluid >> 11); } //_____________________________________________________________________________ AliGeomManager::ELayerID AliGeomManager::VolUIDToLayerSafe(UShort_t voluid, Int_t &modId) { // From voluid, unique numerical identity of that volume inside ALICE, // (voluid is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values)), returns // the identity of the layer to which that volume belongs and sets the // argument modId to the identity of that volume internally to the layer. // Checks the validity of the given voluid // ELayerID layId = VolUIDToLayerSafe(voluid); if(layId != AliGeomManager::kInvalidLayer){ Int_t mId = Int_t(voluid & 0x7ff); if( mId>=0 && mId<LayerSize(layId)){ modId = mId; return layId; } } AliErrorClass(Form("Invalid unique volume id: %d !",voluid)); modId = -1; return kInvalidLayer; } //_____________________________________________________________________________ AliGeomManager::ELayerID AliGeomManager::VolUIDToLayerSafe(UShort_t voluid) { // From voluid, unique numerical identity of that volume inside ALICE, // (voluid is 16 bits, first 5 reserved for layerID (32 possible values), // remaining 11 for module ID inside det (2048 possible values)), returns // the identity of the layer to which that volume belongs // Checks the validity of the given voluid // if( (voluid >> 11) < kLastLayer) return ELayerID(voluid >> 11); AliErrorClass(Form("Invalid layer id: %d !",(voluid >> 11))); return kInvalidLayer; } //_____________________________________________________________________________ Bool_t AliGeomManager::GetFromGeometry(const char *symname, AliAlignObj &alobj) { // Get the alignment object which corresponds to the symbolic volume name // symname (in case equal to the TGeo volume path) // The method is extremely slow due to the searching by string, // therefore it should be used with great care!! // This method returns FALSE if the symname of the object was not // valid neither to get a TGeoPEntry nor as a volume path, or if the path // associated to the TGeoPNEntry was not valid. // // Reset the alignment object alobj.SetPars(0,0,0,0,0,0); alobj.SetSymName(symname); if (!fgGeometry || !fgGeometry->IsClosed()) { AliErrorClass("Can't get the alignment object! gGeoManager doesn't exist or it is still opened!"); return kFALSE; } if (!fgGeometry->GetListOfPhysicalNodes()) { AliErrorClass("Can't get the alignment object! gGeoManager doesn't contain any aligned nodes!"); return kFALSE; } const char *path; TGeoPNEntry* pne = fgGeometry->GetAlignableEntry(symname); if(pne){ path = pne->GetTitle(); }else{ AliWarningClass(Form("The symbolic volume name %s does not correspond to a physical entry. Using it as a volume path!",symname)); path = symname; } TObjArray* nodesArr = fgGeometry->GetListOfPhysicalNodes(); TGeoPhysicalNode* node = NULL; for (Int_t iNode = 0; iNode < nodesArr->GetEntriesFast(); iNode++) { TGeoPhysicalNode* tempNode = (TGeoPhysicalNode*) nodesArr->UncheckedAt(iNode); const char *nodePath = tempNode->GetName(); if (strcmp(path,nodePath) == 0) { node = tempNode; break; } } if (!node) { if (!fgGeometry->cd(path)) { AliErrorClass(Form("%s not valid neither as symbolic volume name nor as volume path!",path)); return kFALSE; } else { AliWarningClass(Form("Volume (%s) has not been misaligned!",path)); return kTRUE; } } TGeoHMatrix align,gprime,g,ginv,l; gprime = *node->GetMatrix(); l = *node->GetOriginalMatrix(); g = *node->GetMatrix(node->GetLevel()-1); g *= l; ginv = g.Inverse(); align = gprime * ginv; return alobj.SetMatrix(align); } //_____________________________________________________________________________ void AliGeomManager::InitAlignObjFromGeometry() { // Loop over all alignable volumes and extract // the corresponding alignment objects from // the TGeo geometry // for (Int_t iLayer = kFirstLayer; iLayer < AliGeomManager::kLastLayer; iLayer++) { if (!fgAlignObjs[iLayer-kFirstLayer]) { fgAlignObjs[iLayer-kFirstLayer] = new AliAlignObj*[LayerSize(iLayer)]; } for (Int_t iModule = 0; iModule < LayerSize(iLayer); iModule++) { UShort_t volid = LayerToVolUID(iLayer,iModule); fgAlignObjs[iLayer-kFirstLayer][iModule] = new AliAlignObjParams("",volid,0,0,0,0,0,0,kTRUE); const char *symname = SymName(volid); if (!GetFromGeometry(symname, *fgAlignObjs[iLayer-kFirstLayer][iModule])) AliErrorClass(Form("Failed to extract the alignment object for the volume (ID=%d and path=%s) !",volid,symname)); } } } //_____________________________________________________________________________ AliAlignObj* AliGeomManager::GetAlignObj(UShort_t voluid) { // Returns the alignment object for given volume ID // Int_t modId; ELayerID layerId = VolUIDToLayer(voluid,modId); return GetAlignObj(layerId,modId); } //_____________________________________________________________________________ AliAlignObj* AliGeomManager::GetAlignObj(ELayerID layerId, Int_t modId) { // Returns pointer to alignment object given its layer and module ID // if(modId<0 || modId>=fgLayerSize[layerId-kFirstLayer]){ AliWarningClass(Form("Module number %d not in the valid range (0->%d) !",modId,fgLayerSize[layerId-kFirstLayer]-1)); return NULL; } InitAlignObjFromGeometry(); return fgAlignObjs[layerId-kFirstLayer][modId]; } //_____________________________________________________________________________ const char* AliGeomManager::SymName(UShort_t voluid) { // Returns the symbolic volume name for given volume ID // Int_t modId; ELayerID layerId = VolUIDToLayer(voluid,modId); return SymName(layerId,modId); } //_____________________________________________________________________________ const char* AliGeomManager::SymName(ELayerID layerId, Int_t modId) { // Returns the symbolic volume name given for a given layer // and module ID // if(!fgGeometry){ AliErrorClass("No geometry instance loaded yet!"); return NULL; } if(modId<0 || modId>=fgLayerSize[layerId-kFirstLayer]){ AliWarningClass(Form("Module number %d not in the valid range (0->%d) !",modId,fgLayerSize[layerId-kFirstLayer]-1)); return NULL; } TGeoPNEntry* pne = fgPNEntry[layerId-kFirstLayer][modId]; if(!pne) { AliWarningClass(Form("Module %d of layer %s is not activated!",modId,LayerName(layerId))); return NULL; } return pne->GetName(); } //_____________________________________________________________________________ Bool_t AliGeomManager::CheckSymNamesLUT(const char* /*detsToBeChecked*/) { // Check the look-up table which associates the unique numerical identity of // each alignable volume to the corresponding symbolic volume name. // The LUT is now held inside the geometry and handled by TGeo. // The method is meant to be launched when loading a geometry to verify that // no changes in the symbolic names have been introduced, which would prevent // backward compatibility with alignment objects. // To accept both complete and partial geometry, this method skips the check // for TRD and TOF volumes which are missing in the partial geometry. // // TString detsString(detsToBeChecked); // if(detsString.Contains("ALL")) detsString="ITS TPC TOF TRD HMPID PHOS EMCAL"; // Temporary measure to face the case of reconstruction over detectors not present in the geometry TString detsString = ""; if(fgGeometry->CheckPath("ALIC_1/ITSV_1")) detsString+="ITS "; if(fgGeometry->CheckPath("ALIC_1/TPC_M_1")) detsString+="TPC "; TString tofsm; TString baseTof("ALIC_1/B077_1/BSEGMO"); TString middleTof("_1/BTOF"); TString trailTof("_1/FTOA_0"); Bool_t tofActive=kFALSE; Bool_t tofSMs[18]; for(Int_t sm=0; sm<18; sm++) { tofSMs[sm]=kFALSE; tofsm=baseTof; tofsm += sm; tofsm += middleTof; tofsm += sm; tofsm += trailTof; if(fgGeometry->CheckPath(tofsm.Data())) { tofActive=kTRUE; tofSMs[sm]=kTRUE; } } if(tofActive) detsString+="TOF "; TString trdsm; TString baseTrd("ALIC_1/B077_1/BSEGMO"); TString middleTrd("_1/BTRD"); TString trailTrd("_1/UTR1_1"); Bool_t trdActive=kFALSE; Bool_t trdSMs[18]; for(Int_t sm=0; sm<18; sm++) { trdSMs[sm]=kFALSE; trdsm=baseTrd; trdsm += sm; trdsm += middleTrd; trdsm += sm; trdsm += trailTrd; if(fgGeometry->CheckPath(trdsm.Data())) { trdActive=kTRUE; trdSMs[sm]=kTRUE; } } if(trdActive) detsString+="TRD "; if(fgGeometry->CheckPath("ALIC_1/Hmp0_0")) detsString+="HMPID "; TString phosMod, cpvMod; TString basePhos("ALIC_1/PHOS_"); Bool_t phosActive=kFALSE; Bool_t cpvActive=kFALSE; Bool_t phosMods[5]; for(Int_t pmod=0; pmod<5; pmod++) { phosMods[pmod]=kFALSE; phosMod = basePhos; phosMod += (pmod+1); cpvMod = phosMod; cpvMod += "/PCPV_1"; if(fgGeometry->CheckPath(phosMod.Data())) { phosActive=kTRUE; phosMods[pmod]=kTRUE; if(fgGeometry->CheckPath(cpvMod.Data())) cpvActive=kTRUE; } } if(phosActive) detsString+="PHOS "; // Check over the ten EMCAL full supermodules and the two EMCAL half supermodules TString emcalSM; TString baseEmcalSM("ALIC_1/XEN1_1/"); Bool_t emcalActive=kFALSE; Bool_t emcalSMs[22] = {kFALSE}; for(Int_t sm=0; sm<22; sm++) { emcalSM=baseEmcalSM; if(sm<10){ emcalSM += "SMOD_"; emcalSM += (sm+1); }else if(sm/2 == 5){ emcalSM += "SM10_"; emcalSM += (sm-9); }else if(sm > 11){ emcalSM += "DCSM_"; emcalSM += (sm-11); } if(fgGeometry->CheckPath(emcalSM.Data())) { emcalActive=kTRUE; emcalSMs[sm]=kTRUE; } } if(emcalActive) detsString+="EMCAL "; TString symname; const char* sname; TGeoPNEntry* pne = 0x0; Int_t uid; // global unique identity Int_t modnum; // unique id inside layer; in the following, set it to 0 at the start of each layer if(detsString.Contains("ITS")){ /********************* ITS layers ***********************/ AliDebugClass(2,"Checking consistency of symbolic names for ITS layers"); TString strSPD = "ITS/SPD"; TString strSDD = "ITS/SDD"; TString strSSD = "ITS/SSD"; TString strStave = "/Stave"; TString strHalfStave = "/HalfStave"; TString strLadder = "/Ladder"; TString strSector = "/Sector"; TString strSensor = "/Sensor"; TString strEntryName1; TString strEntryName2; TString strEntryName3; /********************* SPD layer1 ***********************/ { modnum = 0; for(Int_t cSect = 0; cSect<10; cSect++){ strEntryName1 = strSPD; strEntryName1 += 0; strEntryName1 += strSector; strEntryName1 += cSect; for(Int_t cStave =0; cStave<2; cStave++){ strEntryName2 = strEntryName1; strEntryName2 += strStave; strEntryName2 += cStave; for (Int_t cHS=0; cHS<2; cHS++) { strEntryName3 = strEntryName2; strEntryName3 += strHalfStave; strEntryName3 += cHS; for(Int_t cLad =0; cLad<2; cLad++){ symname = strEntryName3; symname += strLadder; symname += cLad+cHS*2; uid = LayerToVolUID(kSPD1,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d." "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } } } /********************* SPD layer2 ***********************/ { modnum = 0; for(Int_t cSect = 0; cSect<10; cSect++){ strEntryName1 = strSPD; strEntryName1 += 1; strEntryName1 += strSector; strEntryName1 += cSect; for(Int_t cStave =0; cStave<4; cStave++){ strEntryName2 = strEntryName1; strEntryName2 += strStave; strEntryName2 += cStave; for (Int_t cHS=0; cHS<2; cHS++) { strEntryName3 = strEntryName2; strEntryName3 += strHalfStave; strEntryName3 += cHS; for(Int_t cLad =0; cLad<2; cLad++){ symname = strEntryName3; symname += strLadder; symname += cLad+cHS*2; uid = LayerToVolUID(kSPD2,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d." "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } } } /********************* SDD layer1 ***********************/ { modnum=0; for(Int_t c1 = 1; c1<=14; c1++){ strEntryName1 = strSDD; strEntryName1 += 2; strEntryName1 +=strLadder; strEntryName1 += (c1-1); for(Int_t c2 =1; c2<=6; c2++){ symname = strEntryName1; symname += strSensor; symname += (c2-1); uid = LayerToVolUID(kSDD1,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } /********************* SDD layer2 ***********************/ { modnum=0; for(Int_t c1 = 1; c1<=22; c1++){ strEntryName1 = strSDD; strEntryName1 += 3; strEntryName1 +=strLadder; strEntryName1 += (c1-1); for(Int_t c2 = 1; c2<=8; c2++){ symname = strEntryName1; symname += strSensor; symname += (c2-1); uid = LayerToVolUID(kSDD2,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } /********************* SSD layer1 ***********************/ { modnum=0; for(Int_t c1 = 1; c1<=34; c1++){ strEntryName1 = strSSD; strEntryName1 += 4; strEntryName1 +=strLadder; strEntryName1 += (c1-1); for(Int_t c2 = 1; c2<=22; c2++){ symname = strEntryName1; symname += strSensor; symname += (c2-1); uid = LayerToVolUID(kSSD1,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } /********************* SSD layer2 ***********************/ { modnum=0; for(Int_t c1 = 1; c1<=38; c1++){ strEntryName1 = strSSD; strEntryName1 += 5; strEntryName1 +=strLadder; strEntryName1 += (c1-1); for(Int_t c2 = 1; c2<=25; c2++){ symname = strEntryName1; symname += strSensor; symname += (c2-1); uid = LayerToVolUID(kSSD2,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } AliDebugClass(2,"Consistency check for ITS symbolic names finished successfully."); } if(detsString.Contains("TPC")) { /*************** TPC inner and outer layers ****************/ AliDebugClass(2,"Checking consistency of symbolic names for TPC layers"); TString sAsector="TPC/EndcapA/Sector"; TString sCsector="TPC/EndcapC/Sector"; TString sInner="/InnerChamber"; TString sOuter="/OuterChamber"; /*************** TPC inner chambers' layer ****************/ { modnum = 0; for(Int_t cnt=1; cnt<=18; cnt++) { symname = sAsector; symname += cnt; symname += sInner; uid = LayerToVolUID(kTPC1,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } for(Int_t cnt=1; cnt<=18; cnt++) { symname = sCsector; symname += cnt; symname += sInner; uid = LayerToVolUID(kTPC1,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } /*************** TPC outer chambers' layer ****************/ { modnum = 0; for(Int_t cnt=1; cnt<=18; cnt++) { symname = sAsector; symname += cnt; symname += sOuter; uid = LayerToVolUID(kTPC2,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } for(Int_t cnt=1; cnt<=18; cnt++) { symname = sCsector; symname += cnt; symname += sOuter; uid = LayerToVolUID(kTPC2,modnum++); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } AliDebugClass(2,"Consistency check for TPC symbolic names finished successfully."); } if(detsString.Contains("TOF")) { /********************* TOF layer ***********************/ AliDebugClass(2,"Checking consistency of symbolic names for TOF layers"); modnum=0; Int_t nstrA=15; Int_t nstrB=19; Int_t nstrC=19; Int_t nSectors=18; Int_t nStrips=nstrA+2*nstrB+2*nstrC; TString snSM = "TOF/sm"; TString snSTRIP = "/strip"; for (Int_t isect = 0; isect < nSectors; isect++) { if(tofSMs[isect]) AliDebugClass(3,Form("Consistency check for symnames of TOF supermodule %d.",isect)); for (Int_t istr = 1; istr <= nStrips; istr++) { symname = snSM; symname += Form("%02d",isect); symname += snSTRIP; symname += Form("%02d",istr); uid = LayerToVolUID(kTOF,modnum++); if(!tofSMs[isect]) continue; // taking possible missing TOF sectors (partial geometry) into account if ((isect==13 || isect==14 || isect==15) && (istr >= 39 && istr <= 53)) continue; //taking holes into account pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } AliDebugClass(2,"Consistency check for TOF symbolic names finished successfully."); } if(detsString.Contains("HMPID")) { /********************* HMPID layer ***********************/ AliDebugClass(2,"Checking consistency of symbolic names for HMPID layers"); TString str = "/HMPID/Chamber"; for (modnum=0; modnum < 7; modnum++) { symname = str; symname += modnum; uid = LayerToVolUID(kHMPID,modnum); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } AliDebugClass(2,"Consistency check for HMPID symbolic names finished successfully."); } if(detsString.Contains("TRD")) { /********************* TRD layers 1-6 *******************/ //!! 6 layers with index increasing in outwards direction AliDebugClass(2,"Checking consistency of symbolic names for TRD layers"); Int_t arTRDlayId[6] = {kTRD1, kTRD2, kTRD3, kTRD4, kTRD5, kTRD6}; TString snStr = "TRD/sm"; TString snApp1 = "/st"; TString snApp2 = "/pl"; for(Int_t layer=0; layer<6; layer++){ modnum=0; AliDebugClass(3,Form("Consistency check for symnames of TRD layer %d.",layer)); for (Int_t isect = 0; isect < 18; isect++) { for (Int_t icham = 0; icham < 5; icham++) { symname = snStr; symname += Form("%02d",isect); symname += snApp1; symname += icham; symname += snApp2; symname += layer; uid = LayerToVolUID(arTRDlayId[layer],modnum++); if(!trdSMs[isect]) continue; if ((isect==13 || isect==14 || isect==15) && icham==2) continue; //keeping holes into account pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } } } AliDebugClass(2,"Consistency check for TRD symbolic names finished successfully."); } if(detsString.Contains("PHOS")) { /********************* PHOS EMC layer ***********************/ AliDebugClass(2,"Checking consistency of symbolic names for PHOS layers"); TString str = "PHOS/Module"; modnum=0; for (Int_t iModule=0; iModule < 5; iModule++) { if(!phosMods[iModule]) continue; symname = str; symname += (iModule+1); uid = LayerToVolUID(kPHOS1,iModule); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } /********************* PHOS CPV layer ***********************/ if(!cpvActive) continue; symname += "/CPV"; uid = LayerToVolUID(kPHOS2,iModule); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } AliDebugClass(2,"Consistency check for PHOS symbolic names finished successfully."); } if(detsString.Contains("EMCAL")) { /********************* EMCAL layer ***********************/ AliDebugClass(2,"Checking consistency of symbolic names for EMCAL layers"); TString str = "EMCAL/FullSupermodule"; modnum=0; for (Int_t iModule=0; iModule < 22; iModule++) { if(!emcalSMs[iModule]) continue; symname = str; symname += iModule+1; if(iModule/2 == 5) {// 10,11 symname = "EMCAL/HalfSupermodule"; symname += iModule-9; }else if(iModule > 11) {// 12 ~ 21 symname = "EMCAL/DCALSupermodule"; symname += iModule-11; } modnum = iModule; uid = LayerToVolUID(kEMCAL,modnum); pne = fgGeometry->GetAlignableEntryByUID(uid); if(!pne) { AliErrorClass(Form("In the currently loaded geometry there is no TGeoPNEntry with unique id %d",uid)); return kFALSE; } sname = pne->GetName(); if(symname.CompareTo(sname)) { AliErrorClass(Form("Current loaded geometry differs in the definition of symbolic name for uid %d" "Expected was %s, found was %s!", uid, symname.Data(), sname)); return kFALSE; } } AliDebugClass(2,"Consistency check for EMCAL symbolic names finished successfully."); } return kTRUE; } //_____________________________________________________________________________ void AliGeomManager::InitPNEntriesLUT() { // Initialize the look-up table which associates the unique // numerical identity of each alignable volume to the // corresponding TGeoPNEntry. // The LUTs are static; they are created at the creation of the // AliGeomManager instance and recreated if the geometry has changed // if(!fgGeometry) { AliErrorClass("Impossible to initialize PNEntries LUT without an active geometry"); return; } for (Int_t iLayer = 0; iLayer < (kLastLayer - kFirstLayer); iLayer++){ if (!fgPNEntry[iLayer]) fgPNEntry[iLayer] = new TGeoPNEntry*[fgLayerSize[iLayer]]; for(Int_t modnum=0; modnum<fgLayerSize[iLayer]; modnum++){ fgPNEntry[iLayer][modnum] = fgGeometry->GetAlignableEntryByUID(LayerToVolUID(iLayer+1,modnum)); } } } //______________________________________________________________________ TGeoHMatrix* AliGeomManager::GetMatrix(TGeoPNEntry *pne) { // Get the global transformation matrix for a given PNEntry // by quering the TGeoManager if (!fgGeometry || !fgGeometry->IsClosed()) { AliErrorClass("Can't get the global matrix! gGeoManager doesn't exist or it is still opened!"); return NULL; } // if matrix already known --> return it TGeoPhysicalNode *pnode = pne->GetPhysicalNode(); if (pnode) return pnode->GetMatrix(); // otherwise calculate it from title and attach via TGeoPhysicalNode pne->SetPhysicalNode(new TGeoPhysicalNode(pne->GetTitle())); return pne->GetPhysicalNode()->GetMatrix(); } //______________________________________________________________________ TGeoHMatrix* AliGeomManager::GetMatrix(Int_t index) { // Get the global transformation matrix for a given alignable volume // identified by its unique ID 'index' by quering the TGeoManager TGeoPNEntry *pne = GetPNEntry(index); if (!pne) return NULL; return GetMatrix(pne); } //______________________________________________________________________ TGeoHMatrix* AliGeomManager::GetMatrix(const char* symname) { // Get the global transformation matrix for a given alignable volume // identified by its symbolic name 'symname' by quering the TGeoManager if (!fgGeometry || !fgGeometry->IsClosed()) { AliErrorClass("No active geometry or geometry not yet closed!"); return NULL; } TGeoPNEntry* pne = fgGeometry->GetAlignableEntry(symname); if (!pne) return NULL; return GetMatrix(pne); } //______________________________________________________________________ Bool_t AliGeomManager::GetTranslation(Int_t index, Double_t t[3]) { // Get the translation vector for a given module 'index' // by quering the TGeoManager TGeoHMatrix *m = GetMatrix(index); if (!m) return kFALSE; Double_t *trans = m->GetTranslation(); for (Int_t i = 0; i < 3; i++) t[i] = trans[i]; return kTRUE; } //______________________________________________________________________ Bool_t AliGeomManager::GetRotation(Int_t index, Double_t r[9]) { // Get the rotation matrix for a given module 'index' // by quering the TGeoManager TGeoHMatrix *m = GetMatrix(index); if (!m) return kFALSE; Double_t *rot = m->GetRotationMatrix(); for (Int_t i = 0; i < 9; i++) r[i] = rot[i]; return kTRUE; } //_____________________________________________________________________________ Bool_t AliGeomManager::GetDeltaForBranch(Int_t index, TGeoHMatrix &inclusiveD) { // The method sets the matrix passed as argument as the global delta // (for the volume referred by the unique index) including the displacements // of all parent volumes in the branch. // TGeoHMatrix go,invgo; go = *GetOrigGlobalMatrix(index); invgo = go.Inverse(); inclusiveD = *GetMatrix(index); inclusiveD.Multiply(&invgo); return kTRUE; } //_____________________________________________________________________________ Bool_t AliGeomManager::GetDeltaForBranch(AliAlignObj& aao, TGeoHMatrix &inclusiveD) { // The method sets the matrix passed as argument as the global delta // (for the volume referred by the alignment object) including the displacements // of all parent volumes in the brach. // Int_t index = aao.GetVolUID(); if(!index){ AliErrorClass("Either the alignment object or its index are not valid"); return kFALSE; } return GetDeltaForBranch(index, inclusiveD); } //______________________________________________________________________ Bool_t AliGeomManager::GetOrigGlobalMatrix(const char* symname, TGeoHMatrix &m) { // Get the global transformation matrix (ideal geometry) for a given alignable volume // The alignable volume is identified by 'symname' which has to be either a valid symbolic // name, the query being performed after alignment, or a valid volume path if the query is // performed before alignment. // m.Clear(); if (!fgGeometry || !fgGeometry->IsClosed()) { AliErrorClass("No active geometry or geometry not yet closed!"); return kFALSE; } if (!fgGeometry->GetListOfPhysicalNodes()) { AliWarningClass("gGeoManager doesn't contain any aligned nodes!"); if (!fgGeometry->cd(symname)) { AliErrorClass(Form("Volume path %s not valid!",symname)); return kFALSE; } else { m = *fgGeometry->GetCurrentMatrix(); return kTRUE; } } TGeoPNEntry* pne = fgGeometry->GetAlignableEntry(symname); const char* path = NULL; if(pne){ m = *pne->GetGlobalOrig(); return kTRUE; }else{ AliWarningClass(Form("The symbolic volume name %s does not correspond to a physical entry. Using it as a volume path!",symname)); path=symname; } return GetOrigGlobalMatrixFromPath(path,m); } //_____________________________________________________________________________ Bool_t AliGeomManager::GetOrigGlobalMatrixFromPath(const char *path, TGeoHMatrix &m) { // The method returns the global matrix for the volume identified by // 'path' in the ideal detector geometry. // The output global matrix is stored in 'm'. // Returns kFALSE in case TGeo has not been initialized or the volume // path is not valid. // m.Clear(); if (!fgGeometry || !fgGeometry->IsClosed()) { AliErrorClass("Can't get the original global matrix! gGeoManager doesn't exist or it is still opened!"); return kFALSE; } if (!fgGeometry->CheckPath(path)) { AliErrorClass(Form("Volume path %s not valid!",path)); return kFALSE; } TIter next(fgGeometry->GetListOfPhysicalNodes()); fgGeometry->cd(path); while(fgGeometry->GetLevel()){ TGeoPhysicalNode *physNode = NULL; next.Reset(); TGeoNode *node = fgGeometry->GetCurrentNode(); while ((physNode=(TGeoPhysicalNode*)next())) if (physNode->GetNode() == node) break; TGeoMatrix *lm = NULL; if (physNode) { lm = physNode->GetOriginalMatrix(); if (!lm) lm = node->GetMatrix(); } else lm = node->GetMatrix(); m.MultiplyLeft(lm); fgGeometry->CdUp(); } return kTRUE; } //_____________________________________________________________________________ TGeoHMatrix* AliGeomManager::GetOrigGlobalMatrix(TGeoPNEntry * const pne) { // The method returns global matrix for the ideal detector geometry // using the corresponding TGeoPNEntry as an input. // The returned pointer should be copied by the user, since its content could // be overwritten by a following call to the method. // In case of missing TGeoManager the method returns NULL. // if (!fgGeometry || !fgGeometry->IsClosed()) { AliErrorClass("Can't get the global matrix! gGeoManager doesn't exist or it is still opened!"); return NULL; } return pne->GetGlobalOrig(); } //______________________________________________________________________ TGeoHMatrix* AliGeomManager::GetOrigGlobalMatrix(Int_t index) { // The method returns global matrix from the ideal detector geometry // for the volume identified by its index. // The returned pointer should be copied by the user, since its content could // be overwritten by a following call to the method. // In case of missing TGeoManager the method returns NULL. // If possible, the method uses the LUT of original ideal matrices // for fast access. The LUT is reset in case a // new geometry is loaded. // TGeoPNEntry* pne = GetPNEntry(index); return pne->GetGlobalOrig(); } //______________________________________________________________________ Bool_t AliGeomManager::GetOrigTranslation(Int_t index, Double_t t[3]) { // Get the original translation vector (ideal geometry) // for a given module 'index' by quering the TGeoManager TGeoHMatrix *m = GetOrigGlobalMatrix(index); if (!m) return kFALSE; Double_t *trans = m->GetTranslation(); for (Int_t i = 0; i < 3; i++) t[i] = trans[i]; return kTRUE; } //______________________________________________________________________ Bool_t AliGeomManager::GetOrigRotation(Int_t index, Double_t r[9]) { // Get the original rotation matrix (ideal geometry) // for a given module 'index' by quering the TGeoManager TGeoHMatrix *m = GetOrigGlobalMatrix(index); if (!m) return kFALSE; Double_t *rot = m->GetRotationMatrix(); for (Int_t i = 0; i < 9; i++) r[i] = rot[i]; return kTRUE; } //______________________________________________________________________ const TGeoHMatrix* AliGeomManager::GetTracking2LocalMatrix(Int_t index) { // Get the matrix which transforms from the tracking to the local RS // The method queries directly the TGeoPNEntry TGeoPNEntry *pne = GetPNEntry(index); if (!pne) return NULL; const TGeoHMatrix *m = pne->GetMatrix(); if (!m) AliErrorClass(Form("TGeoPNEntry (%s) contains no tracking-to-local matrix !",pne->GetName())); return m; } //______________________________________________________________________ Bool_t AliGeomManager::GetTrackingMatrix(Int_t index, TGeoHMatrix &m) { // Get the matrix which transforms from the tracking r.s. to // the global one. // Returns kFALSE in case of error. m.Clear(); TGeoHMatrix *m1 = GetMatrix(index); if (!m1) return kFALSE; const TGeoHMatrix *m2 = GetTracking2LocalMatrix(index); if (!m2) return kFALSE; m = *m1; m.Multiply(m2); return kTRUE; } //_____________________________________________________________________________ TGeoPNEntry* AliGeomManager::GetPNEntry(Int_t voluid) { // Returns the TGeoPNEntry for the given global volume ID "voluid" // Int_t modId; ELayerID layerId = VolUIDToLayer(voluid,modId); return GetPNEntry(layerId,modId); } //_____________________________________________________________________________ TGeoPNEntry* AliGeomManager::GetPNEntry(ELayerID layerId, Int_t modId) { // Returns the TGeoPNEntry for a given layer // and module ID // if(modId<0 || modId>=fgLayerSize[layerId-kFirstLayer]){ AliWarningClass(Form("Module number %d not in the valid range (0->%d) !",modId,fgLayerSize[layerId-kFirstLayer]-1)); return NULL; } return fgPNEntry[layerId-kFirstLayer][modId]; } //_____________________________________________________________________________ void AliGeomManager::CheckOverlapsOverPNs(Double_t threshold) { // Check for overlaps/extrusions on physical nodes only; // this overlap-checker is meant to be used to check overlaps/extrusions // originated by the application of alignment objects. // TObjArray* ovexlist = 0x0; AliInfoClass("********* Checking overlaps/extrusions over physical nodes only *********"); TObjArray* pnList = gGeoManager->GetListOfPhysicalNodes(); TGeoVolume* mvol = 0; TGeoPhysicalNode* pn; TObjArray* overlaps = new TObjArray(64); overlaps->SetOwner(); TStopwatch timer2; timer2.Start(); for(Int_t pni=0; pni<pnList->GetEntriesFast(); pni++){ pn = (TGeoPhysicalNode*) pnList->UncheckedAt(pni); // checking the volume of the mother (go upper in the tree in case it is an assembly) Int_t levup=1; while(((TGeoVolume*)pn->GetVolume(pn->GetLevel()-levup))->IsAssembly()) levup++; //Printf("Going to upper level"); mvol = pn->GetVolume(pn->GetLevel()-levup); if(!mvol->IsSelected()){ AliInfoClass(Form("Checking overlaps for volume %s",mvol->GetName())); mvol->CheckOverlaps(threshold); ovexlist = gGeoManager->GetListOfOverlaps(); TIter next(ovexlist); TGeoOverlap *ov; while ((ov=(TGeoOverlap*)next())) overlaps->Add(ov->Clone()); mvol->SelectVolume(); } } mvol->SelectVolume(kTRUE); // clears the list of selected volumes AliInfoClass(Form("Number of overlapping/extruding PNs: %d",overlaps->GetEntriesFast())); timer2.Stop(); timer2.Print(); TIter nextN(overlaps); TGeoOverlap *ovlp; while ((ovlp=(TGeoOverlap*)nextN())) ovlp->PrintInfo(); overlaps->Delete(); delete overlaps; } //_____________________________________________________________________________ Int_t AliGeomManager::GetNalignable(const char* module) { // Get number of declared alignable volumes in current geometry // for the given detector "module" passed as a vaild detector name // if the detector name is invalid return -1 // return the detector index corresponding to detector Int_t index = -1 ; for (index = 0; index < fgkNDetectors ; index++) { if ( strcmp(module, fgkDetectorName[index]) == 0 ) break ; } if(index==fgkNDetectors) return -1; return fgNalignable[index]; } //_____________________________________________________________________________ void AliGeomManager::InitNalignable() { // Set number of declared alignable volumes for given detector in current geometry // by looping on the list of PNEntries // Int_t nAlE = gGeoManager->GetNAlignable(); // total number of alignable entries TGeoPNEntry *pne = 0; const char* detName; for (Int_t iDet = 0; iDet < fgkNDetectors ; iDet++) { detName = fgkDetectorName[iDet]; Int_t nAlDet = 0; for(Int_t iE = 0; iE < nAlE; iE++) { pne = gGeoManager->GetAlignableEntry(iE); TString pneName = pne->GetName(); if(pneName.Contains(detName)) nAlDet++; if(!strcmp(detName,"GRP")) if(pneName.Contains("ABSO") || pneName.Contains("DIPO") || pneName.Contains("FRAME") || pneName.Contains("PIPE") || pneName.Contains("SHIL")) nAlDet++; } fgNalignable[iDet] = nAlDet; } } //_____________________________________________________________________________ Bool_t AliGeomManager::ApplyAlignObjsFromCDB(const char* alignDetsList) { // Calls AddAlignObjsFromCDBSingleDet for the detectors appearing in // the list passed as argument (called by AliSimulation and // AliReconstruction) // Read the alignment objects from CDB. // Each detector is supposed to have the // alignment objects in DET/Align/Data CDB path. // All the detector objects are then collected, // sorted by geometry level (starting from ALIC) and // then applied to the TGeo geometry. // Finally an overlaps check is performed. // // avoid alignment procedure if geometry already locked if(gGeoManager->IsLocked()){ AliWarningClass("Not aligning geometry (again); Geometry is locked"); return kFALSE; } TObjArray alignObjArray; alignObjArray.Clear(); alignObjArray.SetOwner(0); TString alObjsNotLoaded=""; TString alObjsLoaded=""; TString alignDetsString(alignDetsList); TObjArray *detsarr = alignDetsString.Tokenize(' '); TIter iter(detsarr); TObjString *str = 0; while((str = (TObjString*) iter.Next())){ TString det(str->String()); AliDebugClass(5,Form("Loading alignment objs for %s",det.Data())); if(!LoadAlignObjsFromCDBSingleDet(det.Data(),alignObjArray)){ alObjsNotLoaded += det.Data(); alObjsNotLoaded += " "; } else { alObjsLoaded += det.Data(); alObjsLoaded += " "; } } detsarr->Delete(); delete detsarr; if(!alObjsLoaded.IsNull()) AliInfoClass(Form("Alignment objects loaded for: %s", alObjsLoaded.Data())); if(!alObjsNotLoaded.IsNull()) AliFatalClass(Form("Could not load alignment objects from OCDB for: %s", alObjsNotLoaded.Data())); return ApplyAlignObjsToGeom(alignObjArray); } //_____________________________________________________________________________ Bool_t AliGeomManager::LoadAlignObjsFromCDBSingleDet(const char* detName, TObjArray& alignObjArray) { // Adds the alignable objects found in the CDBEntry for the detector // passed as argument to the array of all alignment objects to be applyed // to geometry // // Fills array of single detector's alignable objects from CDB AliDebugClass(2, Form("Loading alignment objs for detector: %s",detName)); AliCDBEntry *entry; AliCDBPath path(detName,"Align","Data"); entry=AliCDBManager::Instance()->Get(path.GetPath()); if(!entry){ AliDebugClass(2,Form("Couldn't load alignment data for detector %s",detName)); return kFALSE; } entry->SetOwner(1); TClonesArray *alignArray = (TClonesArray*) entry->GetObject(); alignArray->SetOwner(0); Int_t nAlObjs = alignArray->GetEntries(); AliDebugClass(2,Form("Found %d alignment objects for %s",nAlObjs,detName)); Int_t nAlVols = GetNalignable(detName); if(nAlObjs!=nAlVols) AliWarningClass(Form("%d alignment objects loaded for %s, which has %d alignable volumes",nAlObjs,detName,GetNalignable(detName))); AliAlignObj *alignObj=0; TIter iter(alignArray); // loop over align objects in detector while( ( alignObj=(AliAlignObj *) iter.Next() ) ){ alignObjArray.Add(alignObj); } // delete entry --- Don't delete, it is cached! AliDebugClass(2, Form("fAlignObjArray entries: %d",alignObjArray.GetEntries() )); return kTRUE; } //_____________________________________________________________________________ Bool_t AliGeomManager::ApplyAlignObjsToGeom(TObjArray& alignObjArray, Bool_t ovlpcheck) { // Read collection of alignment objects (AliAlignObj derived) saved // in the TClonesArray alObjArray and apply them to gGeoManager // alignObjArray.Sort(); Int_t nvols = alignObjArray.GetEntriesFast(); Bool_t flag = kTRUE; for(Int_t j=0; j<nvols; j++) { AliAlignObj* alobj = (AliAlignObj*) alignObjArray.UncheckedAt(j); if(!alobj->ApplyToGeometry(ovlpcheck)) { flag = kFALSE; AliDebugClass(5,Form("Error applying alignment object for volume %s !",alobj->GetSymName())); }else{ AliDebugClass(5,Form("Alignment object for volume %s applied successfully",alobj->GetSymName())); } } if (AliDebugLevelClass() > 5) { fgGeometry->CheckOverlaps(0.001); TObjArray* ovexlist = fgGeometry->GetListOfOverlaps(); if(ovexlist->GetEntriesFast()){ AliErrorClass("The application of alignment objects to the geometry caused huge overlaps/extrusions!"); fgGeometry->PrintOverlaps(); } } // Update the TGeoPhysicalNodes fgGeometry->RefreshPhysicalNodes(); return flag; } //_____________________________________________________________________________ Bool_t AliGeomManager::ApplyAlignObjsToGeom(const char* fileName, const char* clArrayName) { // read collection of alignment objects (AliAlignObj derived) saved // in the TClonesArray ClArrayName in the file fileName and apply // them to the geometry // TFile* inFile = TFile::Open(fileName,"READ"); if (!inFile || !inFile->IsOpen()) { AliErrorClass(Form("Could not open file %s !",fileName)); return kFALSE; } TClonesArray* alignObjArray = ((TClonesArray*) inFile->Get(clArrayName)); inFile->Close(); if (!alignObjArray) { AliErrorClass(Form("Could not get array (%s) from file (%s) !",clArrayName,fileName)); return kFALSE; } return ApplyAlignObjsToGeom(*alignObjArray); } //_____________________________________________________________________________ Bool_t AliGeomManager::ApplyAlignObjsToGeom(const char* uri, const char* path, Int_t runnum, Int_t version, Int_t sversion) { // read collection of alignment objects (AliAlignObj derived) saved // in the TClonesArray ClArrayName in the AliCDBEntry identified by // param (to get the AliCDBStorage) and Id; apply the alignment objects // to the geometry // AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage(uri); AliCDBId id(path, runnum, runnum, version, sversion); AliCDBEntry* entry = storage->Get(id); TClonesArray* alignObjArray = dynamic_cast<TClonesArray*>(entry->GetObject()); return ApplyAlignObjsToGeom(*alignObjArray); } //_____________________________________________________________________________ Bool_t AliGeomManager::ApplyAlignObjsToGeom(const char* detName, Int_t runnum, Int_t version, Int_t sversion) { // read collection of alignment objects (AliAlignObj derived) saved // in the TClonesArray ClArrayName in the AliCDBEntry identified by // param (to get the AliCDBStorage) and Id; apply the alignment objects // to the geometry // AliCDBPath path(detName,"Align","Data"); AliCDBEntry* entry = AliCDBManager::Instance()->Get(path.GetPath(),runnum,version,sversion); if(!entry) return kFALSE; TClonesArray* alignObjArray = ((TClonesArray*) entry->GetObject()); return ApplyAlignObjsToGeom(*alignObjArray); } //_____________________________________________________________________________ void AliGeomManager::ResetPNEntriesLUT() { // cleans static arrays containing the information on currently loaded geometry // for (Int_t iLayer = 0; iLayer < (kLastLayer - kFirstLayer); iLayer++){ if (!fgPNEntry[iLayer]) continue; for (Int_t modnum=0; modnum<fgLayerSize[iLayer]; modnum++) fgPNEntry[iLayer][modnum] = 0; } // }
32.66759
154
0.684983
[ "geometry", "object", "vector" ]
d14111de10cdc0017bab5ccab4a00583bbff5f93
715
cc
C++
minimum-moves-to-equal-array-elements.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
minimum-moves-to-equal-array-elements.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
minimum-moves-to-equal-array-elements.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <vector> #include <algorithm> #include <numeric> class Solution { public: int minMoves(std::vector<int> &nums) { int min_elem = *std::min_element(nums.begin(), nums.end()); int res = 0; for (int i = 0; i < nums.size(); i++) res += nums[i] - min_elem; return res; } int minMovesSort(std::vector<int> &nums) { if (nums.size() == 1) return 0; std::sort(nums.begin(), nums.end()); int res = 0; int a, b; a = nums[0]; for (int i = 1; i < nums.size(); i++) { b = nums[i] + res; res += b - a; a = b; } return res; } };
18.815789
67
0.437762
[ "vector" ]
d14437fc197269bf9473dea99a012945beb30e66
4,285
hpp
C++
lib/Framework/TopologyImpl.hpp
lsbharadwaj/PothosCore
02b3491ed06f23924a4c749f35b7fade88b81a14
[ "BSL-1.0" ]
180
2017-09-11T00:44:36.000Z
2022-03-25T09:23:47.000Z
lib/Framework/TopologyImpl.hpp
lsbharadwaj/PothosCore
02b3491ed06f23924a4c749f35b7fade88b81a14
[ "BSL-1.0" ]
109
2015-01-19T07:33:38.000Z
2017-08-12T00:29:13.000Z
lib/Framework/TopologyImpl.hpp
lsbharadwaj/PothosCore
02b3491ed06f23924a4c749f35b7fade88b81a14
[ "BSL-1.0" ]
32
2017-09-20T10:47:29.000Z
2022-03-24T06:13:03.000Z
// Copyright (c) 2014-2017 Josh Blum // SPDX-License-Identifier: BSL-1.0 #pragma once #include <Pothos/Framework/Topology.hpp> #include "Framework/PortsAndFlows.hpp" #include <unordered_map> #include <map> #include <vector> #include <string> /*! * Utility to make a port that is unique to its destination environment. * This port can be used as a key for caching the network iogress blocks. */ static inline Port envTagPort(const Port &port, const Port &other) { Port envTagged = port; envTagged.name += "->" + other.obj.getEnvironment()->getUniquePid(); return envTagged; } /*********************************************************************** * implementation guts **********************************************************************/ struct Pothos::Topology::Impl { Impl(Topology *self): self(self){} Topology *self; ThreadPool threadPool; std::vector<Flow> flows; std::vector<Flow> activeFlatFlows; std::unordered_map<Port, std::pair<Pothos::Proxy, Pothos::Proxy>> srcToNetgressCache; std::vector<Flow> squashFlows(const std::vector<Flow> &); std::vector<Flow> createNetworkFlows(const std::vector<Flow> &); std::vector<Flow> rectifyDomainFlows(const std::vector<Flow> &); std::vector<std::string> inputPortNames; std::vector<std::string> outputPortNames; std::map<std::string, PortInfo> inputPortInfo; std::map<std::string, PortInfo> outputPortInfo; std::map<std::string, Callable> calls; //! remote topology per unique environment std::map<std::string, Pothos::Proxy> remoteTopologies; //! special utility function to make a port with knowledge of this topology Port makePort(const Pothos::Object &obj, const std::string &name) const; Port makePort(const Pothos::Proxy &obj, const std::string &name) const; }; /*********************************************************************** * get a unique object set given flows + excludes **********************************************************************/ inline std::vector<Pothos::Proxy> getObjSetFromFlowList(const std::vector<Flow> &flows, const std::vector<Flow> &excludes = std::vector<Flow>()) { std::map<std::string, Pothos::Proxy> uniques; for (const auto &flow : flows) { if (flow.src.obj) uniques[flow.src.uid] = flow.src.obj; if (flow.dst.obj) uniques[flow.dst.uid] = flow.dst.obj; } for (const auto &flow : excludes) { uniques.erase(flow.src.uid); uniques.erase(flow.dst.uid); } std::vector<Pothos::Proxy> set; for (const auto &pair : uniques) set.push_back(pair.second); return set; } /*********************************************************************** * Make a proxy if not already **********************************************************************/ inline Pothos::Proxy getProxy(const Pothos::Object &o) { if (o.type() == typeid(Pothos::Proxy)) return o.extract<Pothos::Proxy>(); return Pothos::ProxyEnvironment::make("managed")->convertObjectToProxy(o); } /*********************************************************************** * Want the internal block - for language bindings **********************************************************************/ inline Pothos::Proxy getInternalBlock(const Pothos::Proxy &block) { if (not block) return block; Pothos::Proxy internal; try { internal = block.call("getInternalBlock"); } catch (const Pothos::Exception &) { internal = block; } assert(internal.getEnvironment()->getName() == "managed"); return internal; } /*********************************************************************** * Want something to make connectable calls on **********************************************************************/ inline Pothos::Proxy getConnectable(const Pothos::Object &o) { auto proxy = getProxy(o); return getInternalBlock(proxy); } /*********************************************************************** * can this object be connected with -- can we get a uid? **********************************************************************/ inline bool checkObj(const Pothos::Object &o) { try { getProxy(o).call("uid"); } catch(...) { return false; } return true; }
34.28
144
0.537223
[ "object", "vector" ]
d14ab91cce6338579f7026ccd815f6a7296dfede
8,965
hpp
C++
src/xalanc/PlatformSupport/ReusableArenaAllocator.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
null
null
null
src/xalanc/PlatformSupport/ReusableArenaAllocator.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
1
2021-08-18T12:32:31.000Z
2021-08-18T12:32:31.000Z
src/xalanc/PlatformSupport/ReusableArenaAllocator.hpp
AaronNGray/xalan
6741bbdcb64a9d33df8bd7e21b558d66bb4292ec
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680) #define REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680 #include <algorithm> #include "ReusableArenaBlock.hpp" #include "ArenaAllocator.hpp" XALAN_CPP_NAMESPACE_BEGIN template<class ObjectType> class ReusableArenaAllocator : public ArenaAllocator<ObjectType, ReusableArenaBlock<ObjectType> > { public: typedef ReusableArenaBlock<ObjectType> ReusableArenaBlockType; typedef typename ReusableArenaBlockType::size_type size_type; typedef ArenaAllocator<ObjectType, ReusableArenaBlockType> BaseClassType; typedef ReusableArenaAllocator<ObjectType> ThisType; typedef XalanList<ReusableArenaBlockType*> ArenaBlockListType; typedef typename ArenaBlockListType::iterator iterator; typedef typename ArenaBlockListType::const_iterator const_iterator; typedef typename ArenaBlockListType::reverse_iterator reverse_iterator; typedef typename ArenaBlockListType::const_reverse_iterator const_reverse_iterator; /* * Construct an instance that will allocate blocks of the specified size. * * @param theBlockSize The block size. */ ReusableArenaAllocator( MemoryManager& theManager, size_type theBlockSize, bool destroyBlocks = false) : BaseClassType(theManager, theBlockSize), m_destroyBlocks(destroyBlocks) { } virtual ~ReusableArenaAllocator() { } /* * Destroy the object, and free the block for re-use. * * @param theObject the address of the object. * @return true if the object was deleted, false if not. */ bool destroyObject(ObjectType* theObject) { bool bResult = false; assert ( theObject != 0 ); if ( this->m_blocks.empty() ) return bResult; iterator iTerator = this->m_blocks.begin(); iterator iEnd = this->m_blocks.end(); // first , run over unfull blocks ( that consentrated from the head ) while( iTerator != iEnd && (*iTerator)->blockAvailable() ) { if ((*iTerator)->ownsBlock(theObject) == true) { (*iTerator)->destroyObject(theObject); // move the block we have just deleted to the head of the list if (iTerator != this->m_blocks.begin()) { // move the block to the beginning ReusableArenaBlockType* block = *iTerator; assert(block != 0); this->m_blocks.erase(iTerator); this->m_blocks.push_front(block); } if (m_destroyBlocks) { destroyBlock(); } bResult = true; break; } ++iTerator; } reverse_iterator rIterator = this->m_blocks.rbegin(); reverse_iterator rEnd = this->m_blocks.rend(); // if the block hasn't been found from the head , start with full blocks ( from the taile) while ( !bResult && rIterator != rEnd ) { if ((*rIterator)->ownsBlock(theObject)) { (*rIterator)->destroyObject(theObject); if (rIterator != this->m_blocks.rbegin()) { // move the block to the beginning ReusableArenaBlockType* block = *iTerator; assert(block != 0); this->m_blocks.erase(iTerator); this->m_blocks.push_front(block); } if (m_destroyBlocks) { destroyBlock(); } bResult = true; break; } if ( *rIterator == *iTerator) { break; } else { ++rIterator; } } return bResult; } /* * Allocate a block of the appropriate size for an * object. Call commitAllocation() when after * the object is successfully constructed. You _must_ * commit an allocation before performing any other * operation on the allocator. * * * @return A pointer to a block of memory */ virtual ObjectType* allocateBlock() { if( this->m_blocks.empty() || !this->m_blocks.front()->blockAvailable() ) { this->m_blocks.push_front( ReusableArenaBlockType::create( this->getMemoryManager(), this->m_blockSize)); assert( this->m_blocks.front() != 0 ); } assert( this->m_blocks.front() != 0 ); assert( this->m_blocks.front()->blockAvailable() ); return this->m_blocks.front()->allocateBlock(); } /* * Commits the allocation of the previous * allocateBlock() call. * * @param theObject A pointer to a block of memory */ virtual void commitAllocation(ObjectType* theObject) { // Note that this-> is required by template lookup rules. assert( this->m_blocks.empty() == false ); assert( this->m_blocks.front() != 0 ); assert( this->m_blocks.front()->ownsBlock(theObject) == true ); this->m_blocks.front()->commitAllocation(theObject); if( !this->m_blocks.front()->blockAvailable() ) { ReusableArenaBlockType* fullBlock = this->m_blocks.front(); assert ( fullBlock != 0 ); this->m_blocks.pop_front(); this->m_blocks.push_back( fullBlock ); } } virtual bool ownsObject(const ObjectType* theObject) const { if ( this->m_blocks.empty() ) return false; const_iterator iTerator = this->m_blocks.begin(); const_iterator iEnd = this->m_blocks.end(); while( iTerator != iEnd && (*iTerator)->blockAvailable() ) { if ((*iTerator)->ownsBlock(theObject) ) { return true; } ++iTerator; } const_reverse_iterator rIterator = this->m_blocks.rbegin(); const_reverse_iterator rEnd = this->m_blocks.rend(); while( rIterator != rEnd ) { if ((*rIterator)->ownsBlock(theObject) ) { return true; } if ( *iTerator == *rIterator ) { break; } else { ++rIterator; } } return false; } protected: /* * The method destroys an empty block from the head of the list. * For eliminating multiple create/destroy operation, the block * is destroyed only if the second one is not full. */ void destroyBlock() { assert(m_destroyBlocks == true); if ( this->m_blocks.empty() == false) { const_iterator iTerator = this->m_blocks.begin(); if ( (*iTerator)->isEmpty() ) { ++iTerator; if (iTerator == this->m_blocks.end() || (*iTerator)->blockAvailable() ) { this->m_blocks.pop_front(); } } } } // data members const bool m_destroyBlocks; private: // Not defined... ReusableArenaAllocator(const ReusableArenaAllocator<ObjectType>&); ReusableArenaAllocator<ObjectType>& operator=(const ReusableArenaAllocator<ObjectType>&); bool operator==(const ReusableArenaAllocator<ObjectType>&) const; }; XALAN_CPP_NAMESPACE_END #endif // !defined(REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680)
26.761194
98
0.551701
[ "object" ]
d14c8e125784d8ca4cd24b4b7ca9a5c6f7b61894
8,556
cpp
C++
test/util/tpcc/order_status.cpp
hjhhsy120/terrier
c53e1ac9de629ec340c42e9797a7460fdf2a56dc
[ "MIT" ]
1
2019-08-18T21:33:57.000Z
2019-08-18T21:33:57.000Z
test/util/tpcc/order_status.cpp
LiuXiaoxuanPKU/terrier
35916e9435201016903d8a01e3f587b8edb36f0b
[ "MIT" ]
null
null
null
test/util/tpcc/order_status.cpp
LiuXiaoxuanPKU/terrier
35916e9435201016903d8a01e3f587b8edb36f0b
[ "MIT" ]
null
null
null
#include "util/tpcc/order_status.h" #include <map> #include <string> #include <vector> namespace terrier::tpcc { // 2.6.2 bool OrderStatus::Execute(transaction::TransactionManager *const txn_manager, Database *const db, Worker *const worker, const TransactionArgs &args) const { TERRIER_ASSERT(args.type_ == TransactionType::OrderStatus, "Wrong transaction type."); auto *const txn = txn_manager->BeginTransaction(); storage::TupleSlot customer_slot; std::vector<storage::TupleSlot> index_scan_results; if (!args.use_c_last_) { // Look up C_ID, D_ID, W_ID in index const auto customer_key_pr_initializer = db->customer_primary_index_->GetProjectedRowInitializer(); auto *const customer_key = customer_key_pr_initializer.InitializeRow(worker->customer_key_buffer_); *reinterpret_cast<int32_t *>(customer_key->AccessForceNotNull(c_id_key_pr_offset_)) = args.c_id_; *reinterpret_cast<int8_t *>(customer_key->AccessForceNotNull(c_d_id_key_pr_offset_)) = args.d_id_; *reinterpret_cast<int8_t *>(customer_key->AccessForceNotNull(c_w_id_key_pr_offset_)) = args.w_id_; index_scan_results.clear(); db->customer_primary_index_->ScanKey(*txn, *customer_key, &index_scan_results); TERRIER_ASSERT(index_scan_results.size() == 1, "Customer index lookup failed."); customer_slot = index_scan_results[0]; } else { // Look up C_LAST, D_ID, W_ID in index const auto customer_name_key_pr_initializer = db->customer_secondary_index_->GetProjectedRowInitializer(); auto *const customer_name_key = customer_name_key_pr_initializer.InitializeRow(worker->customer_name_key_buffer_); *reinterpret_cast<storage::VarlenEntry *>(customer_name_key->AccessForceNotNull(c_last_name_key_pr_offset_)) = args.c_last_; *reinterpret_cast<int8_t *>(customer_name_key->AccessForceNotNull(c_d_id_name_key_pr_offset_)) = args.d_id_; *reinterpret_cast<int8_t *>(customer_name_key->AccessForceNotNull(c_w_id_name_key_pr_offset_)) = args.w_id_; index_scan_results.clear(); db->customer_secondary_index_->ScanKey(*txn, *customer_name_key, &index_scan_results); TERRIER_ASSERT(!index_scan_results.empty(), "Customer Name index lookup failed."); if (index_scan_results.size() > 1) { std::map<std::string, storage::TupleSlot> sorted_index_scan_results; for (const auto &tuple_slot : index_scan_results) { auto *const c_first_select_tuple = c_first_pr_initializer_.InitializeRow(worker->customer_tuple_buffer_); bool UNUSED_ATTRIBUTE select_result = db->customer_table_->Select(txn, tuple_slot, c_first_select_tuple); TERRIER_ASSERT(select_result, "Customer table doesn't change (no new entries). All lookups should succeed."); const auto c_first = *reinterpret_cast<storage::VarlenEntry *>(c_first_select_tuple->AccessWithNullCheck(0)); sorted_index_scan_results.emplace( std::string(reinterpret_cast<const char *const>(c_first.Content()), c_first.Size()), tuple_slot); } auto median = sorted_index_scan_results.cbegin(); std::advance(median, (sorted_index_scan_results.size() + 1) / 2); customer_slot = median->second; } else { customer_slot = index_scan_results[0]; } } // Select customer in table auto *const customer_select_tuple = customer_select_pr_initializer_.InitializeRow(worker->customer_tuple_buffer_); bool UNUSED_ATTRIBUTE select_result = db->customer_table_->Select(txn, customer_slot, customer_select_tuple); TERRIER_ASSERT(select_result, "Customer table doesn't change (no new entries). All lookups should succeed."); const auto *const c_id_ptr = reinterpret_cast<int32_t *>(customer_select_tuple->AccessWithNullCheck(c_id_select_pr_offset_)); TERRIER_ASSERT(c_id_ptr != nullptr, "This is a non-NULLable field."); const auto UNUSED_ATTRIBUTE c_id = !args.use_c_last_ ? args.c_id_ : *c_id_ptr; TERRIER_ASSERT(c_id >= 1 && c_id <= 3000, "Invalid c_id read from the Customer table."); // look up in secondary Order index const auto order_secondary_key_pr_initializer = db->order_secondary_index_->GetProjectedRowInitializer(); auto *const order_secondary_low_key = order_secondary_key_pr_initializer.InitializeRow(worker->order_secondary_key_buffer_); auto *const order_secondary_high_key = order_secondary_key_pr_initializer.InitializeRow(worker->order_tuple_buffer_); // it's large enough *reinterpret_cast<int32_t *>(order_secondary_low_key->AccessForceNotNull(o_id_secondary_key_pr_offset_)) = 1; *reinterpret_cast<int8_t *>(order_secondary_low_key->AccessForceNotNull(o_d_id_secondary_key_pr_offset_)) = args.d_id_; *reinterpret_cast<int8_t *>(order_secondary_low_key->AccessForceNotNull(o_w_id_secondary_key_pr_offset_)) = args.w_id_; *reinterpret_cast<int32_t *>(order_secondary_low_key->AccessForceNotNull(o_c_id_secondary_key_pr_offset_)) = c_id; *reinterpret_cast<int32_t *>(order_secondary_high_key->AccessForceNotNull(o_id_secondary_key_pr_offset_)) = 10000000; *reinterpret_cast<int8_t *>(order_secondary_high_key->AccessForceNotNull(o_d_id_secondary_key_pr_offset_)) = args.d_id_; *reinterpret_cast<int8_t *>(order_secondary_high_key->AccessForceNotNull(o_w_id_secondary_key_pr_offset_)) = args.w_id_; *reinterpret_cast<int32_t *>(order_secondary_high_key->AccessForceNotNull(o_c_id_secondary_key_pr_offset_)) = c_id; index_scan_results.clear(); db->order_secondary_index_->ScanLimitDescending(*txn, *order_secondary_low_key, *order_secondary_high_key, &index_scan_results, 1); TERRIER_ASSERT(index_scan_results.size() == 1, "Order index lookup failed. There should always be at least one order for each customer."); // Select O_ID, O_ENTRY_D, O_CARRIER_ID from table for largest key (back of vector) auto *const order_select_tuple = order_select_pr_initializer_.InitializeRow(worker->order_tuple_buffer_); select_result = db->order_table_->Select(txn, index_scan_results[0], order_select_tuple); TERRIER_ASSERT(select_result, "Order select failed. This assertion assumes 1:1 mapping between warehouse and workers."); const auto o_id = *reinterpret_cast<int32_t *>(order_select_tuple->AccessWithNullCheck(o_id_select_pr_offset_)); // look up in Order Line index const auto order_line_key_pr_initializer = db->order_line_primary_index_->GetProjectedRowInitializer(); auto *const order_line_low_key = order_line_key_pr_initializer.InitializeRow(worker->order_line_key_buffer_); auto *const order_line_high_key = order_line_key_pr_initializer.InitializeRow(worker->order_line_tuple_buffer_); // it's large enough *reinterpret_cast<int8_t *>(order_line_low_key->AccessForceNotNull(ol_number_key_pr_offset_)) = 1; *reinterpret_cast<int8_t *>(order_line_low_key->AccessForceNotNull(ol_d_id_key_pr_offset_)) = args.d_id_; *reinterpret_cast<int8_t *>(order_line_low_key->AccessForceNotNull(ol_w_id_key_pr_offset_)) = args.w_id_; *reinterpret_cast<int32_t *>(order_line_low_key->AccessForceNotNull(ol_o_id_key_pr_offset_)) = o_id; *reinterpret_cast<int8_t *>(order_line_high_key->AccessForceNotNull(ol_number_key_pr_offset_)) = 15; *reinterpret_cast<int8_t *>(order_line_high_key->AccessForceNotNull(ol_d_id_key_pr_offset_)) = args.d_id_; *reinterpret_cast<int8_t *>(order_line_high_key->AccessForceNotNull(ol_w_id_key_pr_offset_)) = args.w_id_; *reinterpret_cast<int32_t *>(order_line_high_key->AccessForceNotNull(ol_o_id_key_pr_offset_)) = o_id; index_scan_results.clear(); db->order_line_primary_index_->ScanAscending(*txn, *order_line_low_key, *order_line_high_key, &index_scan_results); TERRIER_ASSERT(!index_scan_results.empty() && index_scan_results.size() <= 15, "There should be at least 1 Order Line item, but no more than 15."); // Select OL_I_ID, OL_SUPPLY_W_ID, OL_QUANTITY, OL_AMOUNT, OL_DELIVERY_D for every result of the index scan auto *const order_line_select_tuple = order_line_select_pr_initializer_.InitializeRow(worker->order_line_tuple_buffer_); for (const auto &tuple_slot : index_scan_results) { select_result = db->order_line_table_->Select(txn, tuple_slot, order_line_select_tuple); TERRIER_ASSERT(select_result, "We already confirmed that this is a committed order above, so none of these should fail."); } txn_manager->Commit(txn, TestCallbacks::EmptyCallback, nullptr); return true; } } // namespace terrier::tpcc
58.60274
119
0.772207
[ "vector" ]
d14ccc6c7cf7c1b6060041f75dd856cf7ea725e1
11,597
cpp
C++
src/winc-tm/ui/run_tournament_menu.cpp
ropelinen/winc-tm
9e6b476f6a1f7dcfe136a2df51b88888614e6ee5
[ "MIT" ]
null
null
null
src/winc-tm/ui/run_tournament_menu.cpp
ropelinen/winc-tm
9e6b476f6a1f7dcfe136a2df51b88888614e6ee5
[ "MIT" ]
null
null
null
src/winc-tm/ui/run_tournament_menu.cpp
ropelinen/winc-tm
9e6b476f6a1f7dcfe136a2df51b88888614e6ee5
[ "MIT" ]
null
null
null
#include "precompiled.h" #include "run_tournament_menu.h" #include "3rd_party/imgui/imgui.h" #include "core/file_io.h" #include "data/state.h" #include "data/tournament_data.h" namespace winc { namespace { enum tournament_state { setup, pools, elims, finals, }; tournament_state get_current_state(tournament_data &data) { if (!data.final_pool.empty()) return finals; if (!data.elimination_pools.empty()) return elims; for (size_t i = 0; i < data.pools.size(); ++i) { if (data.pools[i].bouts.empty()) continue; return pools; break; } return setup; } } void sort_pool_result(std::vector<fencer_results> &results) { if (results.empty()) return; std::list<fencer_results> temp_results; temp_results.push_back(results[0]); for (size_t result_index = 1; result_index < results.size(); ++result_index) { bool inserted = false; fencer_results &result = results[result_index]; for (std::list<fencer_results>::iterator it = temp_results.begin(); it != temp_results.end(); ++it) { /* Matchpoint index */ if (get_fencer_matchpoint_index(result) > get_fencer_matchpoint_index(*it)) { temp_results.insert(it, result); inserted = true; break; } if (get_fencer_matchpoint_index(result) != get_fencer_matchpoint_index(*it)) continue; /* Victory index */ if (get_fencer_victory_index(result) > get_fencer_victory_index(*it)) { temp_results.insert(it, result); inserted = true; break; } if (get_fencer_victory_index(result) != get_fencer_victory_index(*it)) continue; /* Q3 ration */ if (get_fencer_q3_ratio(result) > get_fencer_q3_ratio(*it)) { temp_results.insert(it, result); inserted = true; break; } if (get_fencer_q3_ratio(result) != get_fencer_q3_ratio(*it)) continue; /* Clean ratio */ if (get_fencer_clean_ratio(result) > get_fencer_clean_ratio(*it)) { temp_results.insert(it, result); inserted = true; break; } } if (!inserted) temp_results.push_back(result); } assert(temp_results.size() == results.size()); results.clear(); results.reserve(temp_results.size()); for (std::list<fencer_results>::iterator it = temp_results.begin(); it != temp_results.end(); ++it) results.push_back(*it); } void handle_create_bouts_for_pools(tournament_data &data) { uint16_t bout_id = 0; const uint16_t invalid_fencer_id = 0xFFFF; for (size_t pool_index = 0; pool_index < data.pools.size(); ++pool_index) { pool &pl = data.pools[pool_index]; pl.bouts.clear(); bool uneven_fencer_count = pl.fencers.size() % 2 != 0; size_t fencer_count = pl.fencers.size(); if (uneven_fencer_count) ++fencer_count; uint16_t *fencers = new uint16_t[fencer_count]; if (uneven_fencer_count) fencers[fencer_count - 1] = invalid_fencer_id; for (size_t fencer_index = 0; fencer_index < pl.fencers.size(); ++fencer_index) fencers[fencer_index] = pl.fencers[fencer_index]; for (size_t round = 0; round < fencer_count - 1; ++round) { for (size_t bout_index = 0; bout_index < fencer_count / 2; ++bout_index) { uint16_t fencer_a = fencers[bout_index]; uint16_t fencer_b = fencers[fencer_count - 1 - bout_index]; if (fencer_a == invalid_fencer_id || fencer_b == invalid_fencer_id) continue; bout bt; bt.id = bout_id; if (fencer_a < fencer_b) { bt.blue_fencer = fencer_a; bt.red_fencer = fencer_b; } else { bt.blue_fencer = fencer_b; bt.red_fencer = fencer_a; } pl.bouts.push_back(bt); ++bout_id; } /* Advance the fencers */ uint16_t last_fencer_id = fencers[fencer_count - 1]; for (size_t move_index = fencer_count - 1; move_index > 1; --move_index) fencers[move_index] = fencers[move_index - 1]; fencers[1] = last_fencer_id; } delete[] fencers; } write_tournament_data(data); } void handle_main_window_setup_state(tournament_data &data) { std::vector<fencer> &fencers = data.fencers; for (size_t pool_index = 0; pool_index < data.pools.size(); ++pool_index) { /* This is ugly but I'd say we are safe with 9999 pools */ char pool_num_str[4]; sprintf(pool_num_str, "%u", (uint32_t)pool_index + 1); char pool_name[10] = "Pool "; strcat(pool_name, pool_num_str); if (ImGui::CollapsingHeader(pool_name)) { std::vector<uint16_t> &pool = data.pools[pool_index].fencers; for (size_t pool_member_index = 0; pool_member_index < pool.size(); ++pool_member_index) { for (size_t fencer_index = 0; fencer_index < fencers.size(); ++fencer_index) { if (pool[pool_member_index] != fencers[fencer_index].id) continue; if (ImGui::TreeNode((void *)(intptr_t)pool_member_index, "%s, %s (%u)", fencers[fencer_index].name, fencers[fencer_index].club, fencers[fencer_index].hema_rating)) { ImGui::Text("Club: %s", fencers[fencer_index].club); ImGui::Text("Rating: %u", fencers[fencer_index].hema_rating); ImGui::TreePop(); } } } } } if (ImGui::Button("Create bouts")) handle_create_bouts_for_pools(data); } void handle_main_window_pools_states(state &state_data, tournament_state tournament_state) { tournament_data &data = *state_data.tournament_data; std::vector<fencer> &fencers = data.fencers; std::vector<pool> *pools = nullptr; switch (tournament_state) { case setup: break; case tournament_state::pools: pools = &data.pools; break; case elims: pools = &data.elimination_pools; break; case finals: pools = &data.final_pool; break; } for (size_t pool_index = 0; pool_index < pools->size(); ++pool_index) { /* This is ugly but I'd say we are safe with 9999 pools */ char pool_num_str[4]; sprintf(pool_num_str, "%u", (uint32_t)pool_index + 1); char pool_name[10] = "Pool "; strcat(pool_name, pool_num_str); if (ImGui::CollapsingHeader(pool_name)) { pool &pl = (*pools)[pool_index]; bool all_matches_fought = true; for (size_t bout_index = 0; bout_index < pl.bouts.size(); ++bout_index) { bout &bt = pl.bouts[bout_index]; fencer *blue = nullptr; fencer *red = nullptr; if (bt.exchanges.empty()) all_matches_fought = false; for (size_t fencer_index = 0; fencer_index < fencers.size(); ++fencer_index) { uint16_t fencer_id = fencers[fencer_index].id; if (fencer_id == bt.blue_fencer) blue = &fencers[fencer_index]; else if (fencer_id == bt.red_fencer) red = &fencers[fencer_index]; if (blue && red) break; } if (!blue || !red) continue; if (ImGui::TreeNode((void *)(intptr_t)bt.id, "%s (%s) - %s (%s)", blue->name, blue->club, red->name, red->club)) { if (bt.exchanges.empty()) { if (ImGui::Button("Input Bout")) { state_data.bout_to_modify = bt.id; state_data.menu_state = modify_bout; } } else { uint16_t blue_q1, blue_q2, blue_q3; uint16_t red_q1, red_q2, red_q3; get_blue_fencer_score(bt, blue_q1, blue_q2, blue_q3); get_red_fencer_score(bt, red_q1, red_q2, red_q3); if (get_suicidal_double_count(bt) >= 3) ImGui::Text("Double loss, three suicidal doubles"); uint16_t warning_count = get_blue_warning_count(bt); if (warning_count >= 4) ImGui::Text("Blue: Warning loss"); else if (warning_count >= 2) ImGui::Text("Blue: Penaly to highest quality"); warning_count = get_red_warning_count(bt); if (warning_count >= 4) ImGui::Text("Red: Warning loss"); else if (warning_count >= 2) ImGui::Text("Red: Penaly to highest quality"); ImGui::Text("This score takes doubles in count, but doesn't take penalties to count"); ImGui::Text("Blue: Q1(%u) Q2(%u) Q3(%u) - Red: Q1(%u) Q2(%u) Q3(%u)", blue_q1, blue_q2, blue_q3, red_q1, red_q2, red_q3); if (ImGui::Button("Modify Bout")) { state_data.bout_to_modify = bt.id; state_data.menu_state = modify_bout; } } ImGui::TreePop(); } } if (all_matches_fought) { if (ImGui::Button("Show pool results")) { state_data.pool_results.clear(); calculate_pool_results(pl, state_data.pool_results); sort_pool_result(state_data.pool_results); state_data.menu_state = pool_results; } ImGui::SameLine(); } if (ImGui::Button("Write pool to file")) write_pool_to_file(state_data, (*pools)[pool_index], pool_index + 1); } } /* Check for pools done condition */ bool all_pools_done = true; for (size_t pool_index = 0; pool_index < pools->size(); ++pool_index) { pool &pl = (*pools)[pool_index]; for (size_t bout_index = 0; bout_index < pl.bouts.size(); ++bout_index) { if (pl.bouts[bout_index].exchanges.empty()) { all_pools_done = false; break; } } if (!all_pools_done) break; } if (all_pools_done) { if (ImGui::Button("Finish pools")) { state_data.pool_results.clear(); for (size_t pool_index = 0; pool_index < pools->size(); ++pool_index) { pool &pl = (*pools)[pool_index]; calculate_pool_results(pl, state_data.pool_results); } sort_pool_result(state_data.pool_results); switch (tournament_state) { case setup: break; case tournament_state::pools: state_data.menu_state = pools_done; break; case elims: state_data.menu_state = pools_done; break; case finals: state_data.menu_state = pools_done; break; } } } } void handle_run_tournament_menu(state &state_data) { if (!state_data.tournament_data) return; tournament_data &tournament = *state_data.tournament_data; tournament_state current_state = get_current_state(tournament); ImVec2 main_window_size(state_data.resolution_x * 0.9f, state_data.resolution_y * 0.75f); ImGui::SetNextWindowSize(main_window_size, ImGuiCond_Always); ImGui::SetNextWindowPos(ImVec2(state_data.resolution_x / 2.0f, state_data.resolution_y * 0.025f), ImGuiCond_Always, ImVec2(0.5f, 0.0f)); static const ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; /* We could actually have 'Tournament Name - State' as the window name */ ImGui::Begin(tournament.tournament_name, nullptr, window_flags); switch (current_state) { case setup: handle_main_window_setup_state(tournament); break; case pools: handle_main_window_pools_states(state_data, current_state); break; case elims: handle_main_window_pools_states(state_data, current_state); break; case finals: handle_main_window_pools_states(state_data, current_state); break; } ImGui::End(); char pool_window_title[] = "No bouts available"; ImVec2 matches_window_size(state_data.resolution_x * 0.9f, state_data.resolution_y * 0.15f); ImGui::SetNextWindowSize(matches_window_size, ImGuiCond_Always); ImGui::SetNextWindowPos(ImVec2(state_data.resolution_x / 2.0f, state_data.resolution_y * 0.925f), ImGuiCond_Always, ImVec2(0.5f, 1.0f)); ImGui::Begin(pool_window_title, nullptr, window_flags); switch (current_state) { case setup: /* Nothing to show at this point */ break; case pools: break; case elims: break; case finals: break; } ImGui::End(); } }
26.537757
169
0.654825
[ "vector" ]
d14e8d0b88522c7ebaa2b42b4e05d3ab501c36f0
48,058
cc
C++
src/box/xlog.cc
Khatskevich/tarantool
1e154ede60ccd2b301cfba2b8ab7e961a3dd0783
[ "BSD-2-Clause" ]
null
null
null
src/box/xlog.cc
Khatskevich/tarantool
1e154ede60ccd2b301cfba2b8ab7e961a3dd0783
[ "BSD-2-Clause" ]
null
null
null
src/box/xlog.cc
Khatskevich/tarantool
1e154ede60ccd2b301cfba2b8ab7e961a3dd0783
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file. * * 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 <COPYRIGHT HOLDER> ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * <COPYRIGHT 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 "xlog.h" #include <dirent.h> #include <fcntl.h> #include <ctype.h> #include "fiber.h" #include "crc32.h" #include "fio.h" #include "third_party/tarantool_eio.h" #include <msgpuck.h> #include "scoped_guard.h" #include "coeio_file.h" #include "error.h" #include "xrow.h" #include "iproto_constants.h" #include "errinj.h" /* * marker is MsgPack fixext2 * +--------+--------+--------+--------+ * | 0xd5 | type | data | * +--------+--------+--------+--------+ */ typedef uint32_t log_magic_t; static const log_magic_t row_marker = mp_bswap_u32(0xd5ba0bab); /* host byte order */ static const log_magic_t zrow_marker = mp_bswap_u32(0xd5ba0bba); /* host byte order */ static const log_magic_t eof_marker = mp_bswap_u32(0xd510aded); /* host byte order */ static const char inprogress_suffix[] = ".inprogress"; enum { /** * When the number of rows in xlog_tx write buffer * gets this big, don't delay flush any longer, and * issue a write. * This also acts as a default for slab size in the * slab cache so must be a power of 2. */ XLOG_TX_AUTOCOMMIT_THRESHOLD = 128 * 1024, /** * Compress output buffer before dumping it to * disk if it is at least this big. On smaller * sizes compression takes up CPU but doesn't * yield seizable gains. * Maybe this should be a configuration option. */ XLOG_TX_COMPRESS_THRESHOLD = 2 * 1024, }; const struct type type_XlogError = make_type("XlogError", &type_Exception); XlogError::XlogError(const char *file, unsigned line, const char *format, ...) :Exception(&type_XlogError, file, line) { va_list ap; va_start(ap, format); error_vformat_msg(this, format, ap); va_end(ap); } XlogError::XlogError(const struct type *type, const char *file, unsigned line, const char *format, ...) :Exception(type, file, line) { va_list ap; va_start(ap, format); error_vformat_msg(this, format, ap); va_end(ap); } const struct type type_XlogGapError = make_type("XlogGapError", &type_XlogError); XlogGapError::XlogGapError(const char *file, unsigned line, const struct vclock *from, const struct vclock *to) :XlogError(&type_XlogGapError, file, line, "") { char *s_from = vclock_to_string(from); char *s_to = vclock_to_string(to); snprintf(errmsg, sizeof(errmsg), "Missing .xlog file between LSN %lld %s and %lld %s", (long long) vclock_sum(from), s_from ? s_from : "", (long long) vclock_sum(to), s_to ? s_to : ""); free(s_from); free(s_to); } /* {{{ struct xlog_meta */ enum { /* * The maximum length of xlog meta * * @sa xlog_meta_parse() */ XLOG_META_LEN_MAX = 1024 + VCLOCK_STR_LEN_MAX }; #define INSTANCE_UUID_KEY "Instance" #define INSTANCE_UUID_KEY_V12 "Server" #define VCLOCK_KEY "VClock" #define VERSION_KEY "Version" static const char v13[] = "0.13"; static const char v12[] = "0.12"; /** * Format xlog metadata into @a buf of size @a size * * @param buf buffer to use. * @param size the size of buffer. This function write at most @a size bytes. * @retval < size the number of characters printed (excluding the null byte) * @retval >=size the number of characters (excluding the null byte), * which would have been written to the final string if * enough space had been available. * @retval -1 error, check diag * @sa snprintf() */ static int xlog_meta_format(const struct xlog_meta *meta, char *buf, int size) { char *vstr = vclock_to_string(&meta->vclock); if (vstr == NULL) return -1; char *instance_uuid = tt_uuid_str(&meta->instance_uuid); int total = snprintf(buf, size, "%s\n" "%s\n" VERSION_KEY ": %s\n" INSTANCE_UUID_KEY ": %s\n" VCLOCK_KEY ": %s\n\n", meta->filetype, v13, PACKAGE_VERSION, instance_uuid, vstr); assert(total > 0); free(vstr); return total; } /** * Parse xlog meta from buffer, update buffer read * position in case of success * * @retval 0 for success * @retval -1 for parse error * @retval 1 if buffer hasn't enough data */ static ssize_t xlog_meta_parse(struct xlog_meta *meta, const char **data, const char *data_end) { memset(meta, 0, sizeof(*meta)); const char *end = (const char *)memmem(*data, data_end - *data, "\n\n", 2); if (end == NULL) return 1; ++end; /* include the trailing \n to simplify the checks */ const char *pos = (const char *)*data; /* * Parse filetype, i.e "SNAP" or "XLOG" */ const char *eol = (const char *)memchr(pos, '\n', end - pos); if (eol == end || (eol - pos) >= (ptrdiff_t) sizeof(meta->filetype)) { tnt_error(XlogError, "failed to parse xlog type string"); return -1; } memcpy(meta->filetype, pos, eol - pos); meta->filetype[eol - pos] = '\0'; pos = eol + 1; assert(pos <= end); /* * Parse version string, i.e. "0.12" or "0.13" */ char version[10]; eol = (const char *)memchr(pos, '\n', end - pos); if (eol == end || (eol - pos) >= (ptrdiff_t) sizeof(version)) { tnt_error(XlogError, "failed to parse xlog version string"); return -1; } memcpy(version, pos, eol - pos); version[eol - pos] = '\0'; pos = eol + 1; assert(pos <= end); if (strncmp(version, v12, sizeof(v12)) != 0 && strncmp(version, v13, sizeof(v13)) != 0) { tnt_error(XlogError, "unsupported file format version %s", version); return -1; } /* * Parse "key: value" pairs */ while (pos < end) { eol = (const char *)memchr(pos, '\n', end - pos); assert(eol <= end); const char *key = pos; const char *key_end = (const char *) memchr(key, ':', eol - key); if (key_end == NULL) { tnt_error(XlogError, "can't extract meta value"); return -1; } const char *val = key_end + 1; /* Skip space after colon */ while (*val == ' ' || *val == '\t') ++val; const char *val_end = eol; assert(val <= val_end); pos = eol + 1; if (memcmp(key, INSTANCE_UUID_KEY, key_end - key) == 0 || memcmp(key, INSTANCE_UUID_KEY_V12, key_end - key) == 0) { /* * Instance: <uuid> */ if (val_end - val != UUID_STR_LEN) { tnt_error(XlogError, "can't parse instance UUID"); return -1; } char uuid[UUID_STR_LEN + 1]; memcpy(uuid, val, UUID_STR_LEN); uuid[UUID_STR_LEN] = '\0'; if (tt_uuid_from_string(uuid, &meta->instance_uuid) != 0) { tnt_error(XlogError, "can't parse instance UUID"); return -1; } } else if (memcmp(key, VCLOCK_KEY, key_end - key) == 0){ /* * VClock: <vclock> */ if (val_end - val > VCLOCK_STR_LEN_MAX) { tnt_error(XlogError, "can't parse vclock"); return -1; } char vclock[VCLOCK_STR_LEN_MAX + 1]; memcpy(vclock, val, val_end - val); vclock[val_end - val] = '\0'; size_t off = vclock_from_string(&meta->vclock, vclock); if (off != 0) { tnt_error(XlogError, "invalid vclock at " "offset %zd", off); return -1; } } else if (memcmp(key, VERSION_KEY, key_end - key) == 0) { /* Ignore Version: for now */ } else { /* * Unknown key */ say_warn("Unknown meta item: `%.*s'", key_end - key, key); } } *data = end + 1; /* skip the last trailing \n of \n\n sequence */ return 0; } /* struct xlog }}} */ /* {{{ struct xdir */ /* sync snapshot every 16MB */ #define SNAP_SYNC_INTERVAL (1 << 24) void xdir_create(struct xdir *dir, const char *dirname, enum xdir_type type, const tt_uuid *instance_uuid) { memset(dir, 0, sizeof(*dir)); vclockset_new(&dir->index); /* Default mode. */ dir->mode = 0660; dir->instance_uuid = instance_uuid; snprintf(dir->dirname, PATH_MAX, "%s", dirname); dir->open_wflags = O_RDWR | O_CREAT | O_EXCL; switch (type) { case SNAP: dir->filetype = "SNAP"; dir->filename_ext = ".snap"; dir->suffix = INPROGRESS; dir->sync_interval = SNAP_SYNC_INTERVAL; break; case XLOG: dir->sync_is_async = true; dir->filetype = "XLOG"; dir->filename_ext = ".xlog"; dir->suffix = NONE; dir->force_recovery = true; break; case VYLOG: dir->filetype = "VYLOG"; dir->filename_ext = ".vylog"; dir->suffix = INPROGRESS; dir->force_recovery = true; break; default: unreachable(); } dir->type = type; } /** * Delete all members from the set of vector clocks. */ static void vclockset_reset(vclockset_t *set) { struct vclock *vclock = vclockset_first(set); while (vclock != NULL) { struct vclock *next = vclockset_next(set, vclock); vclockset_remove(set, vclock); free(vclock); vclock = next; } } /** * Destroy xdir object and free memory. */ void xdir_destroy(struct xdir *dir) { /** Free vclock objects allocated in xdir_scan(). */ vclockset_reset(&dir->index); } /** * Add a single log file to the index of all log files * in a given log directory. */ static inline int xdir_index_file(struct xdir *dir, int64_t signature) { /* * Open xlog and parse vclock in its text header. * The vclock stores the state of the log at the * time it is created. */ struct xlog_cursor cursor; if (xdir_open_cursor(dir, signature, &cursor) < 0) return -1; struct xlog_meta *meta = &cursor.meta; /* * All log files in a directory must satisfy Lamport's * eventual order: events in each log file must be * separable with consistent cuts, for example: * * log1: {1, 1, 0, 1}, log2: {1, 2, 0, 2} -- good * log2: {1, 1, 0, 1}, log2: {2, 0, 2, 0} -- bad */ struct vclock *dup = vclockset_search(&dir->index, &meta->vclock); if (dup != NULL) { tnt_error(XlogError, "%s: invalid xlog order", cursor.name); xlog_cursor_close(&cursor, false); return -1; } /* * Append the clock describing the file to the * directory index. */ struct vclock *vclock = (struct vclock *) malloc(sizeof(*vclock)); if (vclock == NULL) { tnt_error(OutOfMemory, sizeof(*vclock), "malloc", "vclock"); xlog_cursor_close(&cursor, false); return -1; } vclock_copy(vclock, &meta->vclock); xlog_cursor_close(&cursor, false); vclockset_insert(&dir->index, vclock); return 0; } int xdir_open_cursor(struct xdir *dir, int64_t signature, struct xlog_cursor *cursor) { const char *filename = xdir_format_filename(dir, signature, NONE); int fd = open(filename, O_RDONLY); if (fd < 0) { diag_set(SystemError, "failed to open '%s' file", filename); return -1; } if (xlog_cursor_openfd(cursor, fd, filename) < 0) { close(fd); return -1; } struct xlog_meta *meta = &cursor->meta; if (strcmp(meta->filetype, dir->filetype) != 0) { xlog_cursor_close(cursor, false); diag_set(ClientError, ER_INVALID_XLOG_TYPE, dir->filetype, meta->filetype); return -1; } if (!tt_uuid_is_nil(dir->instance_uuid) && !tt_uuid_is_equal(dir->instance_uuid, &meta->instance_uuid)) { xlog_cursor_close(cursor, false); tnt_error(XlogError, "%s: invalid instance UUID", filename); return -1; } /* * Check the match between log file name and contents: * the sum of vector clock coordinates must be the same * as the name of the file. */ int64_t signature_check = vclock_sum(&meta->vclock); if (signature_check != signature) { xlog_cursor_close(cursor, false); tnt_error(XlogError, "%s: signature check failed", filename); return -1; } return 0; } static int cmp_i64(const void *_a, const void *_b) { const int64_t *a = (const int64_t *) _a, *b = (const int64_t *) _b; if (*a == *b) return 0; return (*a > *b) ? 1 : -1; } /** * Scan (or rescan) a directory with snapshot or write ahead logs. * Read all files matching a pattern from the directory - * the filename pattern is \d+.xlog * The name of the file is based on its vclock signature, * which is the sum of all elements in the vector clock recorded * when the file was created. Elements in the vector * reflect log sequence numbers of replicas in the asynchronous * replication set (see also _cluster system space and vclock.h * comments). * * This function tries to avoid re-reading a file if * it is already in the set of files "known" to the log * dir object. This is done to speed up local hot standby and * recovery_follow_local(), which periodically rescan the * directory to discover newly created logs. * * On error, this function throws an exception. If * dir->force_recovery is true, *some* errors are not * propagated up but only logged in the error log file. * * The list of errors ignored in force_recovery = true mode * includes: * - a file can not be opened * - some of the files have incorrect metadata (such files are * skipped) * * The goal of force_recovery = true mode is partial recovery * from a damaged/incorrect data directory. It doesn't * silence conditions such as out of memory or lack of OS * resources. * * @return nothing. */ int xdir_scan(struct xdir *dir) { DIR *dh = opendir(dir->dirname); /* log dir */ int64_t *signatures = NULL; /* log file names */ size_t s_count = 0, s_capacity = 0; if (dh == NULL) { tnt_error(SystemError, "error reading directory '%s'", dir->dirname); return -1; } auto dir_guard = make_scoped_guard([&]{ closedir(dh); free(signatures); }); struct dirent *dent; /* A note regarding thread safety, readdir vs. readdir_r: POSIX explicitly makes the following guarantee: "The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream. This data is not overwritten by another call to readdir() on a different directory stream. In practice, you don't have a problem with readdir(3) because Android's bionic, Linux's glibc, and OS X and iOS' libc all allocate per-DIR* buffers, and return pointers into those; in Android's case, that buffer is currently about 8KiB. If future file systems mean that this becomes an actual limitation, we can fix the C library and all your applications will keep working. See also http://elliotth.blogspot.co.uk/2012/10/how-not-to-use-readdirr3.html */ while ((dent = readdir(dh)) != NULL) { char *ext = strchr(dent->d_name, '.'); if (ext == NULL) continue; /* * Compare the rest of the filename with * dir->filename_ext. */ if (strcmp(ext, dir->filename_ext) != 0) continue; char *dot; long long signature = strtoll(dent->d_name, &dot, 10); if (ext != dot || signature == LLONG_MAX || signature == LLONG_MIN) { say_warn("can't parse `%s', skipping", dent->d_name); continue; } if (s_count == s_capacity) { s_capacity = s_capacity > 0 ? 2 * s_capacity : 16; size_t size = sizeof(*signatures) * s_capacity; signatures = (int64_t *) realloc(signatures, size); if (signatures == NULL) { tnt_error(OutOfMemory, size, "realloc", "signatures array"); return -1; } } signatures[s_count++] = signature; } /** Sort the list of files */ qsort(signatures, s_count, sizeof(*signatures), cmp_i64); /** * Update the log dir index with the current state: * remove files which no longer exist, add files which * appeared since the last scan. */ struct vclock *vclock = vclockset_first(&dir->index); unsigned i = 0; while (i < s_count || vclock != NULL) { int64_t s_old = vclock ? vclock_sum(vclock) : LLONG_MAX; int64_t s_new = i < s_count ? signatures[i] : LLONG_MAX; if (s_old < s_new) { /** Remove a deleted file from the index */ struct vclock *next = vclockset_next(&dir->index, vclock); vclockset_remove(&dir->index, vclock); free(vclock); vclock = next; } else if (s_old > s_new) { /** Add a new file. */ if (xdir_index_file(dir, s_new) != 0) { /* * force_recovery must not affect OOM */ struct error *e = diag_last_error(&fiber()->diag); if (!dir->force_recovery || type_cast(OutOfMemory, e)) return -1; /** Skip a corrupted file */ error_log(e); return 0; } i++; } else { assert(s_old == s_new && i < s_count && vclock != NULL); vclock = vclockset_next(&dir->index, vclock); i++; } } return 0; } int xdir_check(struct xdir *dir) { DIR *dh = opendir(dir->dirname); /* log dir */ if (dh == NULL) { tnt_error(SystemError, "error reading directory '%s'", dir->dirname); return -1; } closedir(dh); return 0; } char * xdir_format_filename(struct xdir *dir, int64_t signature, enum log_suffix suffix) { static __thread char filename[PATH_MAX + 1]; const char *suffix_str = (suffix == INPROGRESS ? inprogress_suffix : ""); snprintf(filename, PATH_MAX, "%s/%020lld%s%s", dir->dirname, (long long) signature, dir->filename_ext, suffix_str); return filename; } void xdir_collect_garbage(struct xdir *dir, int64_t signature) { struct vclock *it = vclockset_first(&dir->index); while (it != NULL && vclock_sum(it) < signature) { struct vclock *next = vclockset_next(&dir->index, it); char *filename = xdir_format_filename(dir, vclock_sum(it), NONE); say_info("removing %s", filename); if (unlink(filename) < 0 && errno != ENOENT) { say_syserror("error while removing %s", filename); } else { vclockset_remove(&dir->index, it); free(it); } it = next; } } /* }}} */ /* {{{ struct xlog */ int xlog_rename(struct xlog *l) { char *filename = l->filename; char new_filename[PATH_MAX]; char *suffix = strrchr(filename, '.'); assert(l->is_inprogress); assert(suffix); assert(strcmp(suffix, inprogress_suffix) == 0); /* Create a new filename without '.inprogress' suffix. */ memcpy(new_filename, filename, suffix - filename); new_filename[suffix - filename] = '\0'; if (rename(filename, new_filename) != 0) { say_syserror("can't rename %s to %s", filename, new_filename); diag_set(SystemError, "failed to rename '%s' file", filename); return -1; } l->is_inprogress = false; return 0; } static int xlog_init(struct xlog *xlog) { memset(xlog, 0, sizeof(*xlog)); xlog->sync_interval = SNAP_SYNC_INTERVAL; xlog->sync_time = ev_time(); xlog->is_autocommit = true; obuf_create(&xlog->obuf, &cord()->slabc, XLOG_TX_AUTOCOMMIT_THRESHOLD); obuf_create(&xlog->zbuf, &cord()->slabc, XLOG_TX_AUTOCOMMIT_THRESHOLD); xlog->zctx = ZSTD_createCCtx(); if (xlog->zctx == NULL) { diag_set(ClientError, ER_COMPRESSION, "failed to create context"); return -1; } return 0; } void xlog_clear(struct xlog *l) { memset(l, 0, sizeof(*l)); l->fd = -1; } static void xlog_destroy(struct xlog *xlog) { obuf_destroy(&xlog->obuf); obuf_destroy(&xlog->zbuf); ZSTD_freeCCtx(xlog->zctx); TRASH(xlog); xlog->fd = -1; } int xlog_create(struct xlog *xlog, const char *name, const struct xlog_meta *meta) { char meta_buf[XLOG_META_LEN_MAX]; int meta_len; /* * Check that the file without .inprogress suffix doesn't exist. */ if (access(name, F_OK) == 0) { errno = EEXIST; diag_set(SystemError, "file '%s' already exists", name); goto err; } if (xlog_init(xlog) != 0) goto err; xlog->meta = *meta; xlog->is_inprogress = true; snprintf(xlog->filename, PATH_MAX, "%s%s", name, inprogress_suffix); /* * Open the <lsn>.<suffix>.inprogress file. * If it exists, open will fail. Always open/create * a file with .inprogress suffix: for snapshots, * the rename is done when the snapshot is complete. * Fox xlogs, we can rename only when we have written * the log file header, otherwise replication relay * may think that this is a corrupt file and stop * replication. */ xlog->fd = open(xlog->filename, O_RDWR | O_CREAT | O_EXCL, 0644); if (xlog->fd < 0) { say_syserror("open, [%s]", name); diag_set(SystemError, "failed to create file '%s'", name); goto err_open; } /* Format metadata */ meta_len = xlog_meta_format(&xlog->meta, meta_buf, sizeof(meta_buf)); if (meta_len < 0) goto err_write; /* Formatted metadata must fit into meta_buf */ assert(meta_len < (int)sizeof(meta_buf)); /* Write metadata */ if (fio_writen(xlog->fd, meta_buf, meta_len) < 0) { diag_set(SystemError, "%s: failed to write xlog meta", name); goto err_write; } xlog->offset = meta_len; /* first log starts after meta */ return 0; err_write: close(xlog->fd); unlink(xlog->filename); /* try to remove incomplete file */ err_open: xlog_destroy(xlog); err: return -1; } int xlog_open(struct xlog *xlog, const char *name) { char magic[sizeof(log_magic_t)]; char meta_buf[XLOG_META_LEN_MAX]; const char *meta = meta_buf; int meta_len; int rc; if (xlog_init(xlog) != 0) goto err; strncpy(xlog->filename, name, PATH_MAX); xlog->fd = open(xlog->filename, O_RDWR); if (xlog->fd < 0) { say_syserror("open, [%s]", name); diag_set(SystemError, "failed to open file '%s'", name); goto err_open; } meta_len = fio_read(xlog->fd, meta_buf, sizeof(meta_buf)); if (meta_len < 0) { diag_set(SystemError, "failed to read file '%s'", xlog->filename); goto err_read; } rc = xlog_meta_parse(&xlog->meta, &meta, meta + meta_len); if (rc < 0) goto err_read; if (rc > 0) { tnt_error(XlogError, "Unexpected end of file"); goto err_read; } /* * If the file has eof marker, reposition the file pointer so * that the next write will overwrite it. */ xlog->offset = fio_lseek(xlog->fd, -sizeof(magic), SEEK_END); if (xlog->offset < 0) goto no_eof; /* Use pread() so as not to change file pointer. */ rc = fio_pread(xlog->fd, magic, sizeof(magic), xlog->offset); if (rc < 0) { diag_set(SystemError, "failed to read file '%s'", xlog->filename); goto err_read; } if (rc != sizeof(magic) || load_u32(magic) != eof_marker) { no_eof: xlog->offset = fio_lseek(xlog->fd, 0, SEEK_END); if (xlog->offset < 0) { diag_set(SystemError, "failed to seek file '%s'", xlog->filename); goto err_read; } } return 0; err_read: close(xlog->fd); err_open: xlog_destroy(xlog); err: return -1; } int xdir_touch_xlog(struct xdir *dir, const struct vclock *vclock) { char *filename; int64_t signature = vclock_sum(vclock); filename = xdir_format_filename(dir, signature, NONE); if (dir->type != SNAP) { assert(false); diag_set(SystemError, "Can't touch xlog '%s'", filename); return -1; } if (utime(filename, NULL) != 0) { diag_set(SystemError, "Can't update xlog timestamp: '%s'", filename); return -1; } return 0; } /** * In case of error, writes a message to the error log * and sets errno. */ int xdir_create_xlog(struct xdir *dir, struct xlog *xlog, const struct vclock *vclock) { char *filename; int64_t signature = vclock_sum(vclock); struct xlog_meta meta; assert(signature >= 0); assert(!tt_uuid_is_nil(dir->instance_uuid)); /* * Check whether a file with this name already exists. * We don't overwrite existing files. */ filename = xdir_format_filename(dir, signature, NONE); /* Setup inherited values */ snprintf(meta.filetype, sizeof(meta.filetype), "%s", dir->filetype); meta.instance_uuid = *dir->instance_uuid; vclock_copy(&meta.vclock, vclock); if (xlog_create(xlog, filename, &meta) != 0) return -1; /* set sync interval from xdir settings */ xlog->sync_interval = dir->sync_interval; /* free file cache if dir should be synced */ xlog->free_cache = dir->sync_interval != 0 ? true: false; xlog->rate_limit = 0; /* Rename xlog file */ if (dir->suffix != INPROGRESS && xlog_rename(xlog)) { int save_errno = errno; xlog_close(xlog, false); errno = save_errno; return -1; } return 0; } /** * Write a sequence of uncompressed xrow objects. * * @retval -1 error * @retval >= 0 the number of bytes written */ static off_t xlog_tx_write_plain(struct xlog *log) { /** * We created an obuf savepoint at start of xlog_tx, * now populate it with data. */ char *fixheader = (char *)log->obuf.iov[0].iov_base; *(log_magic_t *)fixheader = row_marker; char *data = fixheader + sizeof(log_magic_t); data = mp_encode_uint(data, obuf_size(&log->obuf) - XLOG_FIXHEADER_SIZE); /* Encode crc32 for previous row */ data = mp_encode_uint(data, 0); /* Encode crc32 for current row */ uint32_t crc32c = 0; struct iovec *iov; size_t offset = XLOG_FIXHEADER_SIZE; for (iov = log->obuf.iov; iov->iov_len; ++iov) { crc32c = crc32_calc(crc32c, (char *)iov->iov_base + offset, iov->iov_len - offset); offset = 0; } data = mp_encode_uint(data, crc32c); /* * Encode a padding, to ensure the resulting * fixheader always has the same size. */ ssize_t padding = XLOG_FIXHEADER_SIZE - (data - fixheader); if (padding > 0) { data = mp_encode_strl(data, padding - 1); if (padding > 1) { memset(data, 0, padding - 1); data += padding - 1; } } ERROR_INJECT(ERRINJ_WAL_WRITE_DISK, { diag_set(ClientError, ER_INJECTION, "xlog write injection"); return -1; }); ssize_t written = fio_writevn(log->fd, log->obuf.iov, log->obuf.pos + 1); if (written < 0) { diag_set(SystemError, "failed to write to '%s' file", log->filename); return -1; } return obuf_size(&log->obuf); } /** * Write a compressed block of xrow objects. * @retval -1 error * @retval >= 0 the number of bytes written */ static off_t xlog_tx_write_zstd(struct xlog *log) { char *fixheader = (char *)obuf_alloc(&log->zbuf, XLOG_FIXHEADER_SIZE); uint32_t crc32c = 0; struct iovec *iov; /* 3 is compression level. */ ZSTD_compressBegin(log->zctx, 3); size_t offset = XLOG_FIXHEADER_SIZE; for (iov = log->obuf.iov; iov->iov_len; ++iov) { /* Estimate max output buffer size. */ size_t zmax_size = ZSTD_compressBound(iov->iov_len - offset); /* Allocate a destination buffer. */ void *zdst = obuf_reserve(&log->zbuf, zmax_size); if (!zdst) { tnt_error(OutOfMemory, zmax_size, "runtime arena", "compression buffer"); goto error; } size_t (*fcompress)(ZSTD_CCtx *, void *, size_t, const void *, size_t); /* * If it's the last iov or the last * log has 0 bytes, end the stream. */ if (iov == log->obuf.iov + log->obuf.pos || !(iov + 1)->iov_len) { fcompress = ZSTD_compressEnd; } else { fcompress = ZSTD_compressContinue; } size_t zsize = fcompress(log->zctx, zdst, zmax_size, (char *)iov->iov_base + offset, iov->iov_len - offset); if (ZSTD_isError(zsize)) { diag_set(ClientError, ER_COMPRESSION, ZSTD_getErrorName(zsize)); goto error; } /* Advance output buffer to the end of compressed data. */ obuf_alloc(&log->zbuf, zsize); /* Update crc32c */ crc32c = crc32_calc(crc32c, (char *)zdst, zsize); /* Discount fixheader size for all iovs after first. */ offset = 0; } *(log_magic_t *)fixheader = zrow_marker; char *data; data = fixheader + sizeof(log_magic_t); data = mp_encode_uint(data, obuf_size(&log->zbuf) - XLOG_FIXHEADER_SIZE); /* Encode crc32 for previous row */ data = mp_encode_uint(data, 0); /* Encode crc32 for current row */ data = mp_encode_uint(data, crc32c); /* Encode padding */ ssize_t padding; padding = XLOG_FIXHEADER_SIZE - (data - fixheader); if (padding > 0) { data = mp_encode_strl(data, padding - 1); if (padding > 1) { memset(data, 0, padding - 1); data += padding - 1; } } ERROR_INJECT(ERRINJ_WAL_WRITE_DISK, { diag_set(ClientError, ER_INJECTION, "xlog write injection"); obuf_reset(&log->zbuf); goto error; }); ssize_t written; written = fio_writevn(log->fd, log->zbuf.iov, log->zbuf.pos + 1); if (written < 0) { diag_set(SystemError, "failed to write to '%s' file", log->filename); goto error; } obuf_reset(&log->zbuf); return written; error: obuf_reset(&log->zbuf); return -1; } /* file syncing and posix_fadvise() should be rounded by a page boundary */ #define SYNC_MASK (4096 - 1) #define SYNC_ROUND_DOWN(size) ((size) & ~(4096 - 1)) #define SYNC_ROUND_UP(size) (SYNC_ROUND_DOWN(size + SYNC_MASK)) /** * Writes xlog batch to file */ static ssize_t xlog_tx_write(struct xlog *log) { if (obuf_size(&log->obuf) == XLOG_FIXHEADER_SIZE) return 0; ssize_t written; if (obuf_size(&log->obuf) >= XLOG_TX_COMPRESS_THRESHOLD) { written = xlog_tx_write_zstd(log); } else { written = xlog_tx_write_plain(log); } ERROR_INJECT(ERRINJ_WAL_WRITE, written = -1;); obuf_reset(&log->obuf); /* * Simplify recovery after a temporary write failure: * truncate the file to the best known good write * position. */ if (written < 0) { if (lseek(log->fd, log->offset, SEEK_SET) < 0 || ftruncate(log->fd, log->offset) != 0) panic_syserror("failed to truncate xlog after write error"); return -1; } log->offset += written; log->rows += log->tx_rows; log->tx_rows = 0; if ((log->sync_interval && log->offset >= (off_t)(log->synced_size + log->sync_interval)) || (log->rate_limit && log->offset >= (off_t)(log->synced_size + log->rate_limit))) { off_t sync_from = SYNC_ROUND_DOWN(log->synced_size); size_t sync_len = SYNC_ROUND_UP(log->offset) - sync_from; if (log->rate_limit > 0) { double throttle_time; throttle_time = (double)sync_len / log->rate_limit - (ev_time() - log->sync_time); if (throttle_time > 0) fiber_sleep(throttle_time); } /** sync data from cache to disk */ #ifdef HAVE_SYNC_FILE_RANGE sync_file_range(log->fd, sync_from, sync_len, SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER); #else fdatasync(log->fd); #endif /* HAVE_SYNC_FILE_RANGE */ log->sync_time = ev_time(); if (log->free_cache) { #ifdef HAVE_POSIX_FADVISE /** free page cache */ if (posix_fadvise(log->fd, sync_from, sync_len, POSIX_FADV_DONTNEED) != 0) { say_syserror("posix_fadvise, fd=%i", log->fd); } #else (void) sync_from; (void) sync_len; #endif /* HAVE_POSIX_FADVISE */ } log->synced_size = log->offset; } return written; } /* * Add a row to a log and possibly flush the log. * * @retval -1 error, check diag. * @retval >=0 the number of bytes written to buffer. */ ssize_t xlog_write_row(struct xlog *log, const struct xrow_header *packet) { /* * Automatically reserve space for a fixheader when adding * the first row in * a log. The fixheader is populated * at write. @sa xlog_tx_write(). */ if (obuf_size(&log->obuf) == 0) { if (!obuf_alloc(&log->obuf, XLOG_FIXHEADER_SIZE)) { tnt_error(OutOfMemory, XLOG_FIXHEADER_SIZE, "runtime arena", "xlog tx output buffer"); return -1; } } size_t page_offset = obuf_size(&log->obuf); /** encode row into iovec */ struct iovec iov[XROW_IOVMAX]; int iovcnt = xrow_header_encode(packet, iov, 0); struct obuf_svp svp = obuf_create_svp(&log->obuf); for (int i = 0; i < iovcnt; ++i) { struct errinj *inj = errinj(ERRINJ_WAL_WRITE_PARTIAL, ERRINJ_U64); if (inj != NULL && obuf_size(&log->obuf) > inj->u64param) { diag_set(ClientError, ER_INJECTION, "xlog write injection"); obuf_rollback_to_svp(&log->obuf, &svp); return -1; }; if (obuf_dup(&log->obuf, iov[i].iov_base, iov[i].iov_len) < iov[i].iov_len) { tnt_error(OutOfMemory, XLOG_FIXHEADER_SIZE, "runtime arena", "xlog tx output buffer"); obuf_rollback_to_svp(&log->obuf, &svp); return -1; } } assert(iovcnt <= XROW_IOVMAX); log->tx_rows++; size_t row_size = obuf_size(&log->obuf) - page_offset; if (log->is_autocommit && obuf_size(&log->obuf) >= XLOG_TX_AUTOCOMMIT_THRESHOLD && xlog_tx_write(log) < 0) return -1; return row_size; } /** * Begin a multi-statement xlog transaction. All xrow objects * of a single transaction share the same header and checksum * and are normally written at once. */ void xlog_tx_begin(struct xlog *log) { log->is_autocommit = false; } /* * End a non-interruptible batch of rows, thus enable flushes of * a transaction at any time, on threshold. If the buffer is big * enough already, flush it at once here. * * @retval -1 error * @retval >= 0 the number of bytes written to disk */ ssize_t xlog_tx_commit(struct xlog *log) { log->is_autocommit = true; if (obuf_size(&log->obuf) >= XLOG_TX_AUTOCOMMIT_THRESHOLD) { return xlog_tx_write(log); } return 0; } /* * Rollback a batch of buffered rows without writing to file */ void xlog_tx_rollback(struct xlog *log) { log->is_autocommit = true; log->tx_rows = 0; obuf_reset(&log->obuf); } /** * Flush any outstanding xlog_tx transactions at the end of * a WAL write batch. */ ssize_t xlog_flush(struct xlog *log) { assert(log->is_autocommit); if (log->obuf.used == 0) return 0; return xlog_tx_write(log); } static int sync_cb(eio_req *req) { int fd = (intptr_t) req->data; if (req->result) { errno = req->errorno; say_syserror("%s: fsync() failed", fio_filename(fd)); errno = 0; } close(fd); return 0; } int xlog_sync(struct xlog *l) { if (l->sync_is_async) { int fd = dup(l->fd); if (fd == -1) { say_syserror("%s: dup() failed", l->filename); return -1; } eio_fsync(fd, 0, sync_cb, (void *) (intptr_t) fd); } else if (fsync(l->fd) < 0) { say_syserror("%s: fsync failed", l->filename); return -1; } return 0; } int xlog_close(struct xlog *l, bool reuse_fd) { int rc = fio_writen(l->fd, &eof_marker, sizeof(log_magic_t)); if (rc < 0) say_syserror("%s: failed to write EOF marker", l->filename); /* * Sync the file before closing, since * otherwise we can end up with a partially * written file in case of a crash. * We sync even if file open O_SYNC, simplify code for low cost */ xlog_sync(l); if (!reuse_fd) { rc = close(l->fd); if (rc < 0) say_syserror("%s: close() failed", l->filename); } xlog_destroy(l); return rc; } /** * Free xlog memory and destroy it cleanly, without side * effects (for use in the atfork handler). */ void xlog_atfork(struct xlog *xlog) { /* * Close the file descriptor STDIO buffer does not * make its way into the respective file in * fclose(). */ close(xlog->fd); xlog->fd = -1; } /* }}} */ /* {{{ struct xlog_cursor */ #define XLOG_READ_AHEAD (1 << 14) /** * Ensure that at least count bytes are in read buffer * * @retval 0 at least count bytes are in read buf * @retval 1 if eof * @retval -1 if error */ static int xlog_cursor_ensure(struct xlog_cursor *cursor, size_t count) { if (ibuf_used(&cursor->rbuf) >= count) return 0; /* in-memory mode */ if (cursor->fd < 0) return 1; size_t to_load = count - ibuf_used(&cursor->rbuf); to_load += XLOG_READ_AHEAD; void *dst = ibuf_reserve(&cursor->rbuf, to_load); if (dst == NULL) { diag_set(OutOfMemory, to_load, "runtime", "xlog cursor read buffer"); return -1; } ssize_t readen; readen = fio_pread(cursor->fd, dst, to_load, cursor->read_offset); if (readen < 0) { diag_set(SystemError, "failed to read '%s' file", cursor->name); return -1; } /* ibuf_reserve() has been called above, ibuf_alloc() must not fail */ assert((size_t)readen <= to_load); ibuf_alloc(&cursor->rbuf, readen); cursor->read_offset += readen; return ibuf_used(&cursor->rbuf) >= count ? 0: 1; } /** * Cursor parse position */ static inline off_t xlog_cursor_pos(struct xlog_cursor *cursor) { return cursor->read_offset - ibuf_used(&cursor->rbuf); } /** * Decompress zstd-compressed buf into cursor row block * * @retval -1 error, check diag * @retval 0 data fully decompressed * @retval 1 need more bytes in the output buffer */ static int xlog_cursor_decompress(char **rows, char *rows_end, const char **data, const char *data_end, ZSTD_DStream *zdctx) { ZSTD_inBuffer input = {*data, (size_t)(data_end - *data), 0}; ZSTD_outBuffer output = {*rows, (size_t)(rows_end - *rows), 0}; while (input.pos < input.size && output.pos < output.size) { size_t rc = ZSTD_decompressStream(zdctx, &output, &input); if (ZSTD_isError(rc)) { diag_set(ClientError, ER_DECOMPRESSION, ZSTD_getErrorName(rc)); return -1; } assert(output.pos <= (size_t)(rows_end - *rows)); *rows = (char *)output.dst + output.pos; *data = (char *)input.src + input.pos; } return input.pos == input.size ? 0: 1; } /** * xlog fixheader struct */ struct xlog_fixheader { /** * xlog tx magic, row_marker for plain xrows * or zrow_marker for compressed. */ log_magic_t magic; /** * crc32 for the previous xlog tx, not used now */ uint32_t crc32p; /** * crc32 for current xlog tx */ uint32_t crc32c; /** * xlog tx data length excluding fixheader */ uint32_t len; }; /** * Decode xlog tx header, set up magic, crc32c and len * * @retval 0 for success * @retval -1 for error * @retval count of bytes left to parse header */ static ssize_t xlog_fixheader_decode(struct xlog_fixheader *fixheader, const char **data, const char *data_end) { if (data_end - *data < (ptrdiff_t)XLOG_FIXHEADER_SIZE) return XLOG_FIXHEADER_SIZE - (data_end - *data); const char *pos = *data; const char *end = pos + XLOG_FIXHEADER_SIZE; /* Decode magic */ fixheader->magic = load_u32(pos); if (fixheader->magic != row_marker && fixheader->magic != zrow_marker) { tnt_error(XlogError, "invalid magic: 0x%x", fixheader->magic); return -1; } pos += sizeof(fixheader->magic); /* Read length */ const char *val = pos; if (pos >= end || mp_check(&pos, end) != 0 || mp_typeof(*val) != MP_UINT) { tnt_error(XlogError, "broken fixheader length"); return -1; } fixheader->len = mp_decode_uint(&val); assert(val == pos); if (fixheader->len > IPROTO_BODY_LEN_MAX) { tnt_error(XlogError, "too large fixheader length"); return -1; } /* Read previous crc32 */ if (pos >= end || mp_check(&pos, end) != 0 || mp_typeof(*val) != MP_UINT) { tnt_error(XlogError, "broken fixheader crc32p"); return -1; } fixheader->crc32p = mp_decode_uint(&val); assert(val == pos); /* Read current crc32 */ if (pos >= end || mp_check(&pos, end) != 0 || mp_typeof(*val) != MP_UINT) { tnt_error(XlogError, "broken fixheader crc32c"); return -1; } fixheader->crc32c = mp_decode_uint(&val); assert(val == pos); /* Check and skip padding if any */ if (pos < end && (mp_check(&pos, end) != 0 || pos != end)) { tnt_error(XlogError, "broken fixheader padding"); return -1; } assert(pos == end); *data = end; return 0; } int xlog_tx_decode(const char *data, const char *data_end, char *rows, char *rows_end, ZSTD_DStream *zdctx) { /* Decode fixheader */ struct xlog_fixheader fixheader; if (xlog_fixheader_decode(&fixheader, &data, data_end) != 0) return -1; /* Check that buffer has enough bytes */ if (data + fixheader.len != data_end) { tnt_error(XlogError, "invalid compressed length: " "expected %zd, got %u", data_end - data, fixheader.len); return -1; } /* Validate checksum */ if (crc32_calc(0, data, fixheader.len) != fixheader.crc32c) { tnt_error(XlogError, "tx checksum mismatch"); return -1; } /* Copy uncompressed rows */ if (fixheader.magic == row_marker) { if (rows_end - rows != (ptrdiff_t)fixheader.len) { tnt_error(XlogError, "invalid unpacked length: " "expected %zd, got %u", rows_end - data, fixheader.len); return -1; } memcpy(rows, data, fixheader.len); return 0; } /* Decompress zstd rows */ assert(fixheader.magic == zrow_marker); ZSTD_initDStream(zdctx); int rc = xlog_cursor_decompress(&rows, rows_end, &data, data_end, zdctx); if (rc < 0) { return -1; } else if (rc > 0) { tnt_error(XlogError, "invalid decompressed length: " "expected %zd, got %zd", rows_end - data, rows_end - data + XLOG_TX_AUTOCOMMIT_THRESHOLD); return -1; } assert(data == data_end); return 0; } /** * @retval -1 error * @retval 0 success * @retval >0 how many bytes we will have for continue */ ssize_t xlog_tx_cursor_create(struct xlog_tx_cursor *tx_cursor, const char **data, const char *data_end, ZSTD_DStream *zdctx) { const char *rpos = *data; struct xlog_fixheader fixheader; ssize_t to_load; to_load = xlog_fixheader_decode(&fixheader, &rpos, data_end); if (to_load != 0) return to_load; /* Check that buffer has enough bytes */ if ((data_end - rpos) < (ptrdiff_t)fixheader.len) return fixheader.len - (data_end - rpos); /* Validate checksum */ if (crc32_calc(0, rpos, fixheader.len) != fixheader.crc32c) { tnt_error(XlogError, "tx checksum mismatch"); return -1; } data_end = rpos + fixheader.len; ibuf_create(&tx_cursor->rows, &cord()->slabc, XLOG_TX_AUTOCOMMIT_THRESHOLD); if (fixheader.magic == row_marker) { void *dst = ibuf_alloc(&tx_cursor->rows, fixheader.len); if (dst == NULL) { diag_set(OutOfMemory, fixheader.len, "runtime", "xlog rows buffer"); ibuf_destroy(&tx_cursor->rows); return -1; } memcpy(dst, rpos, fixheader.len); *data = (char *)rpos + fixheader.len; assert(*data <= data_end); return 0; }; assert(fixheader.magic == zrow_marker); ZSTD_initDStream(zdctx); int rc; do { if (ibuf_reserve(&tx_cursor->rows, XLOG_TX_AUTOCOMMIT_THRESHOLD) == NULL) { tnt_error(OutOfMemory, XLOG_TX_AUTOCOMMIT_THRESHOLD, "runtime", "xlog output buffer"); ibuf_destroy(&tx_cursor->rows); return -1; } } while ((rc = xlog_cursor_decompress(&tx_cursor->rows.wpos, tx_cursor->rows.end, &rpos, data_end, zdctx)) == 1); if (rc != 0) return -1; *data = rpos; assert(*data <= data_end); return 0; } int xlog_tx_cursor_next_row(struct xlog_tx_cursor *tx_cursor, struct xrow_header *xrow) { if (ibuf_used(&tx_cursor->rows) == 0) return 1; /* Return row from xlog tx buffer */ int rc = xrow_header_decode(xrow, (const char **)&tx_cursor->rows.rpos, (const char *)tx_cursor->rows.wpos); if (rc != 0) { tnt_error(XlogError, "can't parse row"); /* Discard remaining row data */ ibuf_reset(&tx_cursor->rows); return -1; } return 0; } int xlog_tx_cursor_destroy(struct xlog_tx_cursor *tx_cursor) { ibuf_destroy(&tx_cursor->rows); return 0; } /** * Find a next xlog tx magic */ int xlog_cursor_find_tx_magic(struct xlog_cursor *i) { log_magic_t magic; do { /* * Read one extra byte to start searching from the next * byte. */ int rc = xlog_cursor_ensure(i, sizeof(log_magic_t) + 1); if (rc < 0) return -1; if (rc == 1) return 1; ++i->rbuf.rpos; assert(i->rbuf.rpos + sizeof(log_magic_t) <= i->rbuf.wpos); magic = load_u32(i->rbuf.rpos); } while (magic != row_marker && magic != zrow_marker); return 0; } int xlog_cursor_next_tx(struct xlog_cursor *i) { int rc; assert(i->state != XLOG_CURSOR_EOF); /* load at least magic to check eof */ rc = xlog_cursor_ensure(i, sizeof(log_magic_t)); if (rc < 0) return -1; if (rc > 0) return 1; if (load_u32(i->rbuf.rpos) == eof_marker) { /* eof marker found */ i->state = XLOG_CURSOR_EOF; goto eof; } ssize_t to_load; while ((to_load = xlog_tx_cursor_create(&i->tx_cursor, (const char **)&i->rbuf.rpos, i->rbuf.wpos, i->zdctx)) > 0) { /* not enough data in read buffer */ int rc = xlog_cursor_ensure(i, ibuf_used(&i->rbuf) + to_load); if (rc < 0) return -1; if (rc > 0) goto eof; } if (to_load < 0) return -1; i->state = XLOG_CURSOR_TX; return 0; eof: if (i->state == XLOG_CURSOR_EOF) { /* * A eof marker is read, check that there is no * more data in the file. */ rc = xlog_cursor_ensure(i, sizeof(log_magic_t) + sizeof(char)); if (rc < 0) return -1; if (rc == 0) { tnt_error(XlogError, "%s: has some data after " "eof marker at %lld", i->name, xlog_cursor_pos(i)); return -1; } } return 1; } int xlog_cursor_next_row(struct xlog_cursor *cursor, struct xrow_header *xrow) { if (cursor->state != XLOG_CURSOR_TX) return 1; int rc = xlog_tx_cursor_next_row(&cursor->tx_cursor, xrow); if (rc != 0) { cursor->state = XLOG_CURSOR_ACTIVE; xlog_tx_cursor_destroy(&cursor->tx_cursor); } return rc; } int xlog_cursor_next(struct xlog_cursor *cursor, struct xrow_header *xrow, bool force_recovery) { while (true) { int rc; rc = xlog_cursor_next_row(cursor, xrow); if (rc == 0) break; if (rc < 0) { struct error *e = diag_last_error(diag_get()); if (!force_recovery || e->type != &type_XlogError) return -1; say_error("can't decode row: %s", e->errmsg); } while ((rc = xlog_cursor_next_tx(cursor)) < 0) { struct error *e = diag_last_error(diag_get()); if (!force_recovery || e->type != &type_XlogError) return -1; say_error("can't open tx: %s", e->errmsg); if ((rc = xlog_cursor_find_tx_magic(cursor)) < 0) return -1; if (rc > 0) break; } if (rc == 1) return 1; } return 0; } int xlog_cursor_openfd(struct xlog_cursor *i, int fd, const char *name) { memset(i, 0, sizeof(*i)); i->fd = fd; ibuf_create(&i->rbuf, &cord()->slabc, XLOG_TX_AUTOCOMMIT_THRESHOLD << 1); ssize_t rc; /* * we can have eof here, but this is no error, * because we don't know exact meta size */ rc = xlog_cursor_ensure(i, XLOG_META_LEN_MAX); if (rc == -1) goto error; rc = xlog_meta_parse(&i->meta, (const char **)&i->rbuf.rpos, (const char *)i->rbuf.wpos); if (rc == -1) goto error; if (rc > 0) { tnt_error(XlogError, "Unexpected end of file"); goto error; } snprintf(i->name, PATH_MAX, "%s", name); i->zdctx = ZSTD_createDStream(); if (i->zdctx == NULL) { diag_set(ClientError, ER_DECOMPRESSION, "failed to create context"); goto error; } i->state = XLOG_CURSOR_ACTIVE; return 0; error: ibuf_destroy(&i->rbuf); return -1; } int xlog_cursor_open(struct xlog_cursor *i, const char *name) { int fd = open(name, O_RDONLY); if (fd < 0) { diag_set(SystemError, "failed to open '%s' file", name); return -1; } int rc = xlog_cursor_openfd(i, fd, name); if (rc < 0) { close(fd); return -1; } return 0; } int xlog_cursor_openmem(struct xlog_cursor *i, const char *data, size_t size, const char *name) { memset(i, 0, sizeof(*i)); i->fd = -1; ibuf_create(&i->rbuf, &cord()->slabc, XLOG_TX_AUTOCOMMIT_THRESHOLD << 1); void *dst = ibuf_alloc(&i->rbuf, size); if (dst == NULL) { tnt_error(OutOfMemory, size, "runtime", "xlog cursor read buffer"); goto error; } memcpy(dst, data, size); i->read_offset = size; int rc; rc = xlog_meta_parse(&i->meta, (const char **)&i->rbuf.rpos, (const char *)i->rbuf.wpos); if (rc < 0) goto error; if (rc > 0) { tnt_error(XlogError, "Unexpected end of file"); goto error; } snprintf(i->name, PATH_MAX, "%s", name); i->zdctx = ZSTD_createDStream(); if (i->zdctx == NULL) { diag_set(ClientError, ER_DECOMPRESSION, "failed to create context"); goto error; } i->state = XLOG_CURSOR_ACTIVE; return 0; error: ibuf_destroy(&i->rbuf); return -1; } void xlog_cursor_close(struct xlog_cursor *i, bool reuse_fd) { if (i->fd >= 0 && !reuse_fd) close(i->fd); ibuf_destroy(&i->rbuf); if (i->state == XLOG_CURSOR_TX) xlog_tx_cursor_destroy(&i->tx_cursor); ZSTD_freeDStream(i->zdctx); TRASH(i); i->state = XLOG_CURSOR_CLOSED; } /* }}} */
25.508493
86
0.660806
[ "object", "vector" ]
d15165285863c256b2b3af6125d60b657b6a330b
703
cpp
C++
Volume112/11242 - Tour de France/11242-alternative.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
1
2017-01-25T18:07:49.000Z
2017-01-25T18:07:49.000Z
Volume112/11242 - Tour de France/11242-alternative.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
Volume112/11242 - Tour de France/11242-alternative.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define N 128000 using namespace std; typedef pair<int,int> ii; int f,r; int front[N]; int rear[N]; vector<double> ratio; int main() { ios_base::sync_with_stdio(0); cin.tie(0); while(cin>>f && f!=0) { cin>>r; for(int i=0;i<f;++i) cin>>front[i]; for(int i=0;i<r;++i) cin>>rear[i]; for(int i=0;i<f;++i) { for(int j=0;j<r;++j) { double rat= double(rear[j])/front[i]; ratio.push_back(rat); } } sort(ratio.begin(),ratio.end()); double maximum=0; for(int i=0;i<ratio.size()-1;++i) { double d = ratio[i+1]/ratio[i]; if(d>maximum) maximum=d; } ratio.clear(); cout<<fixed<<setprecision(2)<<maximum<<"\n"; } return 0; }
16.348837
46
0.571835
[ "vector" ]
d157332e72198ec004da61e9b54e5ea4fc0ffcb6
11,125
cpp
C++
tests/bitboard_tests.cpp
adajed/chessplusplus
b6bad18a1adfdd00eecefedd196b7c06c1b0a738
[ "MIT" ]
1
2019-10-25T12:33:18.000Z
2019-10-25T12:33:18.000Z
tests/bitboard_tests.cpp
adajed/chess-engine
b6bad18a1adfdd00eecefedd196b7c06c1b0a738
[ "MIT" ]
1
2021-04-21T10:00:12.000Z
2021-05-23T10:54:00.000Z
tests/bitboard_tests.cpp
adajed/chess-engine
b6bad18a1adfdd00eecefedd196b7c06c1b0a738
[ "MIT" ]
null
null
null
#include <gtest/gtest-param-test.h> #include <gtest/gtest.h> #include "types.h" #include "bitboard.h" #include "bithacks.h" #include "position_bitboards.h" #include "positions.h" #include "zobrist_hash.h" #include <functional> #include <gtest/internal/gtest-param-util.h> #include <map> #include <gtest/gtest_pred_impl.h> #include <vector> using namespace engine; // check if only squares that are in bb satisfy pred // (i.e. pred(x, y) <=> (x, y) in bb) void check_bb(Bitboard bb, std::function<bool(int, int)> pred) { for (int rank = 0; rank < 8; ++rank) { for (int file = 0; file < 8; ++file) { EXPECT_EQ(pred(rank, file), bool(bb & square_bb(make_square(Rank(rank), File(file))))) << rank << "," << file; } } } Bitboard bb_from_function(std::function<bool(int, int)> pred) { Bitboard bb = 0ULL; for (int rank = 0; rank < 8; ++rank) { for (int file = 0; file < 8; ++file) { Square sq = make_square(Rank(rank), File(file)); if (pred(rank, file)) bb |= square_bb(sq); } } return bb; } TEST(Bitboard, forward_ranks_bb) { for (int rank = 0; rank < 8; rank++) { for (int file = 0; file < 8; file++) { Square sq = make_square(Rank(rank), File(file)); check_bb(forward_ranks_bb<WHITE>(sq), [rank](int x, int y){return x > rank;}); check_bb(forward_ranks_bb<BLACK>(sq), [rank](int x, int y){return x < rank;}); } } } TEST(Bitboard, passed_pawn_bb) { for (int rank = 0; rank < 8; rank++) { for (int file = 0; file < 8; file++) { Square sq = make_square(Rank(rank), File(file)); auto f_white = [rank, file](int x, int y) { return x > rank && abs(y - file) <= 1; }; check_bb(passed_pawn_bb<WHITE>(sq), f_white); auto f_black = [rank, file](int x, int y) { return x < rank && abs(y - file) <= 1; }; check_bb(passed_pawn_bb<BLACK>(sq), f_black); } } } TEST(Bitboard, squares_left_behind_bb) { for (int rank = 0; rank < 8; rank++) { for (int file = 0; file < 8; file++) { Square sq = make_square(Rank(rank), File(file)); auto f_white = [rank, file](int x, int y) { return x <= rank && abs(y - file) == 1; }; check_bb(squares_left_behind_bb<WHITE>(sq), f_white); auto f_black = [rank, file](int x, int y) { return x >= rank && abs(y - file) == 1; }; check_bb(squares_left_behind_bb<BLACK>(sq), f_black); } } } TEST(Bitboard, get_outposts) { for (const auto& fen : test_positions) { Position position(fen); auto f_white = [&position](int x, int y) { Square sq = make_square(Rank(x), File(y)); Bitboard sq_bb = square_bb(sq); if (position.piece_at(sq) == W_PAWN || position.piece_at(sq) == B_PAWN) return false; if (position.pieces(WHITE, PAWN) & (shift<SOUTHEAST>(sq_bb) | shift<SOUTHWEST>(sq_bb))) { Bitboard bb = NEIGHBOUR_FILES_BB[File(y)] & forward_ranks_bb<WHITE>(sq); return (position.pieces(BLACK, PAWN) & bb) ? false : true; } return false; }; check_bb(get_outposts<WHITE>(position), f_white); auto f_black = [&position](int x, int y) { Square sq = make_square(Rank(x), File(y)); Bitboard sq_bb = square_bb(sq); if (position.piece_at(sq) == W_PAWN || position.piece_at(sq) == B_PAWN) return false; if (position.pieces(BLACK, PAWN) & (shift<NORTHEAST>(sq_bb) | shift<NORTHWEST>(sq_bb))) { Bitboard bb = NEIGHBOUR_FILES_BB[File(y)] & forward_ranks_bb<BLACK>(sq); return (position.pieces(WHITE, PAWN) & bb) ? false : true; } return false; }; check_bb(get_outposts<BLACK>(position), f_black); } } TEST(Bitboard, backward_pawns) { for (auto fen : test_positions) { Position position(fen); Bitboard wPawns = position.pieces(WHITE, PAWN); Bitboard bPawns = position.pieces(BLACK, PAWN); auto f_white = [&position](int x, int y) { if (x == 7) return false; Square sq = make_square(Rank(x), File(y)); Bitboard nextSq = square_bb(make_square(Rank(x + 1), File(y))); if (position.piece_at(sq) != W_PAWN) return false; if (pawn_attacks<WHITE>(position.pieces(WHITE, PAWN)) & nextSq) return false; if (!(pawn_attacks<BLACK>(position.pieces(BLACK, PAWN)) & nextSq)) return false; return true; }; check_bb(backward_pawns<WHITE>(wPawns, bPawns), f_white); auto f_black = [&position](int x, int y) { if (x == 0) return false; Square sq = make_square(Rank(x), File(y)); Bitboard nextSq = square_bb(make_square(Rank(x - 1), File(y))); if (position.piece_at(sq) != B_PAWN) return false; if (pawn_attacks<BLACK>(position.pieces(BLACK, PAWN)) & nextSq) return false; if (!(pawn_attacks<WHITE>(position.pieces(WHITE, PAWN)) & nextSq)) return false; return true; }; check_bb(backward_pawns<BLACK>(bPawns, wPawns), f_black); } } TEST(Bitboard, pseudoattacks_ROOK) { for (Square sq = SQ_A1; sq <= SQ_H8; ++sq) { auto f = [sq](int x, int y) { if (rank(sq) == x && file(sq) == y) return false; return (x == rank(sq) || y == file(sq)); }; check_bb(pseudoattacks<ROOK>(sq), f); } } TEST(Bitboard, pseudoattacks_BISHOP) { for (Square sq = SQ_A1; sq <= SQ_H8; ++sq) { auto f = [sq](int x, int y) { if (rank(sq) == x && file(sq) == y) return false; int c1 = rank(sq) - file(sq); int c2 = rank(sq) + file(sq); return ((x - y) == c1 || (x + y) == c2); }; check_bb(pseudoattacks<BISHOP>(sq), f); } } TEST(Bitboard, pseudoattacks_QUEEN) { for (Square sq = SQ_A1; sq <= SQ_H8; ++sq) { auto f = [sq](int x, int y) { if (rank(sq) == x && file(sq) == y) return false; int c1 = rank(sq) - file(sq); int c2 = rank(sq) + file(sq); return ((x - y) == c1 || (x + y) == c2 || x == rank(sq) || y == file(sq)); }; check_bb(pseudoattacks<QUEEN>(sq), f); } } TEST(Bitboard, lines) { for (Square from = SQ_A1; from <= SQ_H8; ++from) { for (Square to = SQ_A1; to <= SQ_H8; ++to) { auto f = [from, to](int r, int f) { int r_from = static_cast<int>(rank(from)); int r_to = static_cast<int>(rank(to)); int f_from = static_cast<int>(file(from)); int f_to = static_cast<int>(file(to)); if (r_from == r_to) return r == r_from && (std::min(f_from, f_to) <= f && f <= std::max(f_from, f_to)); if (f_from == f_to) return f == f_from && (std::min(r_from, r_to) <= r && r <= std::max(r_from, r_to)); if ((f_from - r_from) == (f_to - r_to)) return (f - r) == (f_to - r_to) && (std::min(r_from, r_to) <= r && r <= std::max(r_from, r_to)); if ((f_from + r_from) == (f_to + r_to)) return (f + r) == (f_to + r_to) && (std::min(r_from, r_to) <= r && r <= std::max(r_from, r_to)); return false; }; check_bb(LINES[from][to], f); } } } TEST(Bitboard, full_lines) { for (Square from = SQ_A1; from <= SQ_H8; ++from) { for (Square to = SQ_A1; to <= SQ_H8; ++to) { auto f = [from, to](int r, int f) { int r_from = static_cast<int>(rank(from)); int r_to = static_cast<int>(rank(to)); int f_from = static_cast<int>(file(from)); int f_to = static_cast<int>(file(to)); if (from == to) return false; if (r_from == r_to) return r == r_from; if (f_from == f_to) return f == f_from; if ((f_from - r_from) == (f_to - r_to)) return (f - r) == (f_to - r_to); if ((f_from + r_from) == (f_to + r_to)) return (f + r) == (f_to + r_to); return false; }; check_bb(FULL_LINES[from][to], f); } } } const std::map<Direction, std::tuple<int, int, std::string>> DIRECTION_MAP = { {NORTH, { 1, 0, "north"}}, {SOUTH, {-1, 0, "south"}}, {EAST, { 0, 1, "east"}}, {WEST, { 0, -1, "west"}}, {NORTHWEST, { 1, -1, "northwest"}}, {NORTHEAST, { 1, 1, "northeast"}}, {SOUTHWEST, {-1, -1, "southwest"}}, {SOUTHEAST, {-1, 1, "southeast"}}, {DOUBLENORTH, { 2, 0, "doublenorth"}}, {DOUBLESOUTH, {-2, 0, "doublesouth"}} }; const std::vector<Bitboard> testCases = { all_squares_bb, ~all_squares_bb, white_squares_bb, black_squares_bb, rank1_bb, rank2_bb, rank3_bb, rank4_bb, rank5_bb, rank6_bb, rank7_bb, rank8_bb, fileA_bb, fileB_bb, fileC_bb, fileD_bb, fileE_bb, fileF_bb, fileG_bb, fileH_bb, NEIGHBOUR_FILES_BB[0], NEIGHBOUR_FILES_BB[1], NEIGHBOUR_FILES_BB[2], NEIGHBOUR_FILES_BB[3], NEIGHBOUR_FILES_BB[4], NEIGHBOUR_FILES_BB[5], NEIGHBOUR_FILES_BB[6], NEIGHBOUR_FILES_BB[7], middle_ranks, }; const std::vector<Direction> ALL_DIRECTIONS = { NORTH, SOUTH, EAST, WEST, NORTHEAST, NORTHWEST, SOUTHEAST, SOUTHWEST, DOUBLENORTH, DOUBLESOUTH }; class ShiftTest : public testing::TestWithParam<Direction> {}; TEST_P(ShiftTest, shift) { Direction dir = GetParam(); for (Bitboard bb : testCases) { auto f = [bb, dir](int x, int y) { int px = x - std::get<0>(DIRECTION_MAP.at(dir)); int py = y - std::get<1>(DIRECTION_MAP.at(dir)); if (px >= 0 && px < 8 && py >= 0 && py < 8) return bool(bb & square_bb(make_square(Rank(px), File(py)))); return false; }; check_bb(shift(bb, dir), f); } } INSTANTIATE_TEST_SUITE_P(Test, ShiftTest, testing::ValuesIn(ALL_DIRECTIONS), [](const testing::TestParamInfo<ShiftTest::ParamType>& info){ return std::get<2>(DIRECTION_MAP.at(info.param)); });
28.164557
122
0.499775
[ "vector" ]
d158f3401f3d09cacaac038f0904a31a89675557
726
hpp
C++
Magic_Recode/Header++/Includes.hpp
wasdasf/Magic
9ecbc8ea194b01ecd68b6ea77a4d2b6cc506857e
[ "Unlicense" ]
null
null
null
Magic_Recode/Header++/Includes.hpp
wasdasf/Magic
9ecbc8ea194b01ecd68b6ea77a4d2b6cc506857e
[ "Unlicense" ]
null
null
null
Magic_Recode/Header++/Includes.hpp
wasdasf/Magic
9ecbc8ea194b01ecd68b6ea77a4d2b6cc506857e
[ "Unlicense" ]
null
null
null
#pragma once #include <d3d9.h> #include "Redirection_Manager.hpp" #include "Byte_Manager.hpp" #include "Menu_Select.hpp" #include "Controller_Move.hpp" #include <vector> #include <cmath> #include "Copy_User_Command.hpp" #include "Client_Send_Move.hpp" #include "Write_User_Command_Delta_To_Buffer.hpp" #include "Physics_Simulate.hpp" #include <cstdio> #include "Chat_Print_Formatted.hpp" #include "imgui.h" #include "imgui_impl_dx9.h" #include "imgui_impl_win32.h" IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #include "Immediate_Mode_Graphical_User_Interface.hpp" #include "Window_Procedure.hpp" #include "Zydis/Zydis.h" #include "Present.hpp"
16.883721
105
0.783747
[ "vector" ]
d159d837a35801b9d8b7c7c486087089babe9dcd
10,647
cpp
C++
packages/python/pyfora/src/PyObjectUtils.cpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
packages/python/pyfora/src/PyObjectUtils.cpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
packages/python/pyfora/src/PyObjectUtils.cpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2016 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #include "PyObjectUtils.hpp" #include <sstream> #include <stdexcept> std::string PyObjectUtils::repr_string(PyObject* obj) { PyObject* obj_repr = PyObject_Repr(obj); if (obj_repr == nullptr) { throw std::runtime_error( "py err in PyObjectUtils::repr_string: " + PyObjectUtils::format_exc() ); } if (not PyString_Check(obj_repr)) { throw std::runtime_error( "error in PyObjectUtils::repr_string: repr returned a non string" ); } std::string tr = std::string( PyString_AS_STRING(obj_repr), PyString_GET_SIZE(obj_repr) ); Py_DECREF(obj_repr); return tr; } std::string PyObjectUtils::str_string(PyObject* obj) { PyObject* obj_str = PyObject_Str(obj); if (obj_str == nullptr) { throw std::runtime_error( "py err in PyObjectUtils::str_string: " + PyObjectUtils::format_exc() ); } if (not PyString_Check(obj_str)) { throw std::runtime_error( "error in PyObjectUtils::str_string: repr returned a non string" ); } std::string tr = std::string( PyString_AS_STRING(obj_str), PyString_GET_SIZE(obj_str) ); Py_DECREF(obj_str); return tr; } std::string PyObjectUtils::std_string(PyObject* string) { if (PyString_Check(string)) { return std::string( PyString_AS_STRING(string), PyString_GET_SIZE(string) ); } else if (PyUnicode_Check(string)) { PyObject* s = PyUnicode_AsASCIIString(string); if (s == nullptr) { throw std::runtime_error( "couldn't get an ascii string from a unicode string: " + PyObjectUtils::exc_string() ); } std::string tr = std::string( PyString_AS_STRING(s), PyString_GET_SIZE(s) ); Py_DECREF(s); return tr; } else { throw std::runtime_error("expected a string or unicode object"); } } std::string PyObjectUtils::format_exc() { PyObject * exception = nullptr, * v = nullptr, * tb = nullptr; PyErr_Fetch(&exception, &v, &tb); if (exception == nullptr) { return "<no exception>"; } PyErr_NormalizeException(&exception, &v, &tb); PyObject* typeString = PyObject_Str(exception); Py_DECREF(exception); if (typeString == nullptr) { Py_XDECREF(tb); Py_XDECREF(v); return "<INTERNAL ERROR: couldn't get typeString in PyObjectUtils::format_exc>"; } if (not PyString_Check(typeString)) { Py_DECREF(typeString); Py_XDECREF(tb); Py_XDECREF(v); return "<INTERNAL ERROR: str(exception) didn't return a string in" " PyObjectUtils::format_exc"; } if (v == nullptr) { Py_DECREF(typeString); Py_XDECREF(tb); return "<v unexpectedly none in PyObjectUtils::format_exc>"; } PyObject* valueString = PyObject_Str(v); Py_DECREF(v); if (valueString == nullptr) { Py_DECREF(typeString); Py_XDECREF(tb); return "<INTERNAL ERROR: couldn't get value string>"; } if (not PyString_Check(valueString)) { Py_DECREF(valueString); Py_DECREF(typeString); Py_XDECREF(tb); return "<INTERNAL ERROR: str(v) didn't return a string!>"; } PyObject* cStringIOModule = PyImport_ImportModule("cStringIO"); if (cStringIOModule == nullptr) { Py_DECREF(valueString); Py_DECREF(typeString); Py_XDECREF(tb); throw std::runtime_error( "py error importing cStringIO module: " + PyObjectUtils::exc_string() ); } PyObject* StringIOClass = PyObject_GetAttrString( cStringIOModule, "StringIO"); Py_DECREF(cStringIOModule); if (StringIOClass == nullptr) { Py_DECREF(valueString); Py_DECREF(typeString); Py_XDECREF(tb); throw std::runtime_error( "py error getting StringIO member on cStringIO in PyObjectUtils::format_exc: " + PyObjectUtils::exc_string() ); } PyObject* stringIO = PyObject_CallFunctionObjArgs(StringIOClass, nullptr); Py_DECREF(StringIOClass); if (stringIO == nullptr) { Py_DECREF(valueString); Py_DECREF(typeString); Py_XDECREF(tb); throw std::runtime_error( "py error calling StringIO in PyObjectUtils::format_exc: " + PyObjectUtils::exc_string() ); } if (tb == nullptr) { Py_DECREF(stringIO); Py_DECREF(valueString); Py_DECREF(typeString); throw std::runtime_error( "<tb unexpectedly nullptr in PyObjectUtils::format_exc>" ); } int retcode = PyTraceBack_Print(tb, stringIO); Py_DECREF(tb); if (retcode < 0) { Py_DECREF(stringIO); Py_DECREF(valueString); Py_DECREF(typeString); throw std::runtime_error( "error calling PyTraceBack_Print in PyObjectUtils::format_exc: " + PyObjectUtils::exc_string() ); } PyObject* tb_string = PyObject_CallMethod( stringIO, const_cast<char*>("getvalue"), const_cast<char*>("()") ); Py_DECREF(stringIO); if (tb_string == nullptr) { Py_DECREF(valueString); Py_DECREF(typeString); throw std::runtime_error( "py error calling getvalue on a StringIO in PyObjectUtils::format_exc:" + PyObjectUtils::exc_string() ); } if (not PyString_Check(tb_string)) { Py_DECREF(tb_string); Py_DECREF(valueString); Py_DECREF(typeString); throw std::runtime_error("<expected getvalue to return a string>"); } std::ostringstream oss; oss.write(PyString_AS_STRING(typeString), PyString_GET_SIZE(typeString)); oss << ": "; oss.write(PyString_AS_STRING(valueString), PyString_GET_SIZE(valueString)); Py_DECREF(valueString); Py_DECREF(typeString); oss << "\n"; oss.write(PyString_AS_STRING(tb_string), PyString_GET_SIZE(tb_string)); Py_DECREF(tb_string); return oss.str(); } std::string PyObjectUtils::exc_string() { PyObject * exception = nullptr, * v = nullptr, * tb = nullptr; /* From the Python C-API documentation: PyErr_Fetch(PyObject** ptype, PyObject** value, PyObject** traceback) Retrieve the error indicator into three variables whose addresses are passed. If the error indicator is not set, set all three variables to nullptr. If it is set, it will be cleared and you own a reference to each object retrieved. The value and traceback object may be nullptr even when the type object is not. */ PyErr_Fetch(&exception, &v, &tb); if (exception == nullptr) { return "<no exception>"; } PyErr_NormalizeException(&exception, &v, &tb); Py_XDECREF(tb); PyObject* typeString = PyObject_Str(exception); Py_DECREF(exception); if (typeString == nullptr) { Py_XDECREF(v); return "<INTERNAL ERROR: couldn't get typeString>"; } if (not PyString_Check(typeString)) { Py_DECREF(typeString); Py_XDECREF(v); return "<INTERNAL ERROR: str(exception) didn't return a string!>"; } PyObject* valueString = PyObject_Str(v); Py_XDECREF(v); if (valueString == nullptr) { Py_DECREF(typeString); return "<INTERNAL ERROR: couldn't get value string>"; } if (not PyString_Check(valueString)) { Py_DECREF(valueString); Py_DECREF(typeString); return "<INTERNAL ERROR: str(v) didn't return a string!>"; } std::ostringstream oss; oss.write(PyString_AS_STRING(typeString), PyString_GET_SIZE(typeString)); oss << ": "; oss.write(PyString_AS_STRING(valueString), PyString_GET_SIZE(valueString)); Py_DECREF(valueString); Py_DECREF(typeString); return oss.str(); } long PyObjectUtils::builtin_id(const PyObject* pyObject) { PyObject* pyObject_builtin_id = PyLong_FromVoidPtr(const_cast<PyObject*>(pyObject)); if (pyObject_builtin_id == nullptr) { throw std::runtime_error( "py err in PyObjectUtils::builtin_id: " + PyObjectUtils::format_exc() ); } int overflow; long tr = PyLong_AsLongAndOverflow(pyObject_builtin_id, &overflow); Py_DECREF(pyObject_builtin_id); if (overflow != 0) { throw std::runtime_error("overflow in converting a python long to a C long"); } return tr; } bool PyObjectUtils::in(PyObject* container, PyObject* value) { if (PySet_Check(container)) { return PySet_Contains(container, value); } else if (PyDict_Check(container)) { return PyDict_Contains(container, value); } else if (PyList_Check(container)) { return _in_list(container, value); } else { throw std::runtime_error("we haven't implemented all alternatives here. " "should just call back into python." ); } } bool PyObjectUtils::_in_list(PyObject* pyList, PyObject* value) { int result; for (Py_ssize_t ix = 0; ix < PyList_GET_SIZE(pyList); ++ix) { PyObject* item = PyList_GET_ITEM(pyList, ix); if (PyObject_Cmp(value, item, &result) == -1) { throw std::runtime_error("error calling cmp"); } if (result == 0) { return true; } } return false; }
29.25
92
0.592937
[ "object" ]
d16354ec806e0fe89188e3221c5ac69154410d6d
19,199
cpp
C++
src/matrix.cpp
ivanbukhtiyarov/OpenBPS
e87e8221ff24cbb06af44a57bcac56b124575fdc
[ "BSD-3-Clause" ]
1
2021-04-01T19:54:09.000Z
2021-04-01T19:54:09.000Z
src/matrix.cpp
ivanbukhtiyarov/OpenBPS
e87e8221ff24cbb06af44a57bcac56b124575fdc
[ "BSD-3-Clause" ]
3
2020-12-08T18:04:43.000Z
2020-12-18T15:51:35.000Z
src/matrix.cpp
ivanbukhtiyarov/OpenBPS
e87e8221ff24cbb06af44a57bcac56b124575fdc
[ "BSD-3-Clause" ]
1
2020-10-01T16:39:44.000Z
2020-10-01T16:39:44.000Z
#include "openbps/matrix.h" #include <vector> #include <memory> #include <initializer_list> #include <cmath> #include "xtensor/xarray.hpp" #include "xtensor/xadapt.hpp" #include "xtensor/xview.hpp" #include "openbps/uncertainty.h" #include "openbps/functionals.h" #include "openbps/nuclide.h" #include "openbps/chain.h" #include "openbps/reactions.h" #include "openbps/materials.h" #include "openbps/configure.h" namespace openbps { //============================================================================== // Decay matrix implementation //============================================================================== //! Form a decay nuclide matrix void DecayMatrix::form_matrixreal(Chain& chain) { size_t i {0}; size_t inucl {0}; size_t k; udouble decay_ {0.0, 0.0}; //Run over all nuclides for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { inucl = it->second; // from nuclides i = chain.get_nuclide_index(it->first); if (nuclides[inucl]->half_life.Real() > 0) { decay_ = (log(2.0) / nuclides[inucl]->half_life); this->data_[i][i] = -decay_.Real(); // Cycle over all decay modes for (auto& v : nuclides[inucl]->get_decaybr()) { if (v.first != std::string("Nothing")) { // To nuclide k = chain.get_nuclide_index(v.first); this->data_[k][i] += decay_.Real() * v.second.Real(); } } } } } //! Form a deviation decay nuclide matrix void DecayMatrix::form_matrixdev(Chain& chain) { size_t i {0}; size_t inucl {0}; size_t k; udouble decay_ {0.0, 0.0}; //Run over all nuclides for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { inucl = it->second; // from nuclide i = chain.get_nuclide_index(it->first); if (nuclides[inucl]->half_life.Real() > 0) { decay_ = (log(2.0) / nuclides[inucl]->half_life); this->data_[i][i] = -decay_.Dev(); // Cycle over all decay modes for (auto& v : nuclides[inucl]->get_decaybr()) { if (v.first != std::string("Nothing")) { // To nuclide k = chain.get_nuclide_index(v.first); this->data_[k][i] += (decay_ * v.second).Dev(); } } } } } //============================================================================== // IterativeMatrix implementation //============================================================================== //! Methods //! Form a real decay nuclide matrix xt::xarray<double> IterMatrix::matrixreal(Chain& chain, const Materials& mat) { // Variables for calculation fissiop product yields by spectrum std::pair<std::vector<double>, std::vector<double>> pair2; std::vector<double> weight; size_t k {0}; // size_t NN {chain.name_idx.size()}; //!< Nuclide number std::vector<std::size_t> shape = { NN, NN }; xt::xarray<double> result(shape, 0.0); for (size_t i = 0; i < NN; i++) { std::copy(&this->data_[i][0], &this->data_[i][NN], (result.begin() + i * NN)); result(i, i) = 0.0; } int icompos {mat.numcomposition}; if (icompos > -1) { // Get neutron flux - energy value descretization pair2 = compositions[icompos]->get_fluxenergy(); for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { size_t inucl = it->second; // from nuclide size_t i = chain.get_nuclide_index(it->first); // For xslib for (auto& obj : compositions[icompos]->xslib) { // If cross section presented for nuclides if (obj.xsname == it->first) { double rr {0.0}; // Sum reaction-rates over energy group for (auto& r: obj.rxs) rr += r.Real(); // Iterate over chain nuclides transition for (auto& r : nuclides[inucl]->get_reactions()) { // If match if (r.first == obj.xstype) { if (obj.xstype != "fission") { // And non-fission then add size_t k = chain.get_nuclide_index(r.second); result(k, i) += rr * PWD * mat.normpower; } else { // Considering fission reaction by energy separately std::vector<double> energies = nuclides[inucl]->get_nfy_energies(); // Fission yields by product for (auto& item: nuclides[inucl]-> get_yield_product()) { k = chain.get_nuclide_index(item.first); double br {0.0}; double norm {0.0}; if (weight.empty()) weight = transition(pair2.first, pair2.second, energies); for (int l = 0; l < weight.size(); l++) { br += weight[l] * item.second[l]; norm += weight[l]; } // for weight result(k, i) += br / norm * rr * PWD * mat.normpower; norm = 1.0; } // for product weight.clear(); } // fission yields } // if reaction = chain.reaction } // run over reaction } // if nuclide is in crossection data and chain } // for xslib in composition } // if composition is presented } // for all nuclides return result; } //! Form a deviation decay nuclide matrix for unceratanties analysis xt::xarray<double> IterMatrix::matrixdev(Chain& chain, const Materials& mat) { // Variables for calculation fissiop product yields by spectrum std::pair<std::vector<double>, std::vector<double>> pair2; std::vector<double> weight; size_t k {0}; // size_t NN {chain.name_idx.size()}; //!< Nuclide number std::vector<std::size_t> shape = { NN, NN }; xt::xarray<double> result(shape, 0.0); for (size_t i = 0; i < NN; i++) { std::copy(&this->data_[i][0], &this->data_[i][NN], (result.begin() + i * NN)); result(i, i) = 0.0; } int icompos {mat.numcomposition}; if (icompos > -1) { // Get neutron flux - energy value descretization pair2 = compositions[icompos]->get_fluxenergy(); for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { size_t inucl = it->second; // from nuclide size_t i = chain.get_nuclide_index(it->first); // For xslib for (auto& obj : compositions[icompos]->xslib) { // If cross section presented for nuclides if (obj.xsname == it->first) { double rr {0.0}; // Sum reaction-rates over energy group for (auto& r: obj.rxs) rr += r.Dev(); // Iterate over chain nuclides transition for (auto& r : nuclides[inucl]->get_reactions()) { // If match if (r.first == obj.xstype) { if (obj.xstype != "fission") { // And non-fission then add size_t k = chain.get_nuclide_index(r.second); result(k, i) += rr * PWD * mat.normpower; } else { // Considering fission reaction by energy separately std::vector<double> energies = nuclides[inucl]->get_nfy_energies(); // Fission yields by product for (auto& item: nuclides[inucl]-> get_yield_product()) { k = chain.get_nuclide_index(item.first); double br {0.0}; double norm {0.0}; if (weight.empty()) weight = transition(pair2.first, pair2.second, energies); for (int l = 0; l < weight.size(); l++) { br += weight[l] * item.second[l]; norm += weight[l]; } // for weight result(k, i) += br / norm * rr * PWD * mat.normpower; norm = 1.0; } // for product weight.clear(); } // fission yields } // if reaction = chain.reaction } // run over reaction } // if nuclide is in crossection data and chain } // for xslib in composition } // if composition is presented } // for all nuclides return result; } //! Form a dev decay nuclide vector for all transition from every nuclide xt::xarray<double> IterMatrix::sigp(Chain& chain, const Materials& mat) { std::vector<size_t> shape {chain.name_idx.size()}; xt::xarray<double> result(shape, 0.0); udouble decay_ {0.0, 0.0}; //Run over all nuclides if (configure::verbose) std::cout << "SIGP: "<<std::endl; for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { size_t inucl = it->second; // from nuclide size_t i = chain.get_nuclide_index(it->first); if (nuclides[inucl]->half_life.Real() > 0) { decay_ = (log(2.0) / nuclides[inucl]->half_life); result(i) = decay_.Real(); } int icompos {mat.numcomposition}; if (icompos > -1) { // For xslib for (auto& obj : compositions[icompos]->xslib) { // If cross section presented for nuclides if (obj.xsname == it->first) { double rr {0.0}; // Sum reaction-rates over energy group for (auto& r: obj.rxs) rr += r.Real(); result(i) += rr * PWD * mat.normpower; } } } if (configure::verbose) std::cout << "sigp: " << it->first << " " << result(i)<<std::endl; } return result; } //! Form a dev decay nuclide vector for all transition from every nuclide xt::xarray<double> IterMatrix::dsigp(Chain& chain, const Materials& mat) { std::vector<size_t> shape {chain.name_idx.size()}; xt::xarray<double> result(shape, 0.0); udouble decay_ {0.0, 0.0}; //Run over all nuclides for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { size_t inucl = it->second; // from nuclide size_t i = chain.get_nuclide_index(it->first); if (nuclides[inucl]->half_life.Real() > 0) { decay_ = (log(2.0) / nuclides[inucl]->half_life); result(i) = decay_.Dev(); } int icompos {mat.numcomposition}; if (icompos > -1) { // For xslib for (auto& obj : compositions[icompos]->xslib) { // If cross section presented for nuclides if (obj.xsname == it->first) { double rr {0.0}; // Sum reaction-rates over energy group for (auto& r: obj.rxs) rr += r.Dev(); result(i) += rr * PWD * mat.normpower; } } } } return result; } //============================================================================== // ChebyshevMatrix implementation //============================================================================== //! Form a real decay nuclide matrix xt::xarray<double> CramMatrix::matrixreal(Chain& chain, const Materials& mat) { // Variables for calculation fissiop product yields by spectrum std::pair<std::vector<double>, std::vector<double>> pair2; std::vector<double> weight; size_t k {0}; // size_t NN {chain.name_idx.size()}; //!< Nuclide number std::vector<std::size_t> shape = { NN, NN }; xt::xarray<double> result(shape, 0.0); for (size_t i = 0; i < NN; i++) std::copy(&this->data_[i][0], &this->data_[i][NN], (result.begin() + i * NN)); int icompos {mat.numcomposition}; if (icompos > -1) { // Get neutron flux - energy value descretization pair2 = compositions[icompos]->get_fluxenergy(); for (auto it = chain.name_idx.begin(); it != chain.name_idx.end(); it++) { size_t inucl = it->second; // from nuclide size_t i = chain.get_nuclide_index(it->first); // For xslib for (auto& obj : compositions[icompos]->xslib) { // If cross section presented for nuclides if (obj.xsname == it->first) { double rr {0.0}; // Sum reaction-rates over energy group for (auto& r: obj.rxs) rr += r.Real(); // Iterate over chain nuclides transition for (auto& r : nuclides[inucl]->get_reactions()) { // If match if (r.first == obj.xstype) { if (obj.xstype != "fission") { // And non-fission then add size_t k = chain.get_nuclide_index(r.second); result(k, i) += rr * PWD * mat.normpower; } else { // Considering fission reaction by energy separately std::vector<double> energies = nuclides[inucl]->get_nfy_energies(); // Fission yields by product for (auto& item: nuclides[inucl]-> get_yield_product()) { k = chain.get_nuclide_index(item.first); double br {0.0}; double norm {0.0}; if (weight.empty()) weight = transition(pair2.first, pair2.second, energies); for (int l = 0; l < weight.size(); l++) { br += weight[l] * item.second[l]; norm += weight[l]; } // for weight result(k, i) += br / norm * rr * PWD * mat.normpower; norm = 1.0; } // for product weight.clear(); } // fission yields } // if reaction = chain.reaction } // run over reaction result(i, i) -= rr * PWD * mat.normpower; } // if nuclide is in crossection data and chain } // for xslib in composition } // if composition is presented } // for all nuclides return result; } //============================================================================== // Non class methods //============================================================================== //! Get a concentration vector according to chain nuclide list xt::xarray<double> make_concentration(Chain& chainer, const std::vector<std::string>& nameconc, const std::vector<udouble>& ro, bool isDev) { xt::xarray<size_t>::shape_type shape = {chainer.name_idx.size()}; xt::xarray<double> result = xt::zeros<double>(shape); for (size_t i = 0; i < ro.size(); i++) { if (std::find_if(chainer.name_idx.begin(), chainer.name_idx.end(), [&] (std::pair<std::string, size_t> item){ return nameconc[i] == item.first;}) != chainer.name_idx.end()) { if (isDev) { result[chainer.get_nuclide_index(nameconc[i])] = ro[i].Dev(); } else { result[chainer.get_nuclide_index(nameconc[i])] = ro[i].Real(); } } } return result; } //! Find out power normalization coefficient to reaction-rate void power_normalization(Materials& mat) { double R {0.0}; for (size_t i = 0; i < mat.conc.size(); i++) { auto search = std::find_if(nuclides.begin(), nuclides.end(), [&mat, i](std::unique_ptr<ChainNuclide>& item) { return item->name_ == mat.namenuclides[i];}); if (search != nuclides.end()) { if (mat.numcomposition > -1) { for (auto& obj : compositions[mat.numcomposition]->xslib) { if (obj.xsname == mat.namenuclides[i]) { size_t index = std::distance(nuclides.begin(), search); auto releases = nuclides[index]->get_qvalue(); if (releases.find(obj.xstype) != releases.end()) { double rr {0.0}; // Sum reaction-rates over energy group for (auto& r: obj.rxs) rr += r.Real(); R += rr * releases[obj.xstype] * mat.conc[i].Real();//eV or Mev } } } } } } if (R > 0 && mat.Volume() > 0.0) { mat.normpower = mat.Power() * PWRC / (R * mat.Volume()); } } } //namespace openbps
43.436652
82
0.434762
[ "shape", "vector" ]
d1723408d96012d59998d394fb3a340a4cd72cfc
40,854
cc
C++
src/formats/cnf.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
4
2015-03-08T07:56:29.000Z
2017-10-12T04:19:27.000Z
src/formats/cnf.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
null
null
null
src/formats/cnf.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
null
null
null
/* =========FOR INTERNAL USE ONLY. NO DISTRIBUTION PLEASE ========== */ /********************************************************************* Copyright 1999-2007, University of Cincinnati. All rights reserved. By using this software the USER indicates that he or she has read, understood and will comply with the following: --- University of Cincinnati hereby grants USER nonexclusive permission to use, copy and/or modify this software for internal, noncommercial, research purposes only. Any distribution, including commercial sale or license, of this software, copies of the software, its associated documentation and/or modifications of either is strictly prohibited without the prior consent of University of Cincinnati. Title to copyright to this software and its associated documentation shall at all times remain with University of Cincinnati. Appropriate copyright notice shall be placed on all software copies, and a complete copy of this notice shall be included in all copies of the associated documentation. No right is granted to use in advertising, publicity or otherwise any trademark, service mark, or the name of University of Cincinnati. --- This software and any associated documentation is provided "as is" UNIVERSITY OF CINCINNATI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT USE OF THE SOFTWARE, MODIFICATIONS, OR ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY. University of Cincinnati shall not be liable under any circumstances for any direct, indirect, special, incidental, or consequential damages with respect to any claim by USER or any third party on account of or arising from the use, or inability to use, this software or its associated documentation, even if University of Cincinnati has been advised of the possibility of those damages. *********************************************************************/ /********************************************************************** * cnf.c (S. Weaver) * Routines for converting from CNF to BDD and from DNF to CNF **********************************************************************/ #include "sbsat.h" #include "sbsat_formats.h" #define CNF_USES_SYMTABLE //#define PRINT_FACTOR_GRAPH int nNumClauses = 0; int nNumCNFVariables = 0; void cnf_process(Clause *pClauses); void free_clauses(Clause *pClauses) { for(int x = 0; x < nNumClauses; x++) { if(pClauses[x].variables != NULL) ite_free((void **)&pClauses[x].variables); } ite_free((void **)&pClauses); } //From M. Heule int clscompfunc(const void *x, const void *y) { Clause pp, qq; pp = *(const Clause *)x; qq = *(const Clause *)y; //Compare the lengths of the clauses. if(pp.length != qq.length ) return (pp.length < qq.length ? -1 : 1); //The lengths of pp and qq are the same. //Now take a look at the variables in the clauses. for(int i = 0; i < pp.length; i++) if(abs(pp.variables[i]) != abs(qq.variables[i])) return (abs(pp.variables[i]) < abs(qq.variables[i]) ? -1 : 1); //If the two clauses contain the same variables, then consider the //literals and compare again. ( So, no abs() is used here ). This is done to make //removal of duplets easy. for(int i = 0; i < pp.length; i++) if(pp.variables[i] != qq.variables[i]) return (pp.variables[i] < qq.variables[i] ? -1 : 1); //Default value if all are equal. ( Thus a duplet... ) #ifndef FORCE_STABLE_QSORT return 0; #else { if (x < y) return -1; else if (x > y) return 1; else return 0; } #endif return 1; } void print_factor_graph(Clause *pClauses) { fprintf(foutputfile, "graph FactorGraph {\n"); // fprintf(foutputfile, "graph [concentrate=true, fontname=ArialMT, nodesep=\"0.30\", ordering=in, rankdir=TB, ranksep=\"2.50\"];\n"); fprintf(foutputfile, "graph [overlap=false,sep=1.5,size=\"8,8\"];\n"); fprintf(foutputfile, "edge [len=1.5];\n"); for(int x = 1; x <= nNumCNFVariables; x++) fprintf(foutputfile, "%d [shape=circle,fontname=Helvetica];\n", x); for(int x = 0; x < nNumClauses; x++) { if(pClauses[x].subsumed) continue; // fprintf(foutputfile, "subgraph sg%x{\n", x); fprintf(foutputfile, "%d [width=0.15,height=0.15,shape=circle,style=filled,fillcolor=black,label=\"\"];\n", x+nNumCNFVariables+1); for(int y = 0; y < pClauses[x].length; y++) { if(pClauses[x].variables[y] > 0) fprintf(foutputfile, "%d -- %d [style=solid,fontname=Helvetica,fontsize=8];\n", x+nNumCNFVariables+1, pClauses[x].variables[y]); else fprintf(foutputfile, "%d -- %d [style=dashed,fontname=Helvetica,fontsize=8];\n", x+nNumCNFVariables+1, -pClauses[x].variables[y]); } // fprintf(foutputfile, "}\n"); } fprintf(foutputfile, "}\n"); } int getNextSymbol_CNF (int *intnum) { int p = 0; while(1) { p = fgetc(finputfile); if(p == EOF) return ERR_IO_READ; else if(((p >= '0') && (p <= '9')) || (p == '-')) { ungetc(p, finputfile); if(fscanf(finputfile, "%d", &(*intnum)) != 1) return ERR_IO_UNEXPECTED_CHAR; d9_printf2("%d", (*intnum)); return NO_ERROR; } else if(p == 'c') { while(p != '\n') { d9_printf2("%c", p); p = fgetc(finputfile); if(p == EOF) return ERR_IO_READ; } d9_printf2("%c", p); p = fgetc(finputfile); if (p == EOF) return ERR_IO_READ; ungetc(p, finputfile); continue; } else if(p == 'p') { d9_printf2("%c", p); return IO_CNF_HEADER; } else if(p >='A' && p<='z') { d9_printf2("%c", p); return ERR_IO_UNEXPECTED_CHAR; } d9_printf2("%c", p); } } int CNF_to_BDD() { //Global variables used in this function: // int nNumCNFVariables, int nNumClauses if(feof(finputfile)) return ERR_IO_READ; int next_symbol; int ret = NO_ERROR; if (int i = fscanf(finputfile, "%d %d\n", &nNumCNFVariables, &nNumClauses) != 2) { fprintf(stderr, "Error while parsing CNF input: bad header %d %d %d\n", i, nNumCNFVariables, nNumClauses); exit(1); } d9_printf3(" cnf %d %d\n", nNumCNFVariables, nNumClauses); int nOrigNumClauses = nNumClauses; #ifdef CNF_USES_SYMTABLE create_all_syms(nNumCNFVariables); #endif Clause *pClauses = (Clause*)ite_calloc(nNumClauses, sizeof(Clause), 9, "read_cnf()::pClauses"); int tempint_max = 100; int *tempint = (int *)ite_calloc(tempint_max, sizeof(int *), 9, "read_cnf()::tempint"); //Get and store the CNF clauses int print_variable_warning = 1; int x = 0; while(1) { if (x%10000 == 0) { d2_printf3("\rReading CNF %d/%d ... ", x, nNumClauses); } ret = getNextSymbol_CNF(&next_symbol); if(ret == ERR_IO_UNEXPECTED_CHAR) { fprintf(stderr, "Error while parsing CNF input: Clause %d\n", x); return ret; } if (x == nNumClauses) { //Should be done reading CNF if (ret == ERR_IO_READ) break; //CNF has been fully read in if (next_symbol == 0) break; //Extra 0 at end of file fprintf(stderr, "Warning while parsing CNF input: more than %d functions found\n", nOrigNumClauses); break; } if (ret != NO_ERROR) { fprintf(stderr, "Error while parsing CNF input: premature end of file, only %d functions found\n", x); return ret; } else { int y = 0; while(1) { if (next_symbol == 0) break; //Clause has been terminated if (y >= tempint_max) { tempint = (int*)ite_recalloc((void*)tempint, tempint_max, tempint_max+100, sizeof(int), 9, "read_cnf()::tempint"); tempint_max += 100; } //#ifdef CNF_USES_SYMTABLE // tempint[y] = i_getsym_int(next_symbol, SYM_VAR); //#else tempint[y] = next_symbol; //#endif if(abs(tempint[y]) > nNumCNFVariables) { if(print_variable_warning) { d2e_printf1("Warning while parsing CNF input: There are more variables in input file than specified\n"); print_variable_warning = 0; } nNumCNFVariables = abs(tempint[y]); #ifdef CNF_USES_SYMTABLE create_all_syms(nNumCNFVariables); #endif } ret = getNextSymbol_CNF(&next_symbol); if (ret != NO_ERROR) { fprintf(stderr, "Error while parsing CNF input: Clause %d\n", x); return ret; } y++; } if(y==0) continue; //A '0' line -- no clause pClauses[x].length = y; pClauses[x].variables = (int *)malloc(y * sizeof(int)); pClauses[x].subsumed = 0; pClauses[x].flag = -1; memcpy_ite(pClauses[x].variables, tempint, y*sizeof(int)); x++; } } d2_printf3("\rReading CNF %d/%d \n", nNumClauses, nNumClauses); cnf_process(pClauses); ite_free((void **)&tempint); tempint_max = 0; dX_printf(3, "Number of BDDs - %d\n", nmbrFunctions); free_clauses(pClauses); return NO_ERROR; } void reduce_clauses(Clause *pClauses) { //Mark duplicate clauses for(int x = 0; x < nNumClauses-1; x++) { int isdup = 0; if(pClauses[x].length == pClauses[x+1].length) { isdup = 1; for(int y = 0; y < pClauses[x].length; y++) { if(pClauses[x].variables[y] != pClauses[x+1].variables[y]) { isdup = 0; break; } } } if(isdup == 1) { pClauses[x+1].subsumed = 1; } } //Remove subsumed clauses int subs = 0; for(int x = 0; x < nNumClauses; x++) { pClauses[x].length = pClauses[x+subs].length; pClauses[x].variables = pClauses[x+subs].variables; pClauses[x].subsumed = pClauses[x+subs].subsumed; if(pClauses[x+subs].subsumed == 1) { pClauses[x+subs].length = 0; ite_free((void **)&pClauses[x+subs].variables); pClauses[x+subs].variables = NULL; subs++;x--;nNumClauses--;continue; } } d2_printf2("Simplify removed %d clauses\n", subs); } void build_clause_BDDs(Clause *pClauses) { for(int x = 0; x < nNumClauses; x++) { if (x%1000 == 0) d2_printf3("\rBuilding clause BDDs %d/%d ... ", x, nNumClauses); //qsort(pClauses[x].variables, pClauses[x].length, sizeof(int), abscompfunc); //This is done above //qsort(pClauses[x].variables, pClauses[x].length, sizeof(int), absrevcompfunc); BDDNode *pOrBDD = false_ptr; for(int y = 0; y < pClauses[x].length; y++) { pOrBDD = ite_or(pOrBDD, ite_var(pClauses[x].variables[y])); } functions_add(pOrBDD, PLAINOR, 0); pClauses[x].subsumed = 1; } d2_printf2("\rBuilt %d clause BDDs \n", nNumClauses); } void find_and_build_xors(Clause *pClauses) { //Search for XORs - This code designed after a snippet of march_dl by M. Heule int xors_found = 0; for(int x = 0; x < nNumClauses; x++) { assert(pClauses[x].length > 0); if(pClauses[x].length>1) { int domain = 1<<(pClauses[x].length-1); if(domain<=1) break; if(domain+x > nNumClauses) break; int cont = 0; for(int y = 1; y < domain; y++) if(pClauses[x+y].length != pClauses[x].length) { x += (y-1); cont = 1; break; } if(cont == 1) continue; for(int y = 0; y < pClauses[x].length; y++) if(abs(pClauses[x].variables[y]) != abs(pClauses[x+domain-1].variables[y])) { cont = 1; break; } if(cont == 1) continue; int sign = 1; for(int y = 0; y < pClauses[x].length; y++) sign *= pClauses[x].variables[y] < 0 ? -1 : 1; for(int y = 1; y < domain; y++) { //Safety check - probably not needed int tmp = 1; for(int z = 0; z < pClauses[x+y].length; z++) //pClauses[x+y].length == pClauses[x].length tmp *= pClauses[x+y].variables[z] < 0 ? -1 : 1; if(tmp != sign) { cont = 1; break; } } if(cont == 1) continue; xors_found++; BDDNode *pXorBDD = false_ptr; for(int y = 0; y < pClauses[x].length; y++) { pXorBDD = ite_xor(pXorBDD, ite_var(pClauses[x].variables[y])); } functions_add(pXorBDD, PLAINXOR, 0); for(int y = 0; y < domain; y++) pClauses[x+y].subsumed = 1; x += domain-1; } } d2_printf2("Found %d XOR functions\n", xors_found); } uint8_t find_and_build_andequals(Clause *pClauses) { //Search for AND= and OR= int *twopos_temp = (int *)ite_calloc(nNumCNFVariables+1, sizeof(int), 9, "twopos_temp"); int *twoneg_temp = (int *)ite_calloc(nNumCNFVariables+1, sizeof(int), 9, "twoneg_temp"); for(int x = 0; x < nNumClauses; x++) { if(pClauses[x].length == 2) { for(int y = 0; y < 2; y++) { if(pClauses[x].variables[y] > 0) twopos_temp[pClauses[x].variables[y]]++; else twoneg_temp[-pClauses[x].variables[y]]++; } } else if(pClauses[x].length > 2) break; //Relies on clauses being sorted } store *two_pos = (store *)ite_calloc(nNumCNFVariables+1, sizeof(store), 9, "two_pos"); store *two_neg = (store *)ite_calloc(nNumCNFVariables+1, sizeof(store), 9, "two_neg"); //two_pos and two_neg are lists that contain all the clauses //that are of length 2. two_pos contains every 2 variable clause //that has a positive variable, two_neg contains every 2 //variable clause that has a negative variable. There will most likely //be some overlaps in the variable storing. //EX) //p cnf 3 3 //2 3 0 //-2 -3 0 //-2 3 0 // //two_pos will point to (2:3) and (-2:3) //two_neg will point to (-2:-3) and (-2:3) //Storing appropriate array sizes... for(int x = 1; x <= nNumCNFVariables; x++) { two_pos[x].num = (int *)ite_calloc(2*twopos_temp[x], sizeof(int), 9, "two_pos[x].num"); two_neg[x].num = (int *)ite_calloc(2*twoneg_temp[x], sizeof(int), 9, "two_neg[x].num"); } ite_free((void **)&twopos_temp); ite_free((void **)&twoneg_temp); //This is where two_pos, two_neg are filled with clauses for(int x = 0; x < nNumClauses; x++) { if(pClauses[x].length == 2) { if(pClauses[x].variables[0] > 0) { int y = two_pos[pClauses[x].variables[0]].length; two_pos[pClauses[x].variables[0]].num[y] = pClauses[x].variables[1]; two_pos[pClauses[x].variables[0]].num[y+1] = x; two_pos[pClauses[x].variables[0]].length+=2; } else { int y = two_neg[-pClauses[x].variables[0]].length; two_neg[-pClauses[x].variables[0]].num[y] = pClauses[x].variables[1]; two_neg[-pClauses[x].variables[0]].num[y+1] = x; two_neg[-pClauses[x].variables[0]].length+=2; } if(pClauses[x].variables[1] > 0) { int y = two_pos[pClauses[x].variables[1]].length; two_pos[pClauses[x].variables[1]].num[y] = pClauses[x].variables[0]; two_pos[pClauses[x].variables[1]].num[y+1] = x; two_pos[pClauses[x].variables[1]].length+=2; } else { int y = two_neg[-pClauses[x].variables[1]].length; two_neg[-pClauses[x].variables[1]].num[y] = pClauses[x].variables[0]; two_neg[-pClauses[x].variables[1]].num[y+1] = x; two_neg[-pClauses[x].variables[1]].length+=2; } } else if(pClauses[x].length > 2) break; //Relies on clauses being sorted } int num_andequals_found = 0; uint8_t find_all = 1; //For all clauses greater than length 2 for(int x = 0; x < nNumClauses; x++) { if (x%1000 == 1) dX_printf(4, "\rAND/OR Search CNF %d/%d ... ", x, nNumClauses); if(pClauses[x].length <= 2) continue; //For each variable in clause x for(int y = 0; y < pClauses[x].length; y++) { //See if the 2-clauses cover clause x on variable v = pClauses[x].variables[y] intmax_t v = pClauses[x].variables[y]; intmax_t vabs = imaxabs(v); store *two_v = (v==vabs) ? two_neg : two_pos; if(two_v[vabs].length < pClauses[x].length-1) continue; uint8_t out = 0; int x_pos = 0; int v_pos = 0; while((out==0) && (x_pos < pClauses[x].length)) { if(x_pos == y) { x_pos++; } else if(v_pos >= two_v[vabs].length) { break; } else if(pClauses[x].variables[x_pos] == -(intmax_t)two_v[vabs].num[v_pos]) { x_pos++; v_pos+=2; } else if(imaxabs(pClauses[x].variables[x_pos]) > imaxabs((intmax_t)two_v[vabs].num[v_pos])) { v_pos+=2; } else { out=1; } } if((out==0) && (x_pos == pClauses[x].length)) { num_andequals_found++; pClauses[x].subsumed = 1; x_pos = 0; v_pos = 0; while((x_pos < pClauses[x].length) && (v_pos < two_v[vabs].length)) { if(x_pos == y) { x_pos++; } else if(pClauses[x].variables[x_pos] == -(intmax_t)two_v[vabs].num[v_pos]) { x_pos++; pClauses[two_v[vabs].num[v_pos+1]].subsumed = 1; v_pos+=2;} else if(imaxabs(pClauses[x].variables[x_pos]) > imaxabs((intmax_t)two_v[vabs].num[v_pos])) { v_pos+=2; } } if(v==vabs) { //Must negate the list BDDNode *pAndEqBDD = true_ptr; for(int z = 0; z < pClauses[x].length; z++) { if(pClauses[x].variables[z] != v) pAndEqBDD = ite_and(pAndEqBDD, ite_var(-pClauses[x].variables[z])); } pAndEqBDD = ite_equ(ite_var(v), pAndEqBDD); functions_add(pAndEqBDD, AND_EQU, v); independantVars[v] = 0; } else { BDDNode *pOrEqBDD = false_ptr; for(int z = 0; z < pClauses[x].length; z++) { if(pClauses[x].variables[z] != v) pOrEqBDD = ite_or(pOrEqBDD, ite_var(pClauses[x].variables[z])); } pOrEqBDD = ite_equ(ite_var(vabs), pOrEqBDD); functions_add(pOrEqBDD, OR_EQU, vabs); independantVars[vabs] = 0; } if(find_all==0) break; } } } //Not needed anymore, free them! for(int x = 1; x < nNumCNFVariables + 1; x++) { ite_free((void **)&two_pos[x].num); ite_free((void **)&two_neg[x].num); } ite_free((void **)&two_pos); ite_free((void **)&two_neg); d2_printf2("\rFound %d AND=/OR= functions \n", num_andequals_found); return num_andequals_found; } void find_and_build_iteequals(Clause *pClauses) { int num_iteequals_found = 0; int *threepos_temp = (int *)ite_calloc(nNumCNFVariables+1, sizeof(int), 9, "threepos_temp"); int *threeneg_temp = (int *)ite_calloc(nNumCNFVariables+1, sizeof(int), 9, "threeneg_temp"); for(int x = 0; x < nNumClauses; x++) { int y = pClauses[x].length; if(y == 3) { for(y = 0; y < 3; y++) { if(pClauses[x].variables[y] > 0) threepos_temp[pClauses[x].variables[y]]++; else threeneg_temp[-pClauses[x].variables[y]]++; } } } store *three_pos = (store *)ite_calloc(nNumCNFVariables+1, sizeof(store), 9, "three_pos"); store *three_neg = (store *)ite_calloc(nNumCNFVariables+1, sizeof(store), 9, "three_neg"); //Store appropriate array sizes to help with memory usage for(int x = 1; x < nNumCNFVariables+1; x++) { three_pos[x].num = (int *)ite_calloc(threepos_temp[x], sizeof(int), 9, "three_pos[x].num"); three_neg[x].num = (int *)ite_calloc(threeneg_temp[x], sizeof(int), 9, "three_neg[x].num"); } ite_free((void **)&threepos_temp); ite_free((void **)&threeneg_temp); //Store all clauses with 3 variables so they can be clustered int count = 0; for(int x = 0; x < nNumClauses; x++) { if(pClauses[x].length == 3) { count++; for(int i = 0; i < 3; i++) { if(pClauses[x].variables[i] < 0) { three_neg[-pClauses[x].variables[i]].num[three_neg[-pClauses[x].variables[i]].length] = x; three_neg[-pClauses[x].variables[i]].length++; } else { three_pos[pClauses[x].variables[i]].num[three_pos[pClauses[x].variables[i]].length] = x; three_pos[pClauses[x].variables[i]].length++; } } } } //v3 is in all clauses //if v0 is positive, both v0 positive clauses have v2, just sign changed //if v0 is negative, both v0 negative clauses have v1, just sign changed //the signs of v1 and v2 are the inverse of the sign of v3 struct ite_3 { int pos; int neg; int v0; int v1; }; int v3_1size = 1000; int v3_2size = 1000; ite_3 *v3_1 = (ite_3 *)ite_calloc(v3_1size, sizeof(ite_3), 9, "v3_1"); ite_3 *v3_2 = (ite_3 *)ite_calloc(v3_2size, sizeof(ite_3), 9, "v3_2"); int v3_1count; int v3_2count; for(int x = 0; x < nNumCNFVariables+1; x++) { v3_1count = 0; v3_2count = 0; for(int i = 0; i < three_pos[x].length; i++) { //Finding clauses that have 1 negative variable //and clauses that have 2 negative variables count = 0; for(int y = 0; y < 3; y++) { if(pClauses[three_pos[x].num[i]].variables[y] < 0) count++; } if(count == 1) { v3_1[v3_1count].pos = three_pos[x].num[i]; v3_1count++; if(v3_1count > v3_1size) { v3_1 = (ite_3 *)ite_recalloc((void*)v3_1, v3_1size, v3_1size+1000, sizeof(ite_3), 9, "v3_1 recalloc"); v3_1size+=1000; } } else if(count == 2) { v3_2[v3_2count].pos = three_pos[x].num[i]; v3_2count++; if(v3_2count > v3_2size) { v3_2 = (ite_3 *)ite_recalloc((void*)v3_2, v3_2size, v3_2size+1000, sizeof(ite_3), 9, "v3_2 recalloc"); v3_2size+=1000; } } } //Search through the clauses with 1 negative variable // and try to find counterparts for(int i = 0; i < v3_1count; i++) { int out = 0; for(int y = 0; (y < three_neg[x].length) && (!out); y++) { v3_1[i].v0 = -1; v3_1[i].v1 = -1; count = 0; for(int z = 0; z < 3; z++) { if(pClauses[v3_1[i].pos].variables[z] != x) { for(int j = 0; j < 3; j++) { if((pClauses[v3_1[i].pos].variables[z] == pClauses[three_neg[x].num[y]].variables[j]) &&(pClauses[v3_1[i].pos].variables[z] > 0)) { count++; v3_1[i].v0 = z; } else if(-pClauses[v3_1[i].pos].variables[z] == pClauses[three_neg[x].num[y]].variables[j]) //&&(pClauses[v3_1[i].pos].variables[z]<0)) { count++; v3_1[i].v1 = z; } } } } if(count == 2) { //The counterpart clause to v3_1[i].pos is v3_1[i].neg v3_1[i].neg = three_neg[x].num[y]; out = 1; } } if(out == 0) { v3_1[i].v0 = -1; v3_1[i].v1 = -1; } } //Search through the clauses with 2 negative variables for(int i = 0; i < v3_2count; i++) { int out = 0; for(int y = 0; (y < three_neg[x].length) && (!out); y++) { v3_2[i].v0 = -1; v3_2[i].v1 = -1; count = 0; for(int z = 0; z < 3; z++) { if(pClauses[v3_2[i].pos].variables[z] != x) { for(int j = 0; j < 3; j++) { if((pClauses[v3_2[i].pos].variables[z] == pClauses[three_neg[x].num[y]].variables[j]) &&(pClauses[v3_2[i].pos].variables[z] < 0)) { count++; v3_2[i].v0 = z; } else if(-pClauses[v3_2[i].pos].variables[z] == pClauses[three_neg[x].num[y]].variables[j]) //&&(-pClauses[v3_2[i].pos].variables[z]>0)); { count++; v3_2[i].v1 = z; } } } } if(count == 2) { //The counterpart clause to v3_2[i].pos is v3_2[i].neg v3_2[i].neg = three_neg[x].num[y]; out = 1; } } if(out == 0) { v3_2[i].v0 = -1; v3_2[i].v1 = -1; } } int out = 0; for(int i = 0; (i < v3_1count) && (!out); i++) { for(int y = 0; (y < v3_2count) && (!out); y++) { if((v3_1[i].v0 == -1) || (v3_1[i].v1 == -1) ||(v3_2[y].v0 == -1) || (v3_2[y].v1 == -1)) continue; if(pClauses[v3_1[i].pos].variables[v3_1[i].v0] == -pClauses[v3_2[y].pos].variables[v3_2[y].v0]) { pClauses[v3_1[i].pos].subsumed = 1; pClauses[v3_1[i].neg].subsumed = 1; pClauses[v3_2[y].pos].subsumed = 1; pClauses[v3_2[y].neg].subsumed = 1; BDDNode *pIteEqBDD = ite_itequ(ite_var(pClauses[v3_1[i].pos].variables[v3_1[i].v0]), ite_var(-pClauses[v3_2[y].pos].variables[v3_2[y].v1]), ite_var(-pClauses[v3_1[i].pos].variables[v3_1[i].v1]), ite_var(x)); functions_add(pIteEqBDD, ITE_EQU, x); independantVars[x] = 0; for(int z = 0; z < three_pos[x].length; z++) { count = 0; for(int j = 0; j < 3; j++) { if((-pClauses[three_pos[x].num[z]].variables[j] == -pClauses[v3_2[y].pos].variables[v3_2[y].v1]) ||(-pClauses[three_pos[x].num[z]].variables[j] == -pClauses[v3_1[i].pos].variables[v3_1[i].v1])) count++; } if(count == 2) pClauses[three_pos[x].num[z]].subsumed = 1; } for(int z = 0; z < three_neg[x].length; z++) { count = 0; for(int j = 0; j < 3; j++) { if((pClauses[three_neg[x].num[z]].variables[j] == -pClauses[v3_2[y].pos].variables[v3_2[y].v1]) ||(pClauses[three_neg[x].num[z]].variables[j] == -pClauses[v3_1[i].pos].variables[v3_1[i].v1])) count++; } if(count == 2) pClauses[three_neg[x].num[z]].subsumed = 1; } num_iteequals_found++; out = 1; } } } } for(int x = 1; x < nNumCNFVariables+1; x++) { ite_free((void **)&three_pos[x].num); ite_free((void **)&three_neg[x].num); } ite_free((void **)&three_pos); ite_free((void **)&three_neg); ite_free((void **)&v3_1); ite_free((void **)&v3_2); d2_printf2("Found %d ITE= functions\n", num_iteequals_found); } ITE_INLINE int pattern_majv_equals(Clause clause, int order[4]) { // fprintf(stderr, "c[%d %d %d]\n", clause.variables[0],clause.variables[1],clause.variables[2]); if((clause.variables[0] == order[0] && clause.variables[1] == order[1] && clause.variables[2] == order[2]) || (clause.variables[0] == order[0] && clause.variables[1] == order[1] && clause.variables[2] == order[3]) || (clause.variables[0] == order[0] && clause.variables[1] == order[2] && clause.variables[2] == order[3]) || (clause.variables[0] == order[1] && clause.variables[1] == order[2] && clause.variables[2] == order[3])) return 1; return 0; } void find_and_build_majvequals(Clause *pClauses) { int num_majvequals_found = 0; int *threepos_temp = (int *)ite_calloc(nNumCNFVariables+1, sizeof(int), 9, "threepos_temp"); int *threeneg_temp = (int *)ite_calloc(nNumCNFVariables+1, sizeof(int), 9, "threeneg_temp"); for(int x = 0; x < nNumClauses; x++) { int y = pClauses[x].length; if(y == 3) { for(y = 0; y < 3; y++) { if(pClauses[x].variables[y] > 0) threepos_temp[pClauses[x].variables[y]]++; else threeneg_temp[-pClauses[x].variables[y]]++; } } } store *three_pos = (store *)ite_calloc(nNumCNFVariables+1, sizeof(store), 9, "three_pos"); store *three_neg = (store *)ite_calloc(nNumCNFVariables+1, sizeof(store), 9, "three_neg"); //Store appropriate array sizes to help with memory usage for(int x = 1; x < nNumCNFVariables+1; x++) { three_pos[x].num = (int *)ite_calloc(threepos_temp[x], sizeof(int), 9, "three_pos[x].num"); three_neg[x].num = (int *)ite_calloc(threeneg_temp[x], sizeof(int), 9, "three_neg[x].num"); } ite_free((void **)&threepos_temp); ite_free((void **)&threeneg_temp); //Store all clauses with 3 variables so they can be clustered int count = 0; for(int x = 0; x < nNumClauses; x++) { if(pClauses[x].length == 3) { count++; for(int i = 0; i < 3; i++) { if(pClauses[x].variables[i] < 0) { three_neg[-pClauses[x].variables[i]].num[three_neg[-pClauses[x].variables[i]].length] = x; three_neg[-pClauses[x].variables[i]].length++; } else { three_pos[pClauses[x].variables[i]].num[three_pos[pClauses[x].variables[i]].length] = x; three_pos[pClauses[x].variables[i]].length++; } } } } //v0 is in all six clauses //When v0 is positive, all other literals are negative //When v0 is negative, all other literals are positive //v0 = majv(v1, v2, v3) //--------------------- //v0 -v1 -v2 //v0 -v1 -v3 //v0 -v2 -v3 //-v0 v1 v2 //-v0 v1 v3 //-v0 v2 v3 //--------------------- for(int v0 = 0; v0 < nNumCNFVariables+1; v0++) { if (v0%1000 == 1) d2_printf3("\rMAJV Search CNF %d/%d ... ", v0, nNumCNFVariables); int out=0; if(three_pos[v0].length < 3 || three_neg[v0].length < 3) continue; for(int i = 0; i < three_pos[v0].length-2 && !out; i++) { int c1 = three_pos[v0].num[i]; //clause number 1 int order[4]; //To hold the ordering; int v1, v2; if(pClauses[c1].variables[0] == v0) { v1 = pClauses[c1].variables[1]; v2 = pClauses[c1].variables[2]; } else if(pClauses[c1].variables[1] == v0) { v1 = pClauses[c1].variables[0]; v2 = pClauses[c1].variables[2]; } else { assert(pClauses[c1].variables[2] == v0); v1 = pClauses[c1].variables[0]; v2 = pClauses[c1].variables[1]; } for(int j = i+1; j < three_pos[v0].length-1 && !out; j++) { int c2 = three_pos[v0].num[j]; //clause number 2 int v3=0; if(pClauses[c2].variables[0] == v0) { if(pClauses[c2].variables[1] == v1) v3 = pClauses[c2].variables[2]; else if(pClauses[c2].variables[2] == v1) v3 = pClauses[c2].variables[1]; else if(pClauses[c2].variables[1] == v2) v3 = pClauses[c2].variables[2]; else if(pClauses[c2].variables[2] == v2) v3 = pClauses[c2].variables[1]; else continue; } else if(pClauses[c2].variables[1] == v0) { if(pClauses[c2].variables[0] == v1) v3 = pClauses[c2].variables[2]; else if(pClauses[c2].variables[2] == v1) v3 = pClauses[c2].variables[0]; else if(pClauses[c2].variables[0] == v2) v3 = pClauses[c2].variables[2]; else if(pClauses[c2].variables[2] == v2) v3 = pClauses[c2].variables[0]; else continue; } else { assert(pClauses[c2].variables[2] == v0); if(pClauses[c2].variables[0] == v1) v3 = pClauses[c2].variables[1]; else if(pClauses[c2].variables[1] == v1) v3 = pClauses[c2].variables[0]; else if(pClauses[c2].variables[0] == v2) v3 = pClauses[c2].variables[1]; else if(pClauses[c2].variables[1] == v2) v3 = pClauses[c2].variables[0]; else continue; } order[0]=v0; order[1]=v1; order[2]=v2; order[3]=v3; qsort(order, 4, sizeof(int), abscompfunc); if(abs(order[0]) == abs(order[1]) || abs(order[1]) == abs(order[2]) || abs(order[2]) == abs(order[3])) continue; // fprintf(stderr, "[%d %d %d %d]", order[0], order[1], order[2], order[3]); int clause_found=0; int c3; for(int k = j+1; k < three_pos[v0].length; k++) { c3 = three_pos[v0].num[k]; //clause number 3 if(pattern_majv_equals(pClauses[c3], order)) { clause_found = 1; break; } } if(!clause_found) continue; order[0]=-order[0]; order[1]=-order[1]; order[2]=-order[2]; order[3]=-order[3]; clause_found=0; int c4; int k1; for(k1 = 0; k1 < three_neg[v0].length-2; k1++) { c4 = three_neg[v0].num[k1]; //clause number 4 if(pattern_majv_equals(pClauses[c4], order)) { clause_found = 1; break; } } if(!clause_found) continue; clause_found=0; int c5; int k2; for(k2 = k1+1; k2 < three_neg[v0].length-1; k2++) { c5 = three_neg[v0].num[k2]; //clause number 5 if(pattern_majv_equals(pClauses[c5], order)) { clause_found = 1; break; } } if(!clause_found) continue; clause_found=0; int c6; for(int k3 = k2+1; k3 < three_neg[v0].length; k3++) { c6 = three_neg[v0].num[k3]; //clause number 6 if(pattern_majv_equals(pClauses[c6], order)) { clause_found = 1; break; } } if(!clause_found) continue; BDDNode *pMAJVEqBDD = ite_equ(ite_var(v0), ite(ite_var(-v1), ite_or(ite_var(-v2),ite_var(-v3)) , ite_and(ite_var(-v2),ite_var(-v3)))); functions_add(pMAJVEqBDD, ITE_EQU, v0); independantVars[v0] = 0; pClauses[c1].subsumed = 1; pClauses[c2].subsumed = 1; pClauses[c3].subsumed = 1; pClauses[c4].subsumed = 1; pClauses[c5].subsumed = 1; pClauses[c6].subsumed = 1; num_majvequals_found++; out=1; } } } for(int x = 1; x < nNumCNFVariables+1; x++) { ite_free((void **)&three_pos[x].num); ite_free((void **)&three_neg[x].num); } ite_free((void **)&three_pos); ite_free((void **)&three_neg); d2_printf2("\rFound %d MAJV= functions \n", num_majvequals_found); } void cnf_process(Clause *pClauses) { dX_printf(3, "Number of Variables: %d\n", nNumCNFVariables); nmbrFunctions = 0; vars_alloc(nNumCNFVariables); functions_alloc(nNumClauses); if(DO_CLUSTER) { //Sort variables in each clause for(int x = 0; x < nNumClauses; x++) qsort(pClauses[x].variables, pClauses[x].length, sizeof(int), abscompfunc); //Sort Clauses qsort(pClauses, nNumClauses, sizeof(Clause), clscompfunc); #ifdef PRINT_FACTOR_GRAPH print_factor_graph(pClauses); #endif reduce_clauses(pClauses); find_and_build_xors(pClauses); reduce_clauses(pClauses); find_and_build_andequals(pClauses); reduce_clauses(pClauses); find_and_build_majvequals(pClauses); reduce_clauses(pClauses); find_and_build_iteequals(pClauses); reduce_clauses(pClauses); } build_clause_BDDs(pClauses); reduce_clauses(pClauses); } void DNF_to_CNF () { typedef struct { int num[50]; } node1; node1 *integers; int lines = 0, len; int y = 0; if (fscanf(finputfile, "%ld %ld\n", &numinp, &numout) != 2) { fprintf(stderr, "Error while parsing DNF input: bad header\n"); exit(1); }; len = numout; integers = new node1[numout+1]; for(int x = 0; x < len; x++) { y = 0; do { if (fscanf(finputfile, "%d", &integers[x].num[y]) != 1) { fprintf(stderr, "Error while parsing DNF input\n"); exit(1); }; y++; lines++; } while(integers[x].num[y - 1] != 0); } char string1[1024]; lines = lines + 1; sprintf(string1, "p cnf %ld %d\n", numinp + len, lines); fprintf(foutputfile, "%s", string1); for(y = 0; y < len; y++) { sprintf(string1, "%ld ", y + numinp + 1); fprintf(foutputfile, "%s", string1); } sprintf(string1, "0\n"); fprintf(foutputfile, "%s", string1); for(int x = 0; x < numout; x++) { sprintf(string1, "%ld ", x + numinp + 1); fprintf(foutputfile, "%s", string1); for(y = 0; integers[x].num[y] != 0; y++) { sprintf(string1, "%d ", -integers[x].num[y]); fprintf(foutputfile, "%s", string1); } sprintf(string1, "0\n"); fprintf(foutputfile, "%s", string1); for(y = 0; integers[x].num[y] != 0; y++) { sprintf(string1, "%ld ", -(x + numinp + 1)); fprintf(foutputfile, "%s", string1); sprintf(string1, "%d ", integers[x].num[y]); fprintf(foutputfile, "%s", string1); sprintf(string1, "0\n"); fprintf(foutputfile, "%s", string1); } } sprintf(string1, "c\n"); fprintf(foutputfile, "%s", string1); //ite_free((void**)&integers); } void DNF_to_BDD () { store *dnf_integers = NULL; long dnf_numinp=0, dnf_numout=0; store *cnf_integers = NULL; long cnf_numinp=0, cnf_numout=0; int y = 0; if (fscanf(finputfile, "%ld %ld\n", &dnf_numinp, &dnf_numout) != 2) { fprintf(stderr, "Error while parsing DNF input: bad header\n"); exit(1); } dnf_integers = (store*)ite_calloc(dnf_numout+1, sizeof(store), 9, "integers"); dX_printf(3, "Storing DNF Inputs"); for(int x = 0; x < dnf_numout; x++) { if (x%1000 == 1) d2_printf3("\rReading DNF %d/%ld ... ", x, dnf_numout); y = 0; do { if (dnf_integers[x].num_alloc <= y) { dnf_integers[x].num = (int*)ite_recalloc((void*)dnf_integers[x].num, dnf_integers[x].num_alloc, dnf_integers[x].num_alloc+100, sizeof(int), 9, "integers[].num"); dnf_integers[x].num_alloc += 100; } int intnum; if (fscanf(finputfile, "%d", &intnum) != 1) { fprintf(stderr, "Error while parsing DNF input\n"); exit(1); } if(abs(intnum) > dnf_numinp) { //Could change this to be number of vars instead of max vars fprintf(stderr, "Variable in input file is greater than allowed:%ld...exiting\n", (long)dnf_numinp-2); exit(1); } #ifdef CNF_USES_SYMTABLE intnum = intnum==0?0:i_getsym_int(intnum, SYM_VAR); #endif dnf_integers[x].num[y] = intnum; y++; cnf_numout++; } while(dnf_integers[x].num[y - 1] != 0); dnf_integers[x].max = y-1; } int extra=0; if (fscanf(finputfile, "%d", &extra) == 1) { fprintf(stderr, "Error while parsing DNF input: extra data\n"); exit(1); } // DNF -> CNF cnf_numout = cnf_numout + 1; // add the big clause cnf_numinp = dnf_numinp + dnf_numout; // for every clause add a variable cnf_integers = (store*)ite_calloc(cnf_numout+1, sizeof(store), 9, "integers"); // the big clause int cnf_out_idx = 1; /* one based index? */ cnf_integers[cnf_out_idx].num_alloc = dnf_numout+1; cnf_integers[cnf_out_idx].num = (int*)ite_calloc(cnf_integers[cnf_out_idx].num_alloc, sizeof(int), 9, "integers[].num"); for(y = 0; y < dnf_numout; y++) { if (y%1000 == 1) d2_printf3("\rCreating Symbol Table Entries %d/%ld ... ", y, dnf_numout); cnf_integers[cnf_out_idx].num[y] = #ifdef CNF_USES_SYMTABLE i_getsym_int(y+dnf_numinp+1, SYM_VAR); #else y + dnf_numinp + 1; #endif } cnf_integers[cnf_out_idx].num[dnf_numout] = 0; cnf_out_idx++; for(int x = 0; x < dnf_numout; x++) { if (x%1000 == 1) d2_printf3("\rTranslating DNF to CNF %d/%ld ...", x, dnf_numout); cnf_integers[cnf_out_idx].num_alloc = dnf_integers[x].max+2; /* plus clause var and 0 */ cnf_integers[cnf_out_idx].num = (int*)ite_calloc(cnf_integers[cnf_out_idx].num_alloc, sizeof(int), 9, "integers[].num"); cnf_integers[cnf_out_idx].num[0] = cnf_integers[1].num[x]; // clause id for(y = 0; dnf_integers[x].num[y] != 0; y++) { cnf_integers[cnf_out_idx].num[y+1] = -dnf_integers[x].num[y]; } cnf_integers[cnf_out_idx].num[y+1] = 0; assert(y == dnf_integers[x].max); cnf_out_idx++; for(y = 0; dnf_integers[x].num[y] != 0; y++) { cnf_integers[cnf_out_idx].num_alloc = 3; cnf_integers[cnf_out_idx].num = (int*)ite_calloc(cnf_integers[cnf_out_idx].num_alloc, sizeof(int), 9, "integers[].num"); cnf_integers[cnf_out_idx].num[0] = -cnf_integers[1].num[x]; // -clause id cnf_integers[cnf_out_idx].num[1] = dnf_integers[x].num[y]; cnf_integers[cnf_out_idx].num[2] = 0; cnf_out_idx++; } } assert(cnf_numout == cnf_out_idx-1); long x; numinp = cnf_numinp; numout = cnf_numout; for(x = 1; x <= cnf_numout; x++) { cnf_integers[x].length = cnf_integers[x].num_alloc-1; cnf_integers[x].dag = -1; } DO_CLUSTER = 0; // cnf_process(cnf_integers, 0, NULL); for(x = 1; x < cnf_numout + 1; x++) { ite_free((void**)&cnf_integers[x].num); } ite_free((void**)&cnf_integers); for(x = 0; x < dnf_numout + 1; x++) { ite_free((void**)&dnf_integers[x].num); } ite_free((void**)&dnf_integers); dX_printf(3, "Number of BDDs - %ld\n", numout); d2_printf1("\rReading DNF ... Done \n"); } /* void DNF_to_CNF () { typedef struct { int num[50]; } node1; node1 *integers; int lines = 0, len; int y = 0; fscanf(finputfile, "%ld %ld\n", &numinp, &numout); len = numout; integers = new node1[numout+1]; for(int x = 0; x < len; x++) { y = 0; do { fscanf(finputfile, "%d", &integers[x].num[y]); y++; lines++; } while(integers[x].num[y - 1] != 0); } char string1[1024]; lines = lines + 1; sprintf(string1, "p cnf %ld %d\n", numinp + len, lines); fprintf(foutputfile, "%s", string1); for(int y = 0; y < len; y++) { sprintf(string1, "%ld ", y + numinp + 1); fprintf(foutputfile, "%s", string1); } sprintf(string1, "0\n"); fprintf(foutputfile, "%s", string1); for(int x = 0; x < numout; x++) { sprintf(string1, "%ld ", x + numinp + 1); fprintf(foutputfile, "%s", string1); for(int y = 0; integers[x].num[y] != 0; y++) { sprintf(string1, "%d ", -integers[x].num[y]); fprintf(foutputfile, "%s", string1); } sprintf(string1, "0\n"); fprintf(foutputfile, "%s", string1); for(int y = 0; integers[x].num[y] != 0; y++) { sprintf(string1, "%ld ", -(x + numinp + 1)); fprintf(foutputfile, "%s", string1); sprintf(string1, "%d ", integers[x].num[y]); fprintf(foutputfile, "%s", string1); sprintf(string1, "0\n"); fprintf(foutputfile, "%s", string1); } } sprintf(string1, "c\n"); fprintf(foutputfile, "%s", string1); } */
32.761828
164
0.589636
[ "shape", "solid" ]
ab6cd600242e0c8ec251b3b6d9b9eeaaea8abdce
3,034
cpp
C++
src/BabylonCpp/src/maths/frustum.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/BabylonCpp/src/maths/frustum.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/BabylonCpp/src/maths/frustum.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/maths/frustum.h> #include <babylon/maths/matrix.h> #include <babylon/maths/plane.h> namespace BABYLON { std::array<Plane, 6> Frustum::GetPlanes(const Matrix& transform) { std::array<Plane, 6> frustumPlanes{ {Plane(0.f, 0.f, 0.f, 0.f), Plane(0.f, 0.f, 0.f, 0.f), Plane(0.f, 0.f, 0.f, 0.f), Plane(0.f, 0.f, 0.f, 0.f), Plane(0.f, 0.f, 0.f, 0.f), Plane(0.f, 0.f, 0.f, 0.f)}}; Frustum::GetPlanesToRef(transform, frustumPlanes); return frustumPlanes; } void Frustum::GetNearPlaneToRef(const Matrix& transform, Plane& frustumPlane) { const auto& m = transform.m(); frustumPlane.normal.x = m[3] + m[2]; frustumPlane.normal.y = m[7] + m[6]; frustumPlane.normal.z = m[11] + m[10]; frustumPlane.d = m[15] + m[14]; frustumPlane.normalize(); } void Frustum::GetFarPlaneToRef(const Matrix& transform, Plane& frustumPlane) { const auto& m = transform.m(); frustumPlane.normal.x = m[3] - m[2]; frustumPlane.normal.y = m[7] - m[6]; frustumPlane.normal.z = m[11] - m[10]; frustumPlane.d = m[15] - m[14]; frustumPlane.normalize(); } void Frustum::GetLeftPlaneToRef(const Matrix& transform, Plane& frustumPlane) { const auto& m = transform.m(); frustumPlane.normal.x = m[3] + m[0]; frustumPlane.normal.y = m[7] + m[4]; frustumPlane.normal.z = m[11] + m[8]; frustumPlane.d = m[15] + m[12]; frustumPlane.normalize(); } void Frustum::GetRightPlaneToRef(const Matrix& transform, Plane& frustumPlane) { const auto& m = transform.m(); frustumPlane.normal.x = m[3] - m[0]; frustumPlane.normal.y = m[7] - m[4]; frustumPlane.normal.z = m[11] - m[8]; frustumPlane.d = m[15] - m[12]; frustumPlane.normalize(); } void Frustum::GetTopPlaneToRef(const Matrix& transform, Plane& frustumPlane) { const auto& m = transform.m(); frustumPlane.normal.x = m[3] - m[1]; frustumPlane.normal.y = m[7] - m[5]; frustumPlane.normal.z = m[11] - m[9]; frustumPlane.d = m[15] - m[13]; frustumPlane.normalize(); } void Frustum::GetBottomPlaneToRef(const Matrix& transform, Plane& frustumPlane) { const auto& m = transform.m(); frustumPlane.normal.x = m[3] + m[1]; frustumPlane.normal.y = m[7] + m[5]; frustumPlane.normal.z = m[11] + m[9]; frustumPlane.d = m[15] + m[13]; frustumPlane.normalize(); } void Frustum::GetPlanesToRef(const Matrix& transform, std::array<Plane, 6>& frustumPlanes) { // Near Frustum::GetNearPlaneToRef(transform, frustumPlanes[0]); // Far Frustum::GetFarPlaneToRef(transform, frustumPlanes[1]); // Left Frustum::GetLeftPlaneToRef(transform, frustumPlanes[2]); // Right Frustum::GetRightPlaneToRef(transform, frustumPlanes[3]); // Top Frustum::GetTopPlaneToRef(transform, frustumPlanes[4]); // Bottom Frustum::GetBottomPlaneToRef(transform, frustumPlanes[5]); } } // end of namespace BABYLON
30.039604
80
0.621292
[ "transform" ]
ab6e5fafd920d0eac022eee8e4b9e7dd0e40f64e
1,364
hpp
C++
include/J3D/J3DUtil.hpp
Sage-of-Mirrors/J3DUltra
bc823846a6a547e74beb4ed9acad38b3ccd63ad3
[ "MIT" ]
1
2022-01-31T14:45:12.000Z
2022-01-31T14:45:12.000Z
include/J3D/J3DUtil.hpp
Sage-of-Mirrors/J3DUltra
bc823846a6a547e74beb4ed9acad38b3ccd63ad3
[ "MIT" ]
null
null
null
include/J3D/J3DUtil.hpp
Sage-of-Mirrors/J3DUltra
bc823846a6a547e74beb4ed9acad38b3ccd63ad3
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> #include <type_traits> #include <filesystem> #include <cstddef> #include <algorithm> namespace J3DUtility { // Returns the index of the given element in the given vector, or -1 if the element is not in that vector. template<typename T> ptrdiff_t VectorIndexOf(const std::vector<T>& vec, const T& elem) { ptrdiff_t result = -1; auto it = std::find(vec.begin(), vec.end(), elem); if (it != vec.end()) result = it - vec.begin(); return result; } // Returns whether the given element is contained in the given vector. template<typename T> bool VectorContains(const std::vector<T>& vec, const T& elem) { return VectorIndexOf(vec, elem) != -1; } // Returns whether the given element is contained in the given vector, with the index parameter set to the element's position. template<typename T> bool VectorContains(const std::vector<T>& vec, const T& elem, ptrdiff_t& index) { index = VectorIndexOf(vec, elem); return index != -1; } template<typename E> constexpr auto EnumToIntegral(E e) -> typename std::underlying_type<E>::type { return static_cast<typename std::underlying_type<E>::type>(e); } std::string LoadTextFile(std::filesystem::path filePath); }
29.021277
130
0.648827
[ "vector" ]
ab6f0f0a337215e94e67c98071d8bab916545355
2,516
hpp
C++
tse/include/tse/application.hpp
jeffrey-cochran/tsl
a9ae6fb2755fcbd1311c16e9faff87445419f7f0
[ "Apache-2.0", "MIT" ]
4
2020-03-05T04:34:28.000Z
2022-02-17T04:39:51.000Z
tse/include/tse/application.hpp
jeffrey-cochran/tsl
a9ae6fb2755fcbd1311c16e9faff87445419f7f0
[ "Apache-2.0", "MIT" ]
47
2019-02-21T11:16:20.000Z
2019-07-10T20:30:13.000Z
tse/include/tse/application.hpp
jovobe/tsl
6c024a2325d1c6cb3019b4169a6f3f214a224587
[ "Apache-2.0", "MIT" ]
4
2020-06-20T15:36:11.000Z
2022-01-04T03:22:45.000Z
#ifndef TSE_APPLICATION_HPP #define TSE_APPLICATION_HPP #include <map> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "tse/window.hpp" using std::string; using std::map; namespace tse { class window; /** * @brief This class represents the running application. Because only one istance of this can be used at a time * it is implemented as a singleton. */ class application { public: // This should neither be movable nor copyable application(application&&) = delete; application(application const &) = delete; application& operator=(const application&) = delete; application& operator=(application&&) = delete; ~application(); /** * @brief Returns the application object. */ static application& get_instance(); /** * @brief Returns the number of frames which were rendered in the last second. */ uint32_t get_last_num_frames() const; /** * @brief Returns the last number of ms the application slept while waiting for the next second to start. */ uint32_t get_last_sleep() const; /** * @brief Creates a window for the application. */ void create_window(string&& title, uint32_t width, uint32_t height); /** * @brief Runs the main loop for the application. */ void run(); // GLFW wrapper functions /** * @brief Returns the current time. */ double get_time() const; private: /// All windows of the application. map<GLFWwindow*, window> windows; /// The number of frames which were rendered in the last second. uint32_t last_num_frames; /// The last number of ms the application slept while waiting for the next second to start. uint32_t last_sleep; /// The number of frames which should be drawn per second. const float FPS_TARGET = 60; /// Private ctor because of singleton implementation. application(); /// Initializes GLFW. void init_glfw() const; // GLFW callbacks static void glfw_error_callback(int error, const char* description); static void glfw_key_callback(GLFWwindow* glfw_window, int key, int scancode, int action, int mods); static void glfw_framebuffer_size_callback(GLFWwindow* glfw_window, int width, int height); static void glfw_window_size_callback(GLFWwindow* glfw_window, int width, int height); static void glfw_mouse_button_callback(GLFWwindow* glfw_window, int button, int action, int mods); friend class window; }; } #endif //TSE_APPLICATION_HPP
26.208333
111
0.692766
[ "object" ]
ab7251c12c3453d90533f4fde70d1c3fccb5bfb8
8,904
hpp
C++
shared.hpp
vsklad/cnfgen
58bd621f174c8b92aeb597acdf4cadb210cdced5
[ "MIT" ]
19
2018-10-28T17:49:51.000Z
2022-02-14T08:11:04.000Z
shared.hpp
vsklad/cnfgen
58bd621f174c8b92aeb597acdf4cadb210cdced5
[ "MIT" ]
3
2021-03-08T07:44:02.000Z
2021-03-21T17:55:47.000Z
shared.hpp
vsklad/cnfgen
58bd621f174c8b92aeb597acdf4cadb210cdced5
[ "MIT" ]
4
2019-07-20T10:11:16.000Z
2021-04-29T05:02:39.000Z
// // CGen // https://cgen.sophisticatedways.net // Copyright © 2018-2020 Volodymyr Skladanivskyy. All rights reserved. // Published under terms of MIT license. // #ifndef shared_hpp #define shared_hpp #include <map> #include <vector> #include "variablesarray.hpp" #define APP_VERSION "1.2" #define APP_TITLE "CGen" #define APP_URL "https://cgen.sophisticatedways.net" #define APP_DESCRIPTION "CGen is a tool for encoding SHA-1 and SHA-256 hash functions into CNF/DIMACS and ANF/PolyBoRi formats" #define APP_USAGE_SHORT "\ Usage: \n\ cgen encode (SHA1|SHA256) [-r <rounds>] [-v <name> <value>]... [<encoder_options>] [<output_options>] [<output_file_name>]\n\ cgen process [<variable>]... [<output_options>] <input_file_name> [<output_file_name>]\n\ cgen --help\n\ cgen --version\n\ "; #define APP_USAGE_LONG "\ Commands:\n\ encode (SHA1|SHA256) - generate the encoding\n\ process - read DIMACS CNF from <input file name>, assign variables as specified, pre-process it and save it to <output file name>\n\ Options:\n\ -f (ANF|CNF) - encoding form, CNF if not specified \n\ -v <name> <value> - specification of the named variable,\n\ its mapping to binary variables and/or its constant values\n\ refer for detailed specifications online\n\ -r <value> - number of SHA1 rounds to encode\n\ -m ((unoptimized | u) | (all | a) | (original | o)) - processing mode\n\ -h | --help\n\ --version\n\ Further documentation and usage examples available at https://cgen.sophisticatedways.net.\n\ "; #define ERROR_COMMAND_NONE "No command specified" #define ERROR_UNKNOWN_OPTION "unknown option" #define ERROR_UNKNOWN_ARGUMENT "unknown argument" #define ERROR_COMMAND_LINE_PARSE "Command line parsing error" #define ERROR_INVALID_ARGUMENT "Error" #define ERROR_OUT_OF_RANGE "Out of range" #define ERROR_MISSING_ALGORITHM "Algorithm for encoding not specified" #define ERROR_UNKNOWN_ALGORITHM "Unknown algorithm for encoding" #define ERROR_INVALID_VARIABLE_NAME "Invalid variable name" #define ERROR_MISSING_VARIABLE_VALUE "Variable value is missing" #define ERROR_INVALID_BINARY_VALUE "Binary variable requires a single binary value" #define ERROR_DUPLICATED_VARIABLE_NAME "Variable may only appear once on the options list" #define ERROR_NO_VARIABLES "No variables specified" #define ERROR_EXCEPT_MUST_FOLLOW_ASSIGN_ENCODE "\"except\" variable modifiers are only allowed for\"assign\" or \"encode\" commands" #define ERROR_EXCEPT_MUST_FOLLOW_DEFINITION "\"except\" variable modifier must be part of variable definition" #define ERROR_PAD_MUST_FOLLOW_DEFINITION "\"pad\" variable modifier must be part of variable definition" #define ERROR_REPLACE_MUST_FOLLOW_DEFINITION "\"replace\" variable modifier must be part of variable definition" #define ERROR_PAD_MUST_FOLLOW_VALUE "\"pad\" variable modifier is incompatible with \"random\" and \"compute\" variable modes" #define ERROR_EXCEPT_REPLACE_INCOMPATIBLE "\"except\" and \"replace\" variable modifiers are incompatible" #define ERROR_EXCEPT_ZERO "\"except\" variable modifier must specify a non-zero number of binary variables to skip" #define ERROR_BINARY_VARIABLE_EXCEPT_INCOMPATIBLE "\"except\" modifier is invalid for a binary variable" #define ERROR_BINARY_VARIABLE_PAD_INCOMPATIBLE "\"pad\" modifier is invalid for a binary variable" #define ERROR_BINARY_VARIABLE_REPLACE_INCOMPATIBLE "\"replace\" modifier is invalid for a binary variable" #define ERROR_RANGE_FIRST_LAST "For binary variables range the first element must be less or equal to the last" #define ERROR_RANGE_FIRST_ZERO "For binary variables range the first element must be greater than 0" #define ERROR_PAD_UNKNOWN_VALUE "\"pad\" variable modifier only supports \"SHA1\" and \"SHA256\" values" #define ERROR_COMPUTE_MODE_CONTEXT "compute mode may be specified for a computed variable only" #define ERROR_R_MUST_FOLLOW_ENCODE "Rounds option can only be specified after \"encode\"" #define ERROR_ADD_MAX_ARGS_MUST_FOLLOW_ENCODE "add_max_args option can only be specified after \"encode\"" #define ERROR_XOR_MAX_ARGS_MUST_FOLLOW_ENCODE "xor_max_args option can only be specified after \"encode\"" #define ERROR_AAE_MUST_FOLLOW_ENCODE "assign_after_encoding option can only be specified after \"encode\"" #define ERROR_V_MUST_FOLLOW_ENCODE_PROCESS "Variable options can only be specified for \"encode\" and \"process\" commands" #define ERROR_NORMALIZE_VARIABLES_MUST_FOLLOW_ENCODE_PROCESS \ "\"normaize variables\" option may only be specified for \"encode\" or \"process\" command" #define ERROR_MISSING_INPUT_FILE_NAME "Input file name is not specified" #define ERROR_INPUT_FILE_FORMAT_MISMATCH "Input file extension does not match the specified format" #define ERROR_OUTPUT_FILE_FORMAT_MISMATCH "Output format is incompatible with the formula" #define ERROR_MISSING_OUTPUT_FILE_NAME "Output file name is not specified" #define ERROR_ROUNDS_RANGE "Rounds number is out of range" #define ERROR_ADD_MAX_ARGS_RANGE "add_max_args should be greater than zero" #define ERROR_XOR_MAX_ARGS_RANGE "xor_max_args should be greater than zero" #define ERROR_ENCODE_UNKNOWN_VARIABLE_NAME "Unknown variable name, \"encode\" only expects \"M\" and \"H\" case sensitive" #define ERROR_UNKNOWN_VARIABLE_NAME "named variable is not defined in the DIMACS file" #define ERROR_VARIABLE_DEFINITION_MODE "named variable definition can only be its template or constant value" #define ERROR_VARIABLE_DEFINITION_EXCEPT "named variable definition may not include \"except\" modifier" #define ERROR_NAMED_VARIABLE_OUT_OF_RANGE " named variable includes a binary variable number greated than than the DIMACS file allows" #define ERROR_COMPUTE_INVALID_ENCODING "Failed to compute variable values" #define ERROR_COMPUTE_MESSAGE_NOT_SUPPORTED "Computing of message value is not supported" #define ERROR_EXCEPT_VARIABLES_RANGE_OUT_OF_BOUNDS "\"except\" variables range is out of bounds" #define ERROR_EXCEPT_NO_VARIABLES \ "Specified number of binary variables to except from assignment is higher than the number of assignable non-constant variables present" #define ERROR_RANDOM_NO_VARIABLES "There are no variables to assign random values to" #define ERROR_FAILED_OPENING_OUTPUT_FILE "Failed to open the output file" #define ERROR_UNKNOWN_FORMAT "Unknown output format" #define ERROR_ANF_UNOPTIMIZED_ONLY "Only unoptimized ANF output is supported" #define ERROR_PROCESS_UNSUPPORTED_MODE "Unsupported mode for \"process\" command" #define ERROR_MODE_UNKNOWN_VALUE "Unknown \"mode\" option" #define ERROR_TRACE_UNKNOWN_VALUE "Unknown \"trace\" option value" #define ERROR_FORMULA_TYPE_UNDEFINED "Formula type, input or output format cannot be determined" #define ERROR_OUTPUT_FORMAT_UNSUPPORTED "Output format is not supported for the chosen operation" #define ERROR_MODE_UNSUPPORTED_COMMAND \ "\"mode\" option may only be specified for \"assign\", \"define\", \"encode\" and \"process\" commands" #define ERROR_TRACE_UNSUPPORTED_COMMAND \ "\"trace\" option is only possible for \"assign\", \"define\", \"encode\" and \"process\" commands" #define ERROR_TRACE_NOT_SUPPORTED "The application is built with configuration which does not support tracing" #define MSG_FORMULA_IS_SATISFIABLE "The formula is SATISFIABLE" enum CGenCommand {cmdNone, cmdEncode, cmdProcess, cmdHelp, cmdVersion}; enum CGenAlgorithm {algNone, algSHA1, algSHA256}; enum CGenFormulaType {ftCnf, ftAnf}; enum CGenOutputFormat {ofAnfPolybori, ofCnfDimacs, ofCnfVIGGraphML, ofCnfWeightedVIGGraphML, ofCnfVIGGEXF}; enum CGenTraceFormat {tfNone, tfNativeStdOut, tfNativeFile, tfCnfVIGGEXF}; enum CGenVariableMode {vmValue, vmRandom, vmCompute}; enum CGenVariableComputeMode {vcmComplete, vcmDifference, vcmConstant}; typedef struct { CGenVariableMode mode; CGenVariableComputeMode compute_mode = vcmDifference; uint32_t except_count = 0; uint32_t except_range_first = 0; uint32_t except_range_size = 0; bal::VariablesArray data; bool replace_existing = false; } CGenVariableInfo; inline bool is_binary_variable_name(const std::string& value) { return (!value.empty() && std::isdigit(*value.begin())); } typedef std::map<std::string, CGenVariableInfo> CGenVariablesMap; inline const char* const get_formula_type_title(const CGenFormulaType value) { switch(value) { case ftCnf: return "CNF"; case ftAnf: return "ANF"; }; }; inline const char* const get_output_format_title(const CGenOutputFormat value) { switch(value) { case ofAnfPolybori: return "ANF Polybori"; case ofCnfDimacs: return "DIMACS CNF"; case ofCnfVIGGraphML: return "CNF VIG GraphML"; case ofCnfWeightedVIGGraphML: return "CNF weighted VIG GraphML"; case ofCnfVIGGEXF: return "CNF VIG GEXF"; }; }; #endif /* shared_hpp */
55.304348
139
0.780773
[ "vector" ]
ab7d2a9b981fdb97bbe3dde45303f9f5873f29de
624
cpp
C++
src/objects/terrain/BaseTerrain.cpp
asilvaigor/opengl_winter
0081c6ee39d493eb4f9e0ac92222937062866776
[ "MIT" ]
1
2020-04-24T22:55:51.000Z
2020-04-24T22:55:51.000Z
src/objects/terrain/BaseTerrain.cpp
asilvaigor/opengl_winter
0081c6ee39d493eb4f9e0ac92222937062866776
[ "MIT" ]
null
null
null
src/objects/terrain/BaseTerrain.cpp
asilvaigor/opengl_winter
0081c6ee39d493eb4f9e0ac92222937062866776
[ "MIT" ]
null
null
null
// // Created by Aloysio Galvão Lopes on 2020-05-08. // #include "BaseTerrain.h" BaseTerrain::BaseTerrain(float xSize, float ySize) : Object(false), xSize(xSize), ySize(ySize) {} BaseTerrain::~BaseTerrain() {} void BaseTerrain::setLight(std::vector<std::shared_ptr<vcl::light_source>> &lights, int currentLight) { this->lights = lights; this->currentLight = currentLight; } float BaseTerrain::getMaxTerrainHeight() { return 0.0f; } bool BaseTerrain::isObstructed(float, float) { return false; } float &BaseTerrain::getXSize() { return xSize; } float &BaseTerrain::getYSize() { return ySize; }
20.8
103
0.701923
[ "object", "vector" ]
ab816bc0895eb41c67ce2b06eef72ce6639b4a0c
1,038
cc
C++
src/utilities/test/test_Iterators.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/utilities/test/test_Iterators.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/utilities/test/test_Iterators.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*-----------------------------------// /** * @file test_Iterators.cc * @brief Test of InputDB * @note Copyright (C) 2013 Jeremy Roberts */ //----------------------------------------------------------------------------// // LIST OF TEST FUNCTIONS #define TEST_LIST \ FUNC(test_Iterators_Reversible) #include "TestDriver.hh" #include "utilities/Iterators.hh" #include <vector> using namespace detran_test; using namespace detran_utilities; int main(int argc, char *argv[]) { RUN(argc, argv); } //----------------------------------------------------------------------------// // TEST DEFINITIONS //----------------------------------------------------------------------------// int test_Iterators_Reversible(int argc, char *argv[]) { return 0; } //----------------------------------------------------------------------------// // end of test_Iterators.cc //----------------------------------------------------------------------------//
27.315789
80
0.352601
[ "vector" ]
ab867d326ed72753b23573e692f50af71f919777
35,883
cpp
C++
compiler/resolution/visibleCandidates.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/resolution/visibleCandidates.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/resolution/visibleCandidates.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2004-2017 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "visibleCandidates.h" #include "astutil.h" #include "callInfo.h" #include "expr.h" #include "resolution.h" #include "stlUtil.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" static void doGatherCandidates(CallInfo& info, Vec<FnSymbol*>& visibleFns, bool generated, Vec<ResolutionCandidate*>& candidates); static void filterCandidate(CallInfo& info, FnSymbol* fn, Vec<ResolutionCandidate*>& candidates); static void filterCandidate(CallInfo& info, ResolutionCandidate* currCandidate, Vec<ResolutionCandidate*>& candidates); static void filterConcrete(CallInfo& info, ResolutionCandidate* currCandidate, Vec<ResolutionCandidate*>& candidates); static void resolveTypeConstructor(CallInfo& info, FnSymbol* fn); static void filterGeneric(CallInfo& info, ResolutionCandidate* currCandidate, Vec<ResolutionCandidate*>& candidates); static int varargAccessIndex(SymExpr* se, CallExpr* parent, int numArgs); static bool isVarargSizeExpr (SymExpr* se, CallExpr* parent); static FnSymbol* expandVarArgs(FnSymbol* origFn, CallInfo& info); /************************************* | ************************************** * * * * * * ************************************** | *************************************/ void findVisibleCandidates(CallInfo& info, Vec<FnSymbol*>& visibleFns, Vec<ResolutionCandidate*>& candidates) { // Search user-defined (i.e. non-compiler-generated) functions first. doGatherCandidates(info, visibleFns, false, candidates); // If no results, try again with any compiler-generated candidates. if (candidates.n == 0) { doGatherCandidates(info, visibleFns, true, candidates); } } static void doGatherCandidates(CallInfo& info, Vec<FnSymbol*>& visibleFns, bool compilerGenerated, Vec<ResolutionCandidate*>& candidates) { forv_Vec(FnSymbol, fn, visibleFns) { // Consider either the user-defined functions or the compiler-generated // functions based on the input 'compilerGenerated'. if (fn->hasFlag(FLAG_COMPILER_GENERATED) == compilerGenerated) { // Consider // // c1.foo(10, 20); // // where foo() is a simple method on some class/record // // Normalize currently converts this to // // #<Call #<Call "foo" _mt c1> 10 20> // // Resolution performs a post-order traversal of this expression // and so the inner call is visited before the outer call. // // In this context, the inner "call" is effectively a field access // rather than a true function call. Normalize sets the methodTag // property to true to indicate this, and this form of call can only // be matched to parentheses-less methods and type constructors. // // Later steps will convert the outer call to become // // #<Call "foo" _mt c1 10 20> // // This outer call has methodTag set to false and this call // should be filtered against the available visibleFunctions. // if (info.call->methodTag == false) { filterCandidate(info, fn, candidates); } else { if (fn->hasFlag(FLAG_NO_PARENS) == true || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR) == true) { filterCandidate(info, fn, candidates); } } } } } /** Tests to see if a function is a candidate for resolving a specific call. * If it is a candidate, we add it to the candidate lists. * * \param info The CallInfo object for the call site. * \param currCandidate The current candidate to consider. * \param candidates The list to add possible candidates to. */ static void filterCandidate(CallInfo& info, FnSymbol* fn, Vec<ResolutionCandidate*>& candidates) { ResolutionCandidate* currCandidate = new ResolutionCandidate(fn); if (fExplainVerbose && ((explainCallLine && explainCallMatch(info.call)) || info.call->id == explainCallID)) { USR_PRINT(fn, "Considering function: %s", toString(fn)); if (info.call->id == breakOnResolveID) { gdbShouldBreakHere(); } } filterCandidate(info, currCandidate, candidates); if (candidates.tail() != currCandidate) { delete currCandidate; } } /** Tests to see if a function is a candidate for resolving a specific call. * If it is a candidate, we add it to the candidate lists. * * This version of filterCandidate is called by other versions of * filterCandidate, and shouldn't be called outside this family of functions. * * \param info The CallInfo object for the call site. * \param currCandidate The current candidate to consider. * \param candidates The list to add possible candidates to. */ static void filterCandidate(CallInfo& info, ResolutionCandidate* currCandidate, Vec<ResolutionCandidate*>& candidates) { if (currCandidate->fn->hasFlag(FLAG_GENERIC) == false) { filterConcrete(info, currCandidate, candidates); } else { filterGeneric (info, currCandidate, candidates); } } /** Candidate filtering logic specific to concrete functions. * * \param info The CallInfo object for the call site. * \param currCandidate The current candidate to consider. * \param candidates The list to add possible candidates to. */ static void filterConcrete(CallInfo& info, ResolutionCandidate* currCandidate, Vec<ResolutionCandidate*>& candidates) { currCandidate->fn = expandIfVarArgs(currCandidate->fn, info); if (currCandidate->fn != NULL) { resolveTypedefedArgTypes(currCandidate->fn); if (currCandidate->computeAlignment(info) == true) { // Ensure that type constructor is resolved before other constructors. if (currCandidate->fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR) == true) { resolveTypeConstructor(info, currCandidate->fn); } if (checkResolveFormalsWhereClauses(currCandidate) == true) { candidates.add(currCandidate); } } } } void resolveTypedefedArgTypes(FnSymbol* fn) { for_formals(formal, fn) { INT_ASSERT(formal->type); // Should be *something*. if (formal->type == dtUnknown) { if (BlockStmt* block = formal->typeExpr) { if (SymExpr* se = toSymExpr(block->body.first())) { if (se->symbol()->hasFlag(FLAG_TYPE_VARIABLE) == true) { Type* type = resolveTypeAlias(se); INT_ASSERT(type); formal->type = type; } } } } } } static void resolveTypeConstructor(CallInfo& info, FnSymbol* fn) { SET_LINENO(fn); // Ignore tuple constructors; they were generated // with their type constructors. if (fn->hasFlag(FLAG_PARTIAL_TUPLE) == false) { CallExpr* typeConstructorCall = new CallExpr(astr("_type", fn->name)); for_formals(formal, fn) { if (!formal->hasFlag(FLAG_IS_MEME)) { if (fn->_this->type->symbol->hasFlag(FLAG_TUPLE)) { if (formal->instantiatedFrom) { typeConstructorCall->insertAtTail(formal->type->symbol); } else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) { typeConstructorCall->insertAtTail(paramMap.get(formal)); } } else { if (strcmp(formal->name, "outer") == 0 || formal->type == dtMethodToken) { typeConstructorCall->insertAtTail(formal); } else if (formal->instantiatedFrom) { SymExpr* se = new SymExpr(formal->type->symbol); NamedExpr* ne = new NamedExpr(formal->name, se); typeConstructorCall->insertAtTail(ne); } else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) { SymExpr* se = new SymExpr(paramMap.get(formal)); NamedExpr* ne = new NamedExpr(formal->name, se); typeConstructorCall->insertAtTail(ne); } } } } info.call->insertBefore(typeConstructorCall); // If instead we call resolveCallAndCallee(typeConstructorCall) // then the line number reported in an error would change // e.g.: domains/deitz/test_generic_class_of_sparse_domain // or: classes/diten/multipledestructor resolveCall(typeConstructorCall); INT_ASSERT(typeConstructorCall->isResolved()); resolveFns(typeConstructorCall->resolvedFunction()); fn->_this->type = typeConstructorCall->isResolved()->retType; typeConstructorCall->remove(); } } /** Candidate filtering logic specific to generic functions. * * \param info The CallInfo object for the call site. * \param currCandidate The current candidate to consider. * \param candidates The list to add possible candidates to. */ static void filterGeneric(CallInfo& info, ResolutionCandidate* currCandidate, Vec<ResolutionCandidate*>& candidates) { currCandidate->fn = expandIfVarArgs(currCandidate->fn, info); if (currCandidate->fn != NULL && currCandidate->computeAlignment(info) == true && checkGenericFormals(currCandidate) == true) { // Compute the param/type substitutions for generic arguments. currCandidate->computeSubstitutions(); if (currCandidate->substitutions.n > 0) { /* * Instantiate enough of the generic to get through the rest of the * filtering and disambiguation processes. */ currCandidate->fn = instantiateSignature(currCandidate->fn, currCandidate->substitutions, info.call); if (currCandidate->fn != NULL) { filterCandidate(info, currCandidate, candidates); } } } } /************************************* | ************************************** * * * Maintain a cache from a vargArgs function to the function with the required * * number of formals. * * * ************************************** | *************************************/ typedef std::map<FnSymbol*, std::vector<FnSymbol*>*> ExpandVarArgsMap; static ExpandVarArgsMap sCache; static FnSymbol* cacheLookup(FnSymbol* fn, int numActuals) { ExpandVarArgsMap::iterator it = sCache.find(fn); FnSymbol* retval = NULL; if (it != sCache.end()) { std::vector<FnSymbol*>* fns = it->second; for (size_t i = 0; i < (*fns).size() && retval == NULL; i++) { if ((*fns)[i]->numFormals() == numActuals) { retval = (*fns)[i]; } } } return retval; } static void cacheExtend(FnSymbol* fn, FnSymbol* expansion) { ExpandVarArgsMap::iterator it = sCache.find(fn); if (it != sCache.end()) { it->second->push_back(expansion); } else { std::vector<FnSymbol*>* fns = new std::vector<FnSymbol*>(); fns->push_back(expansion); sCache[fn] = fns; } } /************************************* | ************************************** * * * If the function accepts a variable number of args, map it to a function * * with the necessary number of formals. * * * * 2017/04/05 There are several points at which this implementation assumes * * there is only one set of varargs. * * * ************************************** | *************************************/ static bool hasVariableArgs(FnSymbol* fn); FnSymbol* expandIfVarArgs(FnSymbol* fn, CallInfo& info) { FnSymbol* retval = fn; if (hasVariableArgs(fn) == true) { retval = cacheLookup(fn, info.actuals.n); // No substitution found if (retval == NULL) { retval = expandVarArgs(fn, info); if (retval != NULL) { cacheExtend(fn, retval); } } } return retval; } static bool hasVariableArgs(FnSymbol* fn) { bool retval = false; for_formals(formal, fn) { if (formal->variableExpr != NULL) { retval = true; } } return retval; } /************************************* | ************************************** * * * The function is known to have at least one var-args set. * * * * Portions of the current implementation assume that there is exactly one * * var-args set. Handling multiple sets is complex for both the user and * * the implementation. * * * * This constraint is enforced by expandVarArgs() and is then implicitly * * assumed by the helper functions. * * * ************************************** | *************************************/ static void expandVarArgsFixed(FnSymbol* origFn, CallInfo& info); static FnSymbol* expandVarArgsQuery(FnSymbol* origFn, CallInfo& info); static void handleSymExprInExpandVarArgs(FnSymbol* workingFn, ArgSymbol* formal, SymExpr* sym); static bool needVarArgTupleAsWhole(BlockStmt* ast, int numArgs, ArgSymbol* formal); static FnSymbol* expandVarArgs(FnSymbol* fn, CallInfo& info) { int numVarArgs = 0; bool isQueryVariable = false; FnSymbol* retval = NULL; for_formals(formal, fn) { if (formal->variableExpr != NULL) { if (isDefExpr(formal->variableExpr->body.tail) == true) { isQueryVariable = true; } numVarArgs = numVarArgs + 1; } } if (numVarArgs == 0) { INT_ASSERT(false); } else if (numVarArgs == 1) { if (isQueryVariable == false) { expandVarArgsFixed(fn, info); retval = fn; } else { retval = expandVarArgsQuery(fn, info); } } else { USR_FATAL(fn, "No support for a function with multiple vararg sets"); } return retval; } // No query variable e.g. proc foo(x, y, z ... 5) // or proc foo(x, y, z ... paramValue) static void expandVarArgsFixed(FnSymbol* fn, CallInfo& info) { bool genericArgSeen = false; for_formals(formal, fn) { if (BlockStmt* block = formal->variableExpr) { if (genericArgSeen == false) { resolveBlockStmt(block); } if (SymExpr* sym = toSymExpr(block->body.tail)) { handleSymExprInExpandVarArgs(fn, formal, sym); } else if (fn->hasFlag(FLAG_GENERIC) == false) { INT_FATAL("bad variableExpr"); } // It is certain that there is just one var-arg set to handle break; } else { if (formal->type && formal->type->symbol->hasFlag(FLAG_GENERIC)) { genericArgSeen = true; } } } } // A query variable e.g. proc foo(x, y, z ... ?N) static FnSymbol* expandVarArgsQuery(FnSymbol* fn, CallInfo& info) { FnSymbol* retval = NULL; for_formals(formal, fn) { if (BlockStmt* block = formal->variableExpr) { int numCopies = info.actuals.n - fn->numFormals() + 1; if (numCopies > 0) { SymbolMap substitutions; retval = fn->copy(&substitutions); retval->addFlag(FLAG_INVISIBLE_FN); fn->defPoint->insertBefore(new DefExpr(retval)); formal = toArgSymbol(substitutions.get(formal)); // newSym queries the number of varargs. Replace it with int literal. Symbol* defSym = toDefExpr(block->body.tail)->sym; Symbol* newSym = substitutions.get(defSym); SymExpr* newSymExpr = new SymExpr(new_IntSymbol(numCopies)); newSymExpr->astloc = newSym->astloc; newSym->defPoint->replace(newSymExpr); subSymbol(retval, newSym, new_IntSymbol(numCopies)); handleSymExprInExpandVarArgs(retval, formal, newSymExpr); } // It is certain that there is just one var-arg set to handle break; } } return retval; } /** Common code for multiple paths through expandVarArgs. * * This code handles the case where the number of varargs are known at compile * time. It inserts the necessary code to copy the values into and out of the * varargs tuple. */ static void handleSymExprInExpandVarArgs(FnSymbol* workingFn, ArgSymbol* formal, SymExpr* sym) { // Handle specified number of variable arguments. // sym->symbol() is not a VarSymbol e.g. in: proc f(param n, v...n) if (VarSymbol* nVar = toVarSymbol(sym->symbol())) { if (nVar->type == dtInt[INT_SIZE_DEFAULT] && nVar->immediate) { workingFn->addFlag(FLAG_EXPANDED_VARARGS); SET_LINENO(formal); VarSymbol* var = new VarSymbol(formal->name); int n = nVar->immediate->int_value(); CallExpr* tupleCall = NULL; // MPF 2016-10-02 // This code used to be run for _build_tuple // and _build_tuple_always_allow_ref but now // only runs for var-args functions. std::vector<ArgSymbol*> varargFormals(n); if (formal->hasFlag(FLAG_TYPE_VARIABLE) == true) tupleCall = new CallExpr("_type_construct__tuple"); else { tupleCall = new CallExpr("_construct__tuple"); // _construct__tuple now calls initCopy, so var // needs to be auto-destroyed. var->addFlag(FLAG_INSERT_AUTO_DESTROY); } tupleCall->insertAtTail(new_IntSymbol(n)); for (int i = 0; i < n; i++) { DefExpr* newArgDef = formal->defPoint->copy(); ArgSymbol* newFormal = toArgSymbol(newArgDef->sym); newFormal->variableExpr = NULL; newFormal->name = astr("_e", istr(i), "_", formal->name); newFormal->cname = astr("_e", istr(i), "_", formal->cname); tupleCall->insertAtTail(new SymExpr(newFormal)); formal->defPoint->insertBefore(newArgDef); varargFormals[i] = newFormal; } bool needTupleInBody = true; //avoid "may be used uninitialized" warning // Replace mappings to the old formal with mappings to the new variable. if (PartialCopyData* pci = getPartialCopyInfo(workingFn)) { bool gotFormal = false; // for assertion only for (int index = pci->partialCopyMap.n; --index >= 0;) { SymbolMapElem& mapElem = pci->partialCopyMap.v[index]; if (mapElem.value == formal) { gotFormal = true; needTupleInBody = needVarArgTupleAsWhole(pci->partialCopySource->body, n, toArgSymbol(mapElem.key)); if (needTupleInBody) { mapElem.value = var; } else { // We will rely on mapElem.value==formal to replace it away // in finalizeCopy(). This assumes a single set of varargs. pci->varargOldFormal = formal; pci->varargNewFormals = varargFormals; } break; } } // If !gotFormal, still need to compute needTupleInBody. // What to pass for 'formal' argument? Or maybe doesn't matter? INT_ASSERT(gotFormal); } else { needTupleInBody = needVarArgTupleAsWhole(workingFn->body, n, formal); } if (formal->hasFlag(FLAG_TYPE_VARIABLE)) { var->addFlag(FLAG_TYPE_VARIABLE); } // This is needed regardless of needTupleInBody... if (formal->intent == INTENT_OUT || formal->intent == INTENT_INOUT) { // ... however, we need temporaries even if !needTupleInBody. // Creating one temporary per formal is left as future work. // A challenge is whether varargFormals should contain these // per-formal temporaries instead of the formals, in this case. needTupleInBody = true; int i = 0; for_actuals(actual, tupleCall) { // Skip the tuple count if (i > 0) { VarSymbol* tmp = newTemp("_varargs_tmp_"); CallExpr* elem = new CallExpr(var, new_IntSymbol(i)); CallExpr* move = new CallExpr(PRIM_MOVE, tmp, elem); CallExpr* assign = new CallExpr("=", actual->copy(), tmp); workingFn->insertIntoEpilogue(new DefExpr(tmp)); workingFn->insertIntoEpilogue(move); workingFn->insertIntoEpilogue(assign); } i++; } } if (needTupleInBody) { // Noakes 2016/02/01. // Enable special handling for strings with blank intent // If the original formal is a string with blank intent then the // new formals appear to be strings with blank intent. However // the resolver is about to update these to be const ref intent. // // Currently this will cause the tuple to appear to be a tuple // ref(String) which is not supported. // // Insert local copies that can be used for the tuple if (isString(formal->type) && formal->intent == INTENT_BLANK) { DefExpr* varDefn = new DefExpr(var); Expr* tail = NULL; // Insert the new locals for (int i = 0; i < n; i++) { const char* localName = astr("_e", istr(i + n), "_", formal->name); VarSymbol* local = newTemp(localName, formal->type); DefExpr* defn = new DefExpr(local); if (tail == NULL) workingFn->insertAtHead(defn); else tail->insertAfter(defn); tail = defn; } // Insert the definition for the tuple tail->insertAfter(varDefn); tail = varDefn; // Insert the copies from the blank-intent strings to the locals // Update the arguments to the tuple call for (int i = 1; i <= n; i++) { DefExpr* localDefn = toDefExpr(workingFn->body->body.get(i)); Symbol* local = localDefn->sym; SymExpr* localExpr = new SymExpr(local); SymExpr* tupleArg = toSymExpr(tupleCall->get(i + 1)); SymExpr* copyArg = tupleArg->copy(); CallExpr* moveExpr = new CallExpr(PRIM_MOVE, localExpr, copyArg); tupleArg->setSymbol(local); tail->insertAfter(moveExpr); tail = moveExpr; } tail->insertAfter(new CallExpr(PRIM_MOVE, var, tupleCall)); } else { workingFn->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall)); workingFn->insertAtHead(new DefExpr(var)); } if (PartialCopyData* pci = getPartialCopyInfo(workingFn)) { // If this is a partial copy, // store the mapping for substitution later. pci->partialCopyMap.put(formal, var); } else { // Otherwise, do the substitution now. subSymbol(workingFn->body, formal, var); } } else { // !needTupleInBody substituteVarargTupleRefs(workingFn->body, n, formal, varargFormals); } if (workingFn->where) { if (needVarArgTupleAsWhole(workingFn->where, n, formal)) { VarSymbol* var = new VarSymbol(formal->name); CallExpr* move = new CallExpr(PRIM_MOVE, var, tupleCall->copy()); if (formal->hasFlag(FLAG_TYPE_VARIABLE)) { var->addFlag(FLAG_TYPE_VARIABLE); } workingFn->where->insertAtHead(move); workingFn->where->insertAtHead(new DefExpr(var)); subSymbol(workingFn->where, formal, var); } else { // !needVarArgTupleAsWhole() substituteVarargTupleRefs(workingFn->where, n, formal, varargFormals); } } formal->defPoint->remove(); } else { // Just documenting the current status. INT_FATAL(formal, "unexpected non-VarSymbol"); } } } // // Does 'ast' contain use(s) of the vararg tuple 'formal' // that require 'formal' as a whole tuple? // // needVarArgTupleAsWhole() and substituteVarargTupleRefs() should handle // the exact same set of SymExprs. // static bool needVarArgTupleAsWhole(BlockStmt* ast, int numArgs, ArgSymbol* formal) { std::vector<SymExpr*> symExprs; collectSymExprs(ast, symExprs); for_vector(SymExpr, se, symExprs) { if (se->symbol() == formal) { if (CallExpr* parent = toCallExpr(se->parentExpr)) { if (parent->isPrimitive(PRIM_TUPLE_EXPAND)) { // (...formal) -- does not require continue; } if (varargAccessIndex(se, parent, numArgs) > 0) { // formal(i) -- does not require continue; } if (isVarargSizeExpr(se, parent)) { // formal.size -- does not require continue; } } // Something else ==> may require. return true; } } // The 'formal' is used only in "does not require" cases. return false; } /************************************* | ************************************** * * * * * * ************************************** | *************************************/ static void replaceVarargAccess(CallExpr* parent, SymExpr* se, ArgSymbol* replFormal, SymbolMap& tempReps); // // Replace, in 'ast', uses of the vararg tuple 'formal' // with references to individual formals. // // needVarArgTupleAsWhole() and substituteVarargTupleRefs() should handle // the exact same set of SymExprs. // void substituteVarargTupleRefs(BlockStmt* ast, int numArgs, ArgSymbol* formal, std::vector<ArgSymbol*>& varargFormals) { std::vector<SymExpr*> symExprs; SymbolMap tempReps; collectSymExprs(ast, symExprs); for_vector(SymExpr, se, symExprs) { if (se->symbol() == formal) { if (CallExpr* parent = toCallExpr(se->parentExpr)) { SET_LINENO(parent); if (parent->isPrimitive(PRIM_TUPLE_EXPAND)) { // Replace 'parent' with a sequence of individual args. for_vector(ArgSymbol, arg, varargFormals) parent->insertBefore(new SymExpr(arg)); parent->remove(); continue; } if (int idxNum = varargAccessIndex(se, parent, numArgs)) { INT_ASSERT(1 <= idxNum && idxNum <= numArgs); ArgSymbol* replFormal = varargFormals[idxNum-1]; replaceVarargAccess(parent, se, replFormal, tempReps); continue; } if (isVarargSizeExpr(se, parent)) { parent->replace(new SymExpr(new_IntSymbol(numArgs))); continue; } } // Cases not "continue"-ed above should have been ruled out // by needVarArgTupleAsWhole(). INT_ASSERT(false); } else if (Symbol* replmt = tempReps.get(se->symbol())) { SET_LINENO(se); se->replace(new SymExpr(replmt)); } } } // // 'parent' corresponds to tuple(i); replace it with 'replFormal'. // // If 'parent' is the source of a prim_move into a temp 'dest', // then eliminate 'dest' altogether, replacing its uses with 'replFormal'. // // Q: Why not just keep move(dest,replFormal), which is simpler? // A: because 'move' does not preserv replFormal's ref-ness and const-ness, // so we will get errors when using dest on the l.h.s. and miss errors // when dest or deref(dest) is modified and it shouldn't. // Note that we are here before the code is resolved, so we do not // necessarily know whether 'replFormal' is a const and/or a ref. // To keep 'dest' around, instead of move we probably need to add // the AST equivalent of Chapel's "ref dest = replFormal;". // static void replaceVarargAccess(CallExpr* parent, SymExpr* se, ArgSymbol* replFormal, SymbolMap& tempReps) { if (CallExpr* move = toCallExpr(parent->parentExpr)) { if (move->isPrimitive(PRIM_MOVE)) { Symbol* dest = toSymExpr(move->get(1))->symbol(); if (dest->hasFlag(FLAG_TEMP)) { // Remove the def of 'dest'. dest->defPoint->remove(); move->remove(); // Uses of 'dest' will come later. We replace them with 'replFormal' // in substituteVarargTupleRefs() using 'tempReps'. tempReps.put(dest, replFormal); return; } } } // Otherwise, just replace 'parent'. parent->replace(new SymExpr(replFormal)); } /************************************* | ************************************** * * * * * * ************************************** | *************************************/ // Verifies the usage of this candidate function bool checkResolveFormalsWhereClauses(ResolutionCandidate* currCandidate) { /* * A derived generic type will use the type of its parent, * and expects this to be instantiated before it is. */ resolveFormals(currCandidate->fn); int coindex = -1; for_formals(formal, currCandidate->fn) { if (Symbol* actual = currCandidate->formalIdxToActual.v[++coindex]) { if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) { return false; } bool formalIsParam = formal->hasFlag(FLAG_INSTANTIATED_PARAM) || formal->intent == INTENT_PARAM; if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formalIsParam)) { return false; } } } // // Evaluate where clauses // if (!evaluateWhereClause(currCandidate->fn)) { return false; } return true; } // Verify that the generic formals are matched correctly bool checkGenericFormals(ResolutionCandidate* currCandidate) { /* * Early rejection of generic functions. */ int coindex = 0; for_formals(formal, currCandidate->fn) { if (formal->type != dtUnknown) { if (Symbol* actual = currCandidate->formalIdxToActual.v[coindex]) { if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) { return false; } if (formal->type->symbol->hasFlag(FLAG_GENERIC)) { Type* vt = actual->getValType(); Type* st = actual->type->scalarPromotionType; Type* svt = (vt) ? vt->scalarPromotionType : NULL; if (!canInstantiate(actual->type, formal->type) && (!vt || !canInstantiate(vt, formal->type)) && (!st || !canInstantiate(st, formal->type)) && (!svt || !canInstantiate(svt, formal->type))) { return false; } } else { bool formalIsParam = formal->hasFlag(FLAG_INSTANTIATED_PARAM) || formal->intent == INTENT_PARAM; if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formalIsParam)) { return false; } } } } ++coindex; } return true; } /************************************* | ************************************** * * * * * * ************************************** | *************************************/ // // Assuming 'parent' is an indexing expression into the tuple 'se', // return the index, between 1 and numArgs. Otherwise return 0. // static int varargAccessIndex(SymExpr* se, CallExpr* parent, int numArgs) { if (se == parent->baseExpr) { if(parent->numActuals() == 1) { VarSymbol* idxVar = toVarSymbol(toSymExpr(parent->get(1))->symbol()); if (idxVar && idxVar->immediate && idxVar->immediate->const_kind == NUM_KIND_INT) { int idxNum = idxVar->immediate->int_value(); if (1 <= idxNum && idxNum <= numArgs) return idxNum; // report an "index out of bounds" error otherwise? } } } return 0; } // // Is 'parent' the call 'se'.size? // static bool isVarargSizeExpr(SymExpr* se, CallExpr* parent) { if (parent->isNamed("size")) { // Is 'parent' a method call? if (parent->numActuals() == 2) { if (SymExpr* firstArg = toSymExpr(parent->get(1))) { if (firstArg->symbol()->type == dtMethodToken) { // If this fails, ensure that isVarargSizeExpr still works correctly. INT_ASSERT(parent->get(2) == se); return true; } } } } return false; }
34.403643
102
0.542095
[ "object", "vector" ]
ab8b8950c29866801af1ffffe877b6141efad74a
1,046
cc
C++
src/ray/core_worker/task_interface.cc
dmadeka/ray
4f8e100fe0417da4fe1098defbfa478088502244
[ "Apache-2.0" ]
null
null
null
src/ray/core_worker/task_interface.cc
dmadeka/ray
4f8e100fe0417da4fe1098defbfa478088502244
[ "Apache-2.0" ]
null
null
null
src/ray/core_worker/task_interface.cc
dmadeka/ray
4f8e100fe0417da4fe1098defbfa478088502244
[ "Apache-2.0" ]
null
null
null
#include "task_interface.h" namespace ray { Status CoreWorkerTaskInterface::SubmitTask(const RayFunction &function, const std::vector<TaskArg> &args, const TaskOptions &task_options, std::vector<ObjectID> *return_ids) { return Status::OK(); } Status CoreWorkerTaskInterface::CreateActor( const RayFunction &function, const std::vector<TaskArg> &args, const ActorCreationOptions &actor_creation_options, ActorHandle *actor_handle) { return Status::OK(); } Status CoreWorkerTaskInterface::SubmitActorTask(ActorHandle &actor_handle, const RayFunction &function, const std::vector<TaskArg> &args, const TaskOptions &task_options, std::vector<ObjectID> *return_ids) { return Status::OK(); } } // namespace ray
38.740741
84
0.536329
[ "vector" ]
ab926029fe8d03ce2409555d8196ae5da7805c9b
1,363
cpp
C++
Cpp/Codes/Practice/LeetCode/295 Find Median from Data Stream.cpp
QuincyWork/AllCodes
59fe045608dda924cb993dde957da4daff769438
[ "MIT" ]
null
null
null
Cpp/Codes/Practice/LeetCode/295 Find Median from Data Stream.cpp
QuincyWork/AllCodes
59fe045608dda924cb993dde957da4daff769438
[ "MIT" ]
null
null
null
Cpp/Codes/Practice/LeetCode/295 Find Median from Data Stream.cpp
QuincyWork/AllCodes
59fe045608dda924cb993dde957da4daff769438
[ "MIT" ]
1
2019-04-01T10:30:03.000Z
2019-04-01T10:30:03.000Z
#include <gtest\gtest.h> #include <common\util.h> #include <queue> #include <math.h> using namespace std; class MedianFinder { public: // Adds a number into the data structure. void addNum(int num) { if (maxHeap.size() == 0 || num < maxHeap.top()) { maxHeap.push(num); if (maxHeap.size() > minHeap.size()+1) { minHeap.push(maxHeap.top()); maxHeap.pop(); } } else { minHeap.push(num); if (minHeap.size() > maxHeap.size()+1) { maxHeap.push(minHeap.top()); minHeap.pop(); } } } // Returns the median of current data stream double findMedian() { double r = 0; if (maxHeap.size() == minHeap.size()) { r = (double)(maxHeap.top() + minHeap.top()) / 2; } else if(maxHeap.size() > minHeap.size()) { r = maxHeap.top(); } else { r = minHeap.top(); } return r; } private: priority_queue<int> maxHeap; priority_queue<int,vector<int>,greater<int>> minHeap; }; // Your MedianFinder object will be instantiated and called as such: // MedianFinder mf; // mf.addNum(1); // mf.findMedian(); TEST(LeetCode, tMedianFinder) { MedianFinder mf; mf.addNum(1); ASSERT_DOUBLE_EQ(mf.findMedian(),1.0); mf.addNum(2); ASSERT_DOUBLE_EQ(mf.findMedian(),1.5); mf.addNum(5); mf.addNum(11); mf.addNum(3); ASSERT_DOUBLE_EQ(mf.findMedian(),3.0); }
17.701299
68
0.608217
[ "object", "vector" ]
ab952c4343dae865ce2f2a36ed85546cfb6859b5
4,928
cpp
C++
src/IStrategizer/AttackEntityAction.cpp
ogail/IStrategizer
d214f150fdfee3c3a865a826546058d131dd9100
[ "Apache-2.0" ]
1
2017-12-20T13:53:09.000Z
2017-12-20T13:53:09.000Z
src/IStrategizer/AttackEntityAction.cpp
ogail/IStrategizer
d214f150fdfee3c3a865a826546058d131dd9100
[ "Apache-2.0" ]
null
null
null
src/IStrategizer/AttackEntityAction.cpp
ogail/IStrategizer
d214f150fdfee3c3a865a826546058d131dd9100
[ "Apache-2.0" ]
null
null
null
#include "AttackEntityAction.h" #include <cassert> #include "Vector2.h" #include "OnlineCaseBasedPlannerEx.h" #include "AbstractAdapter.h" #include "CellFeature.h" #include "CaseBasedReasonerEx.h" #include "DataMessage.h" #include "EngineAssist.h" #include "RtsGame.h" #include "GamePlayer.h" #include "GameTechTree.h" #include "GameType.h" #include "GameEntity.h" #include "AdapterEx.h" #include "EntityClassExist.h" #include "And.h" #include "Not.h" using namespace IStrategizer; using namespace Serialization; using namespace std; AttackEntityAction::AttackEntityAction() : Action(ACTIONEX_AttackEntity) { _params[PARAM_EntityClassId] = ECLASS_START; _params[PARAM_TargetEntityClassId] = ECLASS_START; CellFeature::Null().To(_params); } //---------------------------------------------------------------------------------------------- AttackEntityAction::AttackEntityAction(const PlanStepParameters& p_parameters) : Action(ACTIONEX_AttackEntity, p_parameters) { } //---------------------------------------------------------------------------------------------- bool AttackEntityAction::Execute(RtsGame& game, const WorldClock& p_clock) { EntityClassType attackerType = (EntityClassType)_params[PARAM_EntityClassId]; EntityClassType targetType = (EntityClassType)_params[PARAM_TargetEntityClassId]; AbstractAdapter *pAdapter = g_OnlineCaseBasedPlanner->Reasoner()->Adapter(); bool executed = false; // Adapt attacker m_attackerId = pAdapter->GetEntityObjectId(attackerType,AdapterEx::AttackerStatesRank); if (m_attackerId != INVALID_TID) { m_targetId = pAdapter->AdaptTargetEntity(targetType, Parameters()); if (m_targetId != INVALID_TID) { GameEntity* pAttacker = game.Self()->GetEntity(m_attackerId); _ASSERTE(pAttacker); pAttacker->Lock(this); executed = pAttacker->AttackEntity(m_targetId); } } return executed; } //---------------------------------------------------------------------------------------------- bool AttackEntityAction::AliveConditionsSatisfied(RtsGame& game) { bool attackerExists = g_Assist.DoesEntityObjectExist(m_attackerId); if (!attackerExists) { ConditionEx* failedCondition = new EntityClassExist(PLAYER_Self, (EntityClassType)_params[PARAM_EntityClassId], 1); m_history.Add(ESTATE_Failed, failedCondition); } return attackerExists; } //---------------------------------------------------------------------------------------------- bool AttackEntityAction::SuccessConditionsSatisfied(RtsGame& game) { _ASSERTE(PlanStepEx::GetState() == ESTATE_Executing); bool targetExists = g_Assist.DoesEntityObjectExist(m_targetId, PLAYER_Enemy); if (targetExists) { GameEntity* pGameTarget = game.Enemy()->GetEntity(m_targetId); _ASSERTE(pGameTarget); ObjectStateType targetState = (ObjectStateType)pGameTarget->P(OP_State); return targetState == OBJSTATE_UnderAttack; } else { return true; } } //---------------------------------------------------------------------------------------------- void AttackEntityAction::InitializePostConditions() { _postCondition = new Not(new EntityClassExist(PLAYER_Enemy, ECLASS_END, 1)); } //---------------------------------------------------------------------------------------------- void AttackEntityAction::InitializePreConditions() { vector<Expression*> m_terms; EntityClassType attacker = (EntityClassType)_params[PARAM_EntityClassId]; EntityClassType target = (EntityClassType)_params[PARAM_TargetEntityClassId]; m_terms.push_back(new EntityClassExist(PLAYER_Self, attacker, 1)); m_terms.push_back(new EntityClassExist(PLAYER_Enemy, target, 1)); _preCondition = new And(m_terms); } //---------------------------------------------------------------------------------------------- void AttackEntityAction::OnSucccess(RtsGame& game, const WorldClock& p_clock) { GameEntity* pAttacker = game.Self()->GetEntity(m_attackerId); if (pAttacker && pAttacker->IsLocked() && pAttacker->Owner() == this) pAttacker->Unlock(this); } //---------------------------------------------------------------------------------------------- void AttackEntityAction::OnFailure(RtsGame& game, const WorldClock& p_clock) { GameEntity* pAttacker = game.Self()->GetEntity(m_attackerId); if (pAttacker && pAttacker->IsLocked() && pAttacker->Owner() == this) pAttacker->Unlock(this); } //---------------------------------------------------------------------------------------------- bool AttackEntityAction::Equals(PlanStepEx* p_planStep) { return StepTypeId() == p_planStep->StepTypeId() && _params[PARAM_EntityClassId] == p_planStep->Parameter(PARAM_EntityClassId) && _params[PARAM_TargetEntityClassId] == p_planStep->Parameter(PARAM_TargetEntityClassId); }
36.776119
123
0.603896
[ "vector" ]
ab9a87f7b4048599f7b1944cb160d952546bdcd5
5,691
cpp
C++
Display/Display.cpp
ozanarmagan/NESEmulator
e4f7d5662caae85f1147fa8b57ce3dfa222ea164
[ "MIT" ]
11
2021-11-29T15:05:21.000Z
2022-03-25T06:36:19.000Z
Display/Display.cpp
ozanarmagan/NESEmulator
e4f7d5662caae85f1147fa8b57ce3dfa222ea164
[ "MIT" ]
null
null
null
Display/Display.cpp
ozanarmagan/NESEmulator
e4f7d5662caae85f1147fa8b57ce3dfa222ea164
[ "MIT" ]
null
null
null
#include "Display.h" namespace nesemulator { Display::Display(SDL_Event* event,Controller& controller) : eventPtr(event),controller(controller),notificationManager(renderer,font) { if(SDL_Init(SDL_INIT_EVERYTHING) != 0) std::cout << "ERROR: SDL Couldn't initialized!\n"; init(); SDL_AudioSpec audiospec; audiospec.freq = 44100; audiospec.format = AUDIO_F32SYS; audiospec.samples = 735; audiospec.channels = 1; audiospec.callback = NULL; auto audio_open = SDL_OpenAudio(&audiospec,NULL); if(audio_open < 0) std::cout << "ERROR! " << SDL_GetError() << std::endl; std::cout << "Audio Device Initialized\n"; std::cout << "Device Name: " << SDL_GetAudioDeviceName(audio_open,0) << std::endl; std::cout << "Frequency: " << audiospec.freq << std::endl; std::cout << "Samples: " << audiospec.samples << std::endl; std::cout << "Channels: " << (int)audiospec.channels << std::endl; SDL_PauseAudio(0); #ifdef DEBUG initDebug(); #endif } void Display::init() { window = SDL_CreateWindow("NES Emulator - OzanArmagan", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, DISPLAY_WIDTH, DISPLAY_HEIGHT, 0); TTF_Init(); if(!window) { std::cout << "Failed to create window\n"; std::cout << "SDL2 Error: " << SDL_GetError() << "\n"; return; } else std::cout << "SDL Window created!\n", //SDL_SetWindowBordered(window,SDL_FALSE); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); TTF_Font* font = TTF_OpenFont("./sans.ttf",36); notificationManager.setRenderer(renderer); notificationManager.setFont(font); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, RENDER_WIDTH, RENDER_HEIGHT); SDL_RenderSetLogicalSize(renderer, RENDER_WIDTH, RENDER_HEIGHT); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); } void Display::setPixel(int x, int y,PIXEL_RGB pixelColors) { PIXEL pixel = 0; pixel |= 255 << 24; pixel |= (PIXEL)pixelColors.r << 16; pixel |= (PIXEL)pixelColors.g << 8; pixel |= (PIXEL)pixelColors.b << 0; nextFrame[x + y * RENDER_WIDTH - 1] = pixel; } void Display::renderFrame() { SDL_RenderClear(renderer); SDL_UpdateTexture(texture, NULL, currentFrame, RENDER_WIDTH * sizeof(PIXEL)); SDL_RenderCopy(renderer, texture, NULL, NULL); notificationManager.render(); notificationManager.update(); SDL_RenderPresent(renderer); interval1 = interval0; interval0 = SDL_GetTicks(); SDL_SetWindowTitle(window,(std::string("NES Emulator FPS: " + std::to_string(1000.0 / (interval0 - interval1)))).c_str()); while(SDL_PollEvent(eventPtr)) { switch (eventPtr->type) { case SDL_QUIT: std::cout << "LOG: Quit has called! Good bye!\n"; exit(1); break; case SDL_CONTROLLERBUTTONDOWN: controller.setJoyButton(eventPtr->cbutton.button,eventPtr->cbutton.which); break; case SDL_CONTROLLERBUTTONUP: controller.clearJoyButton(eventPtr->cbutton.button,eventPtr->cbutton.which); break; case SDL_KEYDOWN: controller.setKey(eventPtr->key.keysym.scancode); break; case SDL_KEYUP: controller.clearKey(eventPtr->key.keysym.scancode); break; default: break; } } } void Display::frameDone() { for(int i = 0;i < RENDER_WIDTH * RENDER_HEIGHT;i++) currentFrame[i] = nextFrame[i]; } #ifdef DEBUG void Display::initDebug() { debugWindow = SDL_CreateWindow("DEBUG WINDOW", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, DEBUG_WIDTH * 2 , DEBUG_HEIGHT * 2 , 0); if(!debugWindow) { std::cout << "Failed to create debug window\n"; std::cout << "SDL2 Error: " << SDL_GetError() << "\n"; return; } else std::cout << "Debug Window created!\n", Drenderer = SDL_CreateRenderer(debugWindow, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); Dtexture = SDL_CreateTexture(Drenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, DEBUG_WIDTH, DEBUG_HEIGHT); SDL_RenderSetLogicalSize(Drenderer, DEBUG_WIDTH, DEBUG_HEIGHT); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); for(int i = 0;i < DEBUG_HEIGHT;i++) for(int j = 0;j < DEBUG_WIDTH;j++) setPixelDebug(i,j,{84,84,84}); } #endif #ifdef DEBUG void Display::renderDebugFrame() { SDL_UpdateTexture(Dtexture, NULL, debug, DEBUG_WIDTH * sizeof(PIXEL)); SDL_RenderCopy(Drenderer, Dtexture, NULL, NULL); SDL_RenderPresent(Drenderer); } void Display::setPixelDebug(int x, int y,PIXEL_RGB colors) { PIXEL pixel = 0; pixel |= 255 << 24; pixel |= (PIXEL)colors.r << 16; pixel |= (PIXEL)colors.g << 8; pixel |= (PIXEL)colors.b << 0; debug[x + y * DEBUG_WIDTH] = pixel; } #endif }
29.335052
146
0.574943
[ "render" ]
aba5dfed1d3d4ebc66be484b4b8898ac532fb27c
2,547
cpp
C++
Sesion16/main.cpp
Miguel445Ar/A-y-R-Algoritmos-1
c9b64573965d5c4371d2de1a1fff1a9425c34388
[ "CC0-1.0" ]
null
null
null
Sesion16/main.cpp
Miguel445Ar/A-y-R-Algoritmos-1
c9b64573965d5c4371d2de1a1fff1a9425c34388
[ "CC0-1.0" ]
null
null
null
Sesion16/main.cpp
Miguel445Ar/A-y-R-Algoritmos-1
c9b64573965d5c4371d2de1a1fff1a9425c34388
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <functional> #include <vector> using std::function; using std::vector; using std::cout; using std::cin; // left child -> 2 * i + 1 // right chuld -> 2 * i + 2 // parent of a node i -> (i - 1) / 2 template<class T> class Heap { vector<T>* heap; function<bool(T,T)> comp; public: Heap(function<bool(T,T)> comp): comp(comp){ heap = new vector<T>; } ~Heap(){ if (heap->empty()) heap->clear(); delete heap; } void push(T value){ heap->push_back(value); heapifyForInsertion(); } T pop(){ if(heap->size() == 0) return T(); T value = (*heap)[0]; (*heap)[0] = (*heap)[heap->size() - 1]; heap->pop_back(); heapyfyForElimination(); return value; } void print(){ for(auto elem: *heap){ cout << elem << " "; } cout << "\n"; } private: void heapifyForInsertion() { if (heap->size() <= 1) return; size_t child = heap->size() - 1; size_t parent = (child - 1) / 2; while (comp((*heap)[child],(*heap)[parent])){ swap((*heap)[child],(*heap)[parent]); if (parent == 0) break; child = parent; parent = (child - 1) / 2; } } void heapyfyForElimination(){ if(heap->size() <= 1) return; size_t parent = 0; while (true){ size_t leftChild = 2 * parent + 1; size_t rightChild = 2 * parent + 2; if (leftChild >= heap->size() && rightChild >= heap->size()) break; size_t r; if(leftChild >= heap->size()) r = rightChild; else if (rightChild >= heap->size()) r = leftChild; else r = (comp((*heap)[leftChild],(*heap)[rightChild]))? leftChild: rightChild; if(comp((*heap)[r],(*heap)[parent])){ swap((*heap)[r],(*heap)[parent]); parent = r; continue; } break; } } void swap(T& a, T& b){ T c = a; a = b; b = c; } }; int main(){ Heap<int> hp([](int a, int b) -> bool {return a < b;}); hp.push(5); hp.push(11); hp.push(12); hp.push(9); hp.push(7); hp.push(8); hp.push(14); hp.push(4); hp.print(); cout << "\nThe top element is: " << hp.pop() << "\n"; hp.print(); return 0; }
24.490385
90
0.44523
[ "vector" ]
abaf3b38509174b2d459a73bced366b6323917c9
3,810
cpp
C++
src/module/ModuleScene.cpp
marcorod94/Engine-Demo-MR
7fcbcfa809cbe21afaf44c35dff5dd9c443c3bfe
[ "Apache-2.0" ]
1
2020-01-24T18:28:26.000Z
2020-01-24T18:28:26.000Z
src/module/ModuleScene.cpp
marcorod94/Engine-Demo-MR
7fcbcfa809cbe21afaf44c35dff5dd9c443c3bfe
[ "Apache-2.0" ]
null
null
null
src/module/ModuleScene.cpp
marcorod94/Engine-Demo-MR
7fcbcfa809cbe21afaf44c35dff5dd9c443c3bfe
[ "Apache-2.0" ]
null
null
null
#include "main/Application.h" #include "ModuleScene.h" #include "GL/glew.h" #include "MathGeoLib.h" #include "ModuleProgram.h" #include "ModuleTexture.h" #include "ModuleCamera.h" #include "ModuleModel.h" #include "ModuleFileSystem.h" #include "component/Mesh.h" #include "component/Material.h" #include "module/ModuleInput.h" #include "module/ModuleRender.h" #include "component/Camera.h" #include <string> #include "util/DebugDraw.h" #include "imgui.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/istreamwrapper.h" #include <fstream> bool ModuleScene::Init() { root = CreateGameObject("Root Scene"); abbTree = new AABBTree(5); //sceneViewCamera Camera* cam = (Camera*) root->CreateComponent(ComponentType::Camera); //activeCamera GameObject* mainCamera = CreateGameObject("Main Camera"); Camera* cam2 = (Camera*)mainCamera->CreateComponent(ComponentType::Camera); mainCamera->parent = root; root->children.push_back(mainCamera); return true; } update_status ModuleScene::PreUpdate() { return UPDATE_CONTINUE; } update_status ModuleScene::Update() { return UPDATE_CONTINUE; } bool ModuleScene::CleanUp() { root->CleanUp(); return true; } GameObject* ModuleScene::CreateGameObject(const char* name) const { return new GameObject(name); } GameObject* ModuleScene::CreateGameObject(const char* name, const float3* pos, const Quat* rot) const { return new GameObject(name, pos, rot); } void ModuleScene::PickObject(const ImVec2& winSize, const ImVec2& winPos) { int mouseX, mouseY; SDL_GetGlobalMouseState(&mouseX, &mouseY); //float2 normalizedPos = float2(mouseX - winSize.x / 2, (winSize.y - mouseY) - winSize.y / 2).Normalized(); //float2 normalizedPos = float2((mouseX - (winPos.x - winSize.x) / 2) - winPos.x, ((winSize.y - winPos.y) / 2 - mouseY) - winPos.y).Normalized(); //float2 normalizedPos = float2(mouseX - winSize.x / 2, - mouseY / 2).Normalized(); //(mouseX - (winPos.x + (winSize.x / 2)) / (winSize.x / 2), ((winPos.y + (winSize.y / 2)) - mouseY) / (winSize.x / 2)) App->imgui->AddLog("Mouse X: %d, Y: %d", mouseX, mouseY); float2 normalizedPos = float2((mouseX - (winPos.x + (winSize.x / 2))) / (winSize.x / 2), ((winPos.y + (winSize.y / 2)) - mouseY) / (winSize.x / 2)); App->imgui->AddLog("X: %.2F, Y: %.2F", normalizedPos.x, normalizedPos.y); LineSegment ray; App->camera->loadedCameras[0]->CreateRay(normalizedPos, ray); GameObject* isIntersected = App->renderer->RayIntersectsObject(App->camera->loadedCameras[0]->frustum.pos, ray); dd::arrow(ray.a, ray.b, float3(0,0,1), 10.0f); dd::line(ray.a, ray.b, float3(0, 0, 1)); if (isIntersected != nullptr) { //App->imgui->AddLog("Selecting object: %s", isIntersected->name); App->imgui->selected = isIntersected->uuid; } else { return; } } void ModuleScene::LoadScene() { App->camera->CleanUp(); App->texture->CleanUp(); CleanUp(); char* buffer; App->filesys->Load(SCENE_FILE, &buffer); std::string content = ""; content.append(buffer); config.Parse(content.c_str()); assert(config.IsArray()); for (auto& item : config.GetArray()) { root->OnLoad(&item.GetObjectA(), nullptr); } } void ModuleScene::SaveScene() { config.SetArray(); root->OnSave(&config.GetArray(), &config.GetAllocator()); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); config.Accept(writer); std::string json(buffer.GetString(), buffer.GetSize()); App->filesys->Save(SCENE_FILE, json.c_str(), json.size()); } void ModuleScene::DrawAABBTree() { abbTree = new AABBTree(5); for (auto go : root->children) { Mesh* mesh = (Mesh*)go->FindComponent(ComponentType::Mesh); if (mesh != nullptr) { abbTree->insertObject(go); } } abbTree->DrawTree(); abbTree = nullptr; }
29.307692
149
0.69895
[ "mesh", "object" ]
abb64a18b71d66843caec4a6478f5e03fe2b550f
370
cpp
C++
reference.cpp
Arsenic-ATG/CP-setup
4bb07641e6778213263e86f8dd7c6bf9d6ac1c0f
[ "MIT" ]
3
2020-10-02T00:30:14.000Z
2021-02-21T15:43:25.000Z
reference.cpp
Arsenic-ATG/CP-setup
4bb07641e6778213263e86f8dd7c6bf9d6ac1c0f
[ "MIT" ]
6
2020-11-23T10:16:50.000Z
2020-12-12T08:44:14.000Z
reference.cpp
Arsenic-ATG/CP-setup
4bb07641e6778213263e86f8dd7c6bf9d6ac1c0f
[ "MIT" ]
3
2020-12-12T08:08:18.000Z
2021-09-03T14:36:57.000Z
// There will be more added to this file in the future #include <iostream> #include <string> #include <cmath> #include <vector> // to take input from a vector void input(std::vector<int> &v,int n) { for (int i = 0; i < n; ++i) { int e; std::cin>>e; v.push_back(e); } } int main() { int T; std::cin>>T; while(T--) { // solution goes here } return 0; }
13.214286
54
0.6
[ "vector" ]
abb85dd72eb6f2df6eeb209f6151394201a7f5d4
5,988
cpp
C++
src/test_ell2.cpp
gaowenliang/fsrk
4e6492b4bc133d0953bb85cf5416f0414c503644
[ "MIT" ]
31
2018-06-01T12:53:02.000Z
2022-03-22T07:06:30.000Z
src/test_ell2.cpp
gaowenliang/fsrk
4e6492b4bc133d0953bb85cf5416f0414c503644
[ "MIT" ]
1
2019-03-05T04:38:08.000Z
2019-04-18T12:04:15.000Z
src/test_ell2.cpp
gaowenliang/fsrk
4e6492b4bc133d0953bb85cf5416f0414c503644
[ "MIT" ]
4
2018-07-20T02:49:08.000Z
2021-09-29T13:54:32.000Z
#define BACKWARD_HAS_DW 1 #include "backward.hpp" namespace backward { backward::SignalHandling sh; } #include "fsrk/shape/circle.h" #include "fsrk/shape/ellipse.h" #include <code_utils/cv_utils/randomcolor.h> #include <code_utils/sys_utils/tic_toc.h> #include <opencv2/opencv.hpp> using namespace std; #define WINDOW_NAME "image" #define WINDOW_NAME2 "image2" void test1( ) { cv::Mat img( 1000, 1000, CV_8UC3, cv::Scalar( 0 ) ); cv::Rect rect( 0, 0, 1000, 1000 ); for ( int index1 = 1; index1 < 30; ++index1 ) for ( int index2 = 1; index2 < 10; ++index2 ) { cv::RandomColor3 color; cv::Ellipse ell( cv::Point2f( index1 * 30, index2 * 100 ), cv::Size2f( 100 + index1 * 10, 100 + index2 * 10 ), ( float )index1 * 360 / 10 ); ell.draw( img, color.getColor( ) ); if ( rect.contains( ell.getFocalPt0( ) ) ) img.at< cv::Vec3b >( ell.getFocalPt0( ) ) = color.getColorVec( ); if ( rect.contains( ell.getFocalPt1( ) ) ) img.at< cv::Vec3b >( ell.getFocalPt1( ) ) = color.getColorVec( ); } cv::namedWindow( WINDOW_NAME, cv::WINDOW_NORMAL ); cv::imshow( WINDOW_NAME, img ); } void test2( ) { cv::Mat img( 1000, 1000, CV_8UC3, cv::Scalar( 0 ) ); cv::Rect rect( 0, 0, 1000, 1000 ); cv::RandomColor3 color; cv::Ellipse ell( cv::Point2f( 500, 500 ), cv::Size2f( 500, 700 ), 65 ); ell.draw( img, color.getColor( ) ); color.randColor( ); cv::Ellipse ell2( cv::Point2f( 500, 500 ), cv::Size2f( 480, 680 ), 65 ); std::vector< cv::Point > pts; ell2.toPoly( 65, pts ); for ( auto& pt : pts ) { img.at< cv::Vec3b >( pt ) = color.getColorVec( ); color.randColor( ); } std::cout << "pt size " << pts.size( ) << "\n"; cv::ellipse( img, cv::RotatedRect( cv::Point2f( 500, 500 ), cv::Size2f( 400, 600 ), 65 ), color.getColor( ), -1 ); cv::namedWindow( WINDOW_NAME2, cv::WINDOW_NORMAL ); cv::imshow( WINDOW_NAME2, img ); } void test3( ) { cv::namedWindow( "image3", cv::WINDOW_NORMAL ); cv::Mat img( 1000, 1000, CV_8UC3, cv::Scalar( 0 ) ); cv::RandomColor3 color; sys_utils::tic::TicTocPart time; // cv::ellipse( img, // cv::RotatedRect( cv::Point2f( 500, 500 ), cv::Size2f( 50, 100 ), 65 ), // color.getColor( ), // -1 ); std::cout << "ellipse cost " << time.toc( ) << " ms\n"; cv::Ellipse ell2( cv::Point2f( 500, 500 ), cv::Size2f( 50, 100 ), 65 ); ell2.calcParam( ); int _num = 0; cv::Rect rect = ell2.box.boundingRect( ); for ( int row_id = 0; row_id < rect.height; ++row_id ) for ( int col_id = 0; col_id < rect.width; ++col_id ) { cv::Point2f pt( col_id + rect.x, row_id + rect.y ); if ( ell2.inside( pt ) ) { _num++; } } std::cout << "ell2 cost " << time.toc( ) << " ms\n"; std::cout << " _num " << _num << "\n"; for ( int i = 0; i < 10; ++i ) for ( int j = 0; j < 10; ++j ) { cv::Ellipse ell3( cv::Point2f( 50 + 100 * i, 50 + 100 * j ), // cv::Size2f( 1 + 10 * i, 1 + 10 * j ), 5 * ( i + j ) ); color.randColor( ); ell3.drawPoly( img, color.getColor( ) ); std::cout << "ell3 cost " << time.toc( ) << " ms\n"; } cv::imshow( "image3", img ); // cv::waitKey( 0 ); // Create the mask with the polygon // cv::Mat1b mask( rect.height, rect.width, uchar( 0 ) ); // cv::fillPoly( mask, pts, cv::Scalar( 255 ) ); // //// Compute the mean with the computed mask // cv::Scalar average = cv::mean( img( rect ), mask ); // // std::cout << average << std::endl; } void test4( ) { cv::namedWindow( "image4", cv::WINDOW_NORMAL ); cv::Mat img = cv::imread( "/home/gao/ws/devel/lib/camera_model/image_down/IMG_35.png", 0 ); cv::RandomColor1 color; sys_utils::tic::TicTocPart time; cv::Ellipse ell2( cv::Point2f( 500, 500 ), cv::Size2f( 50, 100 ), 65 ); ell2.calcParam( ); time.toc( ); int ell_sum = 0; int ell_num = 0; cv::Rect rect = ell2.box.boundingRect( ); for ( int row_id = 0; row_id < rect.height; ++row_id ) for ( int col_id = 0; col_id < rect.width; ++col_id ) { cv::Point2f pt( col_id + rect.x, row_id + rect.y ); if ( ell2.inside( pt ) ) { ell_sum += img.at< uchar >( pt ); ell_num++; } } std::cout << "ellipse cost " << time.toc( ) << " ms " << ell_sum << " " << ell_num << "\n"; int sum_ell2 = 0; int num_ell2 = 0; cv::Ellipse ell3( cv::Point2f( 500, 500 ), cv::Size2f( 50, 100 ), 65 ); // for ( int i = 0; i < 10; ++i ) // for ( int j = 0; j < 10; ++j ) { // cv::Ellipse ell3( cv::Point2f( 50 + 100 * i, 50 + 100 * j ), // // cv::Size2f( 1 + 10 * i, 1 + 10 * j ), // 5 * ( i + j ) ); // color.randColor( ); // std::cout << "color " << color.getColor( ) << "\n"; ell3.sumPoly( img, sum_ell2, num_ell2 ); std::cout << "ell3 cost " << time.toc( ) << " ms " << sum_ell2 << " " << num_ell2 << "\n"; } cv::imshow( "image4", img ); // cv::waitKey( 0 ); // Create the mask with the polygon // cv::Mat1b mask( rect.height, rect.width, uchar( 0 ) ); // cv::fillPoly( mask, pts, cv::Scalar( 255 ) ); // //// Compute the mean with the computed mask // cv::Scalar average = cv::mean( img( rect ), mask ); // // std::cout << average << std::endl; } int main( ) { // test1( ); // test2( ); // test3( ); test4( ); cv::waitKey( 0 ); return 0; }
28.927536
98
0.492318
[ "shape", "vector" ]
abbe3887948e6568b63045080e66e25a0d08ff09
2,344
cpp
C++
src/object_uart_settings.cpp
ic3man5/python_ics
e2dfbb60e14d6292a14c6f7685ca8dd4ce2f6916
[ "Unlicense" ]
1
2019-07-22T07:19:22.000Z
2019-07-22T07:19:22.000Z
src/object_uart_settings.cpp
ic3man5/python_ics
e2dfbb60e14d6292a14c6f7685ca8dd4ce2f6916
[ "Unlicense" ]
null
null
null
src/object_uart_settings.cpp
ic3man5/python_ics
e2dfbb60e14d6292a14c6f7685ca8dd4ce2f6916
[ "Unlicense" ]
null
null
null
#include "object_uart_settings.h" PyTypeObject uart_settings_object_type = { PyVarObject_HEAD_INIT(NULL, 0) MODULE_NAME "." UART_SETTINGS_OBJECT_NAME, /* tp_name */ sizeof(uart_settings_object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)0, /* tp_dealloc */ 0, /* tp_print */ (getattrfunc)uart_settings_object_getattr, /* tp_getattr */ (setattrfunc)uart_settings_object_setattr, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ UART_SETTINGS_OBJECT_NAME" object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ uart_settings_object_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)uart_settings_object_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; bool setup_uart_settings_object(PyObject* module) { uart_settings_object_type.tp_new = PyType_GenericNew; if (PyType_Ready(&uart_settings_object_type) < 0) { return false; } Py_INCREF(&uart_settings_object_type); PyModule_AddObject(module, UART_SETTINGS_OBJECT_NAME, (PyObject*)&uart_settings_object_type); return true; }
42.618182
97
0.458191
[ "object" ]
abc053096ecebab55ee187760c0ed68f156d943f
666
cpp
C++
Week-4/Editorials/Contest_1/problem_2.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
58
2020-08-02T16:38:43.000Z
2021-04-11T15:17:07.000Z
Week-4/Editorials/Contest_1/problem_2.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
29
2020-08-03T08:48:05.000Z
2020-10-05T08:25:09.000Z
Week-4/Editorials/Contest_1/problem_2.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
44
2020-08-02T16:51:08.000Z
2021-03-04T13:51:01.000Z
int equalStacks(vector<int> h1, vector<int> h2, vector<int> h3) { stack<int>s1,s2,s3; s1.push(0); s2.push(0); s3.push(0); for(int i=h1.size()-1;i>=0;i--) s1.push(s1.top()+h1[i]); for(int i=h2.size()-1;i>=0;i--) s2.push(s2.top()+h2[i]); for(int i=h3.size()-1;i>=0;i--) s3.push(s3.top()+h3[i]); while(true) { if(s1.top()==s2.top()&&s1.top()==s3.top()) return s1.top(); int temp = min(s1.top(),min(s2.top(),s3.top())); while(s1.top()>temp) s1.pop(); while(s2.top()>temp) s2.pop(); while(s3.top()>temp) s3.pop(); } }
25.615385
64
0.453453
[ "vector" ]
abc1887d21c29373ff6405f7a655b20d4a80349c
39,799
cpp
C++
segmatch/src/segmatch.cpp
jidebingfeng/segmatch
c662324d23b9e049fbb49b52cda7895d1a4d2798
[ "BSD-3-Clause" ]
13
2018-11-28T12:02:48.000Z
2021-12-22T01:04:49.000Z
segmatch/src/segmatch.cpp
yuekaka/segmatch
c662324d23b9e049fbb49b52cda7895d1a4d2798
[ "BSD-3-Clause" ]
2
2019-03-03T01:50:51.000Z
2019-08-19T08:06:41.000Z
segmatch/src/segmatch.cpp
yuekaka/segmatch
c662324d23b9e049fbb49b52cda7895d1a4d2798
[ "BSD-3-Clause" ]
8
2019-06-18T19:40:35.000Z
2020-06-15T17:43:06.000Z
#include "segmatch/segmatch.hpp" #include <algorithm> #include <limits> #include <laser_slam/common.hpp> #include <pcl/recognition/cg/geometric_consistency.h> namespace segmatch { using namespace laser_slam; SegMatch::SegMatch(const SegMatchParams& params) { init(params); } SegMatch::SegMatch() { LOG(INFO) << "Do not forget to initialize SegMatch."; } SegMatch::~SegMatch() { descriptors_.reset(); segmenter_.reset(); } void SegMatch::init(const SegMatchParams& params, unsigned int num_tracks) { params_ = params; descriptors_ = std::unique_ptr<Descriptors>(new Descriptors(params.descriptors_params)); segmenter_ = create_segmenter(params.segmenter_params); classifier_ = std::unique_ptr<OpenCvRandomForest>( new OpenCvRandomForest(params.classifier_params)); // Create containers for the segmentation poses. CHECK_GT(num_tracks, 0u); for (unsigned int i = 0u; i < num_tracks; ++i) { segmentation_poses_.push_back(laser_slam::Trajectory()); } } void SegMatch::setParams(const SegMatchParams& params) { LOG(INFO) << "Reseting segmatch's params."; params_ = params; classifier_->resetParams(params.classifier_params); LOG(INFO) << "GC resolution " << params_.geometric_consistency_params.resolution; LOG(INFO) << "GC min cluster size " << params_.geometric_consistency_params.min_cluster_size; } void SegMatch::processAndSetAsSourceCloud(const PointICloud& source_cloud, const laser_slam::Pose& latest_pose, unsigned int track_id) { Clock clock; // Save the segmentation pose. segmentation_poses_[track_id][latest_pose.time_ns] = latest_pose.T_w; last_processed_source_cloud_ = track_id; // Apply a cylindrical filter on the input cloud. PointICloud filtered_cloud = source_cloud; applyCylindricalFilter(laserSlamPoseToPclPoint(latest_pose), params_.segmentation_radius_m, params_.segmentation_height_above_m, params_.segmentation_height_below_m, &filtered_cloud); n_points_in_source_.push_back(filtered_cloud.size()); // Segment the cloud and set segment information. if (segmented_source_clouds_.find(track_id) == segmented_source_clouds_.end()) { segmented_source_clouds_[track_id] = SegmentedCloud(); } segmenter_->segment(filtered_cloud, &segmented_source_clouds_[track_id]); // Filter the boundary segments. if (params_.filter_boundary_segments) { filterBoundarySegmentsOfSourceCloud(laserSlamPoseToPclPoint(latest_pose), track_id); } LOG(INFO) << "Removing too near segments from source map."; filterNearestSegmentsInCloud(&segmented_source_clouds_[track_id], params_.centroid_distance_threshold_m, 5u); segmented_source_clouds_[track_id].setTimeStampOfSegments(latest_pose.time_ns); segmented_source_clouds_[track_id].setLinkPoseOfSegments(latest_pose.T_w); segmented_source_clouds_[track_id].setTrackId(track_id); // Describe the cloud. descriptors_->describe(&segmented_source_clouds_[track_id]); clock.takeTime(); segmentation_and_description_timings_.emplace(latest_pose.time_ns, clock.getRealTime()); n_segments_in_source_.push_back(segmented_source_clouds_[track_id].getNumberOfValidSegments()); } void SegMatch::processAndSetAsTargetCloud(const PointICloud& target_cloud) { // Process the cloud. processCloud(target_cloud, &segmented_target_cloud_); // Overwrite the old target. classifier_->setTarget(segmented_target_cloud_); } void SegMatch::transferSourceToTarget(unsigned int track_id, laser_slam::Time timestamp_ns) { Clock clock; target_queue_.push_back(segmented_source_clouds_[track_id]); // Remove empty clouds from queue. std::vector<SegmentedCloud>::iterator it = target_queue_.begin(); while(it != target_queue_.end()) { if(it->empty()) { it = target_queue_.erase(it); } else { ++it; } } unsigned int num_cloud_transfered = 0u; if (!target_queue_.empty()) { if (params_.filter_duplicate_segments) { LOG(INFO) << "Source cloud size before duplicates: " << target_queue_.at(0u).getNumberOfValidSegments(); filterDuplicateSegmentsOfTargetMap(&target_queue_.at(0u)); LOG(INFO) << "Source cloud size after duplicates: " << target_queue_.at(0u).getNumberOfValidSegments(); } segmented_target_cloud_.addSegmentedCloud(target_queue_.at(0u)); target_queue_.erase(target_queue_.begin()); ++num_cloud_transfered; } if (num_cloud_transfered > 0u) { classifier_->setTarget(segmented_target_cloud_); } clock.takeTime(); source_to_target_timings_.emplace(timestamp_ns, clock.getRealTime()); } void SegMatch::processCloud(const PointICloud& target_cloud, SegmentedCloud* segmented_cloud, std::vector<double>* timings) { laser_slam::Clock clock; segmenter_->segment(target_cloud, segmented_cloud); if (timings != NULL) { clock.takeTime(); // First timing is segmentation. timings->push_back(clock.getRealTime()); } LOG(INFO) << "Removing too near segments from source map."; filterNearestSegmentsInCloud(segmented_cloud, params_.centroid_distance_threshold_m, 5u); std::vector<double> segmentation_timings; descriptors_->describe(segmented_cloud, &segmentation_timings); if (timings != NULL && !segmentation_timings.empty()) { // Following timings are description. for (size_t i = 0u; i < segmentation_timings.size(); ++i) { timings->push_back(segmentation_timings[i]); } } } PairwiseMatches SegMatch::findMatches(PairwiseMatches* matches_after_first_stage, unsigned int track_id, laser_slam::Time timestamp_ns) { Clock clock; PairwiseMatches candidates; if (!segmented_source_clouds_[track_id].empty()) { candidates = classifier_->findCandidates(segmented_source_clouds_[track_id], matches_after_first_stage); } clock.takeTime(); matching_timings_.emplace(timestamp_ns, clock.getRealTime()); return candidates; } Time findTimeOfClosestPose(const Trajectory& poses, std::vector<Segment>& segments) { CHECK(!poses.empty()); CHECK(!segments.empty()); // Compute center of segments. PclPoint segments_center; for (const auto& segment: segments) { segments_center.x += segment.centroid.x; segments_center.y += segment.centroid.y; segments_center.z += segment.centroid.z; } segments_center.x /= double(segments.size()); segments_center.y /= double(segments.size()); segments_center.z /= double(segments.size()); double minimum_distance_m = std::numeric_limits<double>::max(); Time closest_pose_time_ns; for (const auto& pose: poses) { double distance_m = pointToPointDistance(se3ToPclPoint(pose.second), segments_center); if (distance_m < minimum_distance_m) { minimum_distance_m = distance_m; closest_pose_time_ns = pose.first; } } return closest_pose_time_ns; } bool SegMatch::filterMatches(const PairwiseMatches& predicted_matches, PairwiseMatches* filtered_matches_ptr, RelativePose* loop_closure, std::vector<PointICloudPair>* matched_segment_clouds, unsigned int track_id, laser_slam::Time timestamp_ns) { if (matched_segment_clouds != NULL) { matched_segment_clouds->clear(); } PairwiseMatches filtered_matches; Eigen::Matrix4f transformation = Eigen::Matrix4f::Identity(); Clock clock; if (!predicted_matches.empty()) { //TODO: use a (gc) filtering class for an extra layer of abstraction? // Build point clouds out of the centroids for geometric consistency grouping. pcl::CorrespondencesPtr correspondences(new pcl::Correspondences()); PointCloudPtr first_cloud(new PointCloud()); PointCloudPtr second_cloud(new PointCloud()); // Create clouds for geometric consistency. for (size_t i = 0u; i < predicted_matches.size(); ++i) { // First centroid. PclPoint first_centroid = predicted_matches.at(i).getCentroids().first; first_cloud->push_back(first_centroid); // Second centroid. PclPoint second_centroid = predicted_matches.at(i).getCentroids().second; second_cloud->push_back(second_centroid); float squared_distance = 1.0 - predicted_matches.at(i).confidence_; correspondences->push_back(pcl::Correspondence(i, i, squared_distance)); } if (!correspondences->empty()) { // Perform geometric consistency grouping. RotationsTranslations correspondence_transformations; Correspondences clustered_corrs; pcl::GeometricConsistencyGrouping<PclPoint, PclPoint> geometric_consistency_grouping; geometric_consistency_grouping.setGCSize(params_.geometric_consistency_params.resolution); geometric_consistency_grouping.setGCThreshold( params_.geometric_consistency_params.min_cluster_size); geometric_consistency_grouping.setInputCloud(first_cloud); geometric_consistency_grouping.setSceneCloud(second_cloud); geometric_consistency_grouping.setModelSceneCorrespondences(correspondences); geometric_consistency_grouping.recognize(correspondence_transformations, clustered_corrs); // Filter the matches by segment timestamps. LOG(INFO) << "Filtering the matches based on timestamps."; Correspondences time_filtered_clustered_corrs; for (const auto& cluster: clustered_corrs) { pcl::Correspondences time_filtered_cluster; for (const auto& match: cluster) { PairwiseMatch pairwise_match = predicted_matches.at(match.index_query); Segment source_segment, target_segment; if (segmented_source_clouds_[track_id].findValidSegmentById(pairwise_match.ids_.first, &source_segment)) { if (segmented_target_cloud_.findValidSegmentById(pairwise_match.ids_.second, &target_segment)) { if (source_segment.track_id != target_segment.track_id || std::max(source_segment.timestamp_ns, target_segment.timestamp_ns) >= std::min(source_segment.timestamp_ns, target_segment.timestamp_ns) + params_.min_time_between_segment_for_matches_ns) { time_filtered_cluster.push_back(match); } else { LOG(INFO) << "Removed match with source_segment.timestamp_ns " << source_segment.timestamp_ns << " and target_segment.timestamp_ns " << target_segment.timestamp_ns; } } else { LOG(INFO) << "Could not find target segment when filtering on timestamps"; } } else { LOG(INFO) << "Could not find source segment when filtering on timestamps"; } } time_filtered_clustered_corrs.push_back(time_filtered_cluster); LOG(INFO) << "Cluster had size " << cluster.size() << " before and " << time_filtered_cluster.size() << " after."; } clustered_corrs = time_filtered_clustered_corrs; if (!clustered_corrs.empty()) { // Find largest cluster. size_t largest_cluster_size = 0; size_t largest_cluster_index = 0; for (size_t i = 0u; i < clustered_corrs.size(); ++i) { LOG(INFO) << "Cluster " << i << " has " << clustered_corrs[i].size() << "segments."; if (clustered_corrs[i].size() >= largest_cluster_size) { largest_cluster_size = clustered_corrs[i].size(); largest_cluster_index = i; } } LOG(INFO) << "Largest cluster: " << largest_cluster_size << " matches."; // Catch the cases when PCL returns clusters smaller than the minimum cluster size. if (largest_cluster_size >= params_.geometric_consistency_params.min_cluster_size) { // Create pairwise matches from largest cluster pcl::Correspondences largest_cluster = clustered_corrs.at(largest_cluster_index); LOG(INFO) << "Returning the largest cluster at index " << largest_cluster_index << "...of size " << largest_cluster.size() << "."; for (size_t i = 0u; i < largest_cluster.size(); ++i) { // TODO: This assumes the matches from which the cloud was created // are indexed in the same way as the cloud. // (i.e. match[i] -> first_cloud[i] with second_cloud[i]) // Otherwise, this check will fail. CHECK(largest_cluster.at(i).index_query == largest_cluster.at(i).index_match); filtered_matches.push_back(predicted_matches.at(largest_cluster.at(i).index_query)); } transformation = correspondence_transformations.at(largest_cluster_index); // Save the transformation. last_transformation_ = transformation; } } } clock.takeTime(); geometric_verification_timings_.emplace(timestamp_ns, clock.getRealTime()); // If desired, pass the filtered matches. if (filtered_matches_ptr != NULL && !filtered_matches.empty()) { *filtered_matches_ptr = filtered_matches; } // If desired, return the matched segments pointcloud. if (matched_segment_clouds != NULL && !filtered_matches.empty()) { LOG(INFO) << "Returning " << filtered_matches.size() << " matching segment clouds."; for (size_t i = 0u; i < filtered_matches.size(); ++i) { PointICloudPair cloud_pair; Segment segment; segmented_source_clouds_[track_id].findValidSegmentById(filtered_matches[i].ids_.first, &segment); for (size_t i = 0u; i < segment.point_cloud.size(); ++i) { segment.point_cloud[i].x -= segment.centroid.x; segment.point_cloud[i].y -= segment.centroid.y; segment.point_cloud[i].z -= segment.centroid.z; } cloud_pair.first = segment.point_cloud; segmented_target_cloud_.findValidSegmentById( filtered_matches[i].ids_.second, &segment); for (size_t i = 0u; i < segment.point_cloud.size(); ++i) { segment.point_cloud[i].x -= segment.centroid.x; segment.point_cloud[i].y -= segment.centroid.y; segment.point_cloud[i].z -= segment.centroid.z; } cloud_pair.second = segment.point_cloud; matched_segment_clouds->push_back(cloud_pair); } } // If desired, return the loop-closure. if (loop_closure != NULL && !filtered_matches.empty()) { LOG(INFO) << "Found a loop"; loops_timestamps_.push_back(timestamp_ns); laser_slam::Clock clock; // Find the trajectory poses to be linked by the loop-closure. // For each segment, find the timestamp of the closest segmentation pose. std::vector<Time> source_segmentation_times; std::vector<Time> target_segmentation_times; std::vector<Id> source_track_ids; std::vector<Id> target_track_ids; std::vector<Segment> source_segments; std::vector<Segment> target_segments; for (const auto& match: filtered_matches) { Segment segment; CHECK(segmented_source_clouds_[track_id].findValidSegmentById(match.ids_.first, &segment)); source_segmentation_times.push_back(findTimeOfClosestSegmentationPose(segment)); source_segments.push_back(segment); source_track_ids.push_back(segment.track_id); LOG(INFO) << "Source Track id " << segment.track_id << " Source segment ID " << segment.segment_id; CHECK(segmented_target_cloud_.findValidSegmentById(match.ids_.second, &segment)); target_segmentation_times.push_back(findTimeOfClosestSegmentationPose(segment)); target_segments.push_back(segment); target_track_ids.push_back(segment.track_id); LOG(INFO) << "Target Track id " << segment.track_id << " Source segment ID " << segment.segment_id; } const Id source_track_id = findMostOccuringId(source_track_ids); const Id target_track_id = findMostOccuringId(target_track_ids); LOG(INFO) << "source_track_id " << source_track_id << " target_track_id " << target_track_id; const Time target_most_occuring_time = findMostOccuringTime(target_segmentation_times); LOG(INFO) << "Finding source_track_time_ns and target_track_time_ns"; Time source_track_time_ns, target_track_time_ns; if (source_track_id != target_track_id) { // Get the head of the source trajectory. Time trajectory_last_time_ns = segmentation_poses_[source_track_id].rbegin()->first; Time start_time_of_head_ns; if (trajectory_last_time_ns > params_.min_time_between_segment_for_matches_ns) { start_time_of_head_ns = trajectory_last_time_ns - params_.min_time_between_segment_for_matches_ns; } else { start_time_of_head_ns = 0u; } LOG(INFO) << "start_time_of_head_ns " << start_time_of_head_ns; Trajectory head_poses; for (const auto pose: segmentation_poses_[source_track_id]) { if (pose.first > start_time_of_head_ns) { head_poses.emplace(pose.first, pose.second); } } LOG(INFO) << "head_poses.size() " << head_poses.size(); // Get a window over the target trajectory. const Time half_window_size_ns = 180000000000u; const Time window_max_value_ns = target_most_occuring_time + half_window_size_ns; Time window_min_value_ns; if (target_most_occuring_time > half_window_size_ns) { window_min_value_ns = target_most_occuring_time - half_window_size_ns; } else { window_min_value_ns = 0u; } Trajectory poses_in_window; for (const auto& pose: segmentation_poses_[target_track_id]) { if (pose.first >= window_min_value_ns && pose.first <= window_max_value_ns) { // Compute center of segments. PclPoint segments_center; for (const auto& segment: target_segments) { segments_center.z += segment.centroid.z; } segments_center.z /= double(target_segments.size()); // Check that pose lies below the segments center of mass. if (!params_.check_pose_lies_below_segments || pose.second.getPosition()(2) < segments_center.z) { poses_in_window.emplace(pose.first, pose.second); } } } source_track_time_ns = findTimeOfClosestPose(head_poses, source_segments); target_track_time_ns = findTimeOfClosestPose(poses_in_window, target_segments); } else { // Split the trajectory into head and tail. Time trajectory_last_time_ns = segmentation_poses_[source_track_id].rbegin()->first; CHECK_GT(trajectory_last_time_ns, params_.min_time_between_segment_for_matches_ns); Time start_time_of_head_ns = trajectory_last_time_ns - params_.min_time_between_segment_for_matches_ns; Trajectory tail_poses, head_poses; for (const auto pose: segmentation_poses_[source_track_id]) { if (pose.first < start_time_of_head_ns) { tail_poses.emplace(pose.first, pose.second); } else { head_poses.emplace(pose.first, pose.second); } } source_track_time_ns = findTimeOfClosestPose(head_poses, source_segments); target_track_time_ns = findTimeOfClosestPose(tail_poses, target_segments); } LOG(INFO) << "Took " << clock.getRealTime() << " ms to find the LC pose times."; LOG(INFO) << "source_track_time_ns " << source_track_time_ns; LOG(INFO) << "target_track_time_ns " << target_track_time_ns; loop_closure->time_a_ns = target_track_time_ns; loop_closure->time_b_ns = source_track_time_ns; loop_closure->track_id_a = target_track_id; loop_closure->track_id_b = source_track_id; SE3 w_T_a_b = fromApproximateTransformationMatrix(transformation); loop_closure->T_a_b = w_T_a_b; // Save the loop closure. loop_closures_.push_back(*loop_closure); } // Save a copy of the fitered matches. last_filtered_matches_ = filtered_matches; last_predicted_matches_ = predicted_matches; } return !filtered_matches.empty(); } void SegMatch::update(const std::vector<laser_slam::Trajectory>& trajectories) { Clock clock; CHECK_EQ(trajectories.size(), segmentation_poses_.size()); // Update the segmentation positions. for (size_t i = 0u; i < trajectories.size(); ++i) { for (auto& pose: segmentation_poses_[i]){ pose.second = trajectories.at(i).at(pose.first); } } // Update the source, target and clouds in the buffer. for (auto& source_cloud: segmented_source_clouds_) { source_cloud.second.updateSegments(trajectories); } segmented_target_cloud_.updateSegments(trajectories); for (auto& segmented_cloud: target_queue_) { segmented_cloud.updateSegments(trajectories); } // Update the last filtered matches. for (auto& match: last_filtered_matches_) { Segment segment; // TODO Replaced the CHECK with a if. How should we handle the case // when one segment was removed during duplicate check? if (segmented_source_clouds_[last_processed_source_cloud_]. findValidSegmentById(match.ids_.first, &segment)) { match.centroids_.first = segment.centroid; } if (segmented_target_cloud_.findValidSegmentById(match.ids_.second, &segment)) { match.centroids_.second = segment.centroid; } } for (auto& match: last_predicted_matches_) { Segment segment; if (segmented_source_clouds_[last_processed_source_cloud_]. findValidSegmentById(match.ids_.first, &segment)) { match.centroids_.first = segment.centroid; } if (segmented_target_cloud_.findValidSegmentById(match.ids_.second, &segment)) { match.centroids_.second = segment.centroid; } } // Filter duplicates. LOG(INFO) << "Removing too near segments from target map."; filterNearestSegmentsInCloud(&segmented_target_cloud_, params_.centroid_distance_threshold_m, 5u); clock.takeTime(); update_timings_.emplace(trajectories[0u].rbegin()->first, clock.getRealTime()); } void SegMatch::getSourceRepresentation(PointICloud* source_representation, const double& distance_to_raise, unsigned int track_id) const { if (segmented_source_clouds_.find(track_id) != segmented_source_clouds_.end()) { segmentedCloudToCloud(segmented_source_clouds_.at(track_id).transformed( Eigen::Affine3f(Eigen::Translation3f(0,0,distance_to_raise)).matrix()), source_representation); } } void SegMatch::getTargetRepresentation(PointICloud* target_representation) const { segmentedCloudToCloud(segmented_target_cloud_ , target_representation); } void SegMatch::getTargetSegmentsCentroids(PointICloud* segments_centroids) const { CHECK_NOTNULL(segments_centroids); PointICloud cloud; std::vector<int> permuted_indexes; for (unsigned int i = 0u; i < segmented_target_cloud_.getNumberOfValidSegments(); ++i) { permuted_indexes.push_back(i); } std::random_shuffle(permuted_indexes.begin(), permuted_indexes.end()); unsigned int i = 0u; for (std::unordered_map<Id, Segment>::const_iterator it = segmented_target_cloud_.begin(); it != segmented_target_cloud_.end(); ++it) { PointI centroid; Segment segment = it->second; centroid.x = segment.centroid.x; centroid.y = segment.centroid.y; centroid.z = segment.centroid.z; centroid.intensity = permuted_indexes[i]; cloud.points.push_back(centroid); ++i; } cloud.width = 1; cloud.height = cloud.points.size(); // TODO use move to to avoid deep copy. *segments_centroids = cloud; } void SegMatch::getSourceSegmentsCentroids(PointICloud* segments_centroids, unsigned int track_id) const { // TODO combine with function above and reuse code. CHECK_NOTNULL(segments_centroids); if (segmented_source_clouds_.find(track_id) != segmented_source_clouds_.end()) { PointICloud cloud; std::vector<int> permuted_indexes; for (unsigned int i = 0u; i < segmented_source_clouds_.at(track_id).getNumberOfValidSegments(); ++i) { permuted_indexes.push_back(i); } std::random_shuffle(permuted_indexes.begin(), permuted_indexes.end()); unsigned int i = 0u; for (std::unordered_map<Id, Segment>::const_iterator it = segmented_source_clouds_.at(track_id).begin();it != segmented_source_clouds_.at(track_id).end(); ++it) { PointI centroid; Segment segment = it->second; centroid.x = segment.centroid.x; centroid.y = segment.centroid.y; centroid.z = segment.centroid.z; centroid.intensity = permuted_indexes[i]; cloud.points.push_back(centroid); ++i; } cloud.width = 1; cloud.height = cloud.points.size(); // TODO use move to to avoid deep copy. *segments_centroids = cloud; } } void SegMatch::getLoopClosures(std::vector<laser_slam::RelativePose>* loop_closures) const { CHECK_NOTNULL(loop_closures); *loop_closures = loop_closures_; } void SegMatch::getPastMatchesRepresentation(PointPairs* past_matches, PointPairs* invalid_past_matches) const { // TODO } void SegMatch::getLatestMatch(int64_t* time_a, int64_t* time_b, Eigen::Matrix4f* transform_a_b, std::vector<int64_t>* collector_times) const { // TODO } void SegMatch::filterBoundarySegmentsOfSourceCloud(const PclPoint& center, unsigned int track_id) { if (!segmented_source_clouds_[track_id].empty()) { const double squared_radius_m = (params_.segmentation_radius_m - 1.0) * (params_.segmentation_radius_m -1.0); const double height_above_m = params_.segmentation_height_above_m - 1.0; const double height_below_m = params_.segmentation_height_below_m - 1.0; // Get a list of segments with at least one point outside the boundary. std::vector<Id> boundary_segments_ids; for (std::unordered_map<Id, Segment>::const_iterator it = segmented_source_clouds_[track_id].begin(); it != segmented_source_clouds_[track_id].end(); ++it) { Segment segment = it->second; PointICloud segment_cloud = segment.point_cloud; // Loop over points until one is found outside of the boundary. for (size_t j = 0u; j < segment_cloud.size(); ++j) { PointI point = segment_cloud.at(j); point.x -= center.x; point.y -= center.y; if ((point.x * point.x + point.y * point.y) >= squared_radius_m) { // If found, add the segment to the deletion list, and move on to the next segment. boundary_segments_ids.push_back(segment.segment_id); break; } if (point.z > center.z + height_above_m) { boundary_segments_ids.push_back(segment.segment_id); break; } if (point.z < center.z - height_below_m){ boundary_segments_ids.push_back(segment.segment_id); break; } } } // Remove boundary segments. size_t n_removals; segmented_source_clouds_[track_id].deleteSegmentsById(boundary_segments_ids, &n_removals); LOG(INFO) << "Removed " << n_removals << " boundary segments."; } } void SegMatch::filterDuplicateSegmentsOfTargetMap(SegmentedCloud* cloud_to_be_added) { if (!cloud_to_be_added->empty()) { laser_slam::Clock clock; std::vector<Id> duplicate_segments_ids; std::vector<Id> duplicate_segments_ids_in_cloud_to_add; std::vector<Id> target_segment_ids; // Get a cloud with segments centroids which are close to the cloud to be added. PointCloud centroid_cloud = segmented_target_cloud_.centroidsAsPointCloud( cloud_to_be_added->begin()->second.T_w_linkpose, params_.segmentation_radius_m * 3.0, &target_segment_ids); const double minimum_distance_squared = params_.centroid_distance_threshold_m * params_.centroid_distance_threshold_m; unsigned int n_nearest_segments = 4u; const laser_slam::Time max_time_diff_ns = 60000000000u; if (!target_segment_ids.empty()) { n_nearest_segments = std::min(static_cast<unsigned int>(target_segment_ids.size()), n_nearest_segments); // Set up nearest neighbour search. pcl::KdTreeFLANN<PclPoint> kdtree; PointCloudPtr centroid_cloud_ptr(new PointCloud); pcl::copyPointCloud(centroid_cloud, *centroid_cloud_ptr); kdtree.setInputCloud(centroid_cloud_ptr); for (std::unordered_map<Id, Segment>::const_iterator it = cloud_to_be_added->begin(); it != cloud_to_be_added->end(); ++it) { std::vector<int> nearest_neighbour_indice(n_nearest_segments); std::vector<float> nearest_neighbour_squared_distance(n_nearest_segments); // Find the nearest neighbours. if (kdtree.nearestKSearch(it->second.centroid, n_nearest_segments, nearest_neighbour_indice, nearest_neighbour_squared_distance) <= 0) { LOG(ERROR) << "Nearest neighbour search failed."; } for (size_t i = 0u; i < n_nearest_segments; ++i) { // Check if within distance. if (nearest_neighbour_squared_distance[i] <= minimum_distance_squared) { Segment other_segment; segmented_target_cloud_.findValidSegmentById( target_segment_ids[nearest_neighbour_indice[i]], &other_segment); if (other_segment.track_id == it->second.track_id) { // If inside the window, remove the old one. Otherwise remove current one. if (it->second.timestamp_ns < other_segment.timestamp_ns + max_time_diff_ns) { if (std::find(duplicate_segments_ids.begin(), duplicate_segments_ids.end(), other_segment.segment_id) == duplicate_segments_ids.end()) { duplicate_segments_ids.push_back(other_segment.segment_id); } } else { if (std::find(duplicate_segments_ids_in_cloud_to_add.begin(), duplicate_segments_ids_in_cloud_to_add.end(), it->second.segment_id) == duplicate_segments_ids_in_cloud_to_add.end()) { duplicate_segments_ids_in_cloud_to_add.push_back(it->second.segment_id); } } } else { // Remove current segment if other is from another trajectory. if (std::find(duplicate_segments_ids_in_cloud_to_add.begin(), duplicate_segments_ids_in_cloud_to_add.end(), it->second.segment_id) == duplicate_segments_ids_in_cloud_to_add.end()) { duplicate_segments_ids_in_cloud_to_add.push_back(it->second.segment_id); } } } } } } // Remove duplicates. size_t n_removals; segmented_target_cloud_.deleteSegmentsById(duplicate_segments_ids, &n_removals); clock.takeTime(); LOG(INFO) << "Removed " << n_removals << " duplicate segments in target map in " << clock.getRealTime() << " ms."; cloud_to_be_added->deleteSegmentsById(duplicate_segments_ids_in_cloud_to_add, &n_removals); LOG(INFO) << "Removed " << n_removals << " duplicate segments in source map."; } } Time SegMatch::findTimeOfClosestSegmentationPose(const Segment& segment) const { const Time segment_time_ns = segment.timestamp_ns; // Create the time window for which to consider poses. Time min_time_ns; if (segment_time_ns < kMaxTimeDiffBetweenSegmentAndPose_ns) { min_time_ns = 0u; } else { min_time_ns = segment_time_ns - kMaxTimeDiffBetweenSegmentAndPose_ns; } const Time max_time_ns = segment_time_ns + kMaxTimeDiffBetweenSegmentAndPose_ns; // Create a point cloud of segmentation poses which fall within a time window // for the track associated to the segment. PointCloud pose_cloud; std::vector<Time> pose_times; for (const auto& pose: segmentation_poses_.at(segment.track_id)) { if (pose.first >= min_time_ns && pose.first <= max_time_ns) { pose_cloud.points.push_back(se3ToPclPoint(pose.second)); pose_times.push_back(pose.first); } } pose_cloud.width = 1; pose_cloud.height = pose_cloud.points.size(); CHECK_GT(pose_times.size(), 0u); // Find the nearest pose to the segment within that window. pcl::KdTreeFLANN<PclPoint> kd_tree; PointCloudPtr pose_cloud_ptr(new PointCloud); pcl::copyPointCloud(pose_cloud, *pose_cloud_ptr); kd_tree.setInputCloud(pose_cloud_ptr); const unsigned int n_nearest_segments = 1u; std::vector<int> nearest_neighbour_indices(n_nearest_segments); std::vector<float> nearest_neighbour_squared_distances(n_nearest_segments); if (kd_tree.nearestKSearch(segment.centroid, n_nearest_segments, nearest_neighbour_indices, nearest_neighbour_squared_distances) <= 0) { LOG(ERROR) << "Nearest neighbour search failed."; } // Return the time of the closest pose. return pose_times.at(nearest_neighbour_indices.at(0)); } void SegMatch::alignTargetMap() { segmented_source_clouds_[last_processed_source_cloud_].transform(last_transformation_.inverse()); // Overwrite the old target. classifier_->setTarget(segmented_target_cloud_); // Update the last filtered matches. for (auto& match: last_filtered_matches_) { Segment segment; CHECK(segmented_source_clouds_.at(last_processed_source_cloud_). findValidSegmentById(match.ids_.first, &segment)); match.centroids_.first = segment.centroid; CHECK(segmented_target_cloud_.findValidSegmentById(match.ids_.second, &segment)); match.centroids_.second = segment.centroid; } } void SegMatch::filterNearestSegmentsInCloud(SegmentedCloud* cloud, double minimum_distance_m, unsigned int n_nearest_segments) { laser_slam::Clock clock; std::vector<Id> duplicate_segments_ids; std::vector<Id> segment_ids; const double minimum_distance_squared = minimum_distance_m * minimum_distance_m; // Get a cloud with segments centroids. PointCloud centroid_cloud = cloud->centroidsAsPointCloud(&segment_ids); LOG(INFO) << "segment_ids.size() " << segment_ids.size(); if (segment_ids.size() > 2u) { n_nearest_segments = std::min(static_cast<unsigned int>(segment_ids.size()), n_nearest_segments); // Set up nearest neighbour search. pcl::KdTreeFLANN<PclPoint> kdtree; PointCloudPtr centroid_cloud_ptr(new PointCloud); pcl::copyPointCloud(centroid_cloud, *centroid_cloud_ptr); kdtree.setInputCloud(centroid_cloud_ptr); for (std::unordered_map<Id, Segment>::const_iterator it = cloud->begin(); it != cloud->end(); ++it) { // If this id is not already in the list to be removed. if (std::find(duplicate_segments_ids.begin(), duplicate_segments_ids.end(), it->second.segment_id) == duplicate_segments_ids.end()) { std::vector<int> nearest_neighbour_indice(n_nearest_segments); std::vector<float> nearest_neighbour_squared_distance(n_nearest_segments); // Find the nearest neighbours. if (kdtree.nearestKSearch(it->second.centroid, n_nearest_segments, nearest_neighbour_indice, nearest_neighbour_squared_distance) <= 0) { LOG(ERROR) << "Nearest neighbour search failed."; } for (unsigned int i = 1u; i < n_nearest_segments; ++i) { // Check if within distance. if (nearest_neighbour_squared_distance[i] <= minimum_distance_squared) { Segment other_segment; cloud->findValidSegmentById( segment_ids[nearest_neighbour_indice[i]], &other_segment); // Keep the oldest segment. Id id_to_remove; if (it->second.timestamp_ns != other_segment.timestamp_ns) { if (it->second.timestamp_ns > other_segment.timestamp_ns) { id_to_remove = it->second.segment_id; // Add id to remove if not already in the list. if (std::find(duplicate_segments_ids.begin(), duplicate_segments_ids.end(), id_to_remove) == duplicate_segments_ids.end()) { duplicate_segments_ids.push_back(id_to_remove); } break; } else { id_to_remove = other_segment.segment_id; } } else if (it->second.point_cloud.size() > other_segment.point_cloud.size()) { id_to_remove = other_segment.segment_id; } else { id_to_remove = it->second.segment_id; // Add id to remove if not already in the list. if (std::find(duplicate_segments_ids.begin(), duplicate_segments_ids.end(), id_to_remove) == duplicate_segments_ids.end()) { duplicate_segments_ids.push_back(id_to_remove); } break; } // Add id to remove if not already in the list. if (std::find(duplicate_segments_ids.begin(), duplicate_segments_ids.end(), id_to_remove) == duplicate_segments_ids.end()) { duplicate_segments_ids.push_back(id_to_remove); } } } } } } // Remove duplicates. size_t n_removals; cloud->deleteSegmentsById(duplicate_segments_ids, &n_removals); clock.takeTime(); LOG(INFO) << "Removed " << n_removals << " duplicate segments in " << clock.getRealTime() << " ms."; } void SegMatch::displayTimings() const { } void SegMatch::saveTimings() const { Eigen::MatrixXd matrix; toEigenMatrixXd(segmentation_and_description_timings_, &matrix); writeEigenMatrixXdCSV(matrix, "/tmp/timing_segmentation_and_description.csv"); toEigenMatrixXd(matching_timings_, &matrix); writeEigenMatrixXdCSV(matrix, "/tmp/timing_matching.csv"); toEigenMatrixXd(geometric_verification_timings_, &matrix); writeEigenMatrixXdCSV(matrix, "/tmp/timing_geometric_verification.csv"); toEigenMatrixXd(source_to_target_timings_, &matrix); writeEigenMatrixXdCSV(matrix, "/tmp/timing_source_to_target_timings.csv"); toEigenMatrixXd(update_timings_, &matrix); writeEigenMatrixXdCSV(matrix, "/tmp/timing_updates.csv"); matrix.resize(loops_timestamps_.size(), 1); for (size_t i = 0u; i < loops_timestamps_.size(); ++i) { matrix(i,0) = loops_timestamps_[i]; } writeEigenMatrixXdCSV(matrix, "/tmp/timing_loops.csv"); } } // namespace segmatch
41.805672
110
0.670846
[ "vector", "transform" ]