text
stringlengths
5
1.04M
#include "optionsmodel.h" #include "gxcoinunits.h" #include "init.h" #include "walletdb.h" #include "guiutil.h" #include <QSettings> OptionsModel::OptionsModel(QObject *parent) : QAbstractListModel(parent) { Init(); } bool static ApplyProxySettings() { QSettings settings; CService addrProxy(settings.value("addrProxy", "127.0.0.1:9050").toString().toStdString()); int nSocksVersion(settings.value("nSocksVersion", 5).toInt()); if (!settings.value("fUseProxy", false).toBool()) { addrProxy = CService(); nSocksVersion = 0; return false; } if (nSocksVersion && !addrProxy.IsValid()) return false; if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } return true; } void OptionsModel::Init() { QSettings settings; // These are Qt-only settings: nDisplayUnit = settings.value("nDisplayUnit", GxcoinUnits::GXC).toInt(); bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool(); fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool(); fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool(); nTransactionFee = settings.value("nTransactionFee").toLongLong(); language = settings.value("language", "").toString(); // These are shared with core Gxcoin; we want // command-line options to override the GUI settings: if (settings.contains("fUseUPnP")) SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()); if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool()) SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()); if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool()) SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString()); if (!language.isEmpty()) SoftSetArg("-lang", language.toStdString()); } void OptionsModel::Reset() { QSettings settings; // Remove all entries in this QSettings object settings.clear(); // default setting for OptionsModel::StartAtStartup - disabled if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(false); // Re-Init to get default values Init(); // Ensure Upgrade() is not running again by setting the bImportFinished flag settings.setValue("bImportFinished", true); } bool OptionsModel::Upgrade() { QSettings settings; if (settings.contains("bImportFinished")) return false; // Already upgraded settings.setValue("bImportFinished", true); // Move settings from old wallet.dat (if any): CWalletDB walletdb("wallet.dat"); QList<QString> intOptions; intOptions << "nDisplayUnit" << "nTransactionFee"; foreach(QString key, intOptions) { int value = 0; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } QList<QString> boolOptions; boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP"; foreach(QString key, boolOptions) { bool value = false; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } try { CAddress addrProxyAddress; if (walletdb.ReadSetting("addrProxy", addrProxyAddress)) { settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } catch (std::ios_base::failure &e) { // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress CService addrProxy; if (walletdb.ReadSetting("addrProxy", addrProxy)) { settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } ApplyProxySettings(); Init(); return true; } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return QVariant(GUIUtil::GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: #ifdef USE_UPNP return settings.value("fUseUPnP", GetBoolArg("-upnp", true)); #else return QVariant(false); #endif case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ProxyUse: { proxyType proxy; return QVariant(GetProxy(NET_IPV4, proxy)); } case ProxyIP: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(QString::fromStdString(proxy.first.ToStringIP())); else return QVariant(QString::fromStdString("127.0.0.1")); } case ProxyPort: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.first.GetPort()); else return QVariant(9050); } case ProxySocksVersion: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.second); else return QVariant(5); } case Fee: return QVariant(nTransactionFee); case DisplayUnit: return QVariant(nDisplayUnit); case DisplayAddresses: return QVariant(bDisplayAddresses); case Language: return settings.value("language", ""); default: return QVariant(); } } return QVariant(); } bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; case ProxyUse: settings.setValue("fUseProxy", value.toBool()); successful = ApplyProxySettings(); break; case ProxyIP: { proxyType proxy; proxy.first = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); CNetAddr addr(value.toString().toStdString()); proxy.first.SetIP(addr); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxyPort: { proxyType proxy; proxy.first = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); proxy.first.SetPort(value.toInt()); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxySocksVersion: { proxyType proxy; proxy.second = 5; GetProxy(NET_IPV4, proxy); proxy.second = value.toInt(); settings.setValue("nSocksVersion", proxy.second); successful = ApplyProxySettings(); } break; case Fee: nTransactionFee = value.toLongLong(); settings.setValue("nTransactionFee", nTransactionFee); break; case DisplayUnit: nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); break; case DisplayAddresses: bDisplayAddresses = value.toBool(); settings.setValue("bDisplayAddresses", bDisplayAddresses); break; case Language: settings.setValue("language", value); break; default: break; } } emit dataChanged(index, index); return successful; } qint64 OptionsModel::getTransactionFee() { return nTransactionFee; }
/////////////////////////////////////////////////////////////////////// // File: tablefind.cpp // Description: Helper classes to find tables from ColPartitions. // Author: Faisal Shafait (faisal.shafait@dfki.de) // // (C) Copyright 2009, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H # include "config_auto.h" #endif #include <algorithm> #include <cmath> #include "tablefind.h" #include <allheaders.h> #include "colpartitionset.h" #include "tablerecog.h" namespace tesseract { // These numbers are used to calculate the global median stats. // They just set an upper bound on the stats objects. // Maximum vertical spacing between neighbor partitions. const int kMaxVerticalSpacing = 500; // Maximum width of a blob in a partition. const int kMaxBlobWidth = 500; // Minimum whitespace size to split a partition (measured as a multiple // of a partition's median width). const double kSplitPartitionSize = 2.0; // To insert text, the partition must satisfy these size constraints // in AllowTextPartition(). The idea is to filter noise partitions // determined by the size compared to the global medians. // TODO(nbeato): Need to find good numbers again. const double kAllowTextHeight = 0.5; const double kAllowTextWidth = 0.6; const double kAllowTextArea = 0.8; // The same thing applies to blobs (to filter noise). // TODO(nbeato): These numbers are a shot in the dark... // height and width are 0.5 * gridsize() in colfind.cpp // area is a rough guess for the size of a period. const double kAllowBlobHeight = 0.3; const double kAllowBlobWidth = 0.4; const double kAllowBlobArea = 0.05; // Minimum number of components in a text partition. A partition having fewer // components than that is more likely a data partition and is a candidate // table cell. const int kMinBoxesInTextPartition = 10; // Maximum number of components that a data partition can have const int kMaxBoxesInDataPartition = 20; // Maximum allowed gap in a text partitions as a multiple of its median size. const double kMaxGapInTextPartition = 4.0; // Minimum value that the maximum gap in a text partition should have as a // factor of its median size. const double kMinMaxGapInTextPartition = 0.5; // The amount of overlap that is "normal" for adjacent blobs in a text // partition. This is used to calculate gap between overlapping blobs. const double kMaxBlobOverlapFactor = 4.0; // Maximum x-height a table partition can have as a multiple of global // median x-height const double kMaxTableCellXheight = 2.0; // Maximum line spacing between a table column header and column contents // for merging the two (as a multiple of the partition's median_height). const int kMaxColumnHeaderDistance = 4; // Minimum ratio of num_table_partitions to num_text_partitions in a column // block to be called it a table column const double kTableColumnThreshold = 3.0; // Search for horizontal ruling lines within the vertical margin as a // multiple of grid size // const int kRulingVerticalMargin = 3; // Minimum overlap that a colpartition must have with a table region // to become part of that table const double kMinOverlapWithTable = 0.6; // Maximum side space (distance from column boundary) that a typical // text-line in flowing text should have as a multiple of its x-height // (Median size). const int kSideSpaceMargin = 10; // Fraction of the peak of x-projection of a table region to set the // threshold for the x-projection histogram const double kSmallTableProjectionThreshold = 0.35; const double kLargeTableProjectionThreshold = 0.45; // Minimum number of rows required to look for more rows in the projection. const int kLargeTableRowCount = 6; // Minimum number of rows in a table const int kMinRowsInTable = 3; // The amount of padding (multiplied by global_median_xheight_ during use) // that is vertically added to the search adjacent leader search during // ColPartition marking. const int kAdjacentLeaderSearchPadding = 2; // Used when filtering false positives. When finding the last line // of a paragraph (typically left-aligned), the previous line should have // its center to the right of the last line by this scaled amount. const double kParagraphEndingPreviousLineRatio = 1.3; // The maximum amount of whitespace allowed left of a paragraph ending. // Do not filter a ColPartition with more than this space left of it. const double kMaxParagraphEndingLeftSpaceMultiple = 3.0; // Used when filtering false positives. The last line of a paragraph // should be preceded by a line that is predominantly text. This is the // ratio of text to whitespace (to the right of the text) that is required // for the previous line to be a text. const double kMinParagraphEndingTextToWhitespaceRatio = 3.0; // When counting table columns, this is the required gap between two columns // (it is multiplied by global_median_xheight_). const double kMaxXProjectionGapFactor = 2.0; // Used for similarity in partitions using stroke width. Values copied // from ColFind.cpp in Ray's CL. const double kStrokeWidthFractionalTolerance = 0.25; const double kStrokeWidthConstantTolerance = 2.0; #ifndef GRAPHICS_DISABLED static BOOL_VAR(textord_show_tables, false, "Show table regions (ScrollView)"); static BOOL_VAR(textord_tablefind_show_mark, false, "Debug table marking steps in detail (ScrollView)"); static BOOL_VAR(textord_tablefind_show_stats, false, "Show page stats used in table finding (ScrollView)"); #endif static BOOL_VAR(textord_tablefind_recognize_tables, false, "Enables the table recognizer for table layout and filtering."); ELISTIZE(ColSegment) CLISTIZE(ColSegment) // Templated helper function used to create destructor callbacks for the // BBGrid::ClearGridData() method. template <typename T> void DeleteObject(T *object) { delete object; } TableFinder::TableFinder() : resolution_(0) , global_median_xheight_(0) , global_median_blob_width_(0) , global_median_ledding_(0) , left_to_right_language_(true) {} TableFinder::~TableFinder() { // ColPartitions and ColSegments created by this class for storage in grids // need to be deleted explicitly. clean_part_grid_.ClearGridData(&DeleteObject<ColPartition>); leader_and_ruling_grid_.ClearGridData(&DeleteObject<ColPartition>); fragmented_text_grid_.ClearGridData(&DeleteObject<ColPartition>); col_seg_grid_.ClearGridData(&DeleteObject<ColSegment>); table_grid_.ClearGridData(&DeleteObject<ColSegment>); } void TableFinder::set_left_to_right_language(bool order) { left_to_right_language_ = order; } void TableFinder::Init(int grid_size, const ICOORD &bottom_left, const ICOORD &top_right) { // Initialize clean partitions list and grid clean_part_grid_.Init(grid_size, bottom_left, top_right); leader_and_ruling_grid_.Init(grid_size, bottom_left, top_right); fragmented_text_grid_.Init(grid_size, bottom_left, top_right); col_seg_grid_.Init(grid_size, bottom_left, top_right); table_grid_.Init(grid_size, bottom_left, top_right); } // Copy cleaned partitions from part_grid_ to clean_part_grid_ and // insert leaders and rulers into the leader_and_ruling_grid_ void TableFinder::InsertCleanPartitions(ColPartitionGrid *grid, TO_BLOCK *block) { // Calculate stats. This lets us filter partitions in AllowTextPartition() // and filter blobs in AllowBlob(). SetGlobalSpacings(grid); // Iterate the ColPartitions in the grid. ColPartitionGridSearch gsearch(grid); gsearch.SetUniqueMode(true); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { // Reject partitions with nothing useful inside of them. if (part->blob_type() == BRT_NOISE || part->bounding_box().area() <= 0) continue; ColPartition *clean_part = part->ShallowCopy(); ColPartition *leader_part = nullptr; if (part->IsLineType()) { InsertRulingPartition(clean_part); continue; } // Insert all non-text partitions to clean_parts if (!part->IsTextType()) { InsertImagePartition(clean_part); continue; } // Insert text colpartitions after removing noisy components from them // The leaders are split into a separate grid. BLOBNBOX_CLIST *part_boxes = part->boxes(); BLOBNBOX_C_IT pit(part_boxes); for (pit.mark_cycle_pt(); !pit.cycled_list(); pit.forward()) { BLOBNBOX *pblob = pit.data(); // Bad blobs... happens in UNLV set. // news.3G1, page 17 (around x=6) if (!AllowBlob(*pblob)) continue; if (pblob->flow() == BTFT_LEADER) { if (leader_part == nullptr) { leader_part = part->ShallowCopy(); leader_part->set_flow(BTFT_LEADER); } leader_part->AddBox(pblob); } else if (pblob->region_type() != BRT_NOISE) { clean_part->AddBox(pblob); } } clean_part->ComputeLimits(); ColPartition *fragmented = clean_part->CopyButDontOwnBlobs(); InsertTextPartition(clean_part); SplitAndInsertFragmentedTextPartition(fragmented); if (leader_part != nullptr) { // TODO(nbeato): Note that ComputeLimits does not update the column // information. So the leader may appear to span more columns than it // really does later on when IsInSameColumnAs gets called to test // for adjacent leaders. leader_part->ComputeLimits(); InsertLeaderPartition(leader_part); } } // Make the partition partners better for upper and lower neighbors. clean_part_grid_.FindPartitionPartners(); clean_part_grid_.RefinePartitionPartners(false); } // High level function to perform table detection void TableFinder::LocateTables(ColPartitionGrid *grid, ColPartitionSet **all_columns, WidthCallback width_cb, const FCOORD &reskew) { // initialize spacing, neighbors, and columns InitializePartitions(all_columns); #ifndef GRAPHICS_DISABLED if (textord_show_tables) { ScrollView *table_win = MakeWindow(0, 300, "Column Partitions & Neighbors"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE); DisplayColPartitions(table_win, &leader_and_ruling_grid_, ScrollView::AQUAMARINE); DisplayColPartitionConnections(table_win, &clean_part_grid_, ScrollView::ORANGE); table_win = MakeWindow(100, 300, "Fragmented Text"); DisplayColPartitions(table_win, &fragmented_text_grid_, ScrollView::BLUE); } #endif // !GRAPHICS_DISABLED // mark, filter, and smooth candidate table partitions MarkTablePartitions(); // Make single-column blocks from good_columns_ partitions. col_segments are // moved to a grid later which takes the ownership ColSegment_LIST column_blocks; GetColumnBlocks(all_columns, &column_blocks); // Set the ratio of candidate table partitions in each column SetColumnsType(&column_blocks); // Move column segments to col_seg_grid_ MoveColSegmentsToGrid(&column_blocks, &col_seg_grid_); // Detect split in column layout that might have occurred due to the // presence of a table. In such a case, merge the corresponding columns. GridMergeColumnBlocks(); // Group horizontally overlapping table partitions into table columns. // table_columns created here get deleted at the end of this method. ColSegment_LIST table_columns; GetTableColumns(&table_columns); // Within each column, mark the range table regions occupy based on the // table columns detected. table_regions are moved to a grid later which // takes the ownership ColSegment_LIST table_regions; GetTableRegions(&table_columns, &table_regions); #ifndef GRAPHICS_DISABLED if (textord_tablefind_show_mark) { ScrollView *table_win = MakeWindow(1200, 300, "Table Columns and Regions"); DisplayColSegments(table_win, &table_columns, ScrollView::DARK_TURQUOISE); DisplayColSegments(table_win, &table_regions, ScrollView::YELLOW); } #endif // !GRAPHICS_DISABLED // Merge table regions across columns for tables spanning multiple // columns MoveColSegmentsToGrid(&table_regions, &table_grid_); GridMergeTableRegions(); // Adjust table boundaries by including nearby horizontal lines and left // out column headers AdjustTableBoundaries(); GridMergeTableRegions(); if (textord_tablefind_recognize_tables) { // Remove false alarms consisting of a single column DeleteSingleColumnTables(); #ifndef GRAPHICS_DISABLED if (textord_show_tables) { ScrollView *table_win = MakeWindow(1200, 300, "Detected Table Locations"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE); DisplayColSegments(table_win, &table_columns, ScrollView::KHAKI); table_grid_.DisplayBoxes(table_win); } #endif // !GRAPHICS_DISABLED // Find table grid structure and reject tables that are malformed. RecognizeTables(); GridMergeTableRegions(); RecognizeTables(); #ifndef GRAPHICS_DISABLED if (textord_show_tables) { ScrollView *table_win = MakeWindow(1400, 600, "Recognized Tables"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE, ScrollView::BLUE); table_grid_.DisplayBoxes(table_win); } #endif // !GRAPHICS_DISABLED } else { // Remove false alarms consisting of a single column // TODO(nbeato): verify this is a NOP after structured table rejection. // Right now it isn't. If the recognize function is doing what it is // supposed to do, this function is obsolete. DeleteSingleColumnTables(); #ifndef GRAPHICS_DISABLED if (textord_show_tables) { ScrollView *table_win = MakeWindow(1500, 300, "Detected Tables"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE, ScrollView::BLUE); table_grid_.DisplayBoxes(table_win); } #endif // !GRAPHICS_DISABLED } // Merge all colpartitions in table regions to make them a single // colpartition and revert types of isolated table cells not // assigned to any table to their original types. MakeTableBlocks(grid, all_columns, width_cb); } // All grids have the same dimensions. The clean_part_grid_ sizes are set from // the part_grid_ that is passed to InsertCleanPartitions, which was the same as // the grid that is the base of ColumnFinder. Just return the clean_part_grid_ // dimensions instead of duplicated memory. int TableFinder::gridsize() const { return clean_part_grid_.gridsize(); } int TableFinder::gridwidth() const { return clean_part_grid_.gridwidth(); } int TableFinder::gridheight() const { return clean_part_grid_.gridheight(); } const ICOORD &TableFinder::bleft() const { return clean_part_grid_.bleft(); } const ICOORD &TableFinder::tright() const { return clean_part_grid_.tright(); } void TableFinder::InsertTextPartition(ColPartition *part) { ASSERT_HOST(part != nullptr); if (AllowTextPartition(*part)) { clean_part_grid_.InsertBBox(true, true, part); } else { delete part; } } void TableFinder::InsertFragmentedTextPartition(ColPartition *part) { ASSERT_HOST(part != nullptr); if (AllowTextPartition(*part)) { fragmented_text_grid_.InsertBBox(true, true, part); } else { delete part; } } void TableFinder::InsertLeaderPartition(ColPartition *part) { ASSERT_HOST(part != nullptr); if (!part->IsEmpty() && part->bounding_box().area() > 0) { leader_and_ruling_grid_.InsertBBox(true, true, part); } else { delete part; } } void TableFinder::InsertRulingPartition(ColPartition *part) { leader_and_ruling_grid_.InsertBBox(true, true, part); } void TableFinder::InsertImagePartition(ColPartition *part) { // NOTE: If images are placed into a different grid in the future, // the function SetPartitionSpacings needs to be updated. It should // be the only thing that cares about image partitions. clean_part_grid_.InsertBBox(true, true, part); } // Splits a partition into its "words". The splits happen // at locations with wide inter-blob spacing. This is useful // because it allows the table recognize to "cut through" the // text lines on the page. The assumption is that a table // will have several lines with similar overlapping whitespace // whereas text will not have this type of property. // Note: The code Assumes that blobs are sorted by the left side x! // This will not work (as well) if the blobs are sorted by center/right. void TableFinder::SplitAndInsertFragmentedTextPartition(ColPartition *part) { ASSERT_HOST(part != nullptr); // Bye bye empty partitions! if (part->boxes()->empty()) { delete part; return; } // The AllowBlob function prevents this. ASSERT_HOST(part->median_width() > 0); const double kThreshold = part->median_width() * kSplitPartitionSize; ColPartition *right_part = part; bool found_split = true; while (found_split) { found_split = false; BLOBNBOX_C_IT box_it(right_part->boxes()); // Blobs are sorted left side first. If blobs overlap, // the previous blob may have a "more right" right side. // Account for this by always keeping the largest "right" // so far. int previous_right = INT32_MIN; // Look for the next split in the partition. for (box_it.mark_cycle_pt(); !box_it.cycled_list(); box_it.forward()) { const TBOX &box = box_it.data()->bounding_box(); if (previous_right != INT32_MIN && box.left() - previous_right > kThreshold) { // We have a split position. Split the partition in two pieces. // Insert the left piece in the grid and keep processing the right. int mid_x = (box.left() + previous_right) / 2; ColPartition *left_part = right_part; right_part = left_part->SplitAt(mid_x); InsertFragmentedTextPartition(left_part); found_split = true; break; } // The right side of the previous blobs. previous_right = std::max(previous_right, static_cast<int>(box.right())); } } // When a split is not found, the right part is minimized // as much as possible, so process it. InsertFragmentedTextPartition(right_part); } // Some simple criteria to filter out now. We want to make sure the // average blob size in the partition is consistent with the // global page stats. // The area metric will almost always pass for multi-blob partitions. // It is useful when filtering out noise caused by an isolated blob. bool TableFinder::AllowTextPartition(const ColPartition &part) const { const double kHeightRequired = global_median_xheight_ * kAllowTextHeight; const double kWidthRequired = global_median_blob_width_ * kAllowTextWidth; const int median_area = global_median_xheight_ * global_median_blob_width_; const double kAreaPerBlobRequired = median_area * kAllowTextArea; // Keep comparisons strictly greater to disallow 0! return part.median_height() > kHeightRequired && part.median_width() > kWidthRequired && part.bounding_box().area() > kAreaPerBlobRequired * part.boxes_count(); } // Same as above, applied to blobs. Keep in mind that // leaders, commas, and periods are important in tables. bool TableFinder::AllowBlob(const BLOBNBOX &blob) const { const TBOX &box = blob.bounding_box(); const double kHeightRequired = global_median_xheight_ * kAllowBlobHeight; const double kWidthRequired = global_median_blob_width_ * kAllowBlobWidth; const int median_area = global_median_xheight_ * global_median_blob_width_; const double kAreaRequired = median_area * kAllowBlobArea; // Keep comparisons strictly greater to disallow 0! return box.height() > kHeightRequired && box.width() > kWidthRequired && box.area() > kAreaRequired; } // TODO(nbeato): The grid that makes the window doesn't seem to matter. // The only downside is that window messages will be caught by // clean_part_grid_ instead of a useful object. This is a temporary solution // for the debug windows created by the TableFinder. #ifndef GRAPHICS_DISABLED ScrollView *TableFinder::MakeWindow(int x, int y, const char *window_name) { return clean_part_grid_.MakeWindow(x, y, window_name); } #endif // Make single-column blocks from good_columns_ partitions. void TableFinder::GetColumnBlocks(ColPartitionSet **all_columns, ColSegment_LIST *column_blocks) { for (int i = 0; i < gridheight(); ++i) { ColPartitionSet *columns = all_columns[i]; if (columns != nullptr) { ColSegment_LIST new_blocks; // Get boxes from the current vertical position on the grid columns->GetColumnBoxes(i * gridsize(), (i + 1) * gridsize(), &new_blocks); // Merge the new_blocks boxes into column_blocks if they are well-aligned GroupColumnBlocks(&new_blocks, column_blocks); } } } // Merge column segments into the current list if they are well aligned. void TableFinder::GroupColumnBlocks(ColSegment_LIST *new_blocks, ColSegment_LIST *column_blocks) { ColSegment_IT src_it(new_blocks); ColSegment_IT dest_it(column_blocks); // iterate through the source list for (src_it.mark_cycle_pt(); !src_it.cycled_list(); src_it.forward()) { ColSegment *src_seg = src_it.data(); const TBOX &src_box = src_seg->bounding_box(); bool match_found = false; // iterate through the destination list to find a matching column block for (dest_it.mark_cycle_pt(); !dest_it.cycled_list(); dest_it.forward()) { ColSegment *dest_seg = dest_it.data(); TBOX dest_box = dest_seg->bounding_box(); if (ConsecutiveBoxes(src_box, dest_box)) { // If matching block is found, insert the current block into it // and delete the source block. dest_seg->InsertBox(src_box); match_found = true; delete src_it.extract(); break; } } // If no match is found, just append the source block to column_blocks if (!match_found) { dest_it.add_after_then_move(src_it.extract()); } } } // are the two boxes immediate neighbors along the vertical direction bool TableFinder::ConsecutiveBoxes(const TBOX &b1, const TBOX &b2) { int x_margin = 20; int y_margin = 5; return (abs(b1.left() - b2.left()) < x_margin) && (abs(b1.right() - b2.right()) < x_margin) && (abs(b1.top() - b2.bottom()) < y_margin || abs(b2.top() - b1.bottom()) < y_margin); } // Set up info for clean_part_grid_ partitions to be valid during detection // code. void TableFinder::InitializePartitions(ColPartitionSet **all_columns) { FindNeighbors(); SetPartitionSpacings(&clean_part_grid_, all_columns); SetGlobalSpacings(&clean_part_grid_); } // Set left, right and top, bottom spacings of each colpartition. void TableFinder::SetPartitionSpacings(ColPartitionGrid *grid, ColPartitionSet **all_columns) { // Iterate the ColPartitions in the grid. ColPartitionGridSearch gsearch(grid); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { ColPartitionSet *columns = all_columns[gsearch.GridY()]; TBOX box = part->bounding_box(); int y = part->MidY(); ColPartition *left_column = columns->ColumnContaining(box.left(), y); ColPartition *right_column = columns->ColumnContaining(box.right(), y); // set distance from left column as space to the left if (left_column) { int left_space = std::max(0, box.left() - left_column->LeftAtY(y)); part->set_space_to_left(left_space); } // set distance from right column as space to the right if (right_column) { int right_space = std::max(0, right_column->RightAtY(y) - box.right()); part->set_space_to_right(right_space); } // Look for images that may be closer. // NOTE: used to be part_grid_, might cause issues now ColPartitionGridSearch hsearch(grid); hsearch.StartSideSearch(box.left(), box.bottom(), box.top()); ColPartition *neighbor = nullptr; while ((neighbor = hsearch.NextSideSearch(true)) != nullptr) { if (neighbor->type() == PT_PULLOUT_IMAGE || neighbor->type() == PT_FLOWING_IMAGE || neighbor->type() == PT_HEADING_IMAGE) { int right = neighbor->bounding_box().right(); if (right < box.left()) { int space = std::min(box.left() - right, part->space_to_left()); part->set_space_to_left(space); } } } hsearch.StartSideSearch(box.left(), box.bottom(), box.top()); neighbor = nullptr; while ((neighbor = hsearch.NextSideSearch(false)) != nullptr) { if (neighbor->type() == PT_PULLOUT_IMAGE || neighbor->type() == PT_FLOWING_IMAGE || neighbor->type() == PT_HEADING_IMAGE) { int left = neighbor->bounding_box().left(); if (left > box.right()) { int space = std::min(left - box.right(), part->space_to_right()); part->set_space_to_right(space); } } } ColPartition *upper_part = part->SingletonPartner(true); if (upper_part) { int space = std::max( 0, static_cast<int>(upper_part->bounding_box().bottom() - part->bounding_box().bottom())); part->set_space_above(space); } else { // TODO(nbeato): What constitutes a good value? // 0 is the default value when not set, explicitly noting it needs to // be something else. part->set_space_above(INT32_MAX); } ColPartition *lower_part = part->SingletonPartner(false); if (lower_part) { int space = std::max( 0, static_cast<int>(part->bounding_box().bottom() - lower_part->bounding_box().bottom())); part->set_space_below(space); } else { // TODO(nbeato): What constitutes a good value? // 0 is the default value when not set, explicitly noting it needs to // be something else. part->set_space_below(INT32_MAX); } } } // Set spacing and closest neighbors above and below a given colpartition. void TableFinder::SetVerticalSpacing(ColPartition *part) { TBOX box = part->bounding_box(); int top_range = std::min(box.top() + kMaxVerticalSpacing, static_cast<int>(tright().y())); int bottom_range = std::max(box.bottom() - kMaxVerticalSpacing, static_cast<int>(bleft().y())); box.set_top(top_range); box.set_bottom(bottom_range); TBOX part_box = part->bounding_box(); // Start a rect search GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> rectsearch(&clean_part_grid_); rectsearch.StartRectSearch(box); ColPartition *neighbor; int min_space_above = kMaxVerticalSpacing; int min_space_below = kMaxVerticalSpacing; ColPartition *above_neighbor = nullptr; ColPartition *below_neighbor = nullptr; while ((neighbor = rectsearch.NextRectSearch()) != nullptr) { if (neighbor == part) continue; TBOX neighbor_box = neighbor->bounding_box(); if (neighbor_box.major_x_overlap(part_box)) { int gap = abs(part->median_bottom() - neighbor->median_bottom()); // If neighbor is below current partition if (neighbor_box.top() < part_box.bottom() && gap < min_space_below) { min_space_below = gap; below_neighbor = neighbor; } // If neighbor is above current partition else if (part_box.top() < neighbor_box.bottom() && gap < min_space_above) { min_space_above = gap; above_neighbor = neighbor; } } } part->set_space_above(min_space_above); part->set_space_below(min_space_below); part->set_nearest_neighbor_above(above_neighbor); part->set_nearest_neighbor_below(below_neighbor); } // Set global spacing and x-height estimates void TableFinder::SetGlobalSpacings(ColPartitionGrid *grid) { STATS xheight_stats(0, kMaxVerticalSpacing + 1); STATS width_stats(0, kMaxBlobWidth + 1); STATS ledding_stats(0, kMaxVerticalSpacing + 1); // Iterate the ColPartitions in the grid. ColPartitionGridSearch gsearch(grid); gsearch.SetUniqueMode(true); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { // TODO(nbeato): HACK HACK HACK! medians are equal to partition length. // ComputeLimits needs to get called somewhere outside of TableFinder // to make sure the partitions are properly initialized. // When this is called, SmoothPartitionPartners dies in an assert after // table find runs. Alternative solution. // part->ComputeLimits(); if (part->IsTextType()) { // xheight_stats.add(part->median_height(), part->boxes_count()); // width_stats.add(part->median_width(), part->boxes_count()); // This loop can be removed when above issues are fixed. // Replace it with the 2 lines commented out above. BLOBNBOX_C_IT it(part->boxes()); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { xheight_stats.add(it.data()->bounding_box().height(), 1); width_stats.add(it.data()->bounding_box().width(), 1); } ledding_stats.add(part->space_above(), 1); ledding_stats.add(part->space_below(), 1); } } // Set estimates based on median of statistics obtained set_global_median_xheight(static_cast<int>(xheight_stats.median() + 0.5)); set_global_median_blob_width(static_cast<int>(width_stats.median() + 0.5)); set_global_median_ledding(static_cast<int>(ledding_stats.median() + 0.5)); #ifndef GRAPHICS_DISABLED if (textord_tablefind_show_stats) { const char *kWindowName = "X-height (R), X-width (G), and ledding (B)"; ScrollView *stats_win = MakeWindow(500, 10, kWindowName); xheight_stats.plot(stats_win, 10, 200, 2, 15, ScrollView::RED); width_stats.plot(stats_win, 10, 200, 2, 15, ScrollView::GREEN); ledding_stats.plot(stats_win, 10, 200, 2, 15, ScrollView::BLUE); } #endif // !GRAPHICS_DISABLED } void TableFinder::set_global_median_xheight(int xheight) { global_median_xheight_ = xheight; } void TableFinder::set_global_median_blob_width(int width) { global_median_blob_width_ = width; } void TableFinder::set_global_median_ledding(int ledding) { global_median_ledding_ = ledding; } void TableFinder::FindNeighbors() { ColPartitionGridSearch gsearch(&clean_part_grid_); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { // TODO(nbeato): Rename this function, meaning is different now. // IT is finding nearest neighbors its own way // SetVerticalSpacing(part); ColPartition *upper = part->SingletonPartner(true); if (upper) part->set_nearest_neighbor_above(upper); ColPartition *lower = part->SingletonPartner(false); if (lower) part->set_nearest_neighbor_below(lower); } } // High level interface. Input is an unmarked ColPartitionGrid // (namely, clean_part_grid_). Partitions are identified using local // information and filter/smoothed. The function exit should contain // a good sampling of the table partitions. void TableFinder::MarkTablePartitions() { MarkPartitionsUsingLocalInformation(); #ifndef GRAPHICS_DISABLED if (textord_tablefind_show_mark) { ScrollView *table_win = MakeWindow(300, 300, "Initial Table Partitions"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE); DisplayColPartitions(table_win, &leader_and_ruling_grid_, ScrollView::AQUAMARINE); } #endif FilterFalseAlarms(); #ifndef GRAPHICS_DISABLED if (textord_tablefind_show_mark) { ScrollView *table_win = MakeWindow(600, 300, "Filtered Table Partitions"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE); DisplayColPartitions(table_win, &leader_and_ruling_grid_, ScrollView::AQUAMARINE); } #endif SmoothTablePartitionRuns(); #ifndef GRAPHICS_DISABLED if (textord_tablefind_show_mark) { ScrollView *table_win = MakeWindow(900, 300, "Smoothed Table Partitions"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE); DisplayColPartitions(table_win, &leader_and_ruling_grid_, ScrollView::AQUAMARINE); } #endif FilterFalseAlarms(); #ifndef GRAPHICS_DISABLED if (textord_tablefind_show_mark || textord_show_tables) { ScrollView *table_win = MakeWindow(900, 300, "Final Table Partitions"); DisplayColPartitions(table_win, &clean_part_grid_, ScrollView::BLUE); DisplayColPartitions(table_win, &leader_and_ruling_grid_, ScrollView::AQUAMARINE); } #endif } // These types of partitions are marked as table partitions: // 1- Partitions that have at lease one large gap between words // 2- Partitions that consist of only one word (no significant gap // between components) // 3- Partitions that vertically overlap with other partitions within the // same column. // 4- Partitions with leaders before/after them. void TableFinder::MarkPartitionsUsingLocalInformation() { // Iterate the ColPartitions in the grid. GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> gsearch(&clean_part_grid_); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { if (!part->IsTextType()) // Only consider text partitions continue; // Only consider partitions in dominant font size or smaller if (part->median_height() > kMaxTableCellXheight * global_median_xheight_) continue; // Mark partitions with a large gap, or no significant gap as // table partitions. // Comments: It produces several false alarms at: // - last line of a paragraph (fixed) // - single word section headings // - page headers and footers // - numbered equations // - line drawing regions // TODO(faisal): detect and fix above-mentioned cases if (HasWideOrNoInterWordGap(part) || HasLeaderAdjacent(*part)) { part->set_table_type(); } } } // Check if the partition has at least one large gap between words or no // significant gap at all bool TableFinder::HasWideOrNoInterWordGap(ColPartition *part) const { // Should only get text partitions. ASSERT_HOST(part->IsTextType()); // Blob access BLOBNBOX_CLIST *part_boxes = part->boxes(); BLOBNBOX_C_IT it(part_boxes); // Check if this is a relatively small partition (such as a single word) if (part->bounding_box().width() < kMinBoxesInTextPartition * part->median_height() && part_boxes->length() < kMinBoxesInTextPartition) return true; // Variables used to compute inter-blob spacing. int current_x0 = -1; int current_x1 = -1; int previous_x1 = -1; // Stores the maximum gap detected. int largest_partition_gap_found = -1; // Text partition gap limits. If this is text (and not a table), // there should be at least one gap larger than min_gap and no gap // larger than max_gap. const double max_gap = kMaxGapInTextPartition * part->median_height(); const double min_gap = kMinMaxGapInTextPartition * part->median_height(); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { BLOBNBOX *blob = it.data(); current_x0 = blob->bounding_box().left(); current_x1 = blob->bounding_box().right(); if (previous_x1 != -1) { int gap = current_x0 - previous_x1; // TODO(nbeato): Boxes may overlap? Huh? // For example, mag.3B 8003_033.3B.tif in UNLV data. The titles/authors // on the top right of the page are filtered out with this line. // Note 2: Iterating over blobs in a partition, so we are looking for // spacing between the words. if (gap < 0) { // More likely case, the blobs slightly overlap. This can happen // with diacritics (accents) or broken alphabet symbols (characters). // Merge boxes together by taking max of right sides. if (-gap < part->median_height() * kMaxBlobOverlapFactor) { previous_x1 = std::max(previous_x1, current_x1); continue; } // Extreme case, blobs overlap significantly in the same partition... // This should not happen often (if at all), but it does. // TODO(nbeato): investigate cases when this happens. else { // The behavior before was to completely ignore this case. } } // If a large enough gap is found, mark it as a table cell (return true) if (gap > max_gap) return true; if (gap > largest_partition_gap_found) largest_partition_gap_found = gap; } previous_x1 = current_x1; } // Since no large gap was found, return false if the partition is too // long to be a data cell if (part->bounding_box().width() > kMaxBoxesInDataPartition * part->median_height() || part_boxes->length() > kMaxBoxesInDataPartition) return false; // A partition may be a single blob. In this case, it's an isolated symbol // or non-text (such as a ruling or image). // Detect these as table partitions? Shouldn't this be case by case? // The behavior before was to ignore this, making max_partition_gap < 0 // and implicitly return true. Just making it explicit. if (largest_partition_gap_found == -1) return true; // return true if the maximum gap found is smaller than the minimum allowed // max_gap in a text partition. This indicates that there is no significant // space in the partition, hence it is likely a single word. return largest_partition_gap_found < min_gap; } // A criteria for possible tables is that a table may have leaders // between data cells. An aggressive solution to find such tables is to // explicitly mark partitions that have adjacent leaders. // Note that this includes overlapping leaders. However, it does not // include leaders in different columns on the page. // Possible false-positive will include lists, such as a table of contents. // As these arise, the aggressive nature of this search may need to be // trimmed down. bool TableFinder::HasLeaderAdjacent(const ColPartition &part) { if (part.flow() == BTFT_LEADER) return true; // Search range is left and right bounded by an offset of the // median xheight. This offset is to allow some tolerance to the // the leaders on the page in the event that the alignment is still // a bit off. const TBOX &box = part.bounding_box(); const int search_size = kAdjacentLeaderSearchPadding * global_median_xheight_; const int top = box.top() + search_size; const int bottom = box.bottom() - search_size; ColPartitionGridSearch hsearch(&leader_and_ruling_grid_); for (int direction = 0; direction < 2; ++direction) { bool right_to_left = (direction == 0); int x = right_to_left ? box.right() : box.left(); hsearch.StartSideSearch(x, bottom, top); ColPartition *leader = nullptr; while ((leader = hsearch.NextSideSearch(right_to_left)) != nullptr) { // The leader could be a horizontal ruling in the grid. // Make sure it is actually a leader. if (leader->flow() != BTFT_LEADER) continue; // This should not happen, they are in different grids. ASSERT_HOST(&part != leader); // Make sure the leader shares a page column with the partition, // otherwise we are spreading across columns. if (!part.IsInSameColumnAs(*leader)) break; // There should be a significant vertical overlap if (!leader->VSignificantCoreOverlap(part)) continue; // Leader passed all tests, so it is adjacent. return true; } } // No leaders are adjacent to the given partition. return false; } // Filter individual text partitions marked as table partitions // consisting of paragraph endings, small section headings, and // headers and footers. void TableFinder::FilterFalseAlarms() { FilterParagraphEndings(); FilterHeaderAndFooter(); // TODO(nbeato): Fully justified text as non-table? } void TableFinder::FilterParagraphEndings() { // Detect last line of paragraph // Iterate the ColPartitions in the grid. ColPartitionGridSearch gsearch(&clean_part_grid_); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { if (part->type() != PT_TABLE) continue; // Consider only table partitions // Paragraph ending should have flowing text above it. ColPartition *upper_part = part->nearest_neighbor_above(); if (!upper_part) continue; if (upper_part->type() != PT_FLOWING_TEXT) continue; if (upper_part->bounding_box().width() < 2 * part->bounding_box().width()) continue; // Check if its the last line of a paragraph. // In most cases, a paragraph ending should be left-aligned to text line // above it. Sometimes, it could be a 2 line paragraph, in which case // the line above it is indented. // To account for that, check if the partition center is to // the left of the one above it. int mid = (part->bounding_box().left() + part->bounding_box().right()) / 2; int upper_mid = (upper_part->bounding_box().left() + upper_part->bounding_box().right()) / 2; int current_spacing = 0; // spacing of the current line to margin int upper_spacing = 0; // spacing of the previous line to the margin if (left_to_right_language_) { // Left to right languages, use mid - left to figure out the distance // the middle is from the left margin. int left = std::min(part->bounding_box().left(), upper_part->bounding_box().left()); current_spacing = mid - left; upper_spacing = upper_mid - left; } else { // Right to left languages, use right - mid to figure out the distance // the middle is from the right margin. int right = std::max(part->bounding_box().right(), upper_part->bounding_box().right()); current_spacing = right - mid; upper_spacing = right - upper_mid; } if (current_spacing * kParagraphEndingPreviousLineRatio > upper_spacing) continue; // Paragraphs should have similar fonts. if (!part->MatchingSizes(*upper_part) || !part->MatchingStrokeWidth(*upper_part, kStrokeWidthFractionalTolerance, kStrokeWidthConstantTolerance)) { continue; } // The last line of a paragraph should be left aligned. // TODO(nbeato): This would be untrue if the text was right aligned. // How often is that? if (part->space_to_left() > kMaxParagraphEndingLeftSpaceMultiple * part->median_height()) continue; // The line above it should be right aligned (assuming justified format). // Since we can't assume justified text, we compare whitespace to text. // The above line should have majority spanning text (or the current // line could have fit on the previous line). So compare // whitespace to text. if (upper_part->bounding_box().width() < kMinParagraphEndingTextToWhitespaceRatio * upper_part->space_to_right()) continue; // Ledding above the line should be less than ledding below if (part->space_above() >= part->space_below() || part->space_above() > 2 * global_median_ledding_) continue; // If all checks failed, it is probably text. part->clear_table_type(); } } void TableFinder::FilterHeaderAndFooter() { // Consider top-most text colpartition as header and bottom most as footer ColPartition *header = nullptr; ColPartition *footer = nullptr; int max_top = INT32_MIN; int min_bottom = INT32_MAX; ColPartitionGridSearch gsearch(&clean_part_grid_); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { if (!part->IsTextType()) continue; // Consider only text partitions int top = part->bounding_box().top(); int bottom = part->bounding_box().bottom(); if (top > max_top) { max_top = top; header = part; } if (bottom < min_bottom) { min_bottom = bottom; footer = part; } } if (header) header->clear_table_type(); if (footer) footer->clear_table_type(); } // Mark all ColPartitions as table cells that have a table cell above // and below them // TODO(faisal): This is too aggressive at the moment. The method needs to // consider spacing and alignment as well. Detection of false alarm table cells // should also be done as part of it. void TableFinder::SmoothTablePartitionRuns() { // Iterate the ColPartitions in the grid. ColPartitionGridSearch gsearch(&clean_part_grid_); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { if (part->type() >= PT_TABLE || part->type() == PT_UNKNOWN) continue; // Consider only text partitions ColPartition *upper_part = part->nearest_neighbor_above(); ColPartition *lower_part = part->nearest_neighbor_below(); if (!upper_part || !lower_part) continue; if (upper_part->type() == PT_TABLE && lower_part->type() == PT_TABLE) part->set_table_type(); } // Pass 2, do the opposite. If both the upper and lower neighbors // exist and are not tables, this probably shouldn't be a table. gsearch.StartFullSearch(); part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { if (part->type() != PT_TABLE) continue; // Consider only text partitions ColPartition *upper_part = part->nearest_neighbor_above(); ColPartition *lower_part = part->nearest_neighbor_below(); // table can't be by itself if ((upper_part && upper_part->type() != PT_TABLE) && (lower_part && lower_part->type() != PT_TABLE)) { part->clear_table_type(); } } } // Set the type of a column segment based on the ratio of table to text cells void TableFinder::SetColumnsType(ColSegment_LIST *column_blocks) { ColSegment_IT it(column_blocks); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { ColSegment *seg = it.data(); TBOX box = seg->bounding_box(); int num_table_cells = 0; int num_text_cells = 0; GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> rsearch(&clean_part_grid_); rsearch.SetUniqueMode(true); rsearch.StartRectSearch(box); ColPartition *part = nullptr; while ((part = rsearch.NextRectSearch()) != nullptr) { if (part->type() == PT_TABLE) { num_table_cells++; } else if (part->type() == PT_FLOWING_TEXT) { num_text_cells++; } } // If a column block has no text or table partition in it, it is not needed // for table detection. if (!num_table_cells && !num_text_cells) { delete it.extract(); } else { seg->set_num_table_cells(num_table_cells); seg->set_num_text_cells(num_text_cells); // set column type based on the ratio of table to text cells seg->set_type(); } } } // Move column blocks to grid void TableFinder::MoveColSegmentsToGrid(ColSegment_LIST *segments, ColSegmentGrid *col_seg_grid) { ColSegment_IT it(segments); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { ColSegment *seg = it.extract(); col_seg_grid->InsertBBox(true, true, seg); } } // Merge column blocks if a split is detected due to the presence of a // table. A text block is considered split if it has multiple // neighboring blocks above/below it, and at least one of the // neighboring blocks is of table type (has a high density of table // partitions). In this case neighboring blocks in the direction // (above/below) of the table block are merged with the text block. // Comment: This method does not handle split due to a full page table // since table columns in this case do not have a text column on which // split decision can be based. void TableFinder::GridMergeColumnBlocks() { int margin = gridsize(); // Iterate the Column Blocks in the grid. GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> gsearch(&col_seg_grid_); gsearch.StartFullSearch(); ColSegment *seg; while ((seg = gsearch.NextFullSearch()) != nullptr) { if (seg->type() != COL_TEXT) continue; // only consider text blocks for split detection bool neighbor_found = false; bool modified = false; // Modified at least once // keep expanding current box as long as neighboring table columns // are found above or below it. do { TBOX box = seg->bounding_box(); // slightly expand the search region vertically int top_range = std::min(box.top() + margin, static_cast<int>(tright().y())); int bottom_range = std::max(box.bottom() - margin, static_cast<int>(bleft().y())); box.set_top(top_range); box.set_bottom(bottom_range); neighbor_found = false; GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> rectsearch(&col_seg_grid_); rectsearch.StartRectSearch(box); ColSegment *neighbor = nullptr; while ((neighbor = rectsearch.NextRectSearch()) != nullptr) { if (neighbor == seg) continue; const TBOX &neighbor_box = neighbor->bounding_box(); // If the neighbor box significantly overlaps with the current // box (due to the expansion of the current box in the // previous iteration of this loop), remove the neighbor box // and expand the current box to include it. if (neighbor_box.overlap_fraction(box) >= 0.9) { seg->InsertBox(neighbor_box); modified = true; rectsearch.RemoveBBox(); gsearch.RepositionIterator(); delete neighbor; continue; } // Only expand if the neighbor box is of table type if (neighbor->type() != COL_TABLE) continue; // Insert the neighbor box into the current column block if (neighbor_box.major_x_overlap(box) && !box.contains(neighbor_box)) { seg->InsertBox(neighbor_box); neighbor_found = true; modified = true; rectsearch.RemoveBBox(); gsearch.RepositionIterator(); delete neighbor; } } } while (neighbor_found); if (modified) { // Because the box has changed, it has to be removed first. gsearch.RemoveBBox(); col_seg_grid_.InsertBBox(true, true, seg); gsearch.RepositionIterator(); } } } // Group horizontally overlapping table partitions into table columns. // TODO(faisal): This is too aggressive at the moment. The method should // consider more attributes to group table partitions together. Some common // errors are: // 1- page number is merged with a table column above it even // if there is a large vertical gap between them. // 2- column headers go on to catch one of the columns arbitrarily // 3- an isolated noise blob near page top or bottom merges with the table // column below/above it // 4- cells from two vertically adjacent tables merge together to make a // single column resulting in merging of the two tables void TableFinder::GetTableColumns(ColSegment_LIST *table_columns) { ColSegment_IT it(table_columns); // Iterate the ColPartitions in the grid. GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> gsearch(&clean_part_grid_); gsearch.StartFullSearch(); ColPartition *part; while ((part = gsearch.NextFullSearch()) != nullptr) { if (part->inside_table_column() || part->type() != PT_TABLE) continue; // prevent a partition to be assigned to multiple columns const TBOX &box = part->bounding_box(); auto *col = new ColSegment(); col->InsertBox(box); part->set_inside_table_column(true); // Start a search below the current cell to find bottom neighbours // Note: a full search will always process things above it first, so // this should be starting at the highest cell and working its way down. GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> vsearch(&clean_part_grid_); vsearch.StartVerticalSearch(box.left(), box.right(), box.bottom()); ColPartition *neighbor = nullptr; bool found_neighbours = false; while ((neighbor = vsearch.NextVerticalSearch(true)) != nullptr) { // only consider neighbors not assigned to any column yet if (neighbor->inside_table_column()) continue; // Horizontal lines should not break the flow if (neighbor->IsHorizontalLine()) continue; // presence of a non-table neighbor marks the end of current // table column if (neighbor->type() != PT_TABLE) break; // add the neighbor partition to the table column const TBOX &neighbor_box = neighbor->bounding_box(); col->InsertBox(neighbor_box); neighbor->set_inside_table_column(true); found_neighbours = true; } if (found_neighbours) { it.add_after_then_move(col); } else { part->set_inside_table_column(false); delete col; } } } // Mark regions in a column that are x-bounded by the column boundaries and // y-bounded by the table columns' projection on the y-axis as table regions void TableFinder::GetTableRegions(ColSegment_LIST *table_columns, ColSegment_LIST *table_regions) { ColSegment_IT cit(table_columns); ColSegment_IT rit(table_regions); // Iterate through column blocks GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> gsearch(&col_seg_grid_); gsearch.StartFullSearch(); ColSegment *part; int page_height = tright().y() - bleft().y(); ASSERT_HOST(page_height > 0); // create a bool array to hold projection on y-axis bool *table_region = new bool[page_height]; while ((part = gsearch.NextFullSearch()) != nullptr) { const TBOX &part_box = part->bounding_box(); // reset the projection array for (int i = 0; i < page_height; i++) { table_region[i] = false; } // iterate through all table columns to find regions in the current // page column block cit.move_to_first(); for (cit.mark_cycle_pt(); !cit.cycled_list(); cit.forward()) { TBOX col_box = cit.data()->bounding_box(); // find intersection region of table column and page column TBOX intersection_box = col_box.intersection(part_box); // project table column on the y-axis for (int i = intersection_box.bottom(); i < intersection_box.top(); i++) { table_region[i - bleft().y()] = true; } } // set x-limits of table regions to page column width TBOX current_table_box; current_table_box.set_left(part_box.left()); current_table_box.set_right(part_box.right()); // go through the y-axis projection to find runs of table // regions. Each run makes one table region. for (int i = 1; i < page_height; i++) { // detect start of a table region if (!table_region[i - 1] && table_region[i]) { current_table_box.set_bottom(i + bleft().y()); } // TODO(nbeato): Is it guaranteed that the last row is not a table region? // detect end of a table region if (table_region[i - 1] && !table_region[i]) { current_table_box.set_top(i + bleft().y()); if (!current_table_box.null_box()) { auto *seg = new ColSegment(); seg->InsertBox(current_table_box); rit.add_after_then_move(seg); } } } } delete[] table_region; } // Merge table regions corresponding to tables spanning multiple columns if // there is a colpartition (horizontal ruling line or normal text) that // touches both regions. // TODO(faisal): A rare error occurs if there are two horizontally adjacent // tables with aligned ruling lines. In this case, line finder returns a // single line and hence the tables get merged together void TableFinder::GridMergeTableRegions() { // Iterate the table regions in the grid. GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> gsearch(&table_grid_); gsearch.StartFullSearch(); ColSegment *seg = nullptr; while ((seg = gsearch.NextFullSearch()) != nullptr) { bool neighbor_found = false; bool modified = false; // Modified at least once do { // Start a rectangle search x-bounded by the image and y by the table const TBOX &box = seg->bounding_box(); TBOX search_region(box); search_region.set_left(bleft().x()); search_region.set_right(tright().x()); neighbor_found = false; GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> rectsearch(&table_grid_); rectsearch.StartRectSearch(search_region); ColSegment *neighbor = nullptr; while ((neighbor = rectsearch.NextRectSearch()) != nullptr) { if (neighbor == seg) continue; const TBOX &neighbor_box = neighbor->bounding_box(); // Check if a neighbor box has a large overlap with the table // region. This may happen as a result of merging two table // regions in the previous iteration. if (neighbor_box.overlap_fraction(box) >= 0.9) { seg->InsertBox(neighbor_box); rectsearch.RemoveBBox(); gsearch.RepositionIterator(); delete neighbor; modified = true; continue; } // Check if two table regions belong together based on a common // horizontal ruling line if (BelongToOneTable(box, neighbor_box)) { seg->InsertBox(neighbor_box); neighbor_found = true; modified = true; rectsearch.RemoveBBox(); gsearch.RepositionIterator(); delete neighbor; } } } while (neighbor_found); if (modified) { // Because the box has changed, it has to be removed first. gsearch.RemoveBBox(); table_grid_.InsertBBox(true, true, seg); gsearch.RepositionIterator(); } } } // Decide if two table regions belong to one table based on a common // horizontal ruling line or another colpartition bool TableFinder::BelongToOneTable(const TBOX &box1, const TBOX &box2) { // Check the obvious case. Most likely not true because overlapping boxes // should already be merged, but seems like a good thing to do in case things // change. if (box1.overlap(box2)) return true; // Check for ColPartitions spanning both table regions TBOX bbox = box1.bounding_union(box2); // Start a rect search on bbox GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> rectsearch(&clean_part_grid_); rectsearch.StartRectSearch(bbox); ColPartition *part = nullptr; while ((part = rectsearch.NextRectSearch()) != nullptr) { const TBOX &part_box = part->bounding_box(); // return true if a colpartition spanning both table regions is found if (part_box.overlap(box1) && part_box.overlap(box2) && !part->IsImageType()) return true; } return false; } // Adjust table boundaries by: // - building a tight bounding box around all ColPartitions contained in it. // - expanding table boundaries to include all colpartitions that overlap the // table by more than half of their area // - expanding table boundaries to include nearby horizontal rule lines // - expanding table vertically to include left out column headers // TODO(faisal): Expansion of table boundaries is quite aggressive. It usually // makes following errors: // 1- horizontal lines consisting of underlines are included in the table if // they are close enough // 2- horizontal lines originating from noise tend to get merged with a table // near the top of the page // 3- the criteria for including horizontal lines is very generous. Many times // horizontal lines separating headers and footers get merged with a // single-column table in a multi-column page thereby including text // from the neighboring column inside the table // 4- the criteria for including left out column headers also tends to // occasionally include text-lines above the tables, typically from // table caption void TableFinder::AdjustTableBoundaries() { // Iterate the table regions in the grid ColSegment_CLIST adjusted_tables; ColSegment_C_IT it(&adjusted_tables); ColSegmentGridSearch gsearch(&table_grid_); gsearch.StartFullSearch(); ColSegment *table = nullptr; while ((table = gsearch.NextFullSearch()) != nullptr) { const TBOX &table_box = table->bounding_box(); TBOX grown_box = table_box; GrowTableBox(table_box, &grown_box); // To prevent a table from expanding again, do not insert the // modified box back to the grid. Instead move it to a list and // and remove it from the grid. The list is moved later back to the grid. if (!grown_box.null_box()) { auto *col = new ColSegment(); col->InsertBox(grown_box); it.add_after_then_move(col); } gsearch.RemoveBBox(); delete table; } // clear table grid to move final tables in it // TODO(nbeato): table_grid_ should already be empty. The above loop // removed everything. Maybe just assert it is empty? table_grid_.Clear(); it.move_to_first(); // move back final tables to table_grid_ for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { ColSegment *seg = it.extract(); table_grid_.InsertBBox(true, true, seg); } } void TableFinder::GrowTableBox(const TBOX &table_box, TBOX *result_box) { // TODO(nbeato): The growing code is a bit excessive right now. // By removing these lines, the partitions considered need // to have some overlap or be special cases. These lines could // be added again once a check is put in place to make sure that // growing tables don't stomp on a lot of non-table partitions. // search for horizontal ruling lines within the vertical margin // int vertical_margin = kRulingVerticalMargin * gridsize(); TBOX search_box = table_box; // int top = MIN(search_box.top() + vertical_margin, tright().y()); // int bottom = MAX(search_box.bottom() - vertical_margin, bleft().y()); // search_box.set_top(top); // search_box.set_bottom(bottom); GrowTableToIncludePartials(table_box, search_box, result_box); GrowTableToIncludeLines(table_box, search_box, result_box); IncludeLeftOutColumnHeaders(result_box); } // Grow a table by increasing the size of the box to include // partitions with significant overlap with the table. void TableFinder::GrowTableToIncludePartials(const TBOX &table_box, const TBOX &search_range, TBOX *result_box) { // Rulings are in a different grid, so search 2 grids for rulings, text, // and table partitions that are not entirely within the new box. for (int i = 0; i < 2; ++i) { ColPartitionGrid *grid = (i == 0) ? &fragmented_text_grid_ : &leader_and_ruling_grid_; ColPartitionGridSearch rectsearch(grid); rectsearch.StartRectSearch(search_range); ColPartition *part = nullptr; while ((part = rectsearch.NextRectSearch()) != nullptr) { // Only include text and table types. if (part->IsImageType()) continue; const TBOX &part_box = part->bounding_box(); // Include partition in the table if more than half of it // is covered by the table if (part_box.overlap_fraction(table_box) > kMinOverlapWithTable) { *result_box = result_box->bounding_union(part_box); continue; } } } } // Grow a table by expanding to the extents of significantly // overlapping lines. void TableFinder::GrowTableToIncludeLines(const TBOX &table_box, const TBOX &search_range, TBOX *result_box) { ColPartitionGridSearch rsearch(&leader_and_ruling_grid_); rsearch.SetUniqueMode(true); rsearch.StartRectSearch(search_range); ColPartition *part = nullptr; while ((part = rsearch.NextRectSearch()) != nullptr) { // TODO(nbeato) This should also do vertical, but column // boundaries are breaking things. This function needs to be // updated to allow vertical lines as well. if (!part->IsLineType()) continue; // Avoid the following function call if the result of the // function is irrelevant. const TBOX &part_box = part->bounding_box(); if (result_box->contains(part_box)) continue; // Include a partially overlapping horizontal line only if the // extra ColPartitions that will be included due to expansion // have large side spacing w.r.t. columns containing them. if (HLineBelongsToTable(*part, table_box)) *result_box = result_box->bounding_union(part_box); // TODO(nbeato): Vertical } } // Checks whether the horizontal line belong to the table by looking at the // side spacing of extra ColParitions that will be included in the table // due to expansion bool TableFinder::HLineBelongsToTable(const ColPartition &part, const TBOX &table_box) { if (!part.IsHorizontalLine()) return false; const TBOX &part_box = part.bounding_box(); if (!part_box.major_x_overlap(table_box)) return false; // Do not consider top-most horizontal line since it usually // originates from noise. // TODO(nbeato): I had to comment this out because the ruling grid doesn't // have neighbors solved. // if (!part.nearest_neighbor_above()) // return false; const TBOX bbox = part_box.bounding_union(table_box); // In the "unioned table" box (the table extents expanded by the line), // keep track of how many partitions have significant padding to the left // and right. If more than half of the partitions covered by the new table // have significant spacing, the line belongs to the table and the table // grows to include all of the partitions. int num_extra_partitions = 0; int extra_space_to_right = 0; int extra_space_to_left = 0; // Rulings are in a different grid, so search 2 grids for rulings, text, // and table partitions that are introduced by the new box. for (int i = 0; i < 2; ++i) { ColPartitionGrid *grid = (i == 0) ? &clean_part_grid_ : &leader_and_ruling_grid_; // Start a rect search on bbox ColPartitionGridSearch rectsearch(grid); rectsearch.SetUniqueMode(true); rectsearch.StartRectSearch(bbox); ColPartition *extra_part = nullptr; while ((extra_part = rectsearch.NextRectSearch()) != nullptr) { // ColPartition already in table const TBOX &extra_part_box = extra_part->bounding_box(); if (extra_part_box.overlap_fraction(table_box) > kMinOverlapWithTable) continue; // Non-text ColPartitions do not contribute if (extra_part->IsImageType()) continue; // Consider this partition. num_extra_partitions++; // presence of a table cell is a strong hint, so just increment the scores // without looking at the spacing. if (extra_part->type() == PT_TABLE || extra_part->IsLineType()) { extra_space_to_right++; extra_space_to_left++; continue; } int space_threshold = kSideSpaceMargin * part.median_height(); if (extra_part->space_to_right() > space_threshold) extra_space_to_right++; if (extra_part->space_to_left() > space_threshold) extra_space_to_left++; } } // tprintf("%d %d %d\n", // num_extra_partitions,extra_space_to_right,extra_space_to_left); return (extra_space_to_right > num_extra_partitions / 2) || (extra_space_to_left > num_extra_partitions / 2); } // Look for isolated column headers above the given table box and // include them in the table void TableFinder::IncludeLeftOutColumnHeaders(TBOX *table_box) { // Start a search above the current table to look for column headers ColPartitionGridSearch vsearch(&clean_part_grid_); vsearch.StartVerticalSearch(table_box->left(), table_box->right(), table_box->top()); ColPartition *neighbor = nullptr; ColPartition *previous_neighbor = nullptr; while ((neighbor = vsearch.NextVerticalSearch(false)) != nullptr) { // Max distance to find a table heading. const int max_distance = kMaxColumnHeaderDistance * neighbor->median_height(); int table_top = table_box->top(); const TBOX &box = neighbor->bounding_box(); // Do not continue if the next box is way above if (box.bottom() - table_top > max_distance) break; // Unconditionally include partitions of type TABLE or LINE // TODO(faisal): add some reasonable conditions here if (neighbor->type() == PT_TABLE || neighbor->IsLineType()) { table_box->set_top(box.top()); previous_neighbor = nullptr; continue; } // If there are two text partitions, one above the other, without a table // cell on their left or right side, consider them a barrier and quit if (previous_neighbor == nullptr) { previous_neighbor = neighbor; } else { const TBOX &previous_box = previous_neighbor->bounding_box(); if (!box.major_y_overlap(previous_box)) break; } } } // Remove false alarms consisting of a single column based on their // projection on the x-axis. Projection of a real table on the x-axis // should have at least one zero-valley larger than the global median // x-height of the page. void TableFinder::DeleteSingleColumnTables() { int page_width = tright().x() - bleft().x(); ASSERT_HOST(page_width > 0); // create an integer array to hold projection on x-axis int *table_xprojection = new int[page_width]; // Iterate through all tables in the table grid GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> table_search(&table_grid_); table_search.StartFullSearch(); ColSegment *table; while ((table = table_search.NextFullSearch()) != nullptr) { TBOX table_box = table->bounding_box(); // reset the projection array for (int i = 0; i < page_width; i++) { table_xprojection[i] = 0; } // Start a rect search on table_box GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> rectsearch(&clean_part_grid_); rectsearch.SetUniqueMode(true); rectsearch.StartRectSearch(table_box); ColPartition *part; while ((part = rectsearch.NextRectSearch()) != nullptr) { if (!part->IsTextType()) continue; // Do not consider non-text partitions if (part->flow() == BTFT_LEADER) continue; // Assume leaders are in tables TBOX part_box = part->bounding_box(); // Do not consider partitions partially covered by the table if (part_box.overlap_fraction(table_box) < kMinOverlapWithTable) continue; BLOBNBOX_CLIST *part_boxes = part->boxes(); BLOBNBOX_C_IT pit(part_boxes); // Make sure overlapping blobs don't artificially inflate the number // of rows in the table. This happens frequently with things such as // decimals and split characters. Do this by assuming the column // partition is sorted mostly left to right and just clip // bounding boxes by the previous box's extent. int next_position_to_write = 0; for (pit.mark_cycle_pt(); !pit.cycled_list(); pit.forward()) { BLOBNBOX *pblob = pit.data(); // ignore blob height for the purpose of projection since we // are only interested in finding valleys int xstart = pblob->bounding_box().left(); int xend = pblob->bounding_box().right(); xstart = std::max(xstart, next_position_to_write); for (int i = xstart; i < xend; i++) table_xprojection[i - bleft().x()]++; next_position_to_write = xend; } } // Find largest valley between two reasonable peaks in the table if (!GapInXProjection(table_xprojection, page_width)) { table_search.RemoveBBox(); delete table; } } delete[] table_xprojection; } // Return true if at least one gap larger than the global x-height // exists in the horizontal projection bool TableFinder::GapInXProjection(int *xprojection, int length) { // Find peak value of the histogram int peak_value = 0; for (int i = 0; i < length; i++) { if (xprojection[i] > peak_value) { peak_value = xprojection[i]; } } // Peak value represents the maximum number of horizontally // overlapping colpartitions, so this can be considered as the // number of rows in the table if (peak_value < kMinRowsInTable) return false; double projection_threshold = kSmallTableProjectionThreshold * peak_value; if (peak_value >= kLargeTableRowCount) projection_threshold = kLargeTableProjectionThreshold * peak_value; // Threshold the histogram for (int i = 0; i < length; i++) { xprojection[i] = (xprojection[i] >= projection_threshold) ? 1 : 0; } // Find the largest run of zeros between two ones int largest_gap = 0; int run_start = -1; for (int i = 1; i < length; i++) { // detect start of a run of zeros if (xprojection[i - 1] && !xprojection[i]) { run_start = i; } // detect end of a run of zeros and update the value of largest gap if (run_start != -1 && !xprojection[i - 1] && xprojection[i]) { int gap = i - run_start; if (gap > largest_gap) largest_gap = gap; run_start = -1; } } return largest_gap > kMaxXProjectionGapFactor * global_median_xheight_; } // Given the location of a table "guess", try to overlay a cellular // grid in the location, adjusting the boundaries. // TODO(nbeato): Falsely introduces: // -headers/footers (not any worse, too much overlap destroys cells) // -page numbers (not worse, included because maximize margins) // -equations (nicely fit into a celluar grid, but more sparsely) // -figures (random text box, also sparse) // -small left-aligned text areas with overlapping positioned whitespace // (rejected before) // Overall, this just needs some more work. void TableFinder::RecognizeTables() { ScrollView *table_win = nullptr; #ifndef GRAPHICS_DISABLED if (textord_show_tables) { table_win = MakeWindow(0, 0, "Table Structure"); DisplayColPartitions(table_win, &fragmented_text_grid_, ScrollView::BLUE, ScrollView::LIGHT_BLUE); // table_grid_.DisplayBoxes(table_win); } #endif TableRecognizer recognizer; recognizer.Init(); recognizer.set_line_grid(&leader_and_ruling_grid_); recognizer.set_text_grid(&fragmented_text_grid_); recognizer.set_max_text_height(global_median_xheight_ * 2.0); recognizer.set_min_height(1.5 * gridheight()); // Loop over all of the tables and try to fit them. // Store the good tables here. ColSegment_CLIST good_tables; ColSegment_C_IT good_it(&good_tables); ColSegmentGridSearch gsearch(&table_grid_); gsearch.StartFullSearch(); ColSegment *found_table = nullptr; while ((found_table = gsearch.NextFullSearch()) != nullptr) { gsearch.RemoveBBox(); // The goal is to make the tables persistent in a list. // When that happens, this will move into the search loop. const TBOX &found_box = found_table->bounding_box(); StructuredTable *table_structure = recognizer.RecognizeTable(found_box); // Process a table. Good tables are inserted into the grid again later on // We can't change boxes in the grid while it is running a search. if (table_structure != nullptr) { #ifndef GRAPHICS_DISABLED if (textord_show_tables) { table_structure->Display(table_win, ScrollView::LIME_GREEN); } #endif found_table->set_bounding_box(table_structure->bounding_box()); delete table_structure; good_it.add_after_then_move(found_table); } else { delete found_table; } } // TODO(nbeato): MERGE!! There is awesome info now available for merging. // At this point, the grid is empty. We can safely insert the good tables // back into grid. for (good_it.mark_cycle_pt(); !good_it.cycled_list(); good_it.forward()) table_grid_.InsertBBox(true, true, good_it.extract()); } #ifndef GRAPHICS_DISABLED // Displays the column segments in some window. void TableFinder::DisplayColSegments(ScrollView *win, ColSegment_LIST *segments, ScrollView::Color color) { win->Pen(color); win->Brush(ScrollView::NONE); ColSegment_IT it(segments); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { ColSegment *col = it.data(); const TBOX &box = col->bounding_box(); int left_x = box.left(); int right_x = box.right(); int top_y = box.top(); int bottom_y = box.bottom(); win->Rectangle(left_x, bottom_y, right_x, top_y); } win->UpdateWindow(); } // Displays the colpartitions using a new coloring on an existing window. // Note: This method is only for debug purpose during development and // would not be part of checked in code void TableFinder::DisplayColPartitions(ScrollView *win, ColPartitionGrid *grid, ScrollView::Color default_color, ScrollView::Color table_color) { ScrollView::Color color = default_color; // Iterate the ColPartitions in the grid. GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> gsearch(grid); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { color = default_color; if (part->type() == PT_TABLE) color = table_color; const TBOX &box = part->bounding_box(); int left_x = box.left(); int right_x = box.right(); int top_y = box.top(); int bottom_y = box.bottom(); win->Brush(ScrollView::NONE); win->Pen(color); win->Rectangle(left_x, bottom_y, right_x, top_y); } win->UpdateWindow(); } void TableFinder::DisplayColPartitions(ScrollView *win, ColPartitionGrid *grid, ScrollView::Color default_color) { DisplayColPartitions(win, grid, default_color, ScrollView::YELLOW); } void TableFinder::DisplayColPartitionConnections(ScrollView *win, ColPartitionGrid *grid, ScrollView::Color color) { // Iterate the ColPartitions in the grid. GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> gsearch(grid); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { const TBOX &box = part->bounding_box(); int left_x = box.left(); int right_x = box.right(); int top_y = box.top(); int bottom_y = box.bottom(); ColPartition *upper_part = part->nearest_neighbor_above(); if (upper_part) { const TBOX &upper_box = upper_part->bounding_box(); int mid_x = (left_x + right_x) / 2; int mid_y = (top_y + bottom_y) / 2; int other_x = (upper_box.left() + upper_box.right()) / 2; int other_y = (upper_box.top() + upper_box.bottom()) / 2; win->Brush(ScrollView::NONE); win->Pen(color); win->Line(mid_x, mid_y, other_x, other_y); } ColPartition *lower_part = part->nearest_neighbor_below(); if (lower_part) { const TBOX &lower_box = lower_part->bounding_box(); int mid_x = (left_x + right_x) / 2; int mid_y = (top_y + bottom_y) / 2; int other_x = (lower_box.left() + lower_box.right()) / 2; int other_y = (lower_box.top() + lower_box.bottom()) / 2; win->Brush(ScrollView::NONE); win->Pen(color); win->Line(mid_x, mid_y, other_x, other_y); } } win->UpdateWindow(); } #endif // Merge all colpartitions in table regions to make them a single // colpartition and revert types of isolated table cells not // assigned to any table to their original types. void TableFinder::MakeTableBlocks(ColPartitionGrid *grid, ColPartitionSet **all_columns, WidthCallback width_cb) { // Since we have table blocks already, remove table tags from all // colpartitions GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> gsearch(grid); gsearch.StartFullSearch(); ColPartition *part = nullptr; while ((part = gsearch.NextFullSearch()) != nullptr) { if (part->type() == PT_TABLE) { part->clear_table_type(); } } // Now make a single colpartition out of each table block and remove // all colpartitions contained within a table GridSearch<ColSegment, ColSegment_CLIST, ColSegment_C_IT> table_search(&table_grid_); table_search.StartFullSearch(); ColSegment *table; while ((table = table_search.NextFullSearch()) != nullptr) { const TBOX &table_box = table->bounding_box(); // Start a rect search on table_box GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT> rectsearch(grid); rectsearch.StartRectSearch(table_box); ColPartition *part; ColPartition *table_partition = nullptr; while ((part = rectsearch.NextRectSearch()) != nullptr) { // Do not consider image partitions if (!part->IsTextType()) continue; TBOX part_box = part->bounding_box(); // Include partition in the table if more than half of it // is covered by the table if (part_box.overlap_fraction(table_box) > kMinOverlapWithTable) { rectsearch.RemoveBBox(); if (table_partition) { table_partition->Absorb(part, width_cb); } else { table_partition = part; } } } // Insert table colpartition back to part_grid_ if (table_partition) { // To match the columns used when transforming to blocks, the new table // partition must have its first and last column set at the grid y that // corresponds to its bottom. const TBOX &table_box = table_partition->bounding_box(); int grid_x, grid_y; grid->GridCoords(table_box.left(), table_box.bottom(), &grid_x, &grid_y); table_partition->SetPartitionType(resolution_, all_columns[grid_y]); table_partition->set_table_type(); table_partition->set_blob_type(BRT_TEXT); table_partition->set_flow(BTFT_CHAIN); table_partition->SetBlobTypes(); grid->InsertBBox(true, true, table_partition); } } } //////// ColSegment code //////// ColSegment::ColSegment() : ELIST_LINK(), num_table_cells_(0), num_text_cells_(0), type_(COL_UNKNOWN) {} // Provides a color for BBGrid to draw the rectangle. ScrollView::Color ColSegment::BoxColor() const { const ScrollView::Color kBoxColors[PT_COUNT] = { ScrollView::YELLOW, ScrollView::BLUE, ScrollView::YELLOW, ScrollView::MAGENTA, }; return kBoxColors[type_]; } // Insert a box into this column segment void ColSegment::InsertBox(const TBOX &other) { bounding_box_ = bounding_box_.bounding_union(other); } // Set column segment type based on the ratio of text and table partitions // in it. void ColSegment::set_type() { if (num_table_cells_ > kTableColumnThreshold * num_text_cells_) type_ = COL_TABLE; else if (num_text_cells_ > num_table_cells_) type_ = COL_TEXT; else type_ = COL_MIXED; } } // namespace tesseract.
// 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8PermissionStatus.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8AbstractEventListener.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8EventListenerList.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/frame/UseCounter.h" #include "core/inspector/ConsoleMessage.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8PermissionStatus::wrapperTypeInfo = { gin::kEmbedderBlink, V8PermissionStatus::domTemplate, V8PermissionStatus::refObject, V8PermissionStatus::derefObject, V8PermissionStatus::trace, V8PermissionStatus::toActiveDOMObject, 0, V8PermissionStatus::preparePrototypeObject, V8PermissionStatus::installConditionallyEnabledProperties, "PermissionStatus", &V8EventTarget::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::InheritFromEventTarget, WrapperTypeInfo::Dependent, WrapperTypeInfo::GarbageCollectedObject }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in PermissionStatus.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // bindings/core/v8/ScriptWrappable.h. const WrapperTypeInfo& PermissionStatus::s_wrapperTypeInfo = V8PermissionStatus::wrapperTypeInfo; namespace PermissionStatusV8Internal { static void statusAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); PermissionStatus* impl = V8PermissionStatus::toImpl(holder); v8SetReturnValueString(info, impl->state(), info.GetIsolate()); } static void statusAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); UseCounter::countDeprecationIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::PermissionStatusStatus); PermissionStatusV8Internal::statusAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void stateAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); PermissionStatus* impl = V8PermissionStatus::toImpl(holder); v8SetReturnValueString(info, impl->state(), info.GetIsolate()); } static void stateAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); PermissionStatusV8Internal::stateAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void onchangeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); PermissionStatus* impl = V8PermissionStatus::toImpl(holder); EventListener* cppValue(impl->onchange()); v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate()))); } static void onchangeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); PermissionStatusV8Internal::onchangeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void onchangeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); PermissionStatus* impl = V8PermissionStatus::toImpl(holder); moveEventListenerToNewWrapper(info.GetIsolate(), holder, impl->onchange(), v8Value, V8PermissionStatus::eventListenerCacheIndex); impl->setOnchange(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate)); } static void onchangeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Value> v8Value = info[0]; TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter"); PermissionStatusV8Internal::onchangeAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } } // namespace PermissionStatusV8Internal static const V8DOMConfiguration::AccessorConfiguration V8PermissionStatusAccessors[] = { {"status", PermissionStatusV8Internal::statusAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, {"state", PermissionStatusV8Internal::stateAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, {"onchange", PermissionStatusV8Internal::onchangeAttributeGetterCallback, PermissionStatusV8Internal::onchangeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; static void installV8PermissionStatusTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; if (!RuntimeEnabledFeatures::permissionsEnabled()) defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "PermissionStatus", V8EventTarget::domTemplate(isolate), V8PermissionStatus::internalFieldCount, 0, 0, 0, 0, 0, 0); else defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "PermissionStatus", V8EventTarget::domTemplate(isolate), V8PermissionStatus::internalFieldCount, 0, 0, V8PermissionStatusAccessors, WTF_ARRAY_LENGTH(V8PermissionStatusAccessors), 0, 0); v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Local<v8::FunctionTemplate> V8PermissionStatus::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8PermissionStatusTemplate); } bool V8PermissionStatus::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8PermissionStatus::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } PermissionStatus* V8PermissionStatus::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0; } ActiveDOMObject* V8PermissionStatus::toActiveDOMObject(v8::Local<v8::Object> wrapper) { return toImpl(wrapper); } void V8PermissionStatus::refObject(ScriptWrappable* scriptWrappable) { } void V8PermissionStatus::derefObject(ScriptWrappable* scriptWrappable) { } } // namespace blink
#ifndef PCL_TRACKING_IMPL_TRACKING_H_ #define PCL_TRACKING_IMPL_TRACKING_H_ #include <pcl/common/eigen.h> #include <ctime> #include <pcl/tracking/boost.h> #include <pcl/tracking/tracking.h> namespace pcl { namespace tracking { struct _ParticleXYZRPY { PCL_ADD_POINT4D; union { struct { float roll; float pitch; float yaw; float weight; }; float data_c[4]; }; }; // particle definition struct EIGEN_ALIGN16 ParticleXYZRPY : public _ParticleXYZRPY { inline ParticleXYZRPY () { x = y = z = roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYZRPY (float _x, float _y, float _z) { x = _x; y = _y; z = _z; roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYZRPY (float _x, float _y, float _z, float _roll, float _pitch, float _yaw) { x = _x; y = _y; z = _z; roll = _roll; pitch = _pitch; yaw = _yaw; data[3] = 1.0f; } inline static int stateDimension () { return 6; } void sample (const std::vector<double>& mean, const std::vector<double>& cov) { x += static_cast<float> (sampleNormal (mean[0], cov[0])); y += static_cast<float> (sampleNormal (mean[1], cov[1])); z += static_cast<float> (sampleNormal (mean[2], cov[2])); roll += static_cast<float> (sampleNormal (mean[3], cov[3])); pitch += static_cast<float> (sampleNormal (mean[4], cov[4])); yaw += static_cast<float> (sampleNormal (mean[5], cov[5])); } void zero () { x = 0.0; y = 0.0; z = 0.0; roll = 0.0; pitch = 0.0; yaw = 0.0; } inline Eigen::Affine3f toEigenMatrix () const { return getTransformation(x, y, z, roll, pitch, yaw); } static pcl::tracking::ParticleXYZRPY toState (const Eigen::Affine3f &trans) { float trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw; getTranslationAndEulerAngles (trans, trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw); return pcl::tracking::ParticleXYZRPY (trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw); } // a[i] inline float operator [] (unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return roll; case 4: return pitch; case 5: return yaw; default: return 0.0; } } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; inline std::ostream& operator << (std::ostream& os, const ParticleXYZRPY& p) { os << "(" << p.x << "," << p.y << "," << p.z << "," << p.roll << "," << p.pitch << "," << p.yaw << ")"; return (os); } // a * k inline pcl::tracking::ParticleXYZRPY operator * (const ParticleXYZRPY& p, double val) { pcl::tracking::ParticleXYZRPY newp; newp.x = static_cast<float> (p.x * val); newp.y = static_cast<float> (p.y * val); newp.z = static_cast<float> (p.z * val); newp.roll = static_cast<float> (p.roll * val); newp.pitch = static_cast<float> (p.pitch * val); newp.yaw = static_cast<float> (p.yaw * val); return (newp); } // a + b inline pcl::tracking::ParticleXYZRPY operator + (const ParticleXYZRPY& a, const ParticleXYZRPY& b) { pcl::tracking::ParticleXYZRPY newp; newp.x = a.x + b.x; newp.y = a.y + b.y; newp.z = a.z + b.z; newp.roll = a.roll + b.roll; newp.pitch = a.pitch + b.pitch; newp.yaw = a.yaw + b.yaw; return (newp); } // a - b inline pcl::tracking::ParticleXYZRPY operator - (const ParticleXYZRPY& a, const ParticleXYZRPY& b) { pcl::tracking::ParticleXYZRPY newp; newp.x = a.x - b.x; newp.y = a.y - b.y; newp.z = a.z - b.z; newp.roll = a.roll - b.roll; newp.pitch = a.pitch - b.pitch; newp.yaw = a.yaw - b.yaw; return (newp); } } } //########################################################################33 namespace pcl { namespace tracking { struct _ParticleXYZR { PCL_ADD_POINT4D; union { struct { float roll; float pitch; float yaw; float weight; }; float data_c[4]; }; }; // particle definition struct EIGEN_ALIGN16 ParticleXYZR : public _ParticleXYZR { inline ParticleXYZR () { x = y = z = roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYZR (float _x, float _y, float _z) { x = _x; y = _y; z = _z; roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYZR (float _x, float _y, float _z, float, float _pitch, float) { x = _x; y = _y; z = _z; roll = 0; pitch = _pitch; yaw = 0; data[3] = 1.0f; } inline static int stateDimension () { return 6; } void sample (const std::vector<double>& mean, const std::vector<double>& cov) { x += static_cast<float> (sampleNormal (mean[0], cov[0])); y += static_cast<float> (sampleNormal (mean[1], cov[1])); z += static_cast<float> (sampleNormal (mean[2], cov[2])); roll = 0; pitch += static_cast<float> (sampleNormal (mean[4], cov[4])); yaw = 0; } void zero () { x = 0.0; y = 0.0; z = 0.0; roll = 0.0; pitch = 0.0; yaw = 0.0; } inline Eigen::Affine3f toEigenMatrix () const { return getTransformation(x, y, z, roll, pitch, yaw); } static pcl::tracking::ParticleXYZR toState (const Eigen::Affine3f &trans) { float trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw; getTranslationAndEulerAngles (trans, trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw); return (pcl::tracking::ParticleXYZR (trans_x, trans_y, trans_z, 0, trans_pitch, 0)); } // a[i] inline float operator [] (unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return roll; case 4: return pitch; case 5: return yaw; default: return 0.0; } } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; inline std::ostream& operator << (std::ostream& os, const ParticleXYZR& p) { os << "(" << p.x << "," << p.y << "," << p.z << "," << p.roll << "," << p.pitch << "," << p.yaw << ")"; return (os); } // a * k inline pcl::tracking::ParticleXYZR operator * (const ParticleXYZR& p, double val) { pcl::tracking::ParticleXYZR newp; newp.x = static_cast<float> (p.x * val); newp.y = static_cast<float> (p.y * val); newp.z = static_cast<float> (p.z * val); newp.roll = static_cast<float> (p.roll * val); newp.pitch = static_cast<float> (p.pitch * val); newp.yaw = static_cast<float> (p.yaw * val); return (newp); } // a + b inline pcl::tracking::ParticleXYZR operator + (const ParticleXYZR& a, const ParticleXYZR& b) { pcl::tracking::ParticleXYZR newp; newp.x = a.x + b.x; newp.y = a.y + b.y; newp.z = a.z + b.z; newp.roll = 0; newp.pitch = a.pitch + b.pitch; newp.yaw = 0.0; return (newp); } // a - b inline pcl::tracking::ParticleXYZR operator - (const ParticleXYZR& a, const ParticleXYZR& b) { pcl::tracking::ParticleXYZR newp; newp.x = a.x - b.x; newp.y = a.y - b.y; newp.z = a.z - b.z; newp.roll = 0.0; newp.pitch = a.pitch - b.pitch; newp.yaw = 0.0; return (newp); } } } //########################################################################33 namespace pcl { namespace tracking { struct _ParticleXYRPY { PCL_ADD_POINT4D; union { struct { float roll; float pitch; float yaw; float weight; }; float data_c[4]; }; }; // particle definition struct EIGEN_ALIGN16 ParticleXYRPY : public _ParticleXYRPY { inline ParticleXYRPY () { x = y = z = roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYRPY (float _x, float, float _z) { x = _x; y = 0; z = _z; roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYRPY (float _x, float, float _z, float _roll, float _pitch, float _yaw) { x = _x; y = 0; z = _z; roll = _roll; pitch = _pitch; yaw = _yaw; data[3] = 1.0f; } inline static int stateDimension () { return 6; } void sample (const std::vector<double>& mean, const std::vector<double>& cov) { x += static_cast<float> (sampleNormal (mean[0], cov[0])); y = 0; z += static_cast<float> (sampleNormal (mean[2], cov[2])); roll += static_cast<float> (sampleNormal (mean[3], cov[3])); pitch += static_cast<float> (sampleNormal (mean[4], cov[4])); yaw += static_cast<float> (sampleNormal (mean[5], cov[5])); } void zero () { x = 0.0; y = 0.0; z = 0.0; roll = 0.0; pitch = 0.0; yaw = 0.0; } inline Eigen::Affine3f toEigenMatrix () const { return getTransformation(x, y, z, roll, pitch, yaw); } static pcl::tracking::ParticleXYRPY toState (const Eigen::Affine3f &trans) { float trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw; getTranslationAndEulerAngles (trans, trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw); return (pcl::tracking::ParticleXYRPY (trans_x, 0, trans_z, trans_roll, trans_pitch, trans_yaw)); } // a[i] inline float operator [] (unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return roll; case 4: return pitch; case 5: return yaw; default: return 0.0; } } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; inline std::ostream& operator << (std::ostream& os, const ParticleXYRPY& p) { os << "(" << p.x << "," << p.y << "," << p.z << "," << p.roll << "," << p.pitch << "," << p.yaw << ")"; return (os); } // a * k inline pcl::tracking::ParticleXYRPY operator * (const ParticleXYRPY& p, double val) { pcl::tracking::ParticleXYRPY newp; newp.x = static_cast<float> (p.x * val); newp.y = static_cast<float> (p.y * val); newp.z = static_cast<float> (p.z * val); newp.roll = static_cast<float> (p.roll * val); newp.pitch = static_cast<float> (p.pitch * val); newp.yaw = static_cast<float> (p.yaw * val); return (newp); } // a + b inline pcl::tracking::ParticleXYRPY operator + (const ParticleXYRPY& a, const ParticleXYRPY& b) { pcl::tracking::ParticleXYRPY newp; newp.x = a.x + b.x; newp.y = 0; newp.z = a.z + b.z; newp.roll = a.roll + b.roll; newp.pitch = a.pitch + b.pitch; newp.yaw = a.yaw + b.yaw; return (newp); } // a - b inline pcl::tracking::ParticleXYRPY operator - (const ParticleXYRPY& a, const ParticleXYRPY& b) { pcl::tracking::ParticleXYRPY newp; newp.x = a.x - b.x; newp.z = a.z - b.z; newp.y = 0; newp.roll = a.roll - b.roll; newp.pitch = a.pitch - b.pitch; newp.yaw = a.yaw - b.yaw; return (newp); } } } //########################################################################33 namespace pcl { namespace tracking { struct _ParticleXYRP { PCL_ADD_POINT4D; union { struct { float roll; float pitch; float yaw; float weight; }; float data_c[4]; }; }; // particle definition struct EIGEN_ALIGN16 ParticleXYRP : public _ParticleXYRP { inline ParticleXYRP () { x = y = z = roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYRP (float _x, float, float _z) { x = _x; y = 0; z = _z; roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYRP (float _x, float, float _z, float, float _pitch, float _yaw) { x = _x; y = 0; z = _z; roll = 0; pitch = _pitch; yaw = _yaw; data[3] = 1.0f; } inline static int stateDimension () { return 6; } void sample (const std::vector<double>& mean, const std::vector<double>& cov) { x += static_cast<float> (sampleNormal (mean[0], cov[0])); y = 0; z += static_cast<float> (sampleNormal (mean[2], cov[2])); roll = 0; pitch += static_cast<float> (sampleNormal (mean[4], cov[4])); yaw += static_cast<float> (sampleNormal (mean[5], cov[5])); } void zero () { x = 0.0; y = 0.0; z = 0.0; roll = 0.0; pitch = 0.0; yaw = 0.0; } inline Eigen::Affine3f toEigenMatrix () const { return getTransformation(x, y, z, roll, pitch, yaw); } static pcl::tracking::ParticleXYRP toState (const Eigen::Affine3f &trans) { float trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw; getTranslationAndEulerAngles (trans, trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw); return (pcl::tracking::ParticleXYRP (trans_x, 0, trans_z, 0, trans_pitch, trans_yaw)); } // a[i] inline float operator [] (unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return roll; case 4: return pitch; case 5: return yaw; default: return 0.0; } } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; inline std::ostream& operator << (std::ostream& os, const ParticleXYRP& p) { os << "(" << p.x << "," << p.y << "," << p.z << "," << p.roll << "," << p.pitch << "," << p.yaw << ")"; return (os); } // a * k inline pcl::tracking::ParticleXYRP operator * (const ParticleXYRP& p, double val) { pcl::tracking::ParticleXYRP newp; newp.x = static_cast<float> (p.x * val); newp.y = static_cast<float> (p.y * val); newp.z = static_cast<float> (p.z * val); newp.roll = static_cast<float> (p.roll * val); newp.pitch = static_cast<float> (p.pitch * val); newp.yaw = static_cast<float> (p.yaw * val); return (newp); } // a + b inline pcl::tracking::ParticleXYRP operator + (const ParticleXYRP& a, const ParticleXYRP& b) { pcl::tracking::ParticleXYRP newp; newp.x = a.x + b.x; newp.y = 0; newp.z = a.z + b.z; newp.roll = 0; newp.pitch = a.pitch + b.pitch; newp.yaw = a.yaw + b.yaw; return (newp); } // a - b inline pcl::tracking::ParticleXYRP operator - (const ParticleXYRP& a, const ParticleXYRP& b) { pcl::tracking::ParticleXYRP newp; newp.x = a.x - b.x; newp.z = a.z - b.z; newp.y = 0; newp.roll = 0.0; newp.pitch = a.pitch - b.pitch; newp.yaw = a.yaw - b.yaw; return (newp); } } } //########################################################################33 namespace pcl { namespace tracking { struct _ParticleXYR { PCL_ADD_POINT4D; union { struct { float roll; float pitch; float yaw; float weight; }; float data_c[4]; }; }; // particle definition struct EIGEN_ALIGN16 ParticleXYR : public _ParticleXYR { inline ParticleXYR () { x = y = z = roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYR (float _x, float, float _z) { x = _x; y = 0; z = _z; roll = pitch = yaw = 0.0; data[3] = 1.0f; } inline ParticleXYR (float _x, float, float _z, float, float _pitch, float) { x = _x; y = 0; z = _z; roll = 0; pitch = _pitch; yaw = 0; data[3] = 1.0f; } inline static int stateDimension () { return 6; } void sample (const std::vector<double>& mean, const std::vector<double>& cov) { x += static_cast<float> (sampleNormal (mean[0], cov[0])); y = 0; z += static_cast<float> (sampleNormal (mean[2], cov[2])); roll = 0; pitch += static_cast<float> (sampleNormal (mean[4], cov[4])); yaw = 0; } void zero () { x = 0.0; y = 0.0; z = 0.0; roll = 0.0; pitch = 0.0; yaw = 0.0; } inline Eigen::Affine3f toEigenMatrix () const { return getTransformation(x, y, z, roll, pitch, yaw); } static pcl::tracking::ParticleXYR toState (const Eigen::Affine3f &trans) { float trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw; getTranslationAndEulerAngles (trans, trans_x, trans_y, trans_z, trans_roll, trans_pitch, trans_yaw); return (pcl::tracking::ParticleXYR (trans_x, 0, trans_z, 0, trans_pitch, 0)); } // a[i] inline float operator [] (unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return roll; case 4: return pitch; case 5: return yaw; default: return 0.0; } } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; inline std::ostream& operator << (std::ostream& os, const ParticleXYR& p) { os << "(" << p.x << "," << p.y << "," << p.z << "," << p.roll << "," << p.pitch << "," << p.yaw << ")"; return (os); } // a * k inline pcl::tracking::ParticleXYR operator * (const ParticleXYR& p, double val) { pcl::tracking::ParticleXYR newp; newp.x = static_cast<float> (p.x * val); newp.y = static_cast<float> (p.y * val); newp.z = static_cast<float> (p.z * val); newp.roll = static_cast<float> (p.roll * val); newp.pitch = static_cast<float> (p.pitch * val); newp.yaw = static_cast<float> (p.yaw * val); return (newp); } // a + b inline pcl::tracking::ParticleXYR operator + (const ParticleXYR& a, const ParticleXYR& b) { pcl::tracking::ParticleXYR newp; newp.x = a.x + b.x; newp.y = 0; newp.z = a.z + b.z; newp.roll = 0; newp.pitch = a.pitch + b.pitch; newp.yaw = 0.0; return (newp); } // a - b inline pcl::tracking::ParticleXYR operator - (const ParticleXYR& a, const ParticleXYR& b) { pcl::tracking::ParticleXYR newp; newp.x = a.x - b.x; newp.z = a.z - b.z; newp.y = 0; newp.roll = 0.0; newp.pitch = a.pitch - b.pitch; newp.yaw = 0.0; return (newp); } } } #define PCL_STATE_POINT_TYPES \ (pcl::tracking::ParticleXYR) \ (pcl::tracking::ParticleXYZRPY) \ (pcl::tracking::ParticleXYZR) \ (pcl::tracking::ParticleXYRPY) \ (pcl::tracking::ParticleXYRP) #endif //
/* * librdkafka - Apache Kafka C library * * Copyright (c) 2016, Magnus Edenhill * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include "testcpp.h" /** * Issue #1306 * * Consume from an empty topic using Consumer and KafkaConsumer. */ static void do_test_empty_topic_consumer() { std::string errstr; std::string topic = Test::mk_topic_name("0067_empty_topic", 1); const int32_t partition = 0; RdKafka::Conf *conf; Test::conf_init(&conf, NULL, 0); Test::conf_set(conf, "enable.partition.eof", "true"); Test::conf_set(conf, "allow.auto.create.topics", "true"); /* Create simple consumer */ RdKafka::Consumer *consumer = RdKafka::Consumer::create(conf, errstr); if (!consumer) Test::Fail("Failed to create Consumer: " + errstr); RdKafka::Topic *rkt = RdKafka::Topic::create(consumer, topic, NULL, errstr); if (!rkt) Test::Fail("Simple Topic failed: " + errstr); /* Create the topic through a metadata request. */ Test::Say("Creating empty topic " + topic + "\n"); RdKafka::Metadata *md; RdKafka::ErrorCode err = consumer->metadata(false, rkt, &md, tmout_multip(10 * 1000)); if (err) Test::Fail("Failed to create topic " + topic + ": " + RdKafka::err2str(err)); delete md; /* Start consumer */ err = consumer->start(rkt, partition, RdKafka::Topic::OFFSET_BEGINNING); if (err) Test::Fail("Consume start() failed: " + RdKafka::err2str(err)); /* Consume using legacy consumer, should give an EOF and nothing else. */ Test::Say("Simple Consumer: consuming\n"); RdKafka::Message *msg = consumer->consume(rkt, partition, tmout_multip(10 * 1000)); if (msg->err() != RdKafka::ERR__PARTITION_EOF) Test::Fail("Simple consume() expected EOF, got " + RdKafka::err2str(msg->err())); delete msg; /* Nothing else should come now, just a consume() timeout */ msg = consumer->consume(rkt, partition, 1 * 1000); if (msg->err() != RdKafka::ERR__TIMED_OUT) Test::Fail("Simple consume() expected timeout, got " + RdKafka::err2str(msg->err())); delete msg; consumer->stop(rkt, partition); delete rkt; delete consumer; /* * Now do the same thing using the high-level KafkaConsumer. */ Test::conf_set(conf, "group.id", topic); Test::conf_set(conf, "enable.partition.eof", "true"); Test::conf_set(conf, "allow.auto.create.topics", "true"); RdKafka::KafkaConsumer *kconsumer = RdKafka::KafkaConsumer::create(conf, errstr); if (!kconsumer) Test::Fail("Failed to create KafkaConsumer: " + errstr); std::vector<RdKafka::TopicPartition *> part; part.push_back(RdKafka::TopicPartition::create(topic, partition)); err = kconsumer->assign(part); if (err) Test::Fail("assign() failed: " + RdKafka::err2str(err)); RdKafka::TopicPartition::destroy(part); Test::Say("KafkaConsumer: consuming\n"); msg = kconsumer->consume(tmout_multip(5 * 1000)); if (msg->err() != RdKafka::ERR__PARTITION_EOF) Test::Fail("KafkaConsumer consume() expected EOF, got " + RdKafka::err2str(msg->err())); delete msg; /* Nothing else should come now, just a consume() timeout */ msg = kconsumer->consume(1 * 1000); if (msg->err() != RdKafka::ERR__TIMED_OUT) Test::Fail("KafkaConsumer consume() expected timeout, got " + RdKafka::err2str(msg->err())); delete msg; kconsumer->close(); delete kconsumer; delete conf; } extern "C" { int main_0067_empty_topic(int argc, char **argv) { do_test_empty_topic_consumer(); return 0; } }
// // Copyright (c) 2009, Markus Rickert // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "Kinematic.h" #include "NloptInverseKinematics.h" using namespace std::chrono; namespace rl { namespace mdl { NloptInverseKinematics::NloptInverseKinematics(Kinematic* kinematic) : IterativeInverseKinematics(kinematic), lb(this->kinematic->getMinimum()), opt(::nlopt_create(::NLOPT_LD_SLSQP, kinematic->getDofPosition()), ::nlopt_destroy), randDistribution(0, 1), randEngine(::std::random_device()()), ub(this->kinematic->getMaximum()) { Exception::check(::nlopt_set_ftol_abs(opt.get(), ::std::numeric_limits<double>::epsilon())); Exception::check(::nlopt_set_ftol_rel(opt.get(), ::std::numeric_limits<double>::epsilon())); Exception::check(::nlopt_set_lower_bounds(opt.get(), this->lb.data())); Exception::check(::nlopt_set_min_objective(opt.get(), &NloptInverseKinematics::f, this)); Exception::check(::nlopt_set_stopval(opt.get(), ::std::pow(this->getEpsilon(), 2))); Exception::check(::nlopt_set_upper_bounds(opt.get(), this->ub.data())); Exception::check(::nlopt_set_xtol_abs1(opt.get(), ::std::numeric_limits<double>::epsilon())); Exception::check(::nlopt_set_xtol_rel(opt.get(), ::std::numeric_limits<double>::epsilon())); } NloptInverseKinematics::NloptInverseKinematics(Kinematic* kinematic, char flag) : IterativeInverseKinematics(kinematic), lb(this->kinematic->getMinimum()), opt(::nlopt_create(::NLOPT_LD_SLSQP, kinematic->getDofPosition()), ::nlopt_destroy), randDistribution(0, 1), randEngine(::std::random_device()()), ub(this->kinematic->getMaximum()) { Exception::check(::nlopt_set_ftol_abs(opt.get(), ::std::numeric_limits<double>::epsilon())); Exception::check(::nlopt_set_ftol_rel(opt.get(), ::std::numeric_limits<double>::epsilon())); Exception::check(::nlopt_set_lower_bounds(opt.get(), this->lb.data())); Exception::check(::nlopt_set_min_objective(opt.get(), &NloptInverseKinematics::f2, this)); Exception::check(::nlopt_set_stopval(opt.get(), ::std::pow(this->getEpsilon(), 2))); Exception::check(::nlopt_set_upper_bounds(opt.get(), this->ub.data())); Exception::check(::nlopt_set_xtol_abs1(opt.get(), ::std::numeric_limits<double>::epsilon())); Exception::check(::nlopt_set_xtol_rel(opt.get(), ::std::numeric_limits<double>::epsilon())); } NloptInverseKinematics::~NloptInverseKinematics() { } double NloptInverseKinematics::f(unsigned int n, const double* x, double* grad, void* data) { auto start_total = high_resolution_clock::now(); NloptInverseKinematics* ik = static_cast<NloptInverseKinematics*>(data); ++ik->iteration; ::Eigen::Map<const ::Eigen::VectorXd> q(x, n, 1); if (!q.allFinite()) { return ::std::numeric_limits<double>::infinity(); } ik->kinematic->setPosition(q); ik->kinematic->forwardPosition(); ::rl::math::Vector dx = ::rl::math::Vector::Zero(6 * ik->kinematic->getOperationalDof()); for (::std::size_t i = 0; i < ik->goals.size(); ++i) { ::rl::math::VectorBlock dxi = dx.segment(6 * std::get<1>(ik->goals[i]), 6); dxi = ik->kinematic->getOperationalPosition(std::get<1>(ik->goals[i])).toDelta(std::get<0>(ik->goals[i])); } auto stop_objective = high_resolution_clock::now(); auto start_grad = high_resolution_clock::now(); if (nullptr != grad) { ::Eigen::Map<::Eigen::VectorXd> grad2(grad, n, 1); ik->kinematic->calculateJacobian(); grad2 = -2 * ik->kinematic->getJacobian().transpose() * dx; } auto stop_total = high_resolution_clock::now(); auto duration_total = duration_cast<microseconds>(stop_total - start_total); auto grad_total = duration_cast<microseconds>(stop_total - start_grad); auto objective_total = duration_cast<microseconds>(stop_objective - start_total); ik->f_avg_time_micros = ik->f_avg_time_micros*(ik->iteration-1)/ik->iteration + duration_total.count()/ik->iteration; ik->grad_avg_time_micros = ik->grad_avg_time_micros*(ik->iteration-1)/ik->iteration + grad_total.count()/ik->iteration; ik->objective_avg_time_micros = ik->objective_avg_time_micros*(ik->iteration-1)/ik->iteration + objective_total.count()/ik->iteration; return dx.squaredNorm(); } double NloptInverseKinematics::f2(unsigned int n, const double* x, double* grad, void* data) { auto start_total = high_resolution_clock::now(); NloptInverseKinematics* ik = static_cast<NloptInverseKinematics*>(data); ++ik->iteration; ::Eigen::Map<const ::Eigen::VectorXd> q(x, n, 1); if (!q.allFinite()) { return ::std::numeric_limits<double>::infinity(); } ik->kinematic->setPosition(q); ik->kinematic->forwardPosition(); ::rl::math::Vector dx = ::rl::math::Vector::Zero(3 * ik->kinematic->getOperationalDof()); for (::std::size_t i = 0; i < ik->goals.size(); ++i) { ::rl::math::VectorBlock dxi = dx.segment(3 * std::get<1>(ik->goals[i]), 3); dxi = ik->kinematic->getOperationalPosition(std::get<1>(ik->goals[i])).toDelta(std::get<0>(ik->goals[i])).segment(0,3); } auto stop_objective = high_resolution_clock::now(); auto start_grad = high_resolution_clock::now(); if (nullptr != grad) { ::Eigen::Map<::Eigen::VectorXd> grad2(grad, n, 1); ik->kinematic->calculateLinearJacobian(); grad2 = -2 * ik->kinematic->getLinearJacobian().transpose() * dx; } auto stop_total = high_resolution_clock::now(); auto duration_total = duration_cast<microseconds>(stop_total - start_total); auto grad_total = duration_cast<microseconds>(stop_total - start_grad); auto objective_total = duration_cast<microseconds>(stop_objective - start_total); ik->f_avg_time_micros = ik->f_avg_time_micros*(ik->iteration-1)/ik->iteration + duration_total.count()/ik->iteration; ik->grad_avg_time_micros = ik->grad_avg_time_micros*(ik->iteration-1)/ik->iteration + grad_total.count()/ik->iteration; ik->objective_avg_time_micros = ik->objective_avg_time_micros*(ik->iteration-1)/ik->iteration + objective_total.count()/ik->iteration; return dx.squaredNorm(); } ::rl::math::Real NloptInverseKinematics::getFunctionToleranceAbsolute() const { return ::nlopt_get_ftol_abs(this->opt.get()); } ::rl::math::Real NloptInverseKinematics::getFunctionToleranceRelative() const { return ::nlopt_get_ftol_rel(this->opt.get()); } const ::rl::math::Vector& NloptInverseKinematics::getLowerBound() const { return this->lb; } ::rl::math::Vector NloptInverseKinematics::getOptimizationToleranceAbsolute() const { ::rl::math::Vector tol(this->kinematic->getDofPosition()); Exception::check(::nlopt_get_xtol_abs(this->opt.get(), tol.data())); return tol; } ::rl::math::Real NloptInverseKinematics::getOptimizationToleranceRelative() const { return ::nlopt_get_xtol_rel(this->opt.get()); } const ::rl::math::Vector& NloptInverseKinematics::getUpperBound() const { return this->ub; } void NloptInverseKinematics::seed(const ::std::mt19937::result_type& value) { this->randEngine.seed(value); } void NloptInverseKinematics::setEpsilon(const ::rl::math::Real& epsilon) { Exception::check(::nlopt_set_stopval(opt.get(), ::std::pow(epsilon, 2))); IterativeInverseKinematics::setEpsilon(epsilon); } void NloptInverseKinematics::setFunctionToleranceAbsolute(const ::rl::math::Real& functionToleranceAbsolute) { Exception::check(::nlopt_set_ftol_abs(opt.get(), functionToleranceAbsolute)); } void NloptInverseKinematics::setFunctionToleranceRelative(const ::rl::math::Real& functionToleranceRelative) { Exception::check(::nlopt_set_ftol_rel(opt.get(), functionToleranceRelative)); } void NloptInverseKinematics::setLowerBound(const ::rl::math::Vector& lb) { Exception::check(::nlopt_set_lower_bounds(opt.get(), lb.data())); this->lb = lb; } void NloptInverseKinematics::setOptimizationToleranceAbsolute(const ::rl::math::Real& optimizationToleranceAbsolute) { Exception::check(::nlopt_set_xtol_abs1(opt.get(), optimizationToleranceAbsolute)); } void NloptInverseKinematics::setOptimizationToleranceAbsolute(const ::rl::math::Vector& optimizationToleranceAbsolute) { Exception::check(::nlopt_set_xtol_abs(opt.get(), optimizationToleranceAbsolute.data())); } void NloptInverseKinematics::setOptimizationToleranceRelative(const ::rl::math::Real& optimizationToleranceRelative) { Exception::check(::nlopt_set_xtol_rel(opt.get(), optimizationToleranceRelative)); } void NloptInverseKinematics::setUpperBound(const ::rl::math::Vector& ub) { Exception::check(::nlopt_set_upper_bounds(opt.get(), ub.data())); this->ub = ub; } bool NloptInverseKinematics::solve() { ::std::chrono::steady_clock::time_point start = ::std::chrono::steady_clock::now(); double remaining = ::std::chrono::duration<double>(this->getDuration()).count(); this->iteration = 0; ::rl::math::Vector rand(this->kinematic->getDof()); ::rl::math::Vector q = this->kinematic->getPosition(); double optF; do { if (::nlopt_set_maxeval(opt.get(), this->getIterations() - this->iteration) < 0) { return false; } if (::nlopt_set_maxtime(opt.get(), remaining) < 0) { return false; } ::nlopt_result result = ::nlopt_optimize(opt.get(), q.data(), &optF); if (::NLOPT_STOPVAL_REACHED == result) { return true; } else if (result < -1) { return false; } for (::std::size_t i = 0; i < this->kinematic->getDof(); ++i) { rand(i) = this->randDistribution(this->randEngine); } q = this->kinematic->generatePositionUniform(rand, this->lb, this->ub); remaining = ::std::chrono::duration<double>(this->getDuration() - (::std::chrono::steady_clock::now() - start)).count(); } while (remaining > 0 && this->iteration < this->getIterations()); return false; } bool NloptInverseKinematics::solve2() { ::std::chrono::steady_clock::time_point start = ::std::chrono::steady_clock::now(); double remaining = ::std::chrono::duration<double>(this->getDuration()).count(); this->iteration = 0; ::rl::math::Vector q = this->kinematic->getPosition(); double optF; ::nlopt_result result = ::nlopt_optimize(opt.get(), q.data(), &optF); return true; } NloptInverseKinematics::Exception::Exception(const ::nlopt_result& result) : ::rl::mdl::Exception(::std::string()), result(result) { } NloptInverseKinematics::Exception::~Exception() throw() { } void NloptInverseKinematics::Exception::check(const ::nlopt_result& result) { if (result < 0) { throw Exception(result); } } ::nlopt_result NloptInverseKinematics::Exception::getResult() const { return this->result; } const char* NloptInverseKinematics::Exception::what() const throw() { switch (this->result) { case ::NLOPT_FAILURE: return "Generic failure."; break; case ::NLOPT_INVALID_ARGS: return "Invalid arguments."; break; case ::NLOPT_OUT_OF_MEMORY: return "Out of memory."; break; case ::NLOPT_ROUNDOFF_LIMITED: return "Halted because roundoff errors limited progress."; break; case ::NLOPT_FORCED_STOP: return "Halted because of a forced termination."; break; default: return "Unknown error."; break; } } } }
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/imaging/glf/glew.h" #include "pxr/imaging/hd/binding.h" #include "pxr/imaging/hd/drawBatch.h" #include "pxr/imaging/hd/codeGen.h" #include "pxr/imaging/hd/commandBuffer.h" #include "pxr/imaging/hd/geometricShader.h" #include "pxr/imaging/hd/glslProgram.h" #include "pxr/imaging/hd/lightingShader.h" #include "pxr/imaging/hd/mesh.h" #include "pxr/imaging/hd/perfLog.h" #include "pxr/imaging/hd/renderPassState.h" #include "pxr/imaging/hd/renderPassShader.h" #include "pxr/imaging/hd/resourceRegistry.h" #include "pxr/imaging/hd/shader.h" #include "pxr/imaging/hd/surfaceShader.h" #include "pxr/imaging/hd/tokens.h" #include "pxr/imaging/hd/vtBufferSource.h" #include "pxr/imaging/glf/glslfx.h" #include "pxr/base/tf/getenv.h" Hd_DrawBatch::Hd_DrawBatch(HdDrawItemInstance * drawItemInstance) : _shaderHash(0) { } /*virtual*/ void Hd_DrawBatch::_Init(HdDrawItemInstance * drawItemInstance) { _drawItemInstances.push_back(drawItemInstance); // Force shader to refresh. // XXX: Why is this necessary? If the draw item state changes in a // significant way such that the shader needs to be recompiled, that value // should be part of the shader hash and this shouldn't be required. _shaderHash = 0; } Hd_DrawBatch::~Hd_DrawBatch() { } void Hd_DrawBatch::DrawItemInstanceChanged(HdDrawItemInstance const* /*instance*/) { } namespace { inline bool isAggregated(HdBufferArrayRangeSharedPtr const &rangeA, HdBufferArrayRangeSharedPtr const &rangeB) { if (rangeA) { return rangeA->IsAggregatedWith(rangeB); } else { if (not rangeB) { // can batch together if both ranges are empty. return true; } } return false; } } bool Hd_DrawBatch::Append(HdDrawItemInstance * drawItemInstance) { if (not TF_VERIFY(not _drawItemInstances.empty())) { return false; } // XXX: we'll soon refactor this function out and centralize batch // bucketing and reordering logic in HdCommandBuffer. HdDrawItem const* drawItem = drawItemInstance->GetDrawItem(); HdDrawItem const* batchItem = _drawItemInstances.front()->GetDrawItem(); TF_VERIFY(batchItem); if (_IsAggregated(drawItem, batchItem)) { drawItemInstance->SetBatchIndex(_drawItemInstances.size()); drawItemInstance->SetBatch(this); _drawItemInstances.push_back(drawItemInstance); return true; } else { return false; } } /*static*/ bool Hd_DrawBatch::_IsAggregated(HdDrawItem const *drawItem0, HdDrawItem const *drawItem1) { if (not HdSurfaceShader::CanAggregate(drawItem0->GetSurfaceShader(), drawItem1->GetSurfaceShader())) { return false; } if (drawItem0->GetGeometricShader() == drawItem1->GetGeometricShader() and drawItem0->GetInstancePrimVarNumLevels() == drawItem1->GetInstancePrimVarNumLevels() and isAggregated(drawItem0->GetTopologyRange(), drawItem1->GetTopologyRange()) and isAggregated(drawItem0->GetVertexPrimVarRange(), drawItem1->GetVertexPrimVarRange()) and isAggregated(drawItem0->GetElementPrimVarRange(), drawItem1->GetElementPrimVarRange()) and isAggregated(drawItem0->GetConstantPrimVarRange(), drawItem1->GetConstantPrimVarRange()) and isAggregated(drawItem0->GetInstanceIndexRange(), drawItem1->GetInstanceIndexRange())) { int numLevels = drawItem0->GetInstancePrimVarNumLevels(); for (int i = 0; i < numLevels; ++i) { if (not isAggregated(drawItem0->GetInstancePrimVarRange(i), drawItem1->GetInstancePrimVarRange(i))) { return false; } } return true; } return false; } bool Hd_DrawBatch::Rebuild() { std::vector<HdDrawItemInstance const*> instances; instances.swap(_drawItemInstances); _drawItemInstances.reserve(instances.size()); // Ensure all batch state initialized from items/instances is refreshed. _Init(const_cast<HdDrawItemInstance*>(instances.front())); // Start this loop at i=1 because the 0th element was pushed via _Init for (size_t i = 1; i < instances.size(); ++i) { if (TF_VERIFY(not _drawItemInstances.empty())) { if (not Append(const_cast<HdDrawItemInstance*>(instances[i]))) { return false; } } else { return false; } } return true; } Hd_DrawBatch::_DrawingProgram & Hd_DrawBatch::_GetDrawingProgram(HdRenderPassStateSharedPtr const &state, bool indirect) { HD_TRACE_FUNCTION(); HD_MALLOC_TAG_FUNCTION(); HdDrawItem const *firstDrawItem = _drawItemInstances[0]->GetDrawItem(); size_t shaderHash = state->GetShaderHash(); // overrideShader is taken into account boost::hash_combine(shaderHash, firstDrawItem->GetGeometricShader()->ComputeHash()); bool shaderChanged = (_shaderHash != shaderHash); // XXX: if this function appears to be expensive, we might consider caching // programs by shaderHash. if (not _program.GetGLSLProgram() or shaderChanged) { // compose shaders HdShaderSharedPtrVector shaders(3); shaders[0] = state->GetLightingShader(); shaders[1] = state->GetRenderPassShader(); HdShaderSharedPtr overrideShader = state->GetOverrideShader(); shaders[2] = overrideShader ? overrideShader : firstDrawItem->GetSurfaceShader(); _program.CompileShader(firstDrawItem, firstDrawItem->GetGeometricShader(), shaders, indirect); _shaderHash = shaderHash; } return _program; } void Hd_DrawBatch::_DrawingProgram::CompileShader( HdDrawItem const *drawItem, Hd_GeometricShaderPtr const &geometricShader, HdShaderSharedPtrVector const &shaders, bool indirect) { HD_TRACE_FUNCTION(); HD_MALLOC_TAG_FUNCTION(); // glew has to be intialized if (not glLinkProgram) return; // determine binding points and populate metaData HdBindingRequestVector customBindings; bool instanceDraw = true; _GetCustomBindings(&customBindings, &instanceDraw); // also (surface, renderPass) shaders use their bindings TF_FOR_ALL(it, shaders) { (*it)->AddBindings(&customBindings); } Hd_CodeGen codeGen(geometricShader, shaders); // let resourcebinder resolve bindings and populate metadata // which is owned by codegen. _resourceBinder.ResolveBindings(drawItem, shaders, codeGen.GetMetaData(), indirect, instanceDraw, customBindings); HdGLSLProgram::ID hash = codeGen.ComputeHash(); HdResourceRegistry *resourceRegistry = &HdResourceRegistry::GetInstance(); { HdInstance<HdGLSLProgram::ID, HdGLSLProgramSharedPtr> programInstance; // ask registry to see if there's already compiled program std::unique_lock<std::mutex> regLock = resourceRegistry->RegisterGLSLProgram(hash, &programInstance); if (programInstance.IsFirstInstance()) { HdGLSLProgramSharedPtr glslProgram = codeGen.Compile(); if (_Link(glslProgram)) { // store the program into the program registry. programInstance.SetValue(glslProgram); } } _glslProgram = programInstance.GetValue(); if (_glslProgram) { _resourceBinder.IntrospectBindings(_glslProgram->GetProgram().GetId()); } } } /* virtual */ void Hd_DrawBatch::_DrawingProgram::_GetCustomBindings( HdBindingRequestVector *customBindings, bool *enableInstanceDraw) const { if (not TF_VERIFY(enableInstanceDraw)) return; // set enableInstanceDraw true by default, which means the shader is // expected to be invoked by instanced-draw call. // XFB culling is an exception, which uses glDrawArrays. *enableInstanceDraw = true; } /* virtual */ bool Hd_DrawBatch::_DrawingProgram::_Link( HdGLSLProgramSharedPtr const & glslProgram) { if (not TF_VERIFY(glslProgram)) return false; return glslProgram->Link(); }
//===-- RenameTests.cpp -----------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Annotations.h" #include "TestFS.h" #include "TestTU.h" #include "refactor/Rename.h" #include "clang/Tooling/Core/Replacement.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace clang { namespace clangd { namespace { TEST(RenameTest, SingleFile) { struct Test { const char* Before; const char* After; } Tests[] = { // Rename function. { R"cpp( void foo() { fo^o(); } )cpp", R"cpp( void abcde() { abcde(); } )cpp", }, // Rename type. { R"cpp( struct foo{}; foo test() { f^oo x; return x; } )cpp", R"cpp( struct abcde{}; abcde test() { abcde x; return x; } )cpp", }, // Rename variable. { R"cpp( void bar() { if (auto ^foo = 5) { foo = 3; } } )cpp", R"cpp( void bar() { if (auto abcde = 5) { abcde = 3; } } )cpp", }, }; for (const Test &T : Tests) { Annotations Code(T.Before); auto TU = TestTU::withCode(Code.code()); TU.HeaderCode = "void foo();"; // outside main file, will not be touched. auto AST = TU.build(); auto RenameResult = renameWithinFile(AST, testPath(TU.Filename), Code.point(), "abcde"); ASSERT_TRUE(bool(RenameResult)) << RenameResult.takeError(); auto ApplyResult = tooling::applyAllReplacements(Code.code(), *RenameResult); ASSERT_TRUE(bool(ApplyResult)) << ApplyResult.takeError(); EXPECT_EQ(T.After, *ApplyResult) << T.Before; } } } // namespace } // namespace clangd } // namespace clang
#include "ai/hl/stp/action/chip_action.h" #include <gtest/gtest.h> #include "ai/intent/chip_intent.h" #include "ai/intent/move_intent.h" TEST(ChipActionTest, robot_behind_ball_chipping_towards_positive_x_positive_y) { Robot robot = Robot(0, Point(-0.5, 0), Vector(), Angle::zero(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(0, 0), Angle::zero(), 5.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); ChipIntent chip_intent = dynamic_cast<ChipIntent &>(*intent_ptr); EXPECT_EQ(0, chip_intent.getRobotId()); EXPECT_EQ(Point(0, 0), chip_intent.getChipOrigin()); EXPECT_EQ(Angle::zero(), chip_intent.getChipDirection()); EXPECT_EQ(5.0, chip_intent.getChipDistance()); } TEST(ChipActionTest, robot_behind_ball_chipping_towards_negative_x_positive_y) { Robot robot = Robot(0, Point(-2.3, 2.1), Vector(), Angle::quarter(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(-2.5, 2.5), Angle::ofDegrees(105), 5.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); ChipIntent chip_intent = dynamic_cast<ChipIntent &>(*intent_ptr); EXPECT_EQ(0, chip_intent.getRobotId()); EXPECT_EQ(Point(-2.5, 2.5), chip_intent.getChipOrigin()); EXPECT_EQ(Angle::ofDegrees(105), chip_intent.getChipDirection()); EXPECT_EQ(5.0, chip_intent.getChipDistance()); } TEST(ChipActionTest, robot_behind_ball_chipping_towards_negative_x_negative_y) { Robot robot = Robot(0, Point(0, 0), Vector(), Angle::quarter(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(-0.1, -0.4), Angle::ofDegrees(255), 3.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); ChipIntent chip_intent = dynamic_cast<ChipIntent &>(*intent_ptr); EXPECT_EQ(0, chip_intent.getRobotId()); EXPECT_EQ(Point(-0.1, -0.4), chip_intent.getChipOrigin()); EXPECT_EQ(Angle::ofDegrees(255), chip_intent.getChipDirection()); EXPECT_EQ(3.0, chip_intent.getChipDistance()); } TEST(ChipActionTest, robot_behind_ball_chipping_towards_positive_x_negative_y) { Robot robot = Robot(0, Point(-0.25, 0.5), Vector(), Angle::threeQuarter(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(0, 0), Angle::ofDegrees(306), 5.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); ChipIntent chip_intent = dynamic_cast<ChipIntent &>(*intent_ptr); EXPECT_EQ(0, chip_intent.getRobotId()); EXPECT_EQ(Point(0, 0), chip_intent.getChipOrigin()); EXPECT_EQ(Angle::ofDegrees(306), chip_intent.getChipDirection()); EXPECT_EQ(5.0, chip_intent.getChipDistance()); } TEST(ChipActionTest, robot_not_behind_ball_chipping_towards_positive_x_positive_y) { Robot robot = Robot(0, Point(-1, 0.0), Vector(), Angle::zero(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(0, 0), Angle::zero(), 5.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); MoveIntent move_intent = dynamic_cast<MoveIntent &>(*intent_ptr); EXPECT_EQ(0, move_intent.getRobotId()); // Check the MoveIntent is moving roughly behind the ball EXPECT_TRUE(move_intent.getDestination().isClose(Point(-0.28, 0), 0.1)); EXPECT_EQ(Angle::zero(), move_intent.getFinalAngle()); EXPECT_EQ(0.0, move_intent.getFinalSpeed()); } TEST(ChipActionTest, robot_not_behind_ball_chipping_towards_negative_x_positive_y) { Robot robot = Robot(0, Point(-2, 5), Vector(), Angle::quarter(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(-2.5, 2.5), Angle::ofDegrees(105), 5.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); MoveIntent move_intent = dynamic_cast<MoveIntent &>(*intent_ptr); EXPECT_EQ(0, move_intent.getRobotId()); // Check the MoveIntent is moving roughly behind the ball EXPECT_TRUE(move_intent.getDestination().isClose(Point(-2.45, 2.25), 0.1)); EXPECT_EQ(Angle::ofDegrees(105), move_intent.getFinalAngle()); EXPECT_EQ(0.0, move_intent.getFinalSpeed()); } TEST(ChipActionTest, robot_not_behind_ball_chipping_towards_negative_x_negative_y) { Robot robot = Robot(0, Point(0, 0), Vector(), Angle::quarter(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(-1, -4), Angle::ofDegrees(255), 3.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); MoveIntent move_intent = dynamic_cast<MoveIntent &>(*intent_ptr); EXPECT_EQ(0, move_intent.getRobotId()); // Check the MoveIntent is moving roughly behind the ball EXPECT_TRUE(move_intent.getDestination().isClose(Point(-0.85, -3.75), 0.1)); EXPECT_EQ(Angle::ofDegrees(255), move_intent.getFinalAngle()); EXPECT_EQ(0.0, move_intent.getFinalSpeed()); } TEST(ChipActionTest, robot_not_behind_ball_chipping_towards_positive_x_negative_y) { Robot robot = Robot(0, Point(0.5, 1), Vector(), Angle::threeQuarter(), AngularVelocity::zero(), Timestamp::fromSeconds(0)); ChipAction action = ChipAction(); auto intent_ptr = action.updateStateAndGetNextIntent(robot, Point(0, 0), Angle::ofDegrees(306), 5.0); // Check an intent was returned (the pointer is not null) EXPECT_TRUE(intent_ptr); EXPECT_FALSE(action.done()); MoveIntent move_intent = dynamic_cast<MoveIntent &>(*intent_ptr); EXPECT_EQ(0, move_intent.getRobotId()); // Check the MoveIntent is moving roughly behind the ball EXPECT_TRUE(move_intent.getDestination().isClose(Point(-0.15, 0.25), 0.1)); EXPECT_EQ(Angle::ofDegrees(306), move_intent.getFinalAngle()); EXPECT_EQ(0.0, move_intent.getFinalSpeed()); }
/*********************************************************************** created: Tue Mar 7 2006 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/XMLParserModules/TinyXML/XMLParserModule.h" #include "CEGUI/XMLParserModules/TinyXML/XMLParser.h" CEGUI::XMLParser* createParser(void) { return new CEGUI::TinyXMLParser(); } void destroyParser(CEGUI::XMLParser* parser) { delete parser; }
// // HAPFakeGatoSwitch.cpp // Homekit // // Created on: 21.12.2019 // Author: michael // #include "HAPFakeGatoSwitch.hpp" #include "HAPServer.hpp" #define HAP_FAKEGATO_SIGNATURE_LENGTH 1 // number of 16 bits word of the following "signature" portion #define HAP_FAKEGATO_DATA_LENGTH 11 // length of the data HAPFakeGatoSwitch::HAPFakeGatoSwitch(){ _interval = HAP_FAKEGATO_INTERVAL; _previousMillis = 0; _isEnabled = true; _name = ""; _memoryUsed = 0; _requestedEntry = 0; _refTime = 0; _vectorBuffer = nullptr; _idxRead = 0; // gets incremented when poped _idxWrite = 0; // gets incremented when pushed _transfer = false; _rolledOver = false; _periodicUpdates = false; // only write a fakegato entry if an action; not periodic ! } HAPFakeGatoSwitch::~HAPFakeGatoSwitch(){ if (_vectorBuffer != nullptr){ _vectorBuffer->clear(); delete _vectorBuffer; } } void HAPFakeGatoSwitch::begin(){ if (_vectorBuffer == nullptr) { _vectorBuffer = new std::vector<HAPFakeGatoSwitchData>(HAP_FAKEGATO_BUFFER_SIZE); } } int HAPFakeGatoSwitch::signatureLength(){ return HAP_FAKEGATO_SIGNATURE_LENGTH; } void HAPFakeGatoSwitch::getSignature(uint8_t* signature){ ui16_to_ui8 s1; s1.ui16 = __builtin_bswap16(0x0E01); memcpy(signature, s1.ui8, 2); } bool HAPFakeGatoSwitch::addEntry(String status){ LogD(HAPServer::timeString() + " " + String(__CLASS_NAME__) + "->" + String(__FUNCTION__) + " [ ] " + "Adding entry for " + _name + " [size=" + String(_memoryUsed) + "]: status=" + status, true); uint8_t valueStatus = status.toInt(); HAPFakeGatoSwitchData data = (HAPFakeGatoSwitchData){ HAPServer::timestamp(), valueStatus }; return addEntry(data); } bool HAPFakeGatoSwitch::addEntry(HAPFakeGatoSwitchData data){ // if (_ringbuffer == nullptr) { // begin(); // } LogD(HAPServer::timeString() + " " + String(__CLASS_NAME__) + "->" + String(__FUNCTION__) + " [ ] " + "Add fakegato data for " + _name + " ..." , true); if (_vectorBuffer == nullptr) { begin(); } if (_memoryUsed < HAP_FAKEGATO_BUFFER_SIZE){ _memoryUsed++; } _timestampLastEntry = data.timestamp; (*_vectorBuffer)[_idxWrite] = data; // increment write index _idxWrite = incrementIndex(_idxWrite); // Serial.print("_idxWrite: "); // Serial.println(_idxWrite); if (_memoryUsed == _vectorBuffer->size()){ // Serial.println("Rolled over"); _rolledOver = true; _idxRead = incrementIndex(_idxWrite); } #if HAP_DEBUG_FAKEGATO Serial.print("_memoryUsed: "); Serial.println(_memoryUsed); for (int i=0; i< HAP_FAKEGATO_BUFFER_SIZE; i++){ HAPFakeGatoSwitchData entryData; entryData = (*_vectorBuffer)[i]; if (i == _idxWrite) { Serial.printf("No. %d - %d status: %d <<< w:%d\n", i, entryData.timestamp,entryData.status, _idxWrite); } else { Serial.printf("No. %d - %d status: %d\n", i, entryData.timestamp,entryData.status); } } #endif updateS2R1Value(); return !_rolledOver; } // TODO: Read from index requested by EVE app void HAPFakeGatoSwitch::getData(const size_t count, uint8_t *data, size_t* length, uint16_t offset){ #if HAP_DEBUG_FAKEGATO LogD(HAPServer::timeString() + " " + String(__CLASS_NAME__) + "->" + String(__FUNCTION__) + " [ ] " + "Get fakegato data for " + _name + " ..." , true); #endif #if HAP_DEBUG_FAKEGATO for (int i=0; i< HAP_FAKEGATO_BUFFER_SIZE; i++){ HAPFakeGatoSwitchData entryData; entryData = (*_vectorBuffer)[i]; if (i == _idxWrite) { Serial.printf("No. %d - %d status: %d <<< w:%d\n", i, entryData.timestamp,entryData.status, _idxWrite); } else { Serial.printf("No. %d - %d status: %d\n", i, entryData.timestamp,entryData.status); } } #endif uint32_t tmpRequestedEntry = (_requestedEntry - 1) % HAP_FAKEGATO_BUFFER_SIZE; #if HAP_DEBUG_FAKEGATO Serial.println(">>>>> getData"); Serial.print("0 tmpRequestedEntry: "); Serial.println(tmpRequestedEntry); Serial.print("0 _idxRead: "); Serial.println(_idxRead); Serial.print("0 _requestedEntry: "); Serial.println(_requestedEntry); Serial.print("0 _idxWrite: "); Serial.println(_idxWrite); #endif if ( (tmpRequestedEntry >= _idxWrite) && ( _rolledOver == false) ){ _transfer = false; LogE("ERROR: Fakegato Switch could not send the requested entry. The requested index does not exist!", true); LogE(" - tmpRequestedEntry=" + String(tmpRequestedEntry), true); LogE(" - _requestedEntry=" + String(_requestedEntry), true); LogE(" - _idxWrite=" + String(_idxWrite), true); LogE(" - _rolledOver=" + String(_rolledOver), true); return; } HAPFakeGatoSwitchData entryData; entryData = (*_vectorBuffer)[tmpRequestedEntry]; for (int i = 0; i < count; i++){ #if HAP_DEBUG_FAKEGATO Serial.print("tmpRequestedEntry: "); Serial.println(tmpRequestedEntry); Serial.print("_idxRead: "); Serial.println(_idxRead); Serial.print("_requestedEntry: "); Serial.println(_requestedEntry); #endif uint8_t size = HAP_FAKEGATO_DATA_LENGTH; memcpy(data + offset, (uint8_t *)&size, 1); ui32_to_ui8 eC; eC.ui32 = _requestedEntry++; memcpy(data + offset + 1, eC.ui8, 4); ui32_to_ui8 secs; secs.ui32 = entryData.timestamp - _refTime; memcpy(data + offset + 1 + 4, secs.ui8, 4); uint8_t bitmask = 0x01; memcpy(data + offset + 1 + 4 + 4, (uint8_t*)&bitmask, 1); uint8_t status = entryData.status; memcpy(data + offset + 1 + 4 + 4 + 1, (uint8_t*)&status, 1); *length = offset + HAP_FAKEGATO_DATA_LENGTH; offset = offset + HAP_FAKEGATO_DATA_LENGTH; // _noOfEntriesSent++; if ( (tmpRequestedEntry + 1 >= _idxWrite ) && ( _rolledOver == false) ){ _transfer = false; LogE("ERROR: Fakegato Switch could not send the requested entry. The requested index does not exist!", true); LogE(" - tmpRequestedEntry=" + String(tmpRequestedEntry), true); LogE(" - _requestedEntry=" + String(_requestedEntry), true); LogE(" - _idxWrite=" + String(_idxWrite), true); LogE(" - _rolledOver=" + String(_rolledOver), true); break; } uint32_t tsOld = entryData.timestamp; tmpRequestedEntry = incrementIndex(tmpRequestedEntry); entryData = (*_vectorBuffer)[tmpRequestedEntry]; if ( _rolledOver == true) { if (tsOld > entryData.timestamp) { _transfer = false; LogE("ERROR: Fakegato Switch could not send the requested entry. The requested index does not exist!", true); LogE(" - tmpRequestedEntry=" + String(tmpRequestedEntry), true); LogE(" - _requestedEntry=" + String(_requestedEntry), true); LogE(" - _idxWrite=" + String(_idxWrite), true); LogE(" - _rolledOver=" + String(_rolledOver), true); break; } } #if HAP_DEBUG_FAKEGATO Serial.print("2 _idxWrite: "); Serial.println(_idxWrite); Serial.print("2 _idxRead: "); Serial.println(_idxRead); Serial.print("2 tmpRequestedEntry: "); Serial.println(tmpRequestedEntry); Serial.println("====================================================================="); #endif } }
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/log_loss_op.h" namespace paddle { namespace operators { class LogLossOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("Predicted"), "Input(Predicted) must be initialized."); PADDLE_ENFORCE(ctx->HasInput("Labels"), "Input(Labels) must be initialized."); auto pred_dims = ctx->GetInputDim("Predicted"); auto label_dims = ctx->GetInputDim("Labels"); PADDLE_ENFORCE_EQ(pred_dims, label_dims); PADDLE_ENFORCE_EQ(pred_dims.size(), 2, "The rank of Input(Predicted) must be 2 and the shape is " "[batch_size, 1]."); PADDLE_ENFORCE_EQ(pred_dims[1], 1, "Each row of Input(Predicted) contains a real value, " "so the 2nd dimension of Input(X) must be 1."); ctx->SetOutputDim("Loss", {pred_dims[0], 1}); ctx->ShareLoD("Predicted", "Loss"); } }; template <typename AttrType> class LogLossOpMaker : public framework::OpProtoAndCheckerMaker { public: LogLossOpMaker(OpProto* proto, OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("Predicted", "The input value (Predicted) of Log loss op." "Predicted is a 2-D tensor with shape [batch_size, 1]."); AddInput("Labels", "The target value (Labels) of Log loss op." "Labels is a 2-D tensor with shape [batch_size, 1]."); AddOutput("Loss", "The output tensor with shape [batch_size, 1] " "which represents the log loss."); AddAttr<AttrType>("epsilon", "Epsilon in log loss."); AddComment(R"DOC( LogLoss Operator. Log loss is a loss function used for binary classification. Log Loss quantifies the accuracy of a classifier by penalising false classifications. Minimising the Log Loss is equivalent to maximising the accuracy of the classifier. We define Predicted as the values predicted by our model and Labels as the target ground truth value. Log loss can evaluate how close the predicted values are to the target. The shapes of Predicted and Labels are both [batch_size, 1]. The equation is: $$ Loss = - Labels * log(Predicted + \epsilon) - (1 - Labels) * log(1 - Predicted + \epsilon) $$ )DOC"); } }; class LogLossGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("Predicted"), "Input(Predicted) should not be null."); PADDLE_ENFORCE(ctx->HasInput("Labels"), "Input(Labels) should not be null."); PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")), "Input(Loss@GRAD) should not be null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Predicted")), "Output(Predicted@GRAD) should not be null."); auto pred_dims = ctx->GetInputDim("Predicted"); auto label_dims = ctx->GetInputDim("Labels"); auto loss_grad_dims = ctx->GetInputDim(framework::GradVarName("Loss")); PADDLE_ENFORCE_EQ(loss_grad_dims, pred_dims); auto pred_grad_name = framework::GradVarName("Predicted"); ctx->SetOutputDim(pred_grad_name, pred_dims); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(log_loss, ops::LogLossOp, ops::LogLossOpMaker<float>, log_loss_grad, ops::LogLossGradOp); REGISTER_OP_CPU_KERNEL( log_loss, ops::LogLossKernel<paddle::platform::CPUDeviceContext, float>); REGISTER_OP_CPU_KERNEL( log_loss_grad, ops::LogLossGradKernel<paddle::platform::CPUDeviceContext, float>);
/* * This file is part of the Simutrans-Extended project under the Artistic License. * (see LICENSE.txt) */ #include <stdlib.h> #include <algorithm> #include <cmath> #include "simdebug.h" #include "simunits.h" #include "simworld.h" #include "simware.h" #include "player/finance.h" // convert_money #include "player/simplay.h" #include "simconvoi.h" #include "simhalt.h" #include "simdepot.h" #include "gui/simwin.h" #include "simmenu.h" #include "simcolor.h" #include "simmesg.h" #include "simintr.h" #include "simlinemgmt.h" #include "simline.h" #include "freight_list_sorter.h" #include "gui/minimap.h" #include "gui/convoi_info_t.h" #include "gui/schedule_gui.h" #include "gui/depot_frame.h" #include "gui/messagebox.h" #include "gui/convoi_detail_t.h" #include "boden/grund.h" #include "boden/wege/schiene.h" // for railblocks #include "boden/wege/strasse.h" #include "bauer/vehikelbauer.h" #include "descriptor/vehicle_desc.h" #include "descriptor/roadsign_desc.h" #include "descriptor/building_desc.h" #include "dataobj/schedule.h" #include "dataobj/route.h" #include "dataobj/loadsave.h" #include "dataobj/replace_data.h" #include "dataobj/translator.h" #include "dataobj/environment.h" #include "dataobj/livery_scheme.h" #include "display/viewport.h" #include "obj/crossing.h" #include "obj/roadsign.h" #include "obj/wayobj.h" #include "obj/signal.h" #include "vehicle/simvehicle.h" #include "vehicle/overtaker.h" #include "utils/simstring.h" #include "utils/cbuffer_t.h" #include "convoy.h" #include "descriptor/goods_desc.h" #ifdef MULTI_THREAD #include "utils/simthread.h" static pthread_mutex_t step_convois_mutex = PTHREAD_MUTEX_INITIALIZER; static vector_tpl<pthread_t> unreserve_threads; waytype_t convoi_t::current_waytype = road_wt; uint16 convoi_t::current_unreserver = 0; #endif //#if _MSC_VER //#define snprintf _snprintf //#endif /* * Waiting time for loading (ms) */ #define WTT_LOADING 500 karte_ptr_t convoi_t::welt; /* * Debugging helper - translate state value to human readable name */ static const char * state_names[convoi_t::MAX_STATES] = { "INITIAL", "EDIT_SCHEDULE", "ROUTING_1", "ROUTING_2", "", "NO_ROUTE", "DRIVING", "LOADING", "WAITING_FOR_CLEARANCE", "WAITING_FOR_CLEARANCE_ONE_MONTH", "CAN_START", "CAN_START_ONE_MONTH", "SELF_DESTRUCT", "WAITING_FOR_CLEARANCE_TWO_MONTHS", "CAN_START_TWO_MONTHS", "LEAVING_DEPOT", "ENTERING_DEPOT", "REVERSING", "OUT_OF_RANGE", "EMERGENCY_STOP", "JUST_FOUND_ROUTE", "NO_ROUTE_TOO_COMPLEX", "WAITING_FOR_LOADING_THREE_MONTHS", "WAITING_FOR_LOADING_FOUR_MONTHS" }; // Reset some values. Used in init and replacing. void convoi_t::reset() { is_electric = false; //sum_gesamtweight = sum_weight = 0; previous_delta_v = 0; withdraw = false; has_obsolete = false; no_load = false; depot_when_empty = false; reverse_schedule = false; jahresgewinn = 0; set_akt_speed(0); // momentane Geschwindigkeit / current speed sp_soll = 0; //brake_speed_soll = 2147483647; // ==SPEED_UNLIMITED highest_axle_load = 0; longest_min_loading_time = 0; longest_max_loading_time = 0; current_loading_time = 0; clear_departures(); for(uint8 i = 0; i < MAX_CONVOI_COST; i ++) { rolling_average[i] = 0; rolling_average_count[i] = 0; } } void convoi_t::init(player_t *player) { owner = player; schedule = NULL; replace = NULL; schedule_target = koord3d::invalid; line = linehandle_t(); reset(); vehicle_count = 0; steps_driven = -1; wait_lock = 0; wait_lock_next_step = 0; go_on_ticks = WAIT_INFINITE; requested_change_lane = false; jahresgewinn = 0; total_distance_traveled = 0; steps_since_last_odometer_increment = 0; //distance_since_last_stop = 0; //sum_speed_limit = 0; //maxspeed_average_count = 0; next_reservation_index = 0; alte_direction = ribi_t::none; next_wolke = 0; state = INITIAL; *name_and_id = 0; name_offset = 0; freight_info_resort = true; freight_info_order = 0; loading_level = 0; loading_limit = 0; free_seats = 0; //speed_limit = SPEED_UNLIMITED; //brake_speed_soll = SPEED_UNLIMITED; akt_speed_soll = 0; // target speed set_akt_speed(0); // current speed sp_soll = 0; next_stop_index = INVALID_INDEX; line_update_pending = linehandle_t(); home_depot = koord3d::invalid; last_signal_pos = koord3d::invalid; last_stop_id = 0; yielding_quit_index = -1; lane_affinity = 0; next_cross_lane = false; prev_tiles_overtaking = 0; reversable = false; reversed = false; re_ordered = false; livery_scheme_index = 0; needs_full_route_flush = false; } convoi_t::convoi_t(loadsave_t* file) : vehicle(max_vehicle, NULL) { self = convoihandle_t(); init(0); replace = NULL; is_choosing = false; last_stop_was_depot = true; max_signal_speed = SPEED_UNLIMITED; no_route_retry_count = 0; rdwr(file); current_stop = schedule == NULL ? 255 : schedule->get_current_stop() - 1; // Added by : Knightly old_schedule = NULL; free_seats = 0; recalc_catg_index(); calc_classes_carried(); has_obsolete = calc_obsolescence(welt->get_timeline_year_month()); validate_vehicle_summary(); validate_adverse_summary(); validate_freight_summary(); validate_weight_summary(); get_continuous_power(); get_starting_force(); get_braking_force(); } convoi_t::convoi_t(player_t* player) : vehicle(max_vehicle, NULL) { self = convoihandle_t(this); player->book_convoi_number(1); init(player); set_name( "Unnamed" ); welt->add_convoi( self ); init_financial_history(); current_stop = 255; is_choosing = false; last_stop_was_depot = true; max_signal_speed = SPEED_UNLIMITED; // Added by : Knightly old_schedule = NULL; free_seats = 0; livery_scheme_index = 0; no_route_retry_count = 0; } convoi_t::~convoi_t() { owner->book_convoi_number( -1); assert(self.is_bound()); assert(vehicle_count==0); destroy_win( magic_convoi_detail + self.get_id() ); close_windows(); DBG_MESSAGE("convoi_t::~convoi_t()", "destroying %d, %p", self.get_id(), this); // stop following if(welt->get_viewport()->get_follow_convoi()==self) { welt->get_viewport()->set_follow_convoi( convoihandle_t() ); } welt->sync.remove( this ); welt->rem_convoi( self ); if (!welt->is_destroying()) { clear_estimated_times(); // if lineless convoy -> unregister from stops if (!line.is_bound()) { unregister_stops(); } } // force asynchronous recalculation if(schedule) { if(!schedule->is_editing_finished()) { destroy_win((ptrdiff_t)schedule); } if (!schedule->empty() && !line.is_bound()) { // New method - recalculate as necessary // Added by : Knightly haltestelle_t::refresh_routing(schedule, goods_catg_index, NULL, NULL, owner); // NULL because if we are refreshing all goods categories, there is no need to refresh the classes, too, as these are subsets. } delete schedule; } clear_replace(); // deregister from line (again) unset_line(); self.detach(); } void convoi_t::close_windows() { // close windows destroy_win( magic_convoi_info+self.get_id() ); destroy_win( magic_replace+self.get_id() ); } // waypoint: no stop, resp. for airplanes in air (i.e. no air strip below) bool convoi_t::is_waypoint( koord3d ziel ) const { if (vehicle[0]->get_waytype() == air_wt) { // separate logic for airplanes, since the can have waypoints over stops etc. grund_t *gr = welt->lookup_kartenboden(ziel.get_2d()); if( gr == NULL || gr->get_weg(air_wt) == NULL ) { // during flight always a waypoint return true; } else if( gr->get_depot() ) { // but a depot is not a waypoint return false; } // so we are on a taxiway/runway here ... } return !haltestelle_t::get_halt(ziel,get_owner()).is_bound(); } #ifdef MULTI_THREAD void convoi_t::unreserve_route_range(route_range_specification range) { const vector_tpl<weg_t *> &all_ways = weg_t::get_alle_wege(); for (uint32 i = range.start; i <= range.end; i++) { weg_t* const way = all_ways[i]; //schiene_t* const sch = obj_cast<schiene_t>(way); schiene_t* const sch = way->is_rail_type() || way->get_waytype() == air_wt ? (schiene_t*)way : NULL; if (sch && sch->get_reserved_convoi().get_id() == convoi_t::current_unreserver) { convoihandle_t ch; ch.set_id(convoi_t::current_unreserver); sch->unreserve(ch); } } } #endif /** * unreserves the whole remaining route */ void convoi_t::unreserve_route() { // Clears all reserved tiles on the whole map belonging to this convoy. #ifdef MULTI_THREAD_ROUTE_UNRESERVER current_unreserver = self.get_id(); current_waytype = front()->get_waytype(); simthread_barrier_wait(&karte_t::unreserve_route_barrier); simthread_barrier_wait(&karte_t::unreserve_route_barrier); current_unreserver = 0; current_waytype = invalid_wt; #else FOR(vector_tpl<weg_t*>, const way, weg_t::get_alle_wege()) { if(way->get_waytype() == front()->get_waytype()) { //schiene_t* const sch = obj_cast<schiene_t>(way); schiene_t* const sch = way->is_rail_type() ? (schiene_t*)way : NULL; if(sch && sch->get_reserved_convoi() == self) { sch->unreserve(front()); } } } #endif set_needs_full_route_flush(false); } void convoi_t::reserve_own_tiles(bool unreserve) { if(vehicle_count > 0) { for (unsigned i = 0; i != vehicle_count; ++i) { vehicle_t& v = *vehicle[i]; grund_t* gr = welt->lookup(v.get_pos()); if(gr) { if(schiene_t *sch = dynamic_cast<schiene_t *>(gr->get_weg(front()->get_waytype()))) { if(!route.empty()) { if (unreserve) { sch->unreserve(self); } else { sch->reserve(self, ribi_type(route.at(max(1u, 1) - 1u), route.at(min(route.get_count() - 1u, 0 + 1u)))); } } } } } } } /** * Sets route_index of all vehicles to startindex. * Puts all vehicles on tile at this position in the route. * Convoy stills needs to be pushed that the convoy is right on track. * @returns length of convoy minus last vehicle */ uint32 convoi_t::move_to(uint16 const start_index) { steps_driven = -1; koord3d k = route.at(start_index); grund_t* gr = welt->lookup(k); uint32 train_length = 0; for (unsigned i = 0; i != vehicle_count; ++i) { vehicle_t& v = *vehicle[i]; if( welt->lookup(v.get_pos()) ) { v.mark_image_dirty(v.get_image(), 0); v.leave_tile(); // maybe unreserve this weg_t* const way = v.get_weg(); schiene_t* const rails = obj_cast<schiene_t>(way); if(rails) { if(state != REVERSING) { rails->unreserve(&v); } } } // propagate new index to vehicle, will set all movement related variables, in particular pos v.initialise_journey(start_index, true); // now put vehicle on the tile if (gr) { v.enter_tile(gr); } if (i != vehicle_count - 1U) { train_length += v.get_desc()->get_length(); } } return train_length; } void convoi_t::finish_rd() { if(schedule==NULL) { if( state!=INITIAL ) { emergency_go_to_depot(); return; } // anyway reassign convoi pointer ... for( uint8 i=0; i<vehicle_count; i++ ) { vehicle[i]->set_convoi(this); // This call used to update the fixed monthly maintenance costs; this was deleted due to // the fact that these change each month due to depreciation, so this doesn't work. // It would be good to restore it. // --neroden // vehicle[i]->finish_rd(); } return; } else { // restore next schedule target for non-stop waypoint handling const koord3d ziel = schedule->get_current_entry().pos; if( vehicle_count>0 && is_waypoint(ziel) ) { schedule_target = ziel; } } bool realing_position = false; if( vehicle_count>0 ) { DBG_MESSAGE("convoi_t::finish_rd()","state=%s, next_stop_index=%d", state_names[state], next_stop_index ); const uint32 max_route_index = get_route() ? get_route()->get_count() - 1 : 0; // only realign convois not leaving depot to avoid jumps through signals if( steps_driven!=-1 ) { for( uint8 i=0; i<vehicle_count; i++ ) { vehicle_t* v = vehicle[i]; if(v->get_route_index() > max_route_index && max_route_index > 0 && i > 0) { dbg->error("convoi_t::finish_rd()", "Route index is %i, whereas maximum route index is %i for convoy %i", v->get_route_index(), max_route_index, self.get_id()); v->set_route_index(front()->get_route_index()); } v->set_leading( i==0 ); v->set_last( i+1==vehicle_count ); v->calc_height(); // this sets the convoi and will renew the block reservation, if needed! v->set_convoi(this); } } else { // test also for realignment koord3d drive_pos; for( uint8 i=0; i<vehicle_count; i++ ) { vehicle_t* v = vehicle[i]; /*if(v->get_route_index() > max_route_index && max_route_index > 0 && i > 0) { dbg->error("convoi_t::finish_rd()", "Route index is %i, whereas maximum route index is %i for convoy %i", v->get_route_index(), max_route_index, self.get_id()); v->set_route_index(front()->get_route_index()); }*/ v->set_leading( i==0 ); v->set_last( i+1==vehicle_count ); v->calc_height(); // this sets the convoi and will renew the block reservation, if needed! v->set_convoi(this); // wrong alignment here => must relocate if(v->need_realignment()) { // diagonal => convoi must restart realing_position |= ribi_t::is_bend(v->get_direction()) && (state==DRIVING || is_waiting()); } } } DBG_MESSAGE("convoi_t::finish_rd()","next_stop_index=%d", next_stop_index ); linehandle_t new_line = line; if( !new_line.is_bound() ) { // if there is a line with id=0 in the savegame try to assign cnv to this line new_line = get_owner()->simlinemgmt.get_line_with_id_zero(); } if( new_line.is_bound() ) { if ( !schedule->matches( welt, new_line->get_schedule() ) ) { // 101 version produced broken line ids => we have to find our line the hard way ... vector_tpl<linehandle_t> lines; get_owner()->simlinemgmt.get_lines(schedule->get_type(), &lines); new_line = linehandle_t(); FOR(vector_tpl<linehandle_t>, const l, lines) { if( schedule->matches( welt, l->get_schedule() ) ) { // if a line is assigned, set line! new_line = l; break; } } } // now the line should match our schedule or else ... if(new_line.is_bound()) { line = new_line; line->add_convoy(self, true); DBG_DEBUG("convoi_t::finish_rd()","%s registers for %d", name_and_id, line.get_id()); } else { line = linehandle_t(); } } } else { // no vehicles in this convoi?!? dbg->error( "convoi_t::finish_rd()","No vehicles in Convoi %i: will be destroyed!", self.get_id() ); destroy(); return; } // put convoi again right on track? if(realing_position && vehicle_count>1) { // display just a warning DBG_MESSAGE("convoi_t::finish_rd()","cnv %i is currently too long.",self.get_id()); if (route.empty()) { // realigning needs a route state = NO_ROUTE; owner->report_vehicle_problem( self, koord3d::invalid ); dbg->error( "convoi_t::finish_rd()", "No valid route, but needs realignment at (%s)!", front()->get_pos().get_str() ); } else { // since start may have been changed const uint8 v_count = vehicle_count - 1; uint16 last_route_index = vehicle[v_count]->get_route_index(); if(last_route_index > route.get_count() - 1 && v_count > 0) { last_route_index = 0; dbg->warning("convoi_t::finish_rd()", "Convoy %i's route index is out of range: resetting to zero", self.get_id()); } uint16 start_index = min(max(1u, vehicle[vehicle_count - 1u]->get_route_index() - 1u), route.get_count() - 1u); uint32 train_length = move_to(start_index) + 1; const koord3d last_start = front()->get_pos(); // now advance all convoi until it is completely on the track front()->set_leading(false); // switches off signal checks ... for(unsigned i=0; i<vehicle_count; i++) { vehicle_t* v = vehicle[i]; v->get_smoke(false); //"Allowed to smoke" (Google) vehicle[i]->do_drive( (VEHICLE_STEPS_PER_CARUNIT*train_length)<<YARDS_PER_VEHICLE_STEP_SHIFT ); train_length -= v->get_desc()->get_length(); v->get_smoke(true); // eventually reserve this again grund_t *gr=welt->lookup(v->get_pos()); // airplanes may have no ground ... if(gr) { if (schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(vehicle[i]->get_waytype()))) { sch0->reserve(self, v->get_direction()); } } } front()->set_leading(true); if( state != INITIAL && state != EDIT_SCHEDULE && front()->get_pos() != last_start ) { state = WAITING_FOR_CLEARANCE; } } } // when saving with open window, this can happen if( state==EDIT_SCHEDULE ) { if (env_t::networkmode) { wait_lock = 30000; // milliseconds to drive on, if the client in question had left } schedule->finish_editing(); } // remove wrong freight check_freight(); // some convois had wrong old direction in them if( state<DRIVING || is_loading() ) { alte_direction = front()->get_direction(); } // if lineless convoy -> register itself with stops if (state > INITIAL) { if (!line.is_bound()) { register_stops(); } } for(int i = 0; i < vehicle_count; i++) { vehicle[i]->remove_stale_cargo(); // This anomaly can arise afer takeovers in some instances before a bug was fixed. // Vehicles should not be owned by no-one. if (vehicle[i]->get_owner() == NULL) { vehicle[i]->set_owner(get_owner()); } } loading_limit = schedule->get_current_entry().minimum_loading; if(is_loading()) { laden(); } } // since now convoi states go via tool_t void convoi_t::call_convoi_tool( const char function, const char *extra) { tool_t *tmp_tool = create_tool( TOOL_CHANGE_CONVOI | SIMPLE_TOOL ); cbuffer_t param; param.printf("%c,%u", function, self.get_id()); if( extra && *extra ) { param.printf(",%s", extra); } tmp_tool->set_default_param(param); welt->set_tool( tmp_tool, get_owner() ); // since init always returns false, it is safe to delete immediately delete tmp_tool; } void convoi_t::rotate90( const sint16 y_size ) { home_depot.rotate90( y_size ); last_signal_pos.rotate90(y_size); route.rotate90( y_size ); if( schedule_target!=koord3d::invalid ) { schedule_target.rotate90( y_size ); } if(schedule) { schedule->rotate90( y_size ); } for( int i=0; i<vehicle_count; i++ ) { vehicle[i]->rotate90_freight_destinations( y_size ); } // eventually correct freight destinations (and remove all stale freight) check_freight(); } /** * Return the convoi position. * @return Convoi position */ koord3d convoi_t::get_pos() const { if(vehicle_count > 0 && front()) { return state==INITIAL ? home_depot : front()->get_pos(); } else { return koord3d::invalid; } } /** * Sets the name. Creates a copy of name. */ void convoi_t::set_name(const char *name, bool with_new_id) { if( with_new_id ) { char buf[128]; name_offset = sprintf(buf,"(%i) ",self.get_id() ); tstrncpy(buf + name_offset, translator::translate(name, welt->get_settings().get_name_language_id()), lengthof(buf) - name_offset); tstrncpy(name_and_id, buf, lengthof(name_and_id)); } else { char buf[128]; // check if there is a id in the name string name_offset = sprintf(buf,"(%i) ",self.get_id() ); if( strlen(name) < name_offset || strncmp(buf,name,name_offset)!=0) { name_offset = 0; } tstrncpy(buf+name_offset, name+name_offset, sizeof(buf)-name_offset); tstrncpy(name_and_id, buf, lengthof(name_and_id)); } // now tell the windows that we were renamed convoi_detail_t *detail = dynamic_cast<convoi_detail_t*>(win_get_magic( magic_convoi_detail+self.get_id())); if (detail) { detail->update_data(); } convoi_info_t *info = dynamic_cast<convoi_info_t*>(win_get_magic( magic_convoi_info+self.get_id())); if (info) { info->update_data(); } if( in_depot() ) { const grund_t *const ground = welt->lookup( get_home_depot() ); if( ground ) { const depot_t *const depot = ground->get_depot(); if( depot ) { depot_frame_t *const frame = dynamic_cast<depot_frame_t *>( win_get_magic( (ptrdiff_t)depot ) ); if( frame ) { frame->update_data(); } } } } } // length of convoi (16 is one tile) uint32 convoi_t::get_length() const { uint32 len = 0; for( uint8 i=0; i<vehicle_count; i++ ) { len += vehicle[i]->get_desc()->get_length(); } return len; } /** * convoi add their running cost for traveling one tile */ void convoi_t::add_running_cost(sint64 cost, const weg_t *weg) { jahresgewinn += cost; if(weg && weg->get_owner() != get_owner() && weg->get_owner() != NULL && (!welt->get_settings().get_toll_free_public_roads() || (weg->get_waytype() != road_wt || weg->get_player_nr() != 1))) { // running on non-public way costs toll (since running costs are positive => invert) sint32 toll = -(cost * welt->get_settings().get_way_toll_runningcost_percentage()) / 100l; if(welt->get_settings().get_way_toll_waycost_percentage()) { if(weg->is_electrified() && needs_electrification()) { // toll for using electricity grund_t *gr = welt->lookup(weg->get_pos()); for( int i=1; i<gr->get_top(); i++ ) { obj_t *d=gr->obj_bei(i); if( wayobj_t const* const wo = obj_cast<wayobj_t>(d) ) { if( wo->get_waytype()==weg->get_waytype() ) { toll += (wo->get_desc()->get_maintenance()*welt->get_settings().get_way_toll_waycost_percentage())/100l; break; } } } } // now add normal way toll be maintenance toll += (weg->get_desc()->get_maintenance() * welt->get_settings().get_way_toll_waycost_percentage()) / 100l; } weg->get_owner()->book_toll_received( toll, get_schedule()->get_waytype() ); get_owner()->book_toll_paid( -toll, get_schedule()->get_waytype() ); book( -toll, CONVOI_WAYTOLL); book( -toll, CONVOI_PROFIT); } get_owner()->book_running_costs( cost, get_schedule()->get_waytype()); book( cost, CONVOI_OPERATIONS ); book( cost, CONVOI_PROFIT ); } void convoi_t::increment_odometer(uint32 steps) { steps_since_last_odometer_increment += steps; if (steps_since_last_odometer_increment < welt->get_settings().get_steps_per_km()) { return; } // Increment the way distance: used for apportioning revenue by owner of ways. // Use steps, as only relative distance is important here. sint8 player; waytype_t waytype = front()->get_waytype(); weg_t* way = front()->get_weg(); if(way == NULL) { player = MAX_PLAYER_COUNT + 1; } else { const player_t* owner = way->get_owner(); if(waytype == road_wt && owner && owner->is_public_service() && welt->get_settings().get_toll_free_public_roads()) { player = MAX_PLAYER_COUNT + 1; } else { player = way->get_player_nr(); } } if(player < 0) { player = MAX_PLAYER_COUNT + 1; } FOR(departure_map, &i, departures) { i.value.increment_way_distance(player, steps_since_last_odometer_increment); } const sint64 km = steps_since_last_odometer_increment / welt->get_settings().get_steps_per_km(); book( km, CONVOI_DISTANCE ); total_distance_traveled += km; steps_since_last_odometer_increment -= km * steps_since_last_odometer_increment; koord3d pos = koord3d::invalid; weg_t* weg = NULL; sint32 running_cost = 0; bool must_add = false; for(uint8 i= 0; i < vehicle_count; i++) { const vehicle_t& v = *vehicle[i]; if (v.get_pos() != pos) { if (must_add) { add_running_cost(running_cost, weg); } pos = v.get_pos(); weg = v.get_weg(); running_cost = 0; } must_add = true; running_cost -= v.get_desc()->get_running_cost(welt); } if (waytype == air_wt) { // Halve the running cost if we are circling or taxiing. air_vehicle_t* aircraft = (air_vehicle_t*)front(); if (!aircraft->is_using_full_power()) { running_cost /= 2; } } if (must_add) { add_running_cost(running_cost, weg); } } bool convoi_t::has_tall_vehicles() { bool is_tall = false; for (uint32 i = 0; i < vehicle_count; i++) { is_tall |= get_vehicle(i)->get_desc()->get_is_tall(); if (is_tall) { break; } } return is_tall; } // BG, 06.11.2011 route_t::route_result_t convoi_t::calc_route(koord3d start, koord3d ziel, sint32 max_speed) { route_infos.clear(); const grund_t* gr = welt->lookup(ziel); if(gr && front()->get_waytype() == air_wt && gr->get_halt().is_bound() && welt->lookup(ziel)->get_halt()->has_no_control_tower()) { return route_t::no_control_tower; } route_t::route_result_t success = front()->calc_route(start, ziel, max_speed, has_tall_vehicles(), &route); rail_vehicle_t* rail_vehicle = NULL; switch(front()->get_waytype()) { case track_wt: case narrowgauge_wt: case tram_wt: case monorail_wt: case maglev_wt: rail_vehicle = (rail_vehicle_t*)front(); if(rail_vehicle->get_working_method() == token_block || rail_vehicle->get_working_method() == one_train_staff) { // If we calculate a new route while in token block, we must remember this // so that, when it comes to clearing the route, a full flush can be performed // rather than simply iterating back over the route, which will not be enough // in this case. needs_full_route_flush = true; } // fallthrough default: return success; }; return success; } void convoi_t::update_route(uint32 index, const route_t &replacement) { // replace route with replacement starting at index. route_infos.clear(); route.remove_koord_from(index); route.append(&replacement); } void convoi_t::replace_route(const route_t &replacement) { route_infos.clear(); route.clear(); route.append(&replacement); } // BG, 06.11.2011 inline weg_t *get_weg_on_grund(const grund_t *grund, const waytype_t waytype) { return grund != NULL ? grund->get_weg(waytype) : NULL; } /* Calculates (and sets) new akt_speed and sp_soll * needed for driving, entering and leaving a depot) */ void convoi_t::calc_acceleration(uint32 delta_t) { // existing_convoy_t is designed to become a part of convoi_t. // There it will help to minimize updating convoy summary data. vehicle_t &front = *this->front(); const uint32 route_count = route.get_count(); // at least ziel will be there, even if calculating a route failed. const uint16 current_route_index = front.get_route_index(); // actually this is current route index + 1!!! /* * get next speed limit of my route. */ #ifndef DEBUG_PHYSICS sint32 #endif next_speed_limit = 0; // 'limit' for next stop is 0, of course. uint32 next_stop_index = get_next_stop_index(); // actually this is next stop index + 1!!! if(next_stop_index >= 65000u) // BG, 07.10.2011: currently only rail_vehicle_t sets next_stop_index. // BG, 09.08.2012: use ">= 65000u" as INVALID_INDEX (65530u) sometimes is incermented or decremented. { next_stop_index = route_count; } #ifndef DEBUG_PHYSICS sint32 steps_til_limit; sint32 steps_til_brake; #endif const sint32 brake_steps = calc_min_braking_distance(welt->get_settings(), get_weight_summary(), akt_speed); // use get_route_infos() for the first time accessing route_infos to eventually initialize them. const uint32 route_infos_count = get_route_infos().get_count(); if(route_infos_count > 0 && route_infos_count >= next_stop_index && next_stop_index > current_route_index) { sint32 i = current_route_index - 1; if(i < 0) { i = 0; } const convoi_t::route_info_t &current_info = route_infos.get_element(i); if(current_info.speed_limit != vehicle_t::speed_unlimited()) { update_max_speed(speed_to_kmh(current_info.speed_limit)); } const convoi_t::route_info_t &limit_info = route_infos.get_element(next_stop_index - 1); steps_til_limit = route_infos.calc_steps(current_info.steps_from_start, limit_info.steps_from_start); steps_til_brake = steps_til_limit - brake_steps; switch(limit_info.direction) { case ribi_t::north: case ribi_t::west: // BG, 10-11-2011: vehicle_t::hop() reduces the length of the tile, if convoy is going to stop on the tile. // Most probably for eye candy reasons vehicles do not exactly move on their tiles. // We must do the same here to avoid abrupt stopping. sint32 delta_tile_len = current_info.steps_from_start; if(i > 0) delta_tile_len -= route_infos.get_element(i - 1).steps_from_start; delta_tile_len -= (delta_tile_len/2) + 1; steps_til_limit -= delta_tile_len; steps_til_brake -= delta_tile_len; break; } #ifdef DEBUG_ACCELERATION static const char *debug_fmt1 = "at tile %u,%u; at route index: %d; next stop index: % 4u next limit of% 4d km/h, current speed% 4d km/h,% 6d steps until brake,% 6d steps until stop"; dbg->warning("convoi_t::calc_acceleration 1", debug_fmt1, get_pos().x, get_pos().y, current_route_index - 1, next_stop_index, speed_to_kmh(next_speed_limit), speed_to_kmh(akt_speed), steps_til_brake, steps_til_limit); #endif // Brake for upcoming speed limit? sint32 min_limit = akt_speed; // no need to check limits above min_limit, as it won't lead to further restrictions sint32 steps_from_start = current_info.steps_from_start; // speed has to be reduced before entering the tile. Thus distance from start has to be taken from previous tile. for(i++; i < next_stop_index; i++) { const convoi_t::route_info_t &limit_info = route_infos.get_element(i); if(limit_info.speed_limit < min_limit) { min_limit = limit_info.speed_limit; const sint32 limit_steps = brake_steps - calc_min_braking_distance(welt->get_settings(), get_weight_summary(), limit_info.speed_limit); const sint32 route_steps = route_infos.calc_steps(current_info.steps_from_start, steps_from_start); const sint32 st = route_steps - limit_steps; if(steps_til_brake > st) { next_speed_limit = limit_info.speed_limit; steps_til_limit = route_steps; steps_til_brake = st; #ifdef DEBUG_ACCELERATION dbg->warning("convoi_t::calc_acceleration 2", debug_fmt1, current_route_index - 1, i, speed_to_kmh(next_speed_limit), speed_to_kmh(akt_speed), steps_til_brake, steps_til_limit); #endif } } steps_from_start = limit_info.steps_from_start; } } else { steps_til_limit = route_infos.calc_tiles((sint32) current_route_index, (sint32) next_stop_index) * VEHICLE_STEPS_PER_TILE; steps_til_brake = steps_til_limit - brake_steps; if(adverse.max_speed == 0) { if (current_route_index >= route_infos_count) { update_max_speed(speed_to_kmh(route_infos.get_element(current_route_index - 1).speed_limit)); } else { update_max_speed(speed_to_kmh(route_infos.get_element(current_route_index).speed_limit)); } } } sint32 steps_left_on_current_tile = (sint32)front.get_steps_next() + 1 - (sint32)front.get_steps(); steps_til_brake += steps_left_on_current_tile; steps_til_limit += steps_left_on_current_tile; /* * calculate movement in the next delta_t ticks. */ akt_speed_soll = min(get_min_top_speed(), max_signal_speed); if( yielding_quit_index != -1 && akt_speed_soll>kmh_to_speed(15) ) { akt_speed_soll -= kmh_to_speed(15); } calc_move(welt->get_settings(), delta_t, akt_speed_soll, next_speed_limit, steps_til_limit, steps_til_brake, akt_speed, sp_soll, v); } void convoi_t::route_infos_t::set_holding_pattern_indexes(sint32 current_route_index, sint32 touchdown_route_index) { if (touchdown_route_index != INVALID_INDEX && current_route_index < touchdown_route_index - (HOLDING_PATTERN_LENGTH + HOLDING_PATTERN_OFFSET)) { hp_start_index = touchdown_route_index - (HOLDING_PATTERN_LENGTH + HOLDING_PATTERN_OFFSET); hp_end_index = hp_start_index + HOLDING_PATTERN_LENGTH; hp_start_step = get_element(hp_start_index - 1).steps_from_start; hp_end_step = get_element(hp_end_index - 1).steps_from_start; } else { // no holding pattern correction, if aircraft passed the start of it. hp_start_index = -1; hp_end_index = -1; hp_start_step = -1; hp_end_step = -1; } } // extracted from convoi_t::calc_acceleration() convoi_t::route_infos_t& convoi_t::get_route_infos() { if (route_infos.get_count() == 0 && route.get_count() > 0) { vehicle_t &front = *this->front(); const uint32 route_count = route.get_count(); // at least ziel will be there, even if calculating a route failed. const uint16 current_route_index = front.get_route_index(); // actually this is current route index + 1!!! fixed_list_tpl<sint16, 192> corner_data; const waytype_t waytype = front.get_waytype(); // calc route infos route_infos.set_count(route_count); // The below may be a slight optimisation, but it causes uninitialised variables in aircraft in holding patterns. //uint32 i = min(max(0, current_route_index - 2), route_count - 1); uint32 i = 0; koord3d current_tile = route.at(i); convoi_t::route_info_t &start_info = route_infos.get_element(i); start_info.direction = front.get_direction(); start_info.steps_from_start = 0; const weg_t *current_weg = get_weg_on_grund(welt->lookup(current_tile), waytype); start_info.speed_limit = front.calc_speed_limit(current_weg, NULL, &corner_data, get_tile_length(), start_info.direction, start_info.direction); sint32 takeoff_index = front.get_takeoff_route_index(); sint32 touchdown_index = front.get_touchdown_route_index(); uint32 bridge_tiles = 0; for (i++; i < route_count; i++) { convoi_t::route_info_t &current_info = route_infos.get_element(i - 1); convoi_t::route_info_t &this_info = route_infos.get_element(i); const koord3d this_tile = route.at(i); const koord3d next_tile = route.at(min(i + 1, route_count - 1)); this_info.speed_limit = welt->lookup_kartenboden(this_tile.get_2d())->is_water() ? vehicle_t::speed_unlimited() : kmh_to_speed(950); // Do not alow supersonic flight over land. this_info.steps_from_start = current_info.steps_from_start + front.get_tile_steps(current_tile.get_2d(), next_tile.get_2d(), this_info.direction); const grund_t* this_gr = welt->lookup(this_tile); const weg_t *this_weg = get_weg_on_grund(this_gr, waytype); uint32 bridge_tiles_ahead = 0; if (this_gr && this_gr->ist_bruecke()) { bridge_tiles++; for (uint32 j = i + 1; j < route_count; j++) { const koord3d tile = route.at(j); const grund_t* gr = welt->lookup(tile); if (gr && gr->ist_bruecke()) { bridge_tiles_ahead++; } else { break; } } } else { bridge_tiles = 0; } if (i >= touchdown_index || i <= takeoff_index) { // not an aircraft (i <= takeoff_index == INVALID_INDEX == 65530u) or // aircraft on ground (not between takeoff_index and touchdown_index): get speed limit current_info.speed_limit = this_weg ? front.calc_speed_limit(this_weg, current_weg, &corner_data, bridge_tiles + bridge_tiles_ahead, this_info.direction, current_info.direction) : vehicle_t::speed_unlimited(); } current_tile = this_tile; current_weg = this_weg; } route_infos.set_holding_pattern_indexes(current_route_index, touchdown_index); } return route_infos; } int convoi_t::get_vehicle_at_length(uint16 length) { int current_length = 0; for( int i=0; i<vehicle_count; i++ ) { current_length += vehicle[i]->get_desc()->get_length(); if(length<current_length) { return i; } } return vehicle_count; } // moves all vehicles of a convoi sync_result convoi_t::sync_step(uint32 delta_t) { // still have to wait before next action? wait_lock -= delta_t; if(wait_lock > 0) { return SYNC_OK; } wait_lock = 0; switch(state) { case EDIT_SCHEDULE: case ROUTING_1: case ROUTING_2: case ROUTE_JUST_FOUND: case DUMMY5: case OUT_OF_RANGE: case NO_ROUTE: case NO_ROUTE_TOO_COMPLEX: case CAN_START: case CAN_START_ONE_MONTH: case CAN_START_TWO_MONTHS: case WAITING_FOR_LOADING_THREE_MONTHS: case WAITING_FOR_LOADING_FOUR_MONTHS: case REVERSING: case ENTERING_DEPOT: case LOADING: case WAITING_FOR_CLEARANCE: case WAITING_FOR_CLEARANCE_ONE_MONTH: case WAITING_FOR_CLEARANCE_TWO_MONTHS: case SELF_DESTRUCT: case EMERGENCY_STOP: break; case INITIAL: // in depot, should not be in sync list, remove return SYNC_REMOVE; case LEAVING_DEPOT: { // ok, so we will accelerate calc_acceleration(delta_t); //moved to inside calc_acceleration(): sp_soll += (akt_speed*delta_t); // Make sure that the last_stop_pos is set here so as not // to skew average speed readings from vehicles emerging // from depots. // @author: jamespetts front()->last_stop_pos = front()->get_pos(); last_stop_id = 0; // now actually move the units while(sp_soll>>12) { // Attempt to move one step. uint32 sp_hat = front()->do_drive(1<<YARDS_PER_VEHICLE_STEP_SHIFT); if( sp_hat>0 ) { steps_driven++; } int v_nr = get_vehicle_at_length(steps_driven>>4); // stop when depot reached if (state==INITIAL) { return SYNC_REMOVE; } if (state==ROUTING_1) { break; } if( v_nr==vehicle_count ) { // all are moving steps_driven = -1; state = DRIVING; return SYNC_OK; } else if( sp_hat==0 ) { // something went wrong. wait for next sync_step() return SYNC_OK; } // now only the right numbers for(int i=1; i<=v_nr; i++) { vehicle[i]->do_drive(sp_hat); } sp_soll -= sp_hat; } // smoke for the engines next_wolke += delta_t; if(next_wolke>500) { next_wolke = 0; for(int i=0; i<vehicle_count; i++ ) { vehicle[i]->make_smoke(); vehicle[i]->last_stop_pos = vehicle[i]->get_pos(); } } } clear_departures(); break; // LEAVING_DEPOT case DRIVING: { calc_acceleration(delta_t); //akt_speed = kmh_to_speed(50); // now actually move the units //moved to inside calc_acceleration(): //sp_soll += (akt_speed*delta_t); // While sp_soll is a signed integer do_drive() accepts an unsigned integer. // Thus running backwards is impossible. Instead sp_soll < 0 is converted to very large // distances and results in "teleporting" the convoy to the end of its pre-caclulated route. uint32 sp_hat = front()->do_drive(sp_soll < 0 ? 0 : sp_soll); // stop when depot reached ... if(state==INITIAL) { return SYNC_REMOVE; } // now move the rest (so all vehikel are moving synchronously) for(unsigned i=1; i<vehicle_count; i++) { vehicle[i]->do_drive(max(1,sp_hat)); } // maybe we have been stopped be something => avoid wide jumps sp_soll = (sp_soll-sp_hat) & 0x0FFF; // smoke for the engines next_wolke += delta_t; if(next_wolke>500) { next_wolke = 0; for(int i=0; i<vehicle_count; i++ ) { vehicle[i]->make_smoke(); } } } break; // DRIVING default: dbg->fatal("convoi_t::sync_step()", "Wrong state %d!\n", state); break; } // Debug sums: // The difference of sums[1] should be divisible by the difference of sums[0] whenever a single convoi is out of sync. // They should be kept low enough to avoid excessive overflow that would make this impractical. uint32 sum = (v.get_mantissa() % 256) + 1; welt->add_to_debug_sums(0, sum); welt->add_to_debug_sums(1, sum * self.get_id()); // Sums [2] and [3] exist to give an idea of the discrepencies in speed. // They should (almost) never mismatch if [0] and [1] don't either, so there is no need to multiply/divide by ID. welt->add_to_debug_sums(2, speed_to_kmh(akt_speed)); welt->add_to_debug_sums(3, speed_to_kmh(akt_speed_soll)); return SYNC_OK; } bool convoi_t::prepare_for_routing() { if (vehicle_count > 0 && schedule) { koord3d start = front()->get_pos(); koord3d ziel = schedule->get_current_entry().pos; const uint32 distance_to_last_stop_km = ((front()->get_last_stop_pos() != koord3d::invalid && (!welt->lookup(front()->get_pos()) || !welt->lookup(front()->get_pos())->get_depot()) ? shortest_distance(front()->get_last_stop_pos().get_2d(), start.get_2d()) : 0) * welt->get_settings().get_meters_per_tile()) / 1000u; const koord3d original_ziel = ziel; // Check whether the next stop is within range. if (min_range > 0) { int count = 0; const uint8 original_index = schedule->get_current_stop(); const grund_t* gr = welt->lookup(ziel); const depot_t* depot = gr ? gr->get_depot() : NULL; while (count < schedule->get_count() && !haltestelle_t::get_halt(ziel, owner).is_bound() && !depot) { // The next stop is a waypoint - advance reverse_schedule ? schedule->advance_reverse() : schedule->advance(); ziel = schedule->get_current_entry().pos; count++; } uint16 distance; if (original_index == schedule->get_count() - 1 && schedule->is_mirrored()) { // We do not want the distance from the end to the start in this case, but the distance from // end to the immediately previous stop distance = (shortest_distance(schedule->entries[schedule->get_count() - 1].pos.get_2d(), schedule->entries[schedule->get_count() - 2].pos.get_2d()) * welt->get_settings().get_meters_per_tile()) / 1000u; } else { distance = (shortest_distance(start.get_2d(), ziel.get_2d()) * welt->get_settings().get_meters_per_tile()) / 1000u; } distance += distance_to_last_stop_km; schedule->set_current_stop(original_index); ziel = original_ziel; const bool already_out_of_range = state == OUT_OF_RANGE; if (distance > min_range) { state = OUT_OF_RANGE; if (!already_out_of_range) { get_owner()->report_vehicle_problem(self, ziel); } return false; } } halthandle_t destination_halt = haltestelle_t::get_halt(ziel, get_owner()); if (start == ziel) { // For some reason, the schedule has failed to advance. Advance it before calculating the route. reverse_schedule ? schedule->advance_reverse() : schedule->advance(); ziel = schedule->get_current_entry().pos; } // avoid stopping mid-halt // check ziel again, as it may have been advanced in the previous check if (start == ziel) { if (destination_halt.is_bound() && route.is_contained(start)) { for (uint32 i = route.index_of(start); i < route.get_count(); i++) { grund_t *gr = welt->lookup(route.at(i)); if (gr && gr->get_halt() == destination_halt) { ziel = gr->get_pos(); } else { break; } } } } /* const bool rail_type = front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt; if (rail_type) { rail_vehicle_t* rail_vehicle = (rail_vehicle_t*)front(); // If this is token block working, the route must only be unreserved if the token is released. if (rail_vehicle->get_working_method() != token_block && rail_vehicle->get_working_method() != one_train_staff) { unreserve_route(); reserve_own_tiles(); } } else if (front()->get_waytype() == air_wt) { // Sea and road waytypes do not have any sort of reserveation, and calls to unreserve_route() are expensive. unreserve_route(); }*/ } return true; } /** * Berechne route von Start- zu Zielkoordinate * "Compute route from starting to goal coordinate" (Babelfish) */ bool convoi_t::drive_to() { koord3d start = front()->get_pos(); koord3d ziel = schedule->get_current_entry().pos; const koord3d original_destination = ziel; const uint8 original_current_stop = schedule->get_current_stop(); bool schedule_advanced = false; const bool rail_type = front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt; const bool check_onwards = front()->get_waytype() == road_wt || rail_type; route_t::route_result_t success = calc_route(start, ziel, speed_to_kmh(get_min_top_speed())); grund_t* gr = welt->lookup(ziel); grund_t* gr_current = welt->lookup(start); if(check_onwards && gr && !gr->get_depot()) { // Set reversing statuses uint32 counter = schedule->get_count(); const uint32 count = counter; schedule_entry_t* schedule_entry = &schedule->entries[schedule->get_current_stop()]; bool update_line = false; while(success == route_t::valid_route && counter--) { allow_clear_reservation = counter == count; if(schedule_entry->reverse == -1 && (!gr_current || !gr_current->get_depot()) && !last_stop_was_depot) { schedule_entry->reverse = check_destination_reverse() ? 1 : 0; schedule->set_reverse(schedule_entry->reverse, schedule->get_current_stop()); if(line.is_bound()) { schedule_t* line_schedule = line->get_schedule(); schedule_entry_t &line_entry = line_schedule->entries[schedule->get_current_stop()]; line_entry.reverse = schedule_entry->reverse; update_line = true; } } last_stop_was_depot = false; if(schedule_entry->reverse == 1 || haltestelle_t::get_halt(schedule_entry->pos, get_owner()).is_bound()) { // The convoy must stop at the current route's end. break; } advance_schedule(); schedule_advanced = true; schedule_entry = &schedule->entries[schedule->get_current_stop()]; // The below does not actually change the stored route: it only checks that the route is valid. success = front()->reroute(route.get_count() - 1, schedule_entry->pos); } if (schedule_advanced) { // Reset these for now to allow waypoint check below to work. ziel = original_destination; schedule->set_current_stop(original_current_stop); } if (update_line) { #ifdef MULTI_THREAD pthread_mutex_lock(&step_convois_mutex); world()->await_path_explorer(); #endif // There is no need to renew stops here, as this update can only ever come // from a change in reversing status, which does not require renewing stops. simlinemgmt_t::update_line(line, true); #ifdef MULTI_THREAD int error = pthread_mutex_unlock(&step_convois_mutex); assert(error == 0); (void)error; #endif } } allow_clear_reservation = true; if(success != route_t::valid_route && success != route_t::valid_route_halt_too_short) { if(state != NO_ROUTE && state != NO_ROUTE_TOO_COMPLEX) { success == route_t::route_too_complex ? state = NO_ROUTE_TOO_COMPLEX : state = NO_ROUTE; no_route_retry_count = 0; #ifdef MULTI_THREAD pthread_mutex_lock(&step_convois_mutex); #endif get_owner()->report_vehicle_problem(self, ziel); #ifdef MULTI_THREAD int error = pthread_mutex_unlock(&step_convois_mutex); assert(error == 0); (void)error; #endif } // wait before next attempt for a normal no route. // For a "too complex" no route, wait much, much longer, as this can cause serious lag // when repeated many times. The expectation is that the player will manually find // another route in this state. if (success == route_t::route_too_complex) { // 2 minutes wait_lock_next_step = 7200000; } else { // 25 seconds wait_lock_next_step = 25000; } } else { bool route_ok = true; const uint8 current_stop = schedule->get_current_stop(); if(front()->get_waytype() != water_wt) { air_vehicle_t *const plane = dynamic_cast<air_vehicle_t *>(front()); uint32 takeoff = 0, search = 0, landing = 0; air_vehicle_t::flight_state plane_state = air_vehicle_t::taxiing; if(plane) { // due to the complex state system of aircraft, we have to save index and state plane->get_event_index(plane_state, takeoff, search, landing); } ziel = schedule->get_current_entry().pos; // set next schedule target position if next is a waypoint if(is_waypoint(ziel)) { schedule_target = ziel; } // continue route search until the destination is a station/stop or a reversing waypoint while(is_waypoint(ziel) && schedule->get_current_entry().reverse < 1) { allow_clear_reservation = false; start = ziel; advance_schedule(); ziel = schedule->get_current_entry().pos; if(schedule->get_current_stop() == current_stop) { // looped around without finding a halt => entire schedule is waypoints. break; } route_t next_segment; const route_t::route_result_t result = front()->calc_route(start, ziel, speed_to_kmh(get_min_top_speed()), has_tall_vehicles(), &next_segment); if (result != route_t::valid_route) { // do we still have a valid route to proceed => then go until there if(route.get_count() > 1) { break; } // we are stuck on our first routing attempt => give up if(state != NO_ROUTE && state != NO_ROUTE_TOO_COMPLEX) { state = result == route_t::route_too_complex ? NO_ROUTE_TOO_COMPLEX : NO_ROUTE; #ifdef MULTI_THREAD pthread_mutex_lock(&step_convois_mutex); #endif get_owner()->report_vehicle_problem( self, ziel ); #ifdef MULTI_THREAD int error = pthread_mutex_unlock(&step_convois_mutex); assert(error == 0); (void)error; #endif } // wait 25s before next attempt wait_lock_next_step = 25000; route_ok = false; break; } else { bool looped = false; if( front()->get_waytype() != air_wt ) { // check if the route circles back on itself (only check the first tile, should be enough) looped = route.is_contained(next_segment.at(1)); #if 0 // this will forbid an eight figure, which might be clever to avoid a problem of reserving one's own track for(unsigned i = 1; i < next_segment.get_count(); i++) { if(route.is_contained(next_segment.at(i))) { looped = true; break; } } #endif } if(looped) { // proceed up to the waypoint before the loop. Will pause there for a new route search. break; } else { uint32 count_offset = route.get_count()-1; route.append(&next_segment); if(plane) { // maybe we need to restore index air_vehicle_t::flight_state dummy1; uint32 new_takeoff, new_search, new_landing; plane->get_event_index( dummy1, new_takeoff, new_search, new_landing ); if(takeoff == 0x7FFFFFFF && new_takeoff != 0x7FFFFFFF) { takeoff = new_takeoff + count_offset; } if(landing == 0x7FFFFFFF && new_landing != 0x7FFFFFFF) { landing = new_landing + count_offset; } if(search == 0x7FFFFFFF && new_search != 0x7FFFFFF) { search = new_search + count_offset; } } } } allow_clear_reservation = true; } if(plane) { // due to the complex state system of aircrafts, we have to restore index and state plane->set_event_index(plane_state, takeoff, search, landing); } } schedule_target = ziel; if(route_ok) { // When this was single threaded, this was an immediate call to vorfahren(), but this cannot be called when multi-threaded. state = ROUTE_JUST_FOUND; return true; } } return false; } /** * Ein Fahrzeug hat ein Problem erkannt und erzwingt die * Berechnung einer neuen Route */ void convoi_t::suche_neue_route() { state = ROUTING_1; wait_lock = 0; } /** * Things that call a convoy's route finding * but not block reserving */ void convoi_t::threaded_step() { if (state == ROUTING_2) { // Only perform route finding in the threaded step // because we need to be able to run this at the same // time as player interaction in network mode. // ROUTING_2 can only be set in step(), so this is // deterministic. drive_to(); } } /** * Asynchroneous single-threaded stepping of convoys */ void convoi_t::step() { if(wait_lock !=0) { return; } if (wait_lock_next_step != 0) { // threaded_step cannot update wait_lock directly wait_lock = wait_lock_next_step; wait_lock_next_step = 0; return; } checked_tile_this_step = koord3d::invalid; // moved check to here, as this will apply the same update // logic/constraints convois have for manual schedule manipulation if (line_update_pending.is_bound()) { check_pending_updates(); } bool autostart = false; uint8 position; bool rev; grund_t* gr; strasse_t* str; switch(state) { case INITIAL: // If there is a pending replacement, just do it if (replace && replace->get_replacing_vehicles()->get_count()>0) { autostart = replace->get_autostart(); // Knightly : before replacing, copy the existing set of goods category indices minivec_tpl<uint8> old_goods_catg_index(goods_catg_index.get_count()); vector_tpl<uint8> old_passenger_classes_carried; vector_tpl<uint8> old_mail_classes_carried; for( uint8 i = 0; i < goods_catg_index.get_count(); ++i ) { if (i == goods_manager_t::INDEX_PAS) { for (uint32 j = 0; j < passenger_classes_carried.get_count(); ++j) { old_passenger_classes_carried.append(passenger_classes_carried[j]); } } else if (i == goods_manager_t::INDEX_MAIL) { for (uint32 j = 0; j < mail_classes_carried.get_count(); ++j) { old_mail_classes_carried.append(mail_classes_carried[j]); } } old_goods_catg_index.append( goods_catg_index[i] ); } const grund_t *gr = welt->lookup(home_depot); depot_t *dep; if ( gr && (dep = gr->get_depot()) ) { char buf[256]; name_offset = sprintf(buf,"(%i) ",self.get_id() ); tstrncpy(buf + name_offset, translator::translate(front()->get_desc()->get_name()), 116); const bool keep_name = strcmp(get_name(), buf); vector_tpl<vehicle_t*> new_vehicles; vehicle_t* veh = NULL; // Acquire the new one ITERATE_PTR(replace->get_replacing_vehicles(),i) { veh = NULL; // First - check whether there are any of the required vehicles already // in the convoy (free) for(uint8 k = 0; k < vehicle_count; k++) { if(vehicle[k]->get_desc() == replace->get_replacing_vehicle(i)) { veh = remove_vehicle_bei(k); break; } } if(veh == NULL && replace->get_allow_using_existing_vehicles()) { // Second - check whether there are any of the required vehicles already // in the depot (more or less free). veh = dep->find_oldest_newest(replace->get_replacing_vehicle(i), true, &new_vehicles); } if (veh == NULL && !replace->get_retain_in_depot()) { // Third - check whether the vehicle can be upgraded (cheap) // Note: if "retain in depot" is selected, do not upgrade, as // the old vehicles will be needed (e.g., for a cascade). for(uint16 j = 0; j < vehicle_count; j ++) { for(uint8 c = 0; c < vehicle[j]->get_desc()->get_upgrades_count(); c ++) { if(replace->get_replacing_vehicle(i) == vehicle[j]->get_desc()->get_upgrades(c)) { veh = vehicle_builder_t::build(get_pos(), get_owner(), NULL, replace->get_replacing_vehicle(i), true); upgrade_vehicle(j, veh); remove_vehicle_bei(j); goto end_loop; } } } } end_loop: if(veh == NULL) { // Fourth - if all else fails, buy from new (expensive). veh = dep->buy_vehicle(replace->get_replacing_vehicle(i), livery_scheme_index); } // This new method is needed to enable this method to iterate over // the existing vehicles in the convoy while it is adding new vehicles. // They must be added to temporary storage, and appended to the existing // convoy at the end, after the existing convoy has been deleted. assert(veh); if(veh) { new_vehicles.append(veh); } } //First, delete the existing convoy for(sint8 a = vehicle_count-1; a >= 0; a--) { if(!replace->get_retain_in_depot()) { //Sell any vehicles not upgraded or kept. sint64 value = vehicle[a]->calc_sale_value(); waytype_t wt = vehicle[a]->get_desc()->get_waytype(); owner->book_new_vehicle( value, dep->get_pos().get_2d(),wt ); delete vehicle[a]; vehicle_count--; } else { vehicle_t* old_veh = remove_vehicle_bei(a); old_veh->discard_cargo(); old_veh->set_leading(false); old_veh->set_last(false); dep->get_vehicle_list().append(old_veh); } } vehicle_count = 0; reset(); //Next, add all the new vehicles to the convoy in order. ITERATE(new_vehicles,b) { dep->append_vehicle(self, new_vehicles[b], false, false); } if (!keep_name) { set_name(front()->get_desc()->get_name()); } clear_replace(); if (line.is_bound()) { line->recalc_status(); if (line->get_replacing_convoys_count()==0) { char buf[256]; sprintf(buf, translator::translate("Replacing\nvehicles of\n%-20s\ncompleted"), line->get_name()); welt->get_message()->add_message(buf, home_depot.get_2d(),message_t::general, PLAYER_FLAG|get_owner()->get_player_nr(), IMG_EMPTY); } } // Knightly : recalculate goods category index and determine if refresh is needed recalc_catg_index(); // Also recalculate classes carried calc_classes_carried(); minivec_tpl<uint8> catg_differences(goods_catg_index.get_count() + old_goods_catg_index.get_count()); minivec_tpl<uint8> passenger_class_differences; minivec_tpl<uint8> mail_class_differences; // removed categories and classes: present in old category list but not in new category list for ( uint8 i = 0; i < old_goods_catg_index.get_count(); ++i ) { if ( ! goods_catg_index.is_contained( old_goods_catg_index[i] ) ) { catg_differences.append( old_goods_catg_index[i] ); } else { // The categories are the same in both: but what about the classes? // Only relevant for passengers and mail. if (i == goods_manager_t::INDEX_PAS) { for (uint32 j = 0; j < passenger_classes_carried.get_count(); j++) { if (old_passenger_classes_carried.get_count() <= j || !passenger_classes_carried.is_contained(old_passenger_classes_carried.get_element(j))) { passenger_class_differences.append(j); } } for (uint32 j = 0; j < old_passenger_classes_carried.get_count(); j++) { if(passenger_classes_carried.get_count() <= j || !old_passenger_classes_carried.is_contained(passenger_classes_carried.get_element(j))) { passenger_class_differences.append(j); } } } if (i == goods_manager_t::INDEX_MAIL) { for (uint8 j = 0; j < mail_classes_carried.get_count(); j++) { if (old_mail_classes_carried.get_count() <= j || !mail_classes_carried.is_contained(old_mail_classes_carried.get_element(j))) { mail_class_differences.append(j); } } for (uint8 j = 0; j < old_mail_classes_carried.get_count(); j++) { if (mail_classes_carried.get_count() <= j || !old_mail_classes_carried.is_contained(mail_classes_carried.get_element(j))) { mail_class_differences.append(j); } } } } } // added categories : present in new category list but not in old category list for ( uint8 i = 0; i < goods_catg_index.get_count(); ++i ) { if ( ! old_goods_catg_index.is_contained( goods_catg_index[i] ) ) { catg_differences.append( goods_catg_index[i] ); } } if (catg_differences.get_count() > 0 ) { if ( line.is_bound() ) { // let the line decide if refresh is needed line->recalc_catg_index(); } else { // refresh only those categories which are either removed or added to the category list haltestelle_t::refresh_routing(schedule, catg_differences, &passenger_class_differences, &mail_class_differences, owner); } } if (autostart) { dep->start_convoi(self, false); } } } break; case ROUTING_2: case DUMMY5: break; case REVERSING: if(wait_lock == 0) { position = schedule ? schedule->get_current_stop() : 0; rev = !reverse_schedule; schedule->increment_index(&position, &rev); halthandle_t this_halt = haltestelle_t::get_halt(front()->get_pos(), owner); if(this_halt == haltestelle_t::get_halt(schedule->entries[position].pos, owner)) { // Load any newly arrived passengers/mail bundles/goods before setting off. laden(); } // A convoy starts after reversing state = CAN_START; if(front()->last_stop_pos == front()->get_pos()) { book_waiting_times(); } } break; case EDIT_SCHEDULE: // schedule window closed? if (schedule != NULL && schedule->is_editing_finished()) { set_schedule(schedule); schedule_target = koord3d::invalid; if (schedule->empty()) { // no entry => no route ... state = NO_ROUTE; // A convoy without a schedule should not be left lingering on the map. emergency_go_to_depot(); // Get out of this routine; object might be destroyed. return; } else { // The schedule window might be closed whilst this vehicle is still loading. // Do not allow the player to cheat by sending the vehicle on its way before it has finished. const sint64 time = arrival_time < WAIT_INFINITE ? arrival_time : welt->get_ticks(); bool can_go = true; const uint32 reversing_time = schedule->get_current_entry().reverse == 1 ? calc_reverse_delay() : 0; can_go = can_go || welt->get_ticks() > go_on_ticks; can_go = can_go && welt->get_ticks() > time + ((sint64)current_loading_time - (sint64)reversing_time); can_go = can_go || no_load; grund_t *gr = welt->lookup(schedule->get_current_entry().pos); depot_t * this_depot = NULL; bool go_to_depot = false; if (gr) { this_depot = gr->get_depot(); if (this_depot && this_depot->is_suitable_for(front())) { if (schedule->get_current_entry().pos == get_pos()) { // If it's a suitable depot, move into the depot // This check must come before the station check, because for // ships we may be in a depot and at a sea stop! enter_depot(gr->get_depot()); break; } else { // The go to depot command has been set previously and has not been unset. can_go = true; wait_lock = (sint32)((time + ((sint64)current_loading_time - (sint64)reversing_time)) - welt->get_ticks()); go_to_depot = true; } } } halthandle_t h = haltestelle_t::get_halt(get_pos(), get_owner()); if (!go_to_depot && h.is_bound() && h == haltestelle_t::get_halt(schedule->get_current_entry().pos, get_owner())) { // We are at the station we are scheduled to be at // (possibly a different platform) if (route.get_count() > 0) { koord3d const& pos = route.back(); if (h == haltestelle_t::get_halt(pos, get_owner())) { // If this is also the station at the end of the current route // (the correct platform) if (get_pos() == pos) { // And this is also the correct platform... then load. state = LOADING; break; } else { // Right station, wrong platform can_go ? state = DRIVING : state = LOADING; break; } } } else { // We're at the scheduled station, // but there is no programmed route. if (can_go) { // Checking for a route is now multi-threaded // Calculate a route in the next threaded step. if (prepare_for_routing()) { state = ROUTING_2; } break; } else { state = LOADING; } } } // We aren't at our destination; start routing. can_go ? state = ROUTING_1 : state = LOADING; } } else { break; } case ROUTING_1: { vehicle_t* v = front(); if (schedule->empty()) { state = NO_ROUTE; owner->report_vehicle_problem(self, koord3d::invalid); } else { // check first, if we are already there: assert(schedule->get_current_stop()<schedule->get_count()); if (v->get_pos() == schedule->get_current_entry().pos) { advance_schedule(); } // Calculate a route in the next threaded step. if (prepare_for_routing()) { state = ROUTING_2; } } } break; case OUT_OF_RANGE: case NO_ROUTE: case NO_ROUTE_TOO_COMPLEX: { reserve_own_tiles(); // stuck vehicles if (no_route_retry_count < 7) { no_route_retry_count++; } if (no_route_retry_count >= 3 && front()->get_waytype() != water_wt && (!welt->lookup(get_pos())->is_water())) { // If the convoy is stuck for too long, send it to a depot. emergency_go_to_depot(); // get out of this routine; vehicle might be destroyed return; } else if (schedule->empty()) { // no entries => no route ... } else { // Calculate a route in the next threaded step. if (prepare_for_routing()) { state = ROUTING_2; } } break; } case ROUTE_JUST_FOUND: gr = welt->lookup(get_route()->back()); if (front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || (front()->get_waytype() == monorail_wt && gr && !gr->get_depot())) { rail_vehicle_t* rv = (rail_vehicle_t*)back(); rail_vehicle_t* rv_front = (rail_vehicle_t*)front(); if (rv_front->get_working_method() != one_train_staff && rv_front->get_working_method() != token_block) { rv->unreserve_station(); } } vorfahren(); break; // This used to be part of drive_to(), but this was not suitable for use in a multi-threaded state. case CAN_START: case CAN_START_ONE_MONTH: case CAN_START_TWO_MONTHS: { vehicle_t* v = front(); sint32 restart_speed = -1; if( v->can_enter_tile( restart_speed, 0 ) ) { // can reserve new block => drive on state = (steps_driven>=0) ? LEAVING_DEPOT : DRIVING; if(haltestelle_t::get_halt(v->get_pos(),owner).is_bound()) { v->play_sound(); } } else if( steps_driven==0 ) { // on rail depot tile, do not reserve this if( grund_t *gr = welt->lookup(front()->get_pos()) ) { if (schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(front()->get_waytype()))) { sch0->unreserve(front()); } } } if(restart_speed>=0) { set_akt_speed(restart_speed); } if( front()->get_waytype()==road_wt ) { overtaking_mode_t overtaking_mode = static_cast<strasse_t*>(welt->lookup(get_pos())->get_weg(road_wt))->get_overtaking_mode(); if( (state==CAN_START || state==CAN_START_ONE_MONTH) && overtaking_mode>oneway_mode ) { set_tiles_overtaking( 0 ); } } } break; case WAITING_FOR_CLEARANCE_ONE_MONTH: case WAITING_FOR_CLEARANCE_TWO_MONTHS: case WAITING_FOR_CLEARANCE: { sint32 restart_speed = -1; if (front()->get_convoi() != this) { front()->set_convoi(this); } if (front()->can_enter_tile(restart_speed,0)) { state = (steps_driven>=0) ? LEAVING_DEPOT : DRIVING; } if(restart_speed>=0) { set_akt_speed(restart_speed); } if( front()->get_waytype()==road_wt ) { overtaking_mode_t overtaking_mode = static_cast<strasse_t*>(welt->lookup(get_pos())->get_weg(road_wt))->get_overtaking_mode(); if( state!=DRIVING && overtaking_mode>oneway_mode ) { set_tiles_overtaking( 0 ); } } } if (wait_lock < 1) { position = schedule ? schedule->get_current_stop() : 0; rev = !reverse_schedule; schedule->increment_index(&position, &rev); halthandle_t this_halt = haltestelle_t::get_halt(front()->get_pos(), owner); if (this_halt.is_bound() && this_halt == haltestelle_t::get_halt(schedule->entries[position].pos, owner)) { // Load any newly arrived passengers/mail bundles/goods while waiting for a signal to clear. laden(); } } break; case LOADING: case WAITING_FOR_LOADING_THREE_MONTHS: case WAITING_FOR_LOADING_FOUR_MONTHS: laden(); if (state != SELF_DESTRUCT) { //When loading, vehicle should not be on passing lane. str = (strasse_t*)welt->lookup(get_pos())->get_weg(road_wt); if( str && str->get_overtaking_mode()!=halt_mode ) set_tiles_overtaking(0); if(get_depot_when_empty() && has_no_cargo()) { go_to_depot(!replace, (replace && replace->get_use_home_depot())); } break; } // fallthrough // must be here; may otherwise confuse window management case SELF_DESTRUCT: welt->set_dirty(); destroy(); return; // must not continue method after deleting this object default: /* keeps compiler silent*/ break; } // calculate new waiting time vector_tpl<linehandle_t> lines; switch( state ) { // handled by routine case WAITING_FOR_LOADING_THREE_MONTHS: case WAITING_FOR_LOADING_FOUR_MONTHS: case LOADING: break; // immediate action needed case LEAVING_DEPOT: last_stop_was_depot = true; get_owner()->simlinemgmt.get_lines(schedule->get_type(), &lines); FOR(vector_tpl<linehandle_t>, const l, lines) { if(schedule->matches(welt, l->get_schedule())) { // if a line is assigned, set line! set_line(l); line->renew_stops(); break; } } if(!line.is_bound()) { register_stops(); } if (front()->get_waytype() != air_wt) { front()->play_sound(); } // fallthrough case SELF_DESTRUCT: case ENTERING_DEPOT: case DRIVING: case ROUTING_2: case DUMMY5: wait_lock = 0; break; // just waiting for action here case INITIAL: case EDIT_SCHEDULE: wait_lock = max( wait_lock, 25000 ); break; case EMERGENCY_STOP: if(wait_lock < 1) { state = WAITING_FOR_CLEARANCE; } // fallthrough case ROUTING_1: case CAN_START: case WAITING_FOR_CLEARANCE: // action soon needed // Bernd Gabriel: simutrans extended may have presets the wait_lock before. Don't overwrite it here, if it ought to wait longer. wait_lock = max(wait_lock, 250); break; // waiting for free way, not too heavy, not to slow case CAN_START_ONE_MONTH: case WAITING_FOR_CLEARANCE_ONE_MONTH: case CAN_START_TWO_MONTHS: case WAITING_FOR_CLEARANCE_TWO_MONTHS: wait_lock = 2500; break; default: ; } } void convoi_t::advance_schedule() { if(schedule->get_current_stop() == 0) { arrival_to_first_stop.add_to_tail(welt->get_ticks()); } // check if the convoi should switch direction if( schedule->is_mirrored() && schedule->get_current_stop()==schedule->get_count()-1 ) { reverse_schedule = true; } else if( schedule->is_mirrored() && schedule->get_current_stop()==0 ) { reverse_schedule = false; } // advance the schedule cursor if (reverse_schedule) { schedule->advance_reverse(); } else { schedule->advance(); } } void convoi_t::new_year() { jahresgewinn = 0; } uint16 convoi_t::get_overcrowded() const { uint16 overcrowded = 0; for(uint8 i = 0; i < vehicle_count; i ++) { for (uint8 j = 0; j < vehicle[i]->get_desc()->get_number_of_classes(); j++) { overcrowded += vehicle[i]->get_overcrowding(j); } } return overcrowded; } uint16 convoi_t::get_overcrowded_capacity() const { uint16 standing_capacity = 0; for (uint8 i = 0; i < vehicle_count; i++) { for (uint8 j = 0; j < vehicle[i]->get_desc()->get_number_of_classes(); j++) { standing_capacity += vehicle[i]->get_overcrowded_capacity(j); } } return standing_capacity; } uint8 convoi_t::get_comfort(uint8 g_class, bool check_reassigned) const { uint32 comfort = 0; uint8 passenger_vehicles = 0; uint16 passenger_seating = 0; uint16 capacity; const uint8 catering_level = get_catering_level(goods_manager_t::INDEX_PAS); for(uint8 i = 0; i < vehicle_count; i ++) { if (vehicle[i]->get_cargo_type()->get_catg_index() == 0) { passenger_vehicles++; capacity = vehicle[i]->get_accommodation_capacity(g_class); if (check_reassigned) { comfort += vehicle[i]->get_comfort(catering_level, vehicle[i]->get_reassigned_class(g_class)) * capacity; } else { comfort += vehicle[i]->get_comfort(catering_level, g_class) * capacity; } passenger_seating += capacity; } } if(passenger_vehicles < 1 || passenger_seating < 1) { // Avoid division if possible return 0; } // There must be some passenger vehicles if we are here. comfort /= passenger_seating; return comfort; } void convoi_t::new_month() { // should not happen: leftover convoi without vehicles ... if(vehicle_count==0) { DBG_DEBUG("convoi_t::new_month()","no vehicles => self destruct!"); self_destruct(); return; } // everything normal: update history for (int j = 0; j<MAX_CONVOI_COST; j++) { for (int k = MAX_MONTHS-1; k>0; k--) { financial_history[k][j] = financial_history[k-1][j]; } financial_history[0][j] = 0; } // Deduct monthly fixed maintenance costs. // @author: jamespetts sint64 monthly_cost = 0; for(unsigned j=0; j<get_vehicle_count(); j++ ) { // Monthly cost is positive, but add it up to a negative number for booking. monthly_cost -= get_vehicle(j)->get_desc()->get_fixed_cost(welt); } jahresgewinn += monthly_cost; // This is way too tedious a way to get my waytype... waytype_t my_waytype; if (get_schedule()) { my_waytype = get_schedule()->get_waytype(); } else if (get_vehicle_count()) { my_waytype = get_vehicle(0)->get_desc()->get_waytype(); } else { my_waytype = ignore_wt; } get_owner()->book_vehicle_maintenance(monthly_cost, my_waytype); monthly_cost = welt->calc_adjusted_monthly_figure(monthly_cost); book(monthly_cost, CONVOI_OPERATIONS); book(monthly_cost, CONVOI_PROFIT); if(financial_history[1][CONVOI_AVERAGE_SPEED] == 0) { // Last month's average speed is recorded as zero. This means that no // average speed data have been recorded in the last month, making // revenue calculations inaccurate. Use the second previous month's average speed // for the previous month's average speed. financial_history[1][CONVOI_AVERAGE_SPEED] = financial_history[2][CONVOI_AVERAGE_SPEED]; } for(uint8 i = 0; i < MAX_CONVOI_COST; i ++) { rolling_average[i] = 0; rolling_average_count[i] = 0; } // remind every new month again if(state == NO_ROUTE || state == NO_ROUTE_TOO_COMPLEX) { get_owner()->report_vehicle_problem(self, get_pos()); } else if(state == OUT_OF_RANGE) { get_owner()->report_vehicle_problem(self, schedule->get_current_entry().pos); } // check for traffic jam if(state==WAITING_FOR_CLEARANCE) { state = WAITING_FOR_CLEARANCE_ONE_MONTH; // check, if now free ... // might also reset the state! sint32 restart_speed = -1; if (front()->can_enter_tile(restart_speed, 0)) { state = DRIVING; } if(restart_speed>=0) { set_akt_speed(restart_speed); } } else if(state==WAITING_FOR_CLEARANCE_ONE_MONTH) { // make sure, not another vehicle with same line is loading in front bool notify = true; // check, if we are not waiting for load if( line.is_bound() && loading_level==0 ) { for( uint i=0; i < line->count_convoys(); i++ ) { convoihandle_t cnv = line->get_convoy(i); if( cnv.is_bound() && cnv->get_state()==LOADING && cnv->get_loading_level() < cnv->get_loading_limit() ) { // convoi on this line is waiting for load => assume we are waiting behind notify = false; break; } } } if( notify ) { get_owner()->report_vehicle_problem( self, koord3d::invalid ); } state = WAITING_FOR_CLEARANCE_TWO_MONTHS; } // check for traffic jam if(state==CAN_START) { state = CAN_START_ONE_MONTH; } else if(state==CAN_START_ONE_MONTH || state==CAN_START_TWO_MONTHS ) { get_owner()->report_vehicle_problem( self, koord3d::invalid ); state = CAN_START_TWO_MONTHS; } // check for endless loading if (state == LOADING && get_loading_limit() && financial_history[1][CONVOI_DISTANCE] == 0 && financial_history[2][CONVOI_DISTANCE] == 0 && financial_history[2][CONVOI_AVERAGE_SPEED] != 0) { if (financial_history[3][CONVOI_DISTANCE] == 0 && financial_history[3][CONVOI_AVERAGE_SPEED] != 0) { state = WAITING_FOR_LOADING_FOUR_MONTHS; get_owner()->report_vehicle_problem(self, koord3d::invalid); } else { state = WAITING_FOR_LOADING_THREE_MONTHS; } } // check for obsolete vehicles in the convoi if(!has_obsolete && welt->use_timeline()) { has_obsolete = calc_obsolescence(welt->get_timeline_year_month()); } } /** * Make a convoi enter a depot. */ void convoi_t::enter_depot(depot_t *dep) { // first remove reservation, if train is still on track unreserve_route(); if(front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { rail_vehicle_t* w = (rail_vehicle_t*)front(); w->set_working_method(drive_by_sight); } if(reversed) { // Put the convoy back into "forward" position reversable = get_terminal_shunt_mode() == change_direction ? true : false; reverse_order(reversable); } // Clear the departure table... clear_departures(); // Set the speed to zero... set_akt_speed(0); // Make this the new home depot... // (Will be done again in convoi_arrived, but make sure to do it early in case of crashes) home_depot=dep->get_pos(); // remove vehicles from world data structure for(unsigned i=0; i<vehicle_count; i++) { vehicle_t* v = vehicle[i]; // remove from old position grund_t* gr = welt->lookup(v->get_pos()); if(gr) { // remove from blockstrecke v->set_last(true); v->leave_tile(); v->set_flag( obj_t::not_on_map ); } } last_signal_pos = koord3d::invalid; dep->convoi_arrived(self, get_schedule()); close_windows(); state = INITIAL; wait_lock = 0; } void convoi_t::start() { if(state == INITIAL || state == ROUTING_1) { // set home depot to location of depot convoi is leaving if(route.empty()) { home_depot = front()->get_pos(); } else { home_depot = route.front(); front()->set_pos( home_depot ); } // put the convoi on the depot ground, to get automatic rotation // (vorfahren() will remove it anyway again.) grund_t *gr = welt->lookup( home_depot ); assert(gr); gr->obj_add( front() ); // put into sync list welt->sync.add(this); alte_direction = ribi_t::none; no_load = false; depot_when_empty = false; state = ROUTING_1; // recalc weight and image // also for any vehicle entered a depot, set_last is true! => reset it correctly sint64 restwert_delta = 0; for(unsigned i=0; i<vehicle_count; i++) { vehicle[i]->set_leading( false ); vehicle[i]->set_last( false ); restwert_delta -= vehicle[i]->calc_sale_value(); vehicle[i]->set_driven(); restwert_delta += vehicle[i]->calc_sale_value(); vehicle[i]->clear_flag( obj_t::not_on_map ); vehicle[i]->load_cargo( halthandle_t() ); } front()->set_leading( true ); vehicle[vehicle_count-1]->set_last( true ); // do not show the vehicle - it will be wrong positioned -vorfahren() will correct this front()->set_image(IMG_EMPTY); // update finances for used vehicle reduction when first driven owner->update_assets( restwert_delta, get_schedule()->get_waytype()); // calc state for convoi calc_loading(); if(line.is_bound()) { // might have changed the vehicles in this car ... line->recalc_catg_index(); } else { // New method - recalculate as necessary // Added by : Knightly haltestelle_t::refresh_routing(schedule, goods_catg_index, NULL, NULL, owner); } wait_lock = 0; DBG_MESSAGE("convoi_t::start()","Convoi %s wechselt von INITIAL nach ROUTING_1", name_and_id); } else { dbg->warning("convoi_t::start()","called with state=%s\n",state_names[state]); } } /* called, when at a destination * can be waypoint, depot or a stop * called from the first vehicle_t of a convoi */ void convoi_t::ziel_erreicht() { const vehicle_t* v = front(); alte_direction = v->get_direction(); // check, what is at destination! const grund_t *gr = welt->lookup(v->get_pos()); depot_t *dp = gr->get_depot(); // double-check for right depot type based on first vehicle if(dp && dp->is_suitable_for(v) ) { // ok, we are entering a depot // Provide the message since we got here "on schedule". cbuffer_t buf; if ((!replace || !replace->get_autostart()) && owner->check_solvency() != player_t::in_liquidation) { buf.printf( translator::translate("!1_DEPOT_REACHED"), get_name() ); welt->get_message()->add_message(buf, v->get_pos().get_2d(),message_t::warnings, PLAYER_FLAG|get_owner()->get_player_nr(), IMG_EMPTY); } enter_depot(dp); } else { // no suitable depot reached, check for stop! halthandle_t halt = haltestelle_t::get_halt(schedule->get_current_entry().pos,owner); if( halt.is_bound() && gr->get_weg_ribi(v->get_waytype())!=0 ) { // seems to be a stop, so book the money for the trip set_akt_speed(0); halt->book(1, HALT_CONVOIS_ARRIVED); state = LOADING; go_on_ticks = WAIT_INFINITE; // we will eventually wait from now on if(front()->get_waytype() == air_wt) { air_vehicle_t* aircraft = (air_vehicle_t*)front(); if(aircraft->get_flyingheight() > 0) { // VTOL aircraft landing - set to landed state. aircraft->force_land(); } } } else if(schedule->get_current_entry().pos == get_pos()) { // Neither depot nor station: waypoint advance_schedule(); state = ROUTING_1; if(replace && depot_when_empty && has_no_cargo()) { depot_when_empty=false; no_load=false; go_to_depot(false); } } else { state = ROUTING_1; } } wait_lock = 0; } /** * Wait until vehicle 0 returns go-ahead */ void convoi_t::warten_bis_weg_frei(sint32 restart_speed) { if(!is_waiting()) { if(state != EMERGENCY_STOP || wait_lock == 0) { if(state != ROUTING_1) { state = WAITING_FOR_CLEARANCE; } wait_lock = 0; } } if(restart_speed>=0) { // langsam anfahren // "slow start" (Google) set_akt_speed(restart_speed); } } bool convoi_t::add_vehicle(vehicle_t *v, bool infront) { DBG_MESSAGE("convoi_t::add_vehicle()","at pos %i of %i totals.",vehicle_count,max_vehicle); // extend array if requested (only needed for trains) if(vehicle_count == max_vehicle) { DBG_MESSAGE("convoi_t::add_vehicle()","extend array_tpl to %i totals.",max_rail_vehicle); //vehicle.resize(max_rail_vehicle, NULL); vehicle.resize(max_rail_vehicle); } // now append if (vehicle_count < vehicle.get_count()) { v->set_convoi(this); if(infront) { for(unsigned i = vehicle_count; i > 0; i--) { vehicle[i] = vehicle[i - 1]; } vehicle[0] = v; } else { vehicle[vehicle_count] = v; } vehicle_count ++; const vehicle_desc_t *info = v->get_desc(); if(info->get_power()) { is_electric |= info->get_engine_type()==vehicle_desc_t::electric; } //sum_power += info->get_power(); //if(info->get_engine_type() == vehicle_desc_t::steam) //{ // power_from_steam += info->get_power(); // power_from_steam_with_gear += info->get_power() * info->get_gear() *welt->get_settings().get_global_power_factor(); //} //sum_gear_and_power += (info->get_power() * info->get_gear() *welt->get_settings().get_global_power_factor_percent() + 50) / 100; //sum_weight += info->get_weight(); //min_top_speed = min( min_top_speed, kmh_to_speed( v->get_desc()->get_topspeed() ) ); //sum_gesamtweight = sum_weight; calc_loading(); invalidate_vehicle_summary(); freight_info_resort = true; // Add good_catg_index: if(v->get_cargo_max() > 0 || (v->get_cargo_type() == goods_manager_t::passengers && v->get_desc()->get_overcrowded_capacity() > 0)) { const goods_desc_t *ware=v->get_cargo_type(); if(ware!=goods_manager_t::none ) { goods_catg_index.append_unique( ware->get_catg_index() ); calc_classes_carried(); } } // check for obsolete if(!has_obsolete && welt->use_timeline()) { has_obsolete = info->is_obsolete( welt->get_timeline_year_month() ); } player_t::add_maintenance( get_owner(), info->get_maintenance(), info->get_waytype() ); } else { return false; } // der convoi hat jetzt ein neues ende set_erstes_letztes(); calc_min_range(); highest_axle_load = calc_highest_axle_load(); longest_min_loading_time = calc_longest_min_loading_time(); longest_max_loading_time = calc_longest_max_loading_time(); calc_direction_steps(); DBG_MESSAGE("convoi_t::add_vehicle()","now %i of %i total vehicles.",vehicle_count,max_vehicle); return true; } void convoi_t::upgrade_vehicle(uint16 i, vehicle_t* v) { // Adapted from the add/remove vehicle functions // @author: jamespetts, February 2010 DBG_MESSAGE("convoi_t::upgrade_vehicle()","at pos %i of %i totals.",i,max_vehicle); if (i >= vehicle.get_count()) { dbg->error("convoi_t::upgrade_vehicle()", "Attempting to append beyond end of convoy"); return; } // now append v->set_convoi(this); vehicle_t* old_vehicle = vehicle[i]; vehicle[i] = v; // Amend the name if the name is the default name and it is the first vehicle // being replaced. if(i == 0) { char buf[128]; name_offset = sprintf(buf,"(%i) ",self.get_id() ); tstrncpy(buf + name_offset, translator::translate(old_vehicle->get_desc()->get_name()), 116); if(!strcmp(get_name(), buf)) { set_name(v->get_desc()->get_name()); } } // Added by : Knightly // Adapted from : simline_t // Purpose : Try to update supported goods category of this convoy if (v->get_cargo_max() > 0 || (v->get_cargo_type() == goods_manager_t::passengers && v->get_desc()->get_overcrowded_capacity() > 0)) { const goods_desc_t *ware_type = v->get_cargo_type(); if (ware_type != goods_manager_t::none) goods_catg_index.append_unique(ware_type->get_catg_index(), 1); } const vehicle_desc_t *info = v->get_desc(); // still requires electrification? if(is_electric) { is_electric = false; for(unsigned i=0; i<vehicle_count; i++) { if(vehicle[i]->get_desc()->get_power()) { is_electric |= vehicle[i]->get_desc()->get_engine_type()==vehicle_desc_t::electric; } } } if(info->get_power()) { is_electric |= info->get_engine_type()==vehicle_desc_t::electric; } //min_top_speed = calc_min_top_speed(tdriver, vehicle_count); // Add power and weight of the new vehicle //sum_power += info->get_power(); //sum_gear_and_power += (info->get_power() * info->get_gear() *welt->get_settings().get_global_power_factor_percent() + 50) / 100; //sum_weight += info->get_weight(); //sum_gesamtweight = sum_weight; // Remove power and weight of the old vehicle //info = old_vehicle->get_desc(); //sum_power -= info->get_power(); //sum_gear_and_power -= (info->get_power() * info->get_gear() *welt->get_settings().get_global_power_factor_percent() + 50) / 100; //sum_weight -= info->get_weight(); calc_loading(); invalidate_vehicle_summary(); freight_info_resort = true; recalc_catg_index(); calc_classes_carried(); // check for obsolete if(has_obsolete) { has_obsolete = calc_obsolescence(welt->get_timeline_year_month()); } // der convoi hat jetzt ein neues ende set_erstes_letztes(); calc_min_range(); highest_axle_load = calc_highest_axle_load(); longest_min_loading_time = calc_longest_min_loading_time(); longest_max_loading_time = calc_longest_max_loading_time(); calc_direction_steps(); delete old_vehicle; DBG_MESSAGE("convoi_t::upgrade_vehicle()","now %i of %i total vehicles.",i,max_vehicle); } vehicle_t *convoi_t::remove_vehicle_bei(uint16 i) { vehicle_t *v = NULL; if(i<vehicle_count) { v = vehicle[i]; if(v != NULL) { for(unsigned j=i; j<vehicle_count-1u; j++) { vehicle[j] = vehicle[j + 1]; } v->set_convoi(NULL); --vehicle_count; vehicle[vehicle_count] = NULL; // Added by : Knightly // Purpose : To recalculate the list of supported goods category recalc_catg_index(); calc_classes_carried(); //const vehicle_desc_t *info = v->get_desc(); //sum_power -= info->get_power(); //sum_gear_and_power -= (info->get_power() * info->get_gear() *welt->get_settings().get_global_power_factor_percent() + 50) / 100; //sum_weight -= info->get_weight(); //sum_running_costs += info->get_operating_cost(); //player_t::add_maintenance( get_owner(), -info->get_maintenance(), info->get_waytype() ); } //sum_gesamtweight = sum_weight; calc_loading(); invalidate_vehicle_summary(); freight_info_resort = true; // der convoi hat jetzt ein neues ende if(vehicle_count > 0) { set_erstes_letztes(); } // calculate new minimum top speed //min_top_speed = calc_min_top_speed(tdriver, vehicle_count); // check for obsolete if(has_obsolete) { has_obsolete = calc_obsolescence(welt->get_timeline_year_month()); } recalc_catg_index(); calc_classes_carried(); // still requires electrifications? if(is_electric) { is_electric = false; for(unsigned i=0; i<vehicle_count; i++) { if(vehicle[i]->get_desc()->get_power()) { is_electric |= vehicle[i]->get_desc()->get_engine_type()==vehicle_desc_t::electric; } } } } calc_min_range(); highest_axle_load = calc_highest_axle_load(); longest_min_loading_time = calc_longest_min_loading_time(); longest_max_loading_time = calc_longest_max_loading_time(); if(!vehicle.empty() && vehicle[0]) { calc_direction_steps(); } return v; } // recalc what good this convoy is moving void convoi_t::recalc_catg_index() { goods_catg_index.clear(); for( uint8 i = 0; i < get_vehicle_count(); i++ ) { // Only consider vehicles that really transport something // this helps against routing errors through passenger // trains pulling only freight wagons if(get_vehicle(i)->get_cargo_max() == 0 && (get_vehicle(i)->get_cargo_type() != goods_manager_t::passengers || get_vehicle(i)->get_desc()->get_overcrowded_capacity() == 0)) { continue; } const goods_desc_t *ware=get_vehicle(i)->get_cargo_type(); if(ware!=goods_manager_t::none ) { goods_catg_index.append_unique( ware->get_catg_index() ); } } /* since during composition of convois all kinds of composition could happen, * we do not enforce schedule recalculation here; it will be done anyway all times when leaving the INTI state ... */ } //"set only last" (Google) void convoi_t::set_erstes_letztes() { // vehicle_count muss korrekt init sein // "anz vehicle must be correctly INIT" (Babelfish) if(vehicle_count>0) { front()->set_leading(true); for(unsigned i=1; i<vehicle_count; i++) { vehicle[i]->set_leading(false); vehicle[i - 1]->set_last(false); } back()->set_last(true); } else { dbg->warning("convoi_t::set_erstes_letzes()", "called with vehicle_count==0!"); } } // remove wrong freight when schedule changes etc. void convoi_t::check_freight() { for(unsigned i=0; i<vehicle_count; i++) { vehicle[i]->remove_stale_cargo(); } calc_loading(); freight_info_resort = true; } bool convoi_t::set_schedule(schedule_t * sch) { if( state==SELF_DESTRUCT ) { return false; } DBG_DEBUG("convoi_t::set_schedule()", "new=%p, old=%p", sch, schedule); assert(sch != NULL); if(!line.is_bound() && state != INITIAL) { // New method - recalculate as necessary // Added by : Knightly if ( schedule == sch && old_schedule ) // Case : Schedule window of operating convoy { if ( !old_schedule->matches(welt, schedule) ) { haltestelle_t::refresh_routing(old_schedule, goods_catg_index, NULL, NULL, owner); haltestelle_t::refresh_routing(schedule, goods_catg_index, NULL, NULL, owner); } } else { if (schedule != sch) { haltestelle_t::refresh_routing(schedule, goods_catg_index, NULL, NULL, owner); } haltestelle_t::refresh_routing(sch, goods_catg_index, NULL, NULL, owner); } } if (schedule == sch && old_schedule) { schedule = old_schedule; } // happens to be identical? if(schedule!=sch) { // now check, we we have been bond to a line we are about to lose: bool changed = false; if( line.is_bound() ) { if( !sch->matches(welt, schedule)) { changed = true; } if( !sch->matches( welt, line->get_schedule() ) ) { // change from line to individual schedule // -> unset line now and register stops from new schedule later changed = true; unset_line(); } } else { if( !sch->matches( welt, schedule ) ) { // merely change schedule and do not involve line // -> unregister stops from old schedule now and register stops from new schedule later changed = true; unregister_stops(); } } // destroy a possibly open schedule window //"is completed" (Google) if( schedule && !schedule->is_editing_finished() ) { destroy_win((ptrdiff_t)schedule); delete schedule; } schedule = sch; if( changed ) { // if line is unset or schedule is changed // -> register stops from new schedule if(!line.is_bound()) { register_stops(); } // Also, clear the departures table, which may now be out of date. clear_departures(); } } // remove wrong freight check_freight(); // ok, now we have a schedule if(state != INITIAL) { state = EDIT_SCHEDULE; } // to avoid jumping trains alte_direction = front()->get_direction(); wait_lock = 0; return true; } schedule_t *convoi_t::create_schedule() { if(schedule == NULL) { const vehicle_t* v = front(); if (v != NULL) { schedule = v->generate_new_schedule(); schedule->finish_editing(); } } return schedule; } /* checks, if we go in the same direction; * true: convoy prepared * false: must recalculate position * on all error we better use the normal starting procedure ... */ bool convoi_t::can_go_alte_direction() { // invalid route? nothing to test, must start new if(route.empty()) { return false; } // going backwards? then recalculate all ribi_t::ribi neue_direction_rwr = ribi_t::backward(front()->calc_direction(route.front(), route.at(min(2, route.get_count() - 1)))); // DBG_MESSAGE("convoi_t::go_alte_direction()","neu=%i,rwr_neu=%i,alt=%i",neue_direction_rwr,ribi_t::backward(neue_direction_rwr),alte_direction); if(neue_direction_rwr&alte_direction) { set_akt_speed(8); return false; } // now get the actual length and the tile length uint16 convoi_length = 15; uint16 tile_length = 24; unsigned i; // for visual C++ const vehicle_t* pred = NULL; for(i=0; i<vehicle_count; i++) { const vehicle_t* v = vehicle[i]; grund_t *gr = welt->lookup(v->get_pos()); // not last vehicle? // the length of last vehicle does not matter when it comes to positioning of vehicles if ( i+1 < vehicle_count) { convoi_length += v->get_desc()->get_length(); } if(gr==NULL || (pred!=NULL && (abs(v->get_pos().x-pred->get_pos().x)>=2 || abs(v->get_pos().y-pred->get_pos().y)>=2)) ) { // ending here is an error! // this is an already broken train => restart dbg->warning("convoi_t::go_alte_direction()","broken convoy (id %i) found => fixing!",self.get_id()); set_akt_speed(8); return false; } // now check, if ribi is straight and train is not ribi_t::ribi weg_ribi = gr->get_weg_ribi_unmasked(v->get_waytype()); if(ribi_t::is_straight(weg_ribi) && (weg_ribi|v->get_direction())!=weg_ribi) { dbg->warning("convoi_t::go_alte_direction()","convoy with wrong vehicle directions (id %i) found => fixing!",self.get_id()); set_akt_speed(8); return false; } if( pred && pred->get_pos()!=v->get_pos() ) { tile_length += (ribi_t::is_straight(welt->lookup(pred->get_pos())->get_weg_ribi_unmasked(pred->get_waytype())) ? 16 : 8192/vehicle_t::get_diagonal_multiplier())*koord_distance(pred->get_pos(),v->get_pos()); } pred = v; } // check if convoi is way too short (even for diagonal tracks) tile_length += (ribi_t::is_straight(welt->lookup(vehicle[vehicle_count-1]->get_pos())->get_weg_ribi_unmasked(vehicle[vehicle_count-1]->get_waytype())) ? 16 : 8192/vehicle_t::get_diagonal_multiplier()); if( convoi_length>tile_length ) { dbg->warning("convoi_t::go_alte_direction()","convoy too short (id %i) => fixing!",self.get_id()); set_akt_speed(8); return false; } uint16 length = min((convoi_length/16u)+4u,route.get_count()); // maximum length in tiles to check // we just check, whether we go back (i.e. route tiles other than zero have convoi vehicles on them) for( int index=1; index<length; index++ ) { grund_t *gr=welt->lookup(route.at(index)); // now check, if we are already here ... for(unsigned i=0; i<vehicle_count; i++) { if (gr->obj_ist_da(vehicle[i])) { // we are turning around => start slowly and rebuilt train set_akt_speed(8); return false; } } } //DBG_MESSAGE("convoi_t::go_alte_direction()","alte=%d, neu_rwr=%d",alte_direction,neue_direction_rwr); // we continue our journey; however later cars need also a correct route entry // eventually we need to add their positions to the convois route koord3d pos = front()->get_pos(); assert(pos == route.front()); if (welt->lookup(pos)->get_depot()) { return false; } else { for (i = 0; i<vehicle_count; i++) { vehicle_t* v = get_vehicle(i); // eventually add current position to the route if (route.front() != v->get_pos() && route.at(1) != v->get_pos()) { route.insert(v->get_pos()); } } } // since we need the route for every vehicle of this convoi, // we must set the current route index (instead assuming 1) length = min((convoi_length/8u),route.get_count()-1); // maximum length in tiles to check bool ok=false; for(i=0; i<vehicle_count; i++) { vehicle_t* v = get_vehicle(i); // this is such awkward, since it takes into account different vehicle length const koord3d vehicle_start_pos = v->get_pos(); for (int idx = 0; idx <= length; idx++) { if (route.at(idx) == vehicle_start_pos) { // set route index, no recalculations necessary v->initialise_journey(idx, false); ok = true; // check direction ribi_t::ribi dir = v->get_direction(); ribi_t::ribi new_dir = v->calc_direction(get_route()->at(max(idx - 1, 0)), v->get_pos_next()); // we need to move to this place ... if (!(dir&new_dir) && (i != 0 || vehicle_count == 1 || ribi_t::is_bend(new_dir))) { // 90 deg bend! return false; } break; } } // too short?!? (rather broken then!) if (!ok) { return false; } } return true; } // put the convoi on its way void convoi_t::vorfahren() { // init speed settings sp_soll = 0; if( get_tiles_overtaking()<=0 ) { set_tiles_overtaking(0); } uint32 reverse_delay = 0; must_recalc_data(); koord3d k0 = route.front(); grund_t *gr = welt->lookup(k0); bool at_dest = false; if(gr && gr->get_depot()) { // start in depot for(unsigned i=0; i<vehicle_count; i++) { vehicle_t* v = vehicle[i]; grund_t* gr = welt->lookup(v->get_pos()); if(gr) { gr->obj_remove(v); if(gr->ist_uebergang()) { crossing_t *cr = gr->find<crossing_t>(2); cr->release_crossing(v); } // eventually unreserve this if( schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(vehicle[i]->get_waytype())) ) { sch0->unreserve(v); } } v->initialise_journey(0, true); // set at new position gr = welt->lookup(v->get_pos()); assert(gr); v->enter_tile(gr); } // just advances the first vehicle vehicle_t* v0 = front(); v0->set_leading(false); // switches off signal checks ... v0->get_smoke(false); steps_driven = 0; // drive half a tile: for(int i=0; i<vehicle_count; i++) { vehicle[i]->do_drive( (VEHICLE_STEPS_PER_TILE/2)<<YARDS_PER_VEHICLE_STEP_SHIFT ); } v0->get_smoke(true); v0->set_leading(true); // switches on signal checks to reserve the next route // until all other are on the track state = CAN_START; } else { const bool must_change_direction = !can_go_alte_direction(); bool re_reserve = false; // still leaving depot (steps_driven!=0) or going in other direction or misalignment? if(steps_driven > 0 || must_change_direction) { //Convoy needs to reverse //@author: jamespetts if(must_change_direction) { halthandle_t check_halt = haltestelle_t::get_halt(get_pos(), get_owner()); switch(front()->get_waytype()) { case air_wt: case water_wt: if (check_halt.is_bound()) { // Boats and aircraft do not need to change direction book_departure_time(welt->get_ticks()); book_waiting_times(); } break; default: reversable = get_terminal_shunt_mode() == change_direction ? true : false; reverse_delay = calc_reverse_delay(); state = REVERSING; if(front()->last_stop_pos == front()->get_pos()) { // The convoy does not depart until it has reversed. book_departure_time(welt->get_ticks() + reverse_delay); } if (front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { const rail_vehicle_t* rv = (rail_vehicle_t*)front(); if (rv->get_working_method() == drive_by_sight || rv->get_working_method() == time_interval || rv->get_working_method() == time_interval_with_telegraph) { reserve_own_tiles(true); // Unreserve now in case reversing alters the tiles occupied by this convoy. } } reverse_order(reversable); if (front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { const rail_vehicle_t* rv = (rail_vehicle_t*)front(); if (rv->get_working_method() == drive_by_sight || rv->get_working_method() == time_interval || rv->get_working_method() == time_interval_with_telegraph) { // We have to do this later if we are reversing as the train may occupy different tiles. re_reserve = true; } } } } // start route from the beginning at index 0, place everything on start uint32 train_length = move_to(0); // move one train length to the start position ... // in north/west direction, we leave the vehicle away to start as much back as possible ribi_t::ribi neue_direction = front()->get_direction_of_travel(); if(neue_direction==ribi_t::south || neue_direction==ribi_t::east) { // drive the convoi to the same position, but do not hop into next tile! if( train_length%16==0 ) { // any space we need => just add train_length += vehicle[vehicle_count-1]->get_desc()->get_length(); } else { // limit train to front of tile train_length += min( (train_length%CARUNITS_PER_TILE)-1, vehicle[vehicle_count-1]->get_desc()->get_length() ); } } else { train_length += 1; } train_length = max(1,train_length); // now advance all convoi until it is completely on the track front()->set_leading(false); // switches off signal checks ... /*if(reversed && (reversable || front()->is_reversed())) { //train_length -= front()->get_desc()->get_length(); train_length = 0; for(sint8 i = vehicle_count - 1; i >= 0; i--) { vehicle_t* v = vehicle[i]; v->get_smoke(false); vehicle[i]->do_drive( ((OBJECT_OFFSET_STEPS)*train_length)<<12 ); //"fahre" = "go" (Google) train_length += (v->get_desc()->get_length()); // this give the length in 1/OBJECT_OFFSET_STEPS of a full tile => all cars closely coupled! v->get_smoke(true); } train_length -= back()->get_desc()->get_length(); } else {*/ //if(!reversable && front()->get_desc()->is_bidirectional()) //{ // //This can sometimes relieve excess setting back on reversing. // //Unfortunately, it seems to produce bizarre results on occasion. // train_length -= (front()->get_desc()->get_length()) / 2; // train_length = train_length > 0 ? train_length : 0; //} for(sint8 i = 0; i < vehicle_count; i++) { vehicle_t* v = vehicle[i]; v->get_smoke(false); vehicle[i]->do_drive( (VEHICLE_STEPS_PER_CARUNIT*train_length)<<YARDS_PER_VEHICLE_STEP_SHIFT ); train_length -= v->get_desc()->get_length(); // this gives the length in carunits, 1/CARUNITS_PER_TILE of a full tile => all cars closely coupled! v->get_smoke(true); //} } front()->set_leading(true); } if (re_reserve) { reserve_own_tiles(false); // Re-reserve } else if(front()->last_stop_pos == front()->get_pos()) { book_departure_time(welt->get_ticks()); book_waiting_times(); } int counter = 1; schedule_t* sch = schedule; if(line.is_bound()) { counter = 2; } bool need_to_update_line = false; while(counter > 0 && sch->get_count() > 0) { uint8 stop = sch->get_current_stop(); bool rev = !reverse_schedule; sch->increment_index(&stop, &rev); if(stop < sch->get_count()) { // It might be possible for "stop" to be > the number of // items in the schedule if the schedule has changed recently. if(haltestelle_t::get_halt(sch->entries[stop].pos, owner) != (haltestelle_t::get_halt(get_pos(), owner))) { // It is possible that the last entry was a skipped waypoint. sch->increment_index(&stop, &rev); } if((haltestelle_t::get_halt(sch->entries[stop].pos, owner).is_bound() && ((sch->entries[stop].reverse == 1) != (state == REVERSING))) && (state != ROUTE_JUST_FOUND || front()->get_waytype() != road_wt) && !last_stop_was_depot) { need_to_update_line = true; const sint8 reverse_state = state == REVERSING ? 1 : 0; schedule->set_reverse(reverse_state, stop); const linehandle_t line = get_line(); if (line.is_bound() && line->get_schedule()->get_count() > stop) { line->get_schedule()->set_reverse(reverse_state, stop); } } break; } sch->increment_index(&stop, &rev); counter --; if(counter > 0) { sch = line->get_schedule(); } } if(need_to_update_line) { const linehandle_t line = get_line(); if(line.is_bound()) { // Set the bool flag to true, as a change in reversing status, which is all that this is ever called for here, // can never necessitate renewing all the stops on a line. This will avoid unnecessary path explorer refreshes, // especially as there are some circumstances where this is constantly altered for road lines. simlinemgmt_t::update_line(line, true); } } if(!at_dest) { if(state != REVERSING) { // A convoy starts without reversing state = CAN_START; } // to advance more smoothly sint32 restart_speed = -1; if(state != REVERSING) { if(front()->can_enter_tile(restart_speed, 0)) { // can reserve new block => drive on if (haltestelle_t::get_halt(k0, owner).is_bound() && front()->get_waytype() != air_wt) // Aircraft play sounds on taking off instead of taxiing { front()->play_sound(); } state = DRIVING; } } else { // If a rail type vehicle is reversing in a station, reserve the entire platform. const waytype_t wt = front()->get_waytype(); const bool rail_type = front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt; if(rail_type) { grund_t* vgr = gr; schiene_t *w = gr ? (schiene_t *)vgr->get_weg(wt) : NULL; if(w) { // First, reserve under the entire train (which might be outside the station in part) for(unsigned i = 0; i < vehicle_count; i++) { vehicle_t const& v = *vehicle[i]; vgr = welt->lookup(v.get_pos()); if(!vgr) { continue; } w = (schiene_t *)vgr->get_weg(wt); if(!w) { continue; } w->reserve(self, vehicle[i]->get_direction()); } // Next, reserve the rest (if any) of the platform. grund_t* to = gr; if(to) { ribi_t::ribi direction_of_travel = front()->get_direction(); koord3d last_pos = gr->get_pos(); while(haltestelle_t::get_halt(to->get_pos(), owner).is_bound()) { w = (schiene_t *)to->get_weg(wt); if(!w || !ribi_t::is_single(direction_of_travel)) { // If direction_of_travel is not a proper single direction, // odd tile reservations causing blockages can occur. break; } if(last_pos != to->get_pos()) { w->reserve(self, direction_of_travel); last_pos = to->get_pos(); } to->get_neighbour(to, wt, direction_of_travel); direction_of_travel = vehicle_t::calc_direction(last_pos, to->get_pos()); if(last_pos == to->get_pos()) { // Prevent infinite loops. break; } } } } } } } else { ziel_erreicht(); } } // override reversed schedule status for the first and last stops of a mirrored schedule if(schedule->is_mirrored()) { if(schedule->get_current_stop() == 0) { set_reverse_schedule(true); } else if(schedule->get_current_stop() == schedule->get_count()-1) { set_reverse_schedule(false); } } // finally reserve route (if needed) if( front()->get_waytype()!=air_wt && !at_dest ) { // do not pre-reserve for aircraft for(unsigned i=0; i<vehicle_count; i++) { // eventually reserve this vehicle_t const& v = *vehicle[i]; const grund_t* gr = welt->lookup(v.get_pos()); if(gr) { if (schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(v.get_waytype()))) { sch0->reserve(self, front()->get_direction()); } } else { break; } } } wait_lock = reverse_delay; arrival_time = WAIT_INFINITE; // Make sure that the convoy does not use an outdated arrival time. //INT_CHECK("simconvoi 711"); } void convoi_t::reverse_order(bool rev) { // Code snippet obtained and adapted from: // http://www.cprogramming.com/snippets/show.php?tip=15&count=30&page=0 // by John Shao (public domain work) uint8 a = 0; vehicle_t* reverse; uint8 b = vehicle_count; uint8 loco_a = 0; uint8 loco_b = get_front_loco_count(); uint8 back_a = check_new_tail(get_front_loco_count()); uint8 back_b = vehicle_count; //bool reverse_loco = false; // If true, the locomotive number will be reverced. i.e. not using turntable working_method_t wm = drive_by_sight; if(front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { rail_vehicle_t* w = (rail_vehicle_t*)front(); wm = w->get_working_method(); } front()->set_leading(false); back()->set_last(false); if (!rev) { //back()->set_last(false); switch (get_terminal_shunt_mode()) { case change_direction: break; case shunting_loco: a = get_front_loco_count(); // reverse loco if (!check_need_turntable()) { for (; loco_a < --loco_b; loco_a++) { reverse = vehicle[loco_a]; vehicle[loco_a] = vehicle[loco_b]; vehicle[loco_b] = reverse; } } break; case rearrange: a = get_front_loco_count(); b = back_a; // reverse back end chunk if (back_a < back_b) { for (; back_a < --back_b; back_a++) { reverse = vehicle[back_a]; vehicle[back_a] = vehicle[back_b]; vehicle[back_b] = reverse; } } // reverse loco if (!check_need_turntable() && loco_b > 0) { for (; loco_a < --loco_b; loco_a++) { reverse = vehicle[loco_a]; vehicle[loco_a] = vehicle[loco_b]; vehicle[loco_b] = reverse; } } break; case wye: default: // Do not change the order at all if reverse the whole convoy. i.e. consider as using wye front()->set_leading(true); back()->set_last(true); return; break; } } for( ; a<--b; a++) //increment a and decrement b until they meet each other { reverse = vehicle[a]; //put what's in a into swap spacekarte_t::load( vehicle[a] = vehicle[b]; //put what's in b into a vehicle[b] = reverse; //put what's in the swap (a) into b } front()->set_leading(true); back()->set_last(true); reversed = !reversed; if (rev) { re_ordered = !re_ordered; } int start = 0; switch (get_terminal_shunt_mode()) { case shunting_loco: case rearrange: if (check_need_turntable()) { start = get_front_loco_count(); } break; case change_direction: case wye: default: break; } for (int i=start; i < vehicle_count; i++) { vehicle[i]->set_reversed(reversed); } if(front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { rail_vehicle_t* w = (rail_vehicle_t*)front(); w->set_working_method(wm); } welt->set_dirty(); } void convoi_t::rdwr_convoihandle_t(loadsave_t *file, convoihandle_t &cnv) { if( file->is_version_atleast(112, 3) ) { uint16 id = (file->is_saving() && cnv.is_bound()) ? cnv.get_id() : 0; file->rdwr_short( id ); if (file->is_loading()) { cnv.set_id( id ); } } } void convoi_t::rdwr(loadsave_t *file) { xml_tag_t t( file, "convoi_t" ); sint32 dummy; sint32 owner_n = welt->sp2num(owner); if(file->is_saving()) { if( file->is_version_less(101, 0) ) { file->wr_obj_id("Convoi"); // the matching read is in karte_t::load(loadsave*)... } } // do the update, otherwise we might lose the line after save & reload if(file->is_saving() && line_update_pending.is_bound()) { check_pending_updates(); } simline_t::rdwr_linehandle_t(file, line); if( file->get_extended_version() >= 14 ) { file->rdwr_long(yielding_quit_index); file->rdwr_byte(lane_affinity); file->rdwr_long(lane_affinity_end_index); } // we want persistent convoihandles so we can keep dialogues open in network games if( file->is_loading() ) { if( file->is_version_less(112, 3) ) { self = convoihandle_t( this ); } else { uint16 id; file->rdwr_short( id ); self = convoihandle_t( this, id ); } } else if( file->is_version_atleast(112, 3) ) { uint16 id = self.get_id(); file->rdwr_short( id ); } dummy = vehicle_count; file->rdwr_long(dummy); vehicle_count = (uint8)dummy; if(file->is_version_less(99, 14)) { // was anz_ready file->rdwr_long(dummy); } wait_lock += wait_lock_next_step; wait_lock_next_step = 0; file->rdwr_long(wait_lock); // some versions may produce broken savegames apparently if(wait_lock > 1470000 && file->get_extended_version() < 11) { // max as was set by NO_ROUTE in former times. This code is deprecated now as the wait_lock can be higher with the convoy spacing feature. dbg->warning("convoi_t::sync_prepre()","Convoi %d: wait lock out of bounds: wait_lock = %d, setting to 1470000",self.get_id(), wait_lock); wait_lock = 1470000; } bool dummy_bool=false; file->rdwr_bool(dummy_bool); file->rdwr_long(owner_n); file->rdwr_long(akt_speed); sint32 akt_speed_soll = 0; // Former variable now unused file->rdwr_long(akt_speed_soll); file->rdwr_long(sp_soll); file->rdwr_enum(state); file->rdwr_enum(alte_direction); // read the yearly income (which has since then become a 64 bit value) // will be recalculated later directly from the history if(file->is_version_less(89, 4)) { file->rdwr_long(dummy); } route.rdwr(file); if(file->is_loading()) { // extend array if requested (only needed for trains) if(vehicle_count > max_vehicle) { vehicle.resize(max_rail_vehicle, NULL); } owner = welt->get_player( owner_n ); // sanity check for values ... plus correction if(sp_soll < 0) { sp_soll = 0; } set_akt_speed(akt_speed); } file->rdwr_str(name_and_id + name_offset, lengthof(name_and_id) - name_offset); if(file->is_loading()) { set_name(name_and_id+name_offset); // will add id automatically } koord3d dummy_pos; if(file->is_saving()) { for(unsigned i=0; i<vehicle_count; i++) { file->wr_obj_id( vehicle[i]->get_typ() ); vehicle[i]->rdwr_from_convoi(file); } } else { bool override_monorail = false; is_electric = false; for( uint8 i=0; i<vehicle_count; i++ ) { obj_t::typ typ = (obj_t::typ)file->rd_obj_id(); vehicle_t *v = 0; const bool first = (i==0); const bool last = (i==vehicle_count-1u); if(override_monorail) { // ignore type for ancient monorails v = new monorail_rail_vehicle_t(file, first, last); } else { switch(typ) { case obj_t::old_road_vehicle: case obj_t::road_vehicle: v = new road_vehicle_t(file, first, last); break; case obj_t::old_waggon: case obj_t::rail_vehicle: v = new rail_vehicle_t(file, first, last); break; case obj_t::old_schiff: case obj_t::water_vehicle: v = new water_vehicle_t(file, first, last); break; case obj_t::old_aircraft: case obj_t::air_vehicle: v = new air_vehicle_t(file, first, last); break; case obj_t::old_monorail_vehicle: case obj_t::monorail_vehicle: v = new monorail_rail_vehicle_t(file, first, last); break; case obj_t::maglev_vehicle: v = new maglev_rail_vehicle_t(file, first, last); break; case obj_t::narrowgauge_vehicle: v = new narrowgauge_rail_vehicle_t(file, first, last); break; default: dbg->fatal("convoi_t::convoi_t()","Can't load vehicle type %d", typ); } } // no matching vehicle found? if(v->get_desc()==NULL) { // will create orphan object, but better than crashing at deletion ... dbg->error("convoi_t::convoi_t()","Can't load vehicle and no replacement found!"); i --; vehicle_count --; continue; } // in very old games, monorail was a railway // so we need to convert this // freight will be lost, but game will be loadable if(i==0 && v->get_desc()->get_waytype()==monorail_wt && v->get_typ()==obj_t::rail_vehicle) { override_monorail = true; vehicle_t *v_neu = new monorail_rail_vehicle_t( v->get_pos(), v->get_desc(), v->get_owner(), NULL ); v->discard_cargo(); delete v; v = v_neu; } if(file->is_version_less(99, 4)) { dummy_pos.rdwr(file); } const vehicle_desc_t *info = v->get_desc(); assert(info); // if we load a game from a file which was saved from a // game with a different vehicle.tab, there might be no vehicle // info if(info) { //sum_power += info->get_power(); //sum_gear_and_power += (info->get_power() * info->get_gear() *welt->get_settings().get_global_power_factor_percent() + 50) / 100; //sum_weight += info->get_weight(); has_obsolete |= welt->use_timeline() && info->is_retired( welt->get_timeline_year_month() ); is_electric |= info->get_engine_type()==vehicle_desc_t::electric; player_t::add_maintenance( get_owner(), info->get_maintenance(), info->get_waytype() ); } // some versions save vehicles after leaving depot with koord3d::invalid if(v->get_pos()==koord3d::invalid) { state = INITIAL; } if(state!=INITIAL) { grund_t *gr; gr = welt->lookup(v->get_pos()); if(!gr) { gr = welt->lookup_kartenboden(v->get_pos().get_2d()); if(gr) { dbg->error("convoi_t::rdwr()", "invalid position %s for vehicle %s in state %d (setting to %i,%i,%i)", v->get_pos().get_str(), v->get_name(), state, gr->get_pos().x, gr->get_pos().y, gr->get_pos().z ); v->set_pos( gr->get_pos() ); } else { dbg->fatal("convoi_t::rdwr()", "invalid position %s for vehicle %s in state %d", v->get_pos().get_str(), v->get_name(), state); } state = INITIAL; } // add to reservation if(gr && (v->get_waytype()==track_wt || v->get_waytype()==monorail_wt || v->get_waytype()==maglev_wt || v->get_waytype()==narrowgauge_wt)) { schiene_t* sch = (schiene_t*)gr->get_weg(v->get_waytype()); if(sch) { sch->reserve(self, v->get_direction()); } // add to crossing if(gr->ist_uebergang()) { gr->find<crossing_t>()->add_to_crossing(v); } } if( gr->get_top()>253 ) { dbg->warning( "convoi_t::rdwr()", "cannot put vehicle on ground at (%s)", gr->get_pos().get_str() ); } gr->obj_add(v); v->clear_flag(obj_t::not_on_map); } else { v->set_flag(obj_t::not_on_map); } // add to convoi vehicle[i] = v; } //sum_gesamtweight = sum_weight; } bool has_fpl = (schedule != NULL); file->rdwr_bool(has_fpl); if(has_fpl) { //DBG_MESSAGE("convoi_t::rdwr()","convoi has a schedule, state %s!",state_names[state]); const vehicle_t* v = front(); if(file->is_loading() && v) { schedule = v->generate_new_schedule(); } // hack to load corrupted games -> there is a schedule // but no vehicle so we can't determine the exact type of // schedule needed. This hack is safe because convois // without vehicles get deleted right after loading. // Since generic schedules are not allowed, we use a train_schedule_t if(schedule == 0) { schedule = new train_schedule_t(); } // now read the schedule, we have one for sure here schedule->rdwr( file ); } if(file->is_loading()) { next_wolke = 0; calc_loading(); set_akt_speed(akt_speed); invalidate_vehicle_summary(); } // calculate new minimum top speed //min_top_speed = calc_min_top_speed(tdriver, vehicle_count); // since sp_ist became obsolete, sp_soll is used modulo 65536 sp_soll &= 65535; if(file->is_version_less(88, 4)) { // load statistics int j; for (j = 0; j < 3; j++) { for (int k = MAX_MONTHS-1; k >= 0; k--) { if(((j == CONVOI_AVERAGE_SPEED || j == CONVOI_COMFORT) && file->get_extended_version() <= 1) || (j >= CONVOI_REFUNDS && file->get_extended_version() < 8)) { // Versions of Extended saves with 1 and below // did not have settings for average speed or comfort. // Thus, this value must be skipped properly to // assign the values. Likewise, versions of Extended < 8 // did not store refund information. if(file->is_loading()) { financial_history[k][j] = 0; } continue; } file->rdwr_longlong(financial_history[k][j]); } } for (j = 2; j < 5; j++) { for (int k = MAX_MONTHS-1; k >= 0; k--) { if(((j == CONVOI_AVERAGE_SPEED || j == CONVOI_COMFORT) && file->get_extended_version() <= 1) || (j >= CONVOI_REFUNDS && file->get_extended_version() < 8)) { // Versions of Extended saves with 1 and below // did not have settings for average speed or comfort. // Thus, this value must be skipped properly to // assign the values. Likewise, versions of Extended < 8 // did not store refund information. if(file->is_loading()) { financial_history[k][j] = 0; } continue; } file->rdwr_longlong(financial_history[k][j]); } } for (size_t k = MAX_MONTHS; k-- != 0;) { financial_history[k][CONVOI_DISTANCE] = 0; //financial_history[k][CONVOI_WAYTOLL] = 0; } } else if( file->is_version_less(102, 3) || (file->get_extended_version() < 7 && file->get_extended_version() != 0) ){ // load statistics for (int j = 0; j<7; j++) { for (int k = MAX_MONTHS-1; k>=0; k--) { if(((j == CONVOI_AVERAGE_SPEED || j == CONVOI_COMFORT) && file->get_extended_version() <= 1) || (j >= CONVOI_REFUNDS && file->get_extended_version() < 8)) { // Versions of Extended saves with 1 and below // did not have settings for average speed or comfort. // Thus, this value must be skipped properly to // assign the values. Likewise, versions of Extended < 8 // did not store refund information. if(file->is_loading()) { financial_history[k][j] = 0; } continue; } file->rdwr_longlong(financial_history[k][j]); } } for (int j = 7; j< CONVOI_WAYTOLL; j++) { for (int k = MAX_MONTHS-1; k>=0; k--) { financial_history[k][j] = 0; } } } else { // load statistics for (int j = 0; j < MAX_CONVOI_COST; j++) { switch (j) { case CONVOI_AVERAGE_SPEED: case CONVOI_COMFORT: if (file->get_extended_version() < 2) { // Versions of Extended saves with 1 and below // did not have settings for average speed or comfort. // Thus, this value must be skipped properly to // assign the values. if (file->is_loading()) { for (int k = MAX_MONTHS-1; k >= 0; k--) { financial_history[k][j] = 0; } } continue; } break; case CONVOI_DISTANCE: if (file->get_extended_version() < 7) { // Simutrans-Standard: distances in tiles, not km. Convert. sint64 distance; if(file->is_loading()) { for (int k = MAX_MONTHS-1; k >= 0; k--) { file->rdwr_longlong(distance); financial_history[k][j] = (distance *welt->get_settings().get_meters_per_tile()) / 1000; } } else { for (int k = MAX_MONTHS-1; k >= 0; k--) { distance = (financial_history[k][j] * 1000) /welt->get_settings().get_meters_per_tile(); file->rdwr_longlong(distance); } } continue; } break; case CONVOI_REFUNDS: if (file->get_extended_version() < 8) { // versions of Extended < 8 did not store refund information. if (file->is_loading()) { for (int k = MAX_MONTHS-1; k >= 0; k--) { financial_history[k][j] = 0; } if( file->get_extended_version() == 0 && file->is_version_atleast(111, 1) ) { // CONVOI_MAXSPEED - not used in Extended sint64 dummy = 0; for (int k = MAX_MONTHS-1; k >= 0; k--) { file->rdwr_longlong(dummy); } } } continue; } break; case CONVOI_WAYTOLL: if (file->get_extended_version() < 14 || (file->get_extended_version() == 14 && file->get_extended_revision() < 25)) { if (file->is_loading()) { for (int k = MAX_MONTHS - 1; k >= 0; k--) { financial_history[k][j] = 0; } } continue; } break; } for (int k = MAX_MONTHS-1; k >= 0; k--) { file->rdwr_longlong(financial_history[k][j]); } } if (file->is_loading()) { if( file->is_version_atleast(112, 8) && file->get_extended_version() == 0 ) { // CONVOI_WAYTOLL - not used in Extended until Jan 2020 sint64 dummy = 0; for (int k = MAX_MONTHS-1; k >= 0; k--) { file->rdwr_longlong(dummy); } } } } // the convoy odometer if( file->is_version_atleast(102, 3) ) { if(file->get_extended_version() < 7) { //Simutrans-Standard save - this value is in tiles, not km. Convert. if(file->is_loading()) { sint64 tile_distance; file->rdwr_longlong(tile_distance); total_distance_traveled = (tile_distance *welt->get_settings().get_meters_per_tile()) / 1000; } else { sint64 km_distance = (total_distance_traveled * 1000) /welt->get_settings().get_meters_per_tile(); file->rdwr_longlong(km_distance); } } else { file->rdwr_longlong(total_distance_traveled); } } if( file->is_version_atleast(102, 3) && file->get_extended_version() >= 7 ) { if(file->get_extended_version() <= 8) { uint8 old_tiles = uint8(steps_since_last_odometer_increment / VEHICLE_STEPS_PER_TILE); file->rdwr_byte(old_tiles); steps_since_last_odometer_increment = old_tiles * VEHICLE_STEPS_PER_TILE; } else if (file->get_extended_version() > 8 && file->get_extended_version() < 10) { double tiles_since_last_odometer_increment = double(steps_since_last_odometer_increment) / VEHICLE_STEPS_PER_TILE; file->rdwr_double(tiles_since_last_odometer_increment); steps_since_last_odometer_increment = sint64(tiles_since_last_odometer_increment * VEHICLE_STEPS_PER_TILE ); } else if( file->is_version_atleast(110, 6) && file->get_extended_version() >= 9 ) { file->rdwr_longlong(steps_since_last_odometer_increment); } } // since it was saved as an signed int // we recalc it anyhow if(file->is_loading()) { jahresgewinn = 0; //"annual profit" (Babelfish) for(int i=welt->get_last_month()%12; i>=0; i-- ) { jahresgewinn += financial_history[i][CONVOI_PROFIT]; } } // save/restore pending line updates if(file->is_version_atleast(84, 9) && file->is_version_less(99, 13)) { file->rdwr_long(dummy); // ignore } if(file->is_loading()) { line_update_pending = linehandle_t(); } if(file->is_version_atleast(84, 10)) { home_depot.rdwr(file); } // Old versions recorded last_stop_pos in convoi, not in vehicle koord3d last_stop_pos_convoi = koord3d(0,0,0); if (vehicle_count !=0) { last_stop_pos_convoi = front()->last_stop_pos; } if(file->is_version_atleast(87, 1)) { last_stop_pos_convoi.rdwr(file); } else { last_stop_pos_convoi = !route.empty() ? route.front() : vehicle_count != 0 ? front()->get_pos() : koord3d(0, 0, 0); } // for leaving the depot routine if(file->is_version_less(99, 14)) { steps_driven = -1; } else { file->rdwr_short(steps_driven); } // waiting time left ... if(file->is_version_atleast(99, 17)) { if(file->is_saving()) { if(go_on_ticks == WAIT_INFINITE) { if(file->get_extended_version() <= 1) { uint32 old_go_on_ticks = (uint32)go_on_ticks; file->rdwr_long(old_go_on_ticks); } else { file->rdwr_longlong(go_on_ticks); } } else { sint64 diff_ticks = welt->get_ticks() > go_on_ticks ? 0ll : go_on_ticks - welt->get_ticks(); file->rdwr_longlong(diff_ticks); } } else // Loading { if(file->get_extended_version() <= 1) { uint32 old_go_on_ticks = (uint32)go_on_ticks; file->rdwr_long( old_go_on_ticks); go_on_ticks = old_go_on_ticks; } else { file->rdwr_longlong(go_on_ticks); } if(go_on_ticks != WAIT_INFINITE) { go_on_ticks += welt->get_ticks(); } } } // since 99015, the last stop will be maintained by the vehikels themselves if(file->is_version_less(99, 15)) { for(unsigned i=0; i<vehicle_count; i++) { vehicle[i]->last_stop_pos = last_stop_pos_convoi; } } // overtaking status if(file->is_version_less(100, 1)) { set_tiles_overtaking( 0 ); } else { file->rdwr_byte(tiles_overtaking); set_tiles_overtaking( tiles_overtaking ); } // no_load, withdraw if(file->is_version_less(102, 1)) { no_load = false; withdraw = false; } else { file->rdwr_bool(no_load); file->rdwr_bool(withdraw); } // reverse_schedule if(file->get_extended_version() >= 9) { file->rdwr_bool(reverse_schedule); } else if(file->is_loading()) { reverse_schedule = false; } if(file->is_loading()) { calc_min_range(); highest_axle_load = calc_highest_axle_load(); longest_min_loading_time = calc_longest_min_loading_time(); longest_max_loading_time = calc_longest_max_loading_time(); calc_direction_steps(); } if(file->get_extended_version() >= 1) { file->rdwr_bool(reversed); if (file->get_extended_version() >= 13 || file->get_extended_revision() >= 12) { file->rdwr_bool(re_ordered); } //Replacing settings // BG, 31-MAR-2010: new replacing code starts with exp version 8: bool is_replacing = replace && (file->get_extended_version() >= 8); file->rdwr_bool(is_replacing); if(file->get_extended_version() >= 8) { if(is_replacing) { if(file->is_saving()) { replace->rdwr(file); } else { replace = new replace_data_t(file); } } file->rdwr_bool(depot_when_empty); } else { // Original vehicle replacing settings - stored in convoi_t. bool old_autostart; file->rdwr_bool(old_autostart); file->rdwr_bool(depot_when_empty); uint16 replacing_vehicles_count = 0; vector_tpl<const vehicle_desc_t *> *replacing_vehicles; if(file->is_saving()) { // BG, 31-MAR-2010: new replacing code starts with exp version 8. // BG, 31-MAR-2010: to keep compatibility with exp versions < 8 // at least the number of replacing vehicles (always 0) must be written. //replacing_vehicles = replace->get_replacing_vehicles(); //replacing_vehicles_count = replacing_vehicles->get_count(); file->rdwr_short(replacing_vehicles_count); } else { file->rdwr_short(replacing_vehicles_count); if (replacing_vehicles_count > 0) { // BG, 31-MAR-2010: new replacing code starts with exp version 8. // BG, 31-MAR-2010: but we must read all related data from file. replacing_vehicles = new vector_tpl<const vehicle_desc_t *>; for(uint16 i = 0; i < replacing_vehicles_count; i ++) { char vehicle_name[256]; file->rdwr_str(vehicle_name, 256); const vehicle_desc_t* desc = vehicle_builder_t::get_info(vehicle_name); if(desc == NULL) { desc = vehicle_builder_t::get_info(translator::compatibility_name(vehicle_name)); } if(desc == NULL) { dbg->warning("convoi_t::rdwr()","no vehicle pak for '%s' search for something similar", vehicle_name); } else { replacing_vehicles->append(desc); } } // BG, 31-MAR-2010: new replacing code starts with exp version 8. // BG, 31-MAR-2010: we must not create 'replace'. I does not work correct. delete replacing_vehicles; } } } } if(file->get_extended_version() >= 2) { if(file->get_extended_version() <= 9) { const grund_t* gr = welt->lookup(front()->last_stop_pos); if(gr && schedule) { departure_data_t dep; uint8 entry = schedule->get_current_stop(); bool rev = !reverse_schedule; schedule->increment_index(&entry, &rev); departure_point_t departure_point(entry, !rev); dep = departures.get(departure_point); sint64 departure_time = dep.departure_time; file->rdwr_longlong(departure_time); if(file->is_loading()) { departures.clear(); dep.departure_time = departure_time; departures.put(departure_point, dep); } } } else if(file->get_extended_version() < 12) { // Sadly, it is not possible to reconstruct departure data for these intermediate saved games, // as there is inherent ambiguity as to what stops match with which schedule entries (which was // the reason for changing this system in the first place). All that can be done on loading is // to clear the departures and set dummy values. if(file->is_loading()) { uint32 count = 0; file->rdwr_long(count); departures.clear(); uint16 dummy_id = 0; sint64 dummy_departure_time = 0; for(uint i = 0; i < count; i ++) { file->rdwr_short(dummy_id); file->rdwr_longlong(dummy_departure_time); if( file->is_version_atleast(110, 7) ) { uint8 player_count = 0; file->rdwr_byte(player_count); for(uint i = 0; i < player_count; i ++) { uint32 dummy_accumulated_distance; file->rdwr_long(dummy_accumulated_distance); } } } } if(file->is_saving()) { // In theory, this could be set up when saving, but it is unlikely that mail version 12 games // can be made backwards compatible to version 11 or earlier in any event because of factory // entries in passenger packets, so this would be superfluous. uint32 count = 0; file->rdwr_long(count); } } else // Extended version >= 12 { departure_point_t departure_point; sint64 departure_time; uint32 accumulated_distance; if(file->is_saving()) { uint32 count = departures.get_count(); file->rdwr_long(count); FOR(departure_map, const& iter, departures) { departure_point = iter.key; departure_time = iter.value.departure_time; file->rdwr_short(departure_point.entry); file->rdwr_short(departure_point.reversed); file->rdwr_longlong(departure_time); if( file->is_version_atleast(110, 7) ) { uint8 player_count = MAX_PLAYER_COUNT + 2; file->rdwr_byte(player_count); for(int i = 0; i < player_count; i ++) { accumulated_distance = iter.value.get_way_distance(i); file->rdwr_long(accumulated_distance); } } } count = departures_already_booked.get_count(); file->rdwr_long(count); uint16 x; uint16 y; FOR(departure_time_map, const& iter, departures_already_booked) { x = iter.key.x; y = iter.key.y; departure_time = iter.value; file->rdwr_short(x); file->rdwr_short(y); file->rdwr_longlong(departure_time); } uint16 total; uint16 ave_count; count = journey_times_between_schedule_points.get_count(); file->rdwr_long(count); FOR(timings_map, const& iter, journey_times_between_schedule_points) { departure_point = iter.key; total = iter.value.total; ave_count = iter.value.count; file->rdwr_short(departure_point.entry); file->rdwr_short(departure_point.reversed); file->rdwr_short(total); file->rdwr_short(ave_count); } } else if(file->is_loading()) { uint32 count = 0; file->rdwr_long(count); // Do NOT use clear_departures here, as this clears the estimated times // in the halts that have already been loaded, as the halts load before // the convoys. departures.clear(); departures_already_booked.clear(); journey_times_between_schedule_points.clear(); for(uint32 i = 0; i < count; i ++) { file->rdwr_short(departure_point.entry); file->rdwr_short(departure_point.reversed); file->rdwr_longlong(departure_time); departure_data_t dep; dep.departure_time = departure_time; if( file->is_version_atleast(110, 7) ) { uint8 player_count = 0; file->rdwr_byte(player_count); for(uint i = 0; i < player_count; i ++) { uint32 accumulated_distance; file->rdwr_long(accumulated_distance); dep.set_distance(i, accumulated_distance); } } departures.put(departure_point, dep); } file->rdwr_long(count); uint16 x; uint16 y; sint64 departure_time; for(uint32 i = 0; i < count; i ++) { file->rdwr_short(x); file->rdwr_short(y); file->rdwr_longlong(departure_time); id_pair pair(x, y); departures_already_booked.put(pair, departure_time); } file->rdwr_long(count); uint16 total; uint16 ave_count; for(uint32 i = 0; i < count; i ++) { file->rdwr_short(departure_point.entry); file->rdwr_short(departure_point.reversed); file->rdwr_short(total); file->rdwr_short(ave_count); average_tpl<uint16> ave; ave.total = total; ave.count = ave_count; journey_times_between_schedule_points.put(departure_point, ave); } } } const uint8 count = file->is_version_less(103, 0) ? CONVOI_DISTANCE : CONVOI_WAYTOLL; for(uint8 i = 0; i < count; i ++) { file->rdwr_long(rolling_average[i]); file->rdwr_short(rolling_average_count[i]); } } else if(file->is_loading()) { clear_departures(); } if( file->get_extended_version() >= 9 && file->is_version_atleast(110, 6) ) { file->rdwr_short(livery_scheme_index); } else { livery_scheme_index = 0; } if(file->get_extended_version() >= 10) { if(file->is_saving()) { uint32 count = average_journey_times.get_count(); file->rdwr_long(count); if (file->get_extended_version() >= 13 || file->get_extended_revision() >= 14) { // New 32-bit journey times FOR(journey_times_map, const& iter, average_journey_times) { id_pair idp = iter.key; file->rdwr_short(idp.x); file->rdwr_short(idp.y); uint32 value = iter.value.count; file->rdwr_long(value); value = iter.value.total; file->rdwr_long(value); } } else { FOR(journey_times_map, const& iter, average_journey_times) { id_pair idp = iter.key; file->rdwr_short(idp.x); file->rdwr_short(idp.y); sint16 value = (sint16)iter.value.count; file->rdwr_short(value); if (iter.value.total == UINT32_MAX_VALUE) { value = -1; } else { value = (sint16)iter.value.total; } file->rdwr_short(value); } } } else { uint32 count = 0; file->rdwr_long(count); average_journey_times.clear(); if (file->get_extended_version() >= 13 || file->get_extended_revision() >= 14) { // New 32-bit journey times for (uint32 i = 0; i < count; i++) { id_pair idp; file->rdwr_short(idp.x); file->rdwr_short(idp.y); uint32 count; uint32 total; file->rdwr_long(count); file->rdwr_long(total); average_tpl<uint32> average; average.count = count; average.total = total; average_journey_times.put(idp, average); } } else { for (uint32 i = 0; i < count; i++) { id_pair idp; file->rdwr_short(idp.x); file->rdwr_short(idp.y); uint16 count; uint16 total; file->rdwr_short(count); file->rdwr_short(total); average_tpl<uint32> average; average.count = (uint32)count; if (total == 65535) { average.total = UINT32_MAX_VALUE; } else { average.total = (uint32)total; } average_journey_times.put(idp, average); } } } file->rdwr_longlong(arrival_time); //arrival_to_first_stop table // uint8 items_count = arrival_to_first_stop.get_count(); file->rdwr_byte(items_count); if (file->is_loading() ) { for (uint8 i = 0; i < items_count; ++i ) { sint64 item_value; file->rdwr_longlong( item_value ); arrival_to_first_stop.add_to_tail(item_value); } } else { for (uint8 i = 0; i < items_count; ++i ) { sint64 item_value = arrival_to_first_stop[i]; file->rdwr_longlong( item_value ); } } file->rdwr_long(current_loading_time); if( file->is_version_atleast(111, 0) ) { file->rdwr_byte(no_route_retry_count); if(no_route_retry_count > 7) { dbg->warning("convoi_t::rdwr()","Convoi %d: no_route_retry_count out of bounds: = %d, setting to 7",self.get_id(), no_route_retry_count); no_route_retry_count = 7; } } } else { arrival_time = welt->get_ticks(); } if ((file->get_extended_version() == 13 && file->get_extended_revision() >= 2) || file->get_extended_version() >= 14) { if(file->is_saving()) { uint32 count = journey_times_history.get_count(); file->rdwr_long(count); FOR(times_history_map, const& iter, journey_times_history) { departure_point_t idp = iter.key; file->rdwr_short(idp.x); file->rdwr_short(idp.y); times_history_data_t value = iter.value; for (int j = 0; j < TIMES_HISTORY_SIZE; j++) { uint32 time = value.get_entry(j); file->rdwr_long(time); } } } else { uint32 count = 0; file->rdwr_long(count); journey_times_history.clear(); for (uint32 i = 0; i < count; i++) { departure_point_t idp; file->rdwr_short(idp.x); file->rdwr_short(idp.y); times_history_data_t data; for (int j = 0; j < TIMES_HISTORY_SIZE; j++) { uint32 time; file->rdwr_long(time); data.set(j, time); } journey_times_history.put(idp, data); } } } if( file->is_version_atleast(111, 1) && file->get_extended_version() == 0 ) { uint32 dummy = 0; file->rdwr_long( dummy ); // Was distance_since_last_stop file->rdwr_long( dummy ); // Was sum_speed_limit } if( file->is_version_atleast(111, 2) && file->get_extended_version() == 0 ) { // Was maxspeed_average_count uint32 dummy = 0; file->rdwr_long(dummy); } if( file->is_version_atleast(111, 2) && file->get_extended_version() >= 10 ) { file->rdwr_short(last_stop_id); v.rdwr(file); } if( file->is_version_atleast(111, 3) ) { file->rdwr_short( next_stop_index ); file->rdwr_short( next_reservation_index ); } #ifdef SPECIAL_RESCUE_12_5 if(file->get_extended_version() >= 12 && file->is_saving()) #else if(file->get_extended_version() >= 12) #endif { file->rdwr_bool(needs_full_route_flush); } #ifdef SPECIAL_RESCUE_12_6 if(file->get_extended_version() >= 12 && file->is_saving()) #else if(file->get_extended_version() >= 12) #endif { bool ic = is_choosing; file->rdwr_bool(ic); is_choosing = ic; file->rdwr_long(max_signal_speed); last_signal_pos.rdwr(file); if(file->get_extended_revision() >= 8 || file->get_extended_version() >= 13) { // This allows for compatibility with saves from the reserving-through branch uint8 has_reserved = 0; file->rdwr_byte(has_reserved); } } if ((file->get_extended_version() >= 13 && file->get_extended_revision() >= 5) || file->get_extended_version() >= 14) { bool lswd = last_stop_was_depot; file->rdwr_bool(lswd); last_stop_was_depot = lswd; } if (file->get_extended_version() >= 15 || (file->get_extended_version() >= 14 && file->get_extended_revision() >= 6)) { checked_tile_this_step.rdwr(file); } // This must come *after* all the loading/saving. if( file->is_loading() ) { recalc_catg_index(); calc_classes_carried(); } if (akt_speed < 0) { set_akt_speed(0); } } void convoi_t::show_info() { if( in_depot() ) { // Knightly : if ownership matches, we can try to open the depot dialog if( get_owner()==welt->get_active_player() ) { grund_t *const ground = welt->lookup( get_home_depot() ); if( ground ) { depot_t *const depot = ground->get_depot(); if( depot ) { depot->show_info(); // try to activate this particular convoy in the depot depot_frame_t *const frame = dynamic_cast<depot_frame_t *>( win_get_magic( (ptrdiff_t)depot ) ); if( frame ) { frame->activate_convoi(self); } } } } } else { if( env_t::verbose_debug >= log_t::LEVEL_ERROR ) { dump(); } create_win( new convoi_info_t(self), w_info, magic_convoi_info+self.get_id() ); } } #if 0 void convoi_t::info(cbuffer_t & buf) const { const vehicle_t* v = front(); if (v != NULL) { char tmp[128]; buf.printf("\n %d/%dkm/h (%1.2f$/km)\n", speed_to_kmh(min_top_speed), v->get_desc()->get_topspeed(), get_running_cost(welt) / 100.0F); buf.printf(" %s: %ikW\n", translator::translate("Leistung"), sum_power ); buf.printf(" %s: %i (%i) t\n", translator::translate("Gewicht"), sum_weight, sum_gesamtweight-sum_weight ); buf.printf(" %s: ", translator::translate("Gewinn") ); money_to_string( tmp, (double)jahresgewinn ); buf.append(tmp); buf.append("\n"); } } #endif // sort order of convoi void convoi_t::set_sortby(uint8 sort_order) { freight_info_order = sort_order; freight_info_resort = true; } // caches the last info; resorts only when needed // since the sorting of the classes is done here, we simply have two get_freight_info's... void convoi_t::get_freight_info(cbuffer_t & buf) { if (freight_info_resort) { freight_info_resort = false; // rebuilt the list with goods ... vector_tpl<ware_t> total_fracht; vector_tpl<ware_t> pass_fracht[255]; vector_tpl<ware_t> mail_fracht[255]; size_t const n = goods_manager_t::get_count(); ALLOCA(uint32, max_loaded_waren, n); MEMZERON(max_loaded_waren, n); size_t const pass_classes = goods_manager_t::passengers->get_number_of_classes(); size_t const mail_classes = goods_manager_t::mail->get_number_of_classes(); ALLOCA(uint32, max_loaded_pass, pass_classes); MEMZERON(max_loaded_pass, pass_classes); ALLOCA(uint32, max_loaded_mail, mail_classes); MEMZERON(max_loaded_mail, mail_classes); bool sort_by_accommodation = env_t::default_sortmode == convoi_info_t::sort_mode_t::by_accommodation_detail || env_t::default_sortmode == convoi_info_t::sort_mode_t::by_accommodation_via ? true : false; for (uint32 i = 0; i != vehicle_count; ++i) { const vehicle_t* v = vehicle[i]; bool pass_veh = v->get_cargo_type() == goods_manager_t::passengers; bool mail_veh = v->get_cargo_type() == goods_manager_t::mail; const goods_desc_t* ware_desc = v->get_desc()->get_freight_type(); const uint16 menge = v->get_desc()->get_total_capacity(); const uint8 classes_to_check = v->get_desc()->get_number_of_classes(); // first add to capacity indicator if (sort_by_accommodation) { if (pass_veh) { for (uint8 j = 0; j < pass_classes; j++) { max_loaded_pass[v->get_reassigned_class(j)] += v->get_accommodation_capacity(j); } } else if (mail_veh) { for (uint8 j = 0; j < mail_classes; j++) { max_loaded_mail[v->get_reassigned_class(j)] += v->get_accommodation_capacity(j); } } else if (menge > 0 && ware_desc != goods_manager_t::none) { max_loaded_waren[ware_desc->get_index()] += menge; } } else { if (menge > 0 && ware_desc != goods_manager_t::none) { max_loaded_waren[ware_desc->get_index()] += menge; } } // for (uint8 j = 0; j < classes_to_check; j++) { // then add the actual load FOR(slist_tpl<ware_t>, ware, v->get_cargo(j)) { // if != 0 we could not join it to existing => load it if (ware.menge != 0) { if (sort_by_accommodation && pass_veh) { pass_fracht[v->get_reassigned_class(j)].append(ware); } else if (sort_by_accommodation && mail_veh) { mail_fracht[v->get_reassigned_class(j)].append(ware); } else { total_fracht.append(ware); } } } } INT_CHECK("simconvoi 2643"); } buf.clear(); // apend info on total capacity slist_tpl <ware_t>capacity; for (size_t i = 0; i != n; ++i) { if (max_loaded_waren[i] > 0 && i != goods_manager_t::INDEX_NONE) { ware_t ware(goods_manager_t::get_info(i)); ware.menge = max_loaded_waren[i]; // append to category? slist_tpl<ware_t>::iterator j = capacity.begin(); slist_tpl<ware_t>::iterator end = capacity.end(); while (j != end && j->get_desc()->get_catg_index() < ware.get_desc()->get_catg_index()) ++j; if (j != end && j->get_desc()->get_catg_index() == ware.get_desc()->get_catg_index()) { j->menge += max_loaded_waren[i]; } else { // not yet there capacity.insert(j, ware); } } } // show new info if (sort_by_accommodation) { ware_t ware; for (uint8 i = 0; i < pass_classes; i++) { // We pass on details of all classes - freight_list_sorter will ignore the unused ones (unless they are incorrectly occupied!) // Display from highest class to lowest class uint8 j = pass_classes - i - 1; ware = goods_manager_t::passengers; freight_list_sorter_t::sort_freight(pass_fracht[j], buf, (freight_list_sorter_t::sort_mode_t)freight_info_order, NULL, "loaded", j, max_loaded_pass[j], &ware); } for (uint8 i = 0; i < mail_classes; i++) { uint8 j = mail_classes - i - 1; ware = goods_manager_t::mail; freight_list_sorter_t::sort_freight(mail_fracht[j], buf, (freight_list_sorter_t::sort_mode_t)freight_info_order, NULL, "loaded", j, max_loaded_mail[j], &ware); } } freight_list_sorter_t::sort_freight(total_fracht, buf, (freight_list_sorter_t::sort_mode_t)freight_info_order, &capacity, "loaded", 0, 0, NULL); } } void convoi_t::get_freight_info_by_class(cbuffer_t &) { } void convoi_t::open_schedule_window( bool show ) { DBG_MESSAGE("convoi_t::open_schedule_window()","Id = %ld, State = %d, Lock = %d",self.get_id(), state, wait_lock); // manipulation of schedule not allowed while: // - just starting // - a line update is pending // - the convoy is in the process of finding a route (multi-threaded) if (is_locked() || line_update_pending.is_bound()) { if (show) { create_win( new news_img("Not allowed!\nThe convoi's schedule can\nnot be changed currently.\nTry again later!"), w_time_delete, magic_none ); } return; } set_akt_speed(0); // stop the train ... if(state!=INITIAL) { state = EDIT_SCHEDULE; } wait_lock = 25000; alte_direction = front()->get_direction(); // Added by : Knightly // Purpose : To keep a copy of the original schedule before opening schedule window if (schedule) { old_schedule = schedule->copy(); } else { schedule = create_schedule(); } if( show ) { // Open schedule dialog create_win( new schedule_gui_t(schedule,get_owner(),self), w_info, (ptrdiff_t)schedule ); // TODO: what happens if no client opens the window?? } schedule->start_editing(); } bool convoi_t::pruefe_alle() //"examine all" (Babelfish) /** * Check validity of convoi with respect to vehicle constraints */ { bool ok = vehicle_count == 0 || front()->get_desc()->can_follow(NULL); unsigned i; const vehicle_t* pred = front(); for(i = 1; ok && i < vehicle_count; i++) { const vehicle_t* v = vehicle[i]; ok = pred->get_desc()->can_lead(v->get_desc()) && v->get_desc()->can_follow(pred->get_desc()); pred = v; } if(ok) { ok = pred->get_desc()->can_lead(NULL); } return ok; } /** * Kontrolliert Be- und Entladen * * minimum_loading is now stored in the object (not returned) */ void convoi_t::laden() //"load" (Babelfish) { // Calculate average speed and journey time // @author: jamespetts halthandle_t halt = haltestelle_t::get_halt(schedule->get_current_entry().pos, owner); halthandle_t this_halt = haltestelle_t::get_halt(get_pos(), owner); if(!this_halt.is_bound()) { suche_neue_route(); dbg->warning("void convoi_t::laden()", "%s trying to load at %s when not at a halt; rerouting", get_name(), halt.is_bound() ? halt->get_name() : "none"); return; } // The calculation of the journey distance does not need to use normalised halt locations for comparison, so // a more accurate distance can be used. Query whether the formula from halt_detail.cc should be used here instead // (That formula has the effect of finding the distance between the nearest points of two halts). departure_point_t departure(schedule->get_current_stop(), reverse_schedule); const koord3d pos3d = front()->get_pos(); koord pos; halthandle_t new_halt = haltestelle_t::get_halt(pos3d, front()->get_owner()); if(new_halt.is_bound() || !halt.is_bound()) { pos = pos3d.get_2d(); if(halt != new_halt) { halt = new_halt; } } else { pos = halt->get_basis_pos(); } const uint32 journey_distance = shortest_distance(front()->get_pos().get_2d(), front()->last_stop_pos.get_2d()); const uint16 this_halt_id = halt.get_id(); // last_stop_pos will be set to get_pos().get_2d() in hat_gehalten (called from inside halt->request_loading later) // so code inside if will be executed once. At arrival time. minivec_tpl<uint8> departure_entries_to_remove(schedule->get_count()); // Update journey times. // loading in other states such as WAITING_FOR_CLEARANCE and REVERSING are non-scheduled and should be excluded. // perhaps the state == LOADING check could be replaced by a parameter. if(journey_distance > 0 && state == LOADING) { arrival_time = welt->get_ticks(); inthashtable_tpl<uint16, sint64, N_BAGS_SMALL> best_times_in_schedule; // Key: halt ID; value: departure time. FOR(departure_map, const& iter, departures) { const sint64 journey_time_ticks = arrival_time - iter.value.departure_time; if(iter.key.entry > schedule->get_count() - 1) { // For some reason, the schedule has been changed but the departures have not been cleared. // Abort this operation, or else it will crash on the next line, and clear departuers. departures.clear(); break; } const koord3d halt_position = schedule->entries.get_element(iter.key.entry).pos; const halthandle_t departure_halt = haltestelle_t::get_halt(halt_position, front()->get_owner()); if(departure_halt.is_bound()) { if(best_times_in_schedule.is_contained(departure_halt.get_id())) { // There is more than one departure from this stop to here. Check which is the fastest. const sint64 other_journey_time_ticks = arrival_time - best_times_in_schedule.get(departure_halt.get_id()); if(departures_already_booked.get(id_pair(departure_halt.get_id(), this_halt_id)) != iter.value.departure_time) { if(journey_time_ticks < other_journey_time_ticks) { best_times_in_schedule.set(departure_halt.get_id(), iter.value.departure_time); } } else { // If the best departure is already booked, do not allow lesser departures to be registered. best_times_in_schedule.remove(departure_halt.get_id()); } } else if((departures_already_booked.get(id_pair(departure_halt.get_id(), this_halt_id)) < iter.value.departure_time)) { best_times_in_schedule.put(departure_halt.get_id(), iter.value.departure_time); } } } uint8 schedule_entry = schedule->get_current_stop(); bool rev_rev = !reverse_schedule; // decrement(see negation of reverse_schedule) index until previous halt schedule->increment_index_until_next_halt(front()->get_owner(), &schedule_entry, &rev_rev); departure_point_t this_departure(schedule_entry, reverse_schedule); sint64 latest_journey_time; const bool departure_missing = !departures.is_contained(this_departure); const sint32 journey_distance_meters = journey_distance * welt->get_settings().get_meters_per_tile(); if(departure_missing) { //Fall back to ultimate backup: half maximum speed. const sint32 assumed_average_speed = speed_to_kmh(get_min_top_speed()) * 5; // (Equivalent to / 2 * 10) latest_journey_time = (journey_distance_meters * 6) / assumed_average_speed; } else { latest_journey_time = welt->ticks_to_tenths_of_minutes(arrival_time - departures.get(this_departure).departure_time); } if(latest_journey_time <= 0) { // Necessary to prevent divisions by zero. // This code should never be reached. dbg->warning("void convoi_t::laden()", "Journey time is %i for %s.", latest_journey_time, get_name()); latest_journey_time = 1; } if(journey_times_between_schedule_points.is_contained(this_departure)) { // The autoreduce function has the effect of making older timings less and less significant to this figure. journey_times_between_schedule_points.access(this_departure)->add_autoreduce((uint16)latest_journey_time, timings_reduction_point); } else { average_tpl<uint16> ave; ave.add((uint16)latest_journey_time); journey_times_between_schedule_points.put(this_departure, ave); } if (!journey_times_history.is_contained(this_departure)) { journey_times_history.put(this_departure, times_history_data_t()); } journey_times_history.access(this_departure)->put(latest_journey_time); if (line.is_bound()) { times_history_map &line_history = line->get_journey_times_history(); if (!line_history.is_contained(this_departure)) { line_history.put(this_departure, times_history_data_t()); } line_history.access(this_departure)->put(latest_journey_time); } const sint32 average_speed = (journey_distance_meters * 3) / ((sint32)latest_journey_time * 5); // For some odd reason, in some cases, laden() is called when the journey time is // excessively low, resulting in perverse average speeds and journey times. // Testing shows that this still recurs even after the enhanced point to point // system (April 2014). if(average_speed <= get_vehicle_summary().max_speed) { book(average_speed, CONVOI_AVERAGE_SPEED); typedef inthashtable_tpl<uint16, sint64, N_BAGS_SMALL> int_map; FOR(int_map, const& iter, best_times_in_schedule) { id_pair pair(iter.key, this_halt_id); const sint32 this_journey_time = (uint32)welt->ticks_to_tenths_of_minutes(arrival_time - iter.value); departures_already_booked.set(pair, iter.value); const average_tpl<uint32> *average_check = average_journey_times.access(pair); if(!average_check) { average_tpl<uint32> average_new; average_new.add(this_journey_time); average_journey_times.put(pair, average_new); } else { average_journey_times.access(pair)->add_autoreduce(this_journey_time, timings_reduction_point); } if(line.is_bound()) { const average_tpl<uint32> *average = get_average_journey_times().access(pair); if(!average) { average_tpl<uint32> average_new; average_new.add(this_journey_time); get_average_journey_times().put(pair, average_new); } else { get_average_journey_times().access(pair)->add_autoreduce(this_journey_time, timings_reduction_point); } } } } // Recalculate comfort // This is an average of comfort for all classes, // weighted by capacity. // TODO: Consider whether to have separate graphs for different classes of comfort. const uint8 number_of_classes = goods_manager_t::passengers->get_number_of_classes(); sint64 comfort_capacity = 0; uint16 class_capacity; sint64 total_capacity = 0; for (uint8 i = 0; i < number_of_classes; i++) { class_capacity = 0; for (uint8 j = 0; j < vehicle_count; j++) { if (vehicle[j]->get_cargo_type()->get_catg_index() == 0) { class_capacity += vehicle[j]->get_accommodation_capacity(i); } } total_capacity += class_capacity; const uint8 comfort = get_comfort(i, true); comfort_capacity += (comfort * class_capacity); } const sint64 comfort = total_capacity > 0 ? comfort_capacity / total_capacity : 0; if (comfort) { book(comfort, CONVOI_COMFORT); } FOR(departure_map, & iter, departures) { // Accumulate distance since each previous stop on the schedule iter.value.add_overall_distance(journey_distance); } if(state == EDIT_SCHEDULE) { return; } } if(halt.is_bound()) { //const player_t* owner = halt->get_owner(); const grund_t* gr = welt->lookup(schedule->get_current_entry().pos); const weg_t *w = gr ? gr->get_weg(schedule->get_waytype()) : NULL; bool tram_stop_public = false; if(schedule->get_waytype() == tram_wt) { const grund_t* gr = welt->lookup(schedule->get_current_entry().pos); const weg_t *street = gr ? gr->get_weg(road_wt) : NULL; if(street && (street->get_owner() == get_owner() || street->get_owner() == NULL || street->get_owner()->allows_access_to(get_owner()->get_player_nr()))) { tram_stop_public = true; } } const player_t *player = w ? w->get_owner() : NULL; if(halt->check_access(get_owner()) || (w && player == NULL) || (w && player->allows_access_to(get_owner()->get_player_nr())) || tram_stop_public) { // loading/unloading ... // NOTE: Revenue is calculated here. halt->request_loading(self); } } else { // If there is no halt here, nothing will call request loading and the state can never be changed. state = CAN_START; } if(wait_lock == 0) { wait_lock = WTT_LOADING; } } sint64 convoi_t::calc_revenue(const ware_t& ware, array_tpl<sint64> & apportioned_revenues, uint8 g_class) { // Cannot not charge for journey if the journey distance is more than a certain proportion of the straight line distance. // This eliminates the possibility of cheating by building circuitous routes, or the need to prevent that by always using // the straight line distance, which makes the game difficult and unrealistic. // If the origin has been deleted since the packet departed, then the best that we can do is guess by // trebling the distance to the last stop. uint32 max_distance; if(ware.get_last_transfer().is_bound()) { max_distance = shortest_distance(ware.get_last_transfer()->get_basis_pos(), front()->get_pos().get_2d()) * 2; } else { max_distance = shortest_distance(front()->last_stop_pos.get_2d(), front()->get_pos().get_2d()) * 3; } // Because the "departures" hashtable now contains not halts but timetable entries, it is necessary to iterate // through the timetable to find the last time that this convoy called at the stop in question. uint8 entry = schedule->get_current_stop(); bool rev = !reverse_schedule; // Must be negative as going through the schedule backwards: must reverse this when used. const int schedule_count = schedule->is_mirrored() ? schedule->get_count() * 2 : schedule->get_count(); departure_data_t dep; for(int i = 0; i < schedule_count; i++) { schedule->increment_index(&entry, &rev); const uint16 halt_id = haltestelle_t::get_halt(schedule->entries[entry].pos, owner).get_id(); if(halt_id == ware.get_last_transfer().get_id()) { dep = departures.get(departure_point_t(entry, !rev)); break; } } uint32 travel_distance = dep.get_overall_distance(); if(travel_distance == 0) { // Something went wrong, make a wild guess // (This can happen when the departure halt has been deleted // or made inaccessible to this player since departure). travel_distance = max_distance / 2; } const uint32 travel_distance_meters = travel_distance * welt->get_settings().get_meters_per_tile(); const uint32 revenue_distance = min(travel_distance, max_distance); // First try to get the journey minutes and average speed // for the point to point trip. If that fails use line average. // (neroden really believes we should use the minutes and speed for THIS trip.) // (It saves vast amounts of computational effort, // and gives the player a quicker response to improved service.) sint64 journey_tenths = 0; sint64 average_speed; bool valid_journey_time = false; if(ware.get_last_transfer().is_bound()) { const grund_t* gr = welt->lookup(front()->get_pos()); if (gr) { id_pair my_ordered_pair = id_pair(ware.get_last_transfer().get_id(), gr->get_halt().get_id()); journey_tenths = get_average_journey_times().get(my_ordered_pair).get_average(); if (journey_tenths != 0) { // No unreasonably short journeys... average_speed = kmh_from_meters_and_tenths(travel_distance_meters, journey_tenths); if(average_speed > speed_to_kmh(get_min_top_speed())) { dbg->warning("sint64 convoi_t::calc_revenue", "Average speed (%i) for %s exceeded maximum speed (%i); falling back to overall average", average_speed, get_name(), speed_to_kmh(get_min_top_speed())); } else { // We seem to have a believable speed... if(average_speed == 0) { average_speed = 1; } valid_journey_time = true; } } } } if(!valid_journey_time) { // Fallback to the overall average speed for the line under several situations: // - if there are no data for point-to-point timings; // - if the point-to-point timings are less than 1/10 of a minute (unreasonably short) // - if the average speed is faster than the top speed of the convoi (absurdity) if(!line.is_bound()) { // No line - must use convoy if(financial_history[1][CONVOI_AVERAGE_SPEED] == 0) { average_speed = financial_history[0][CONVOI_AVERAGE_SPEED]; } else { average_speed = financial_history[1][CONVOI_AVERAGE_SPEED]; } } else { if(line->get_finance_history(1, LINE_AVERAGE_SPEED) == 0) { average_speed = line->get_finance_history(0, LINE_AVERAGE_SPEED); } else { average_speed = line->get_finance_history(1, LINE_AVERAGE_SPEED); } } if(average_speed == 0) { average_speed = 1; } journey_tenths = tenths_from_meters_and_kmh(travel_distance_meters, average_speed); } sint64 starting_distance; if (ware.get_origin().is_bound()) { sint64 distance_from_ultimate_origin = (sint64)shortest_distance(ware.get_origin()->get_basis_pos(), front()->get_pos().get_2d()); starting_distance = distance_from_ultimate_origin - (sint64)revenue_distance; if (starting_distance < 0) { // Artifact of convoluted routing starting_distance = 0; } } else { starting_distance = 0; } const uint32 revenue_distance_meters = revenue_distance * welt->get_settings().get_meters_per_tile(); const uint32 starting_distance_meters = starting_distance * welt->get_settings().get_meters_per_tile(); const goods_desc_t* goods = ware.get_desc(); sint64 fare; if (ware.is_passenger()) { // First get our comfort. // Note: This takes into account overcrowding. const uint8 comfort = get_comfort(g_class); // Now, get our catering level. const uint8 catering_level = get_catering_level(goods->get_catg_index()); // Finally, get the fare. fare = goods->get_total_fare(revenue_distance_meters, starting_distance_meters, comfort, catering_level, g_class, journey_tenths); } else if(ware.is_mail()) { // Get our "TPO" level. const uint8 catering_level = get_catering_level(goods->get_catg_index()); // Finally, get the fare. fare = goods->get_total_fare(revenue_distance_meters, starting_distance_meters, 0u, catering_level, g_class, journey_tenths); } else { // Freight ignores comfort and catering and TPO. // So here we can skip the complicated version for speed. fare = goods->get_total_fare(revenue_distance_meters, starting_distance_meters); } // Note that fare comes out in units of 1/4096 of a simcent, for computational precision // Finally multiply by the number of items. const sint64 revenue = fare * (sint64)ware.menge; // Now apportion the revenue. uint32 total_way_distance = 0; for(uint8 i = 0; i < MAX_PLAYER_COUNT + 2; i ++) { if (i == MAX_PLAYER_COUNT) { // MAX_PLAYER_COUNT as an index is used for the overall distance - in a different unit. continue; } total_way_distance += dep.get_way_distance(i); } // The apportioned revenue array is passed in. It should be the right size already. // Make sure our returned array is the right size (should do nothing) apportioned_revenues.resize(MAX_PLAYER_COUNT); // It will have some accumulated revenues in it from unloading previous vehicles in the same convoi. for(uint8 i = 0; i < MAX_PLAYER_COUNT; i ++) { if(owner->get_player_nr() == i) { // Never apportion revenue to the convoy-owning player // Revenues from unowned ways/public toll free ways // are also discounted, but these are MAX_PLAYER_COUNT + 1, // so they are not reached in this FOR loop. continue; } // Now, if the player's tracks were actually used, apportion revenue uint32 player_way_distance = dep.get_way_distance(i); if(player_way_distance > 0) { // We allocate even for players who may not exist; we'll check before paying them. apportioned_revenues[i] += (revenue * player_way_distance) / total_way_distance; } } return revenue; } /** * convoi an haltestelle anhalten * "Convoi stop at stop" (Google translations) */ void convoi_t::hat_gehalten(halthandle_t halt) { grund_t *gr = welt->lookup(front()->get_pos()); // now find out station length uint16 vehicles_loading=0; if( gr->is_water() ) { // harbour has any size vehicles_loading = vehicle_count; } else { // calculate real station length // and numbers of vehicles that can be (un)loaded koord zv = koord( ribi_t::backward(front()->get_direction()) ); koord3d pos = front()->get_pos(); // start on bridge? pos.z += gr->get_weg_yoff() / TILE_HEIGHT_STEP; // difference between actual station length and vehicle lenghts sint16 station_length = -vehicle[vehicles_loading]->get_desc()->get_length(); do { // advance one station tile station_length += CARUNITS_PER_TILE; while(station_length >= 0) { vehicles_loading++; if (vehicles_loading < vehicle_count) { station_length -= vehicle[vehicles_loading]->get_desc()->get_length(); } else { // all vehicles fit into station goto station_tile_search_ready; } } // search for next station tile pos += zv; gr = welt->lookup(pos); if (gr == NULL) { gr = welt->lookup(pos-koord3d(0,0,1)); if (gr == NULL) { gr = welt->lookup(pos-koord3d(0,0,2)); } if (gr && (pos.z != gr->get_hoehe() + gr->get_weg_yoff()/TILE_HEIGHT_STEP) ) { // not end/start of bridge break; } } } while( gr && gr->get_halt() == halt ); // finished station_tile_search_ready: ; } last_stop_id = halt.get_id(); halt->update_alternative_seats(self); // only load vehicles in station // Save the old stop position; don't load/unload again if we don't move. const koord3d old_last_stop_pos = front()->last_stop_pos; uint16 changed_loading_level = 0; // We only unload & load vehicles which are within the station. // To fix: this creates undesired behavior for long trains, because the // cars in the back will not load/unload in "short" platforms. // // Proposed fix: load passengers from back of the train to the front, // selectively delaying loading passengers destined for "short" platforms // in order to get them into the cars in the front of the station. Just like // real conductors do. // // Query: this makes sense only for passenger carriages with gangways. // Is it really sensible to implement this for all vehicles, including // older passenger carriages without gangways, mail carriages and goods // trucks, where passing through the train is not possible? // // // This will require tracking platform length in the schedule object. // --neroden // First, unload vehicles. sint64 accumulated_revenue = 0; // This holds the revenues as apportioned to different players by track // Initialize it to the correct size and blank out all entries // It will be added to by the load_cargo method for each vehicle array_tpl<sint64> apportioned_revenues (MAX_PLAYER_COUNT, 0); for(int i = 0; i < vehicles_loading ; i++) { vehicle_t* v = vehicle[i]; // Reset last_stop_pos for all vehicles. koord3d pos = v->get_pos(); if(haltestelle_t::get_halt(pos, v->get_owner()).is_bound()) { v->last_stop_pos = pos; } else { v->last_stop_pos = halt->get_basis_pos3d(); } // hat_gehalten can be called when the convoy hasn't moved... at all. // We should avoid the unloading code when this happens (for speed). if(old_last_stop_pos != front()->get_pos()) { //Unload sint64 revenue_from_unloading = 0; uint16 amount_unloaded = v->unload_cargo(halt, revenue_from_unloading, apportioned_revenues); changed_loading_level += amount_unloaded; // Convert from units of 1/4096 of a simcent to units of ONE simcent. Should be FAST (powers of two). sint64 revenue_cents_from_unloading = (revenue_from_unloading + 2048ll) / 4096ll; if (amount_unloaded && revenue_cents_from_unloading == 0) { // if we unloaded something, provide some minimum revenue. But not if we unloaded nothing. revenue_cents_from_unloading = 1; } // This call needs to be here, per-vehicle, in order to record different freight types properly. owner->book_revenue( revenue_cents_from_unloading, front()->get_pos().get_2d(), get_schedule()->get_waytype(), v->get_cargo_type()->get_index() ); // The finance code will add up the on-screen messages // But add up the total for the port and station use charges accumulated_revenue += revenue_cents_from_unloading; book(revenue_cents_from_unloading, CONVOI_PROFIT); book(revenue_cents_from_unloading, CONVOI_REVENUE); } } if(no_load) { for(int i = 0; i < vehicles_loading ; i++) { vehicle_t* v = vehicle[i]; // Do not load, but call load_cargo() to recalculate vehicle weight as there might be *un*loading happening. v->load_cargo(halthandle_t()); } } else // not "no_load" { bool skip_catg[255] = {false}; lines_loaded_t line_data; line_data.line = get_line(); if(line_data.line.is_bound()) { line_data.reversed = is_reversed(); line_data.current_stop = get_schedule()->get_current_stop(); // flag all categories that have already had all available freight loaded onto convois on this line from this halt this step FOR(vector_tpl<lines_loaded_t>, const& i, halt->access_lines_loaded()) { if(i.line == line_data.line && i.reversed == line_data.reversed && i.current_stop == line_data.current_stop) { skip_catg[i.catg_index] = true; } } } // Three passes at loading vehicles: // (1) without overcrowding, and only to the correct class; // (2) without overcrowding, but to any available lower class of accommodation; and // (3) with overcrowding, to any available equal or lower class of accommodation. for(int j = 0; j < 3; j++) { const bool use_lower_classes = (j >= 1); const bool overcrowd = (j == 2); for(int i = 0; i < vehicles_loading ; i++) { vehicle_t* v = vehicle[i]; const uint8 catg_index = v->get_cargo_type()->get_catg_index(); if(!skip_catg[catg_index]) { bool skip_convois = false; bool skip_vehicles = false; changed_loading_level += v->load_cargo(halt, overcrowd, &skip_convois, &skip_vehicles, use_lower_classes); if(skip_convois || skip_vehicles) { // Not enough freight was available to fill vehicle, or the stop can't supply this type of cargo: don't try to load this category again from this halt onto vehicles in convois on this line this step. skip_catg[catg_index] = true; if(!skip_vehicles && line_data.line.is_bound()) { line_data.catg_index = catg_index; halt->access_lines_loaded().append( line_data ); } } } } } } if(changed_loading_level > 0) { freight_info_resort = true; } if( changed_loading_level ) { halt->recalc_status(); } // any loading went on? calc_loading(); loading_limit = schedule->get_current_entry().minimum_loading; // minimum_loading = max. load. const bool wait_for_time = schedule->get_current_entry().wait_for_time; highest_axle_load = calc_highest_axle_load(); // Bernd Gabriel, Mar 10, 2010: was missing. if( old_last_stop_pos != front()->get_pos() ) { // Only calculate the loading time once, on arriving at the stop: // otherwise, the change in the vehicle's load will not be calculated // correctly. current_loading_time = calc_current_loading_time(changed_loading_level); } if(accumulated_revenue) { jahresgewinn += accumulated_revenue; // Check the apportionment of revenue. // The proportion paid to other players is // not deducted from revenue, but rather // added as a "WAY_TOLL" cost. for(int i = 0; i < MAX_PLAYER_COUNT; i ++) { if(i == owner->get_player_nr()) { continue; } player_t* player = welt->get_player(i); // Only pay tolls to players who actually exist if(player && apportioned_revenues[i]) { // This is the screwy factor of 3000 -- fix this sometime sint64 modified_apportioned_revenue = (apportioned_revenues[i] + 1500ll) / 3000ll; modified_apportioned_revenue *= welt->get_settings().get_way_toll_revenue_percentage(); modified_apportioned_revenue /= 100; if(welt->get_active_player() == player) { player->add_money_message(modified_apportioned_revenue, front()->get_pos().get_2d()); } player->book_toll_received(modified_apportioned_revenue, get_schedule()->get_waytype() ); owner->book_toll_paid(-modified_apportioned_revenue, get_schedule()->get_waytype() ); book(-modified_apportioned_revenue, CONVOI_PROFIT); book(-modified_apportioned_revenue, CONVOI_WAYTOLL); } } // Apportion revenue for air/sea ports if(halt.is_bound() && halt->get_owner() != owner) { sint64 port_charge = 0; if(gr->is_water()) { // This must be a sea port. port_charge = (accumulated_revenue * welt->get_settings().get_seaport_toll_revenue_percentage()) / 100; } else if(front()->get_desc()->get_waytype() == air_wt) { // This is an aircraft - this must be an airport. port_charge = (accumulated_revenue * welt->get_settings().get_airport_toll_revenue_percentage()) / 100; } if (port_charge != 0) { if(welt->get_active_player() == halt->get_owner()) { halt->get_owner()->add_money_message(port_charge, front()->get_pos().get_2d()); } halt->get_owner()->book_toll_received(port_charge, get_schedule()->get_waytype() ); owner->book_toll_paid(-port_charge, get_schedule()->get_waytype() ); book(-port_charge, CONVOI_PROFIT); book(-port_charge, CONVOI_WAYTOLL); } } } if(state == REVERSING) { return; } const sint64 now = welt->get_ticks(); if(arrival_time > now || arrival_time == WAIT_INFINITE) { // This is a workaround for an odd bug the origin of which is as yet unclear. go_on_ticks = WAIT_INFINITE; arrival_time = now; if (arrival_time < WAIT_INFINITE) { dbg->warning("void convoi_t::hat_gehalten(halthandle_t halt)", "Arrival time in the future for %s at %s", get_name(), halt->get_name()); } } const sint64 reversing_time = schedule->get_current_entry().reverse > 0 ? (sint64)calc_reverse_delay() : 0ll; bool running_late = false; sint64 go_on_ticks_waiting = WAIT_INFINITE; const sint64 earliest_departure_time = arrival_time + ((sint64)current_loading_time - reversing_time); if(go_on_ticks == WAIT_INFINITE) { if(haltestelle_t::get_halt(get_pos(), get_owner()) != haltestelle_t::get_halt(schedule->get_current_entry().pos, get_owner())) { // Sometimes, for some reason, the loading method is entered with the wrong schedule entry. Make sure that this does not cause // convoys to become stuck trying to get a full load at stops where this is not possible (freight consumers, etc.). loading_limit = 0; } if((!loading_limit || loading_level >= loading_limit) && !wait_for_time) { // Simple case: do not wait for a full load or a particular time. go_on_ticks = std::max(earliest_departure_time, arrival_time); } else { // Wait for a % load or a spacing slot. sint64 go_on_ticks_spacing = WAIT_INFINITE; if(line.is_bound() && schedule->get_spacing() && line->count_convoys()) { // Departures/month const sint64 spacing = welt->ticks_per_world_month / (sint64)schedule->get_spacing(); const sint64 spacing_shift = (sint64)schedule->get_current_entry().spacing_shift * welt->ticks_per_world_month / (sint64)welt->get_settings().get_spacing_shift_divisor(); const sint64 wait_from_ticks = ((now + reversing_time - spacing_shift) / spacing) * spacing + spacing_shift; // remember, it is integer division sint64 queue_pos = halt.is_bound() ? halt->get_queue_pos(self) : 1ll; go_on_ticks_spacing = (wait_from_ticks + spacing * queue_pos) - reversing_time; } if(schedule->get_current_entry().waiting_time_shift > 0) { // Maximum wait time go_on_ticks_waiting = now + (welt->ticks_per_world_month >> (16ll - (sint64)schedule->get_current_entry().waiting_time_shift)) - (sint64)reversing_time; } if (schedule->get_spacing() && !line.is_bound()) { // Spacing should not be possible without a line, but this can occasionally occur. Without this, the convoy will wait forever. go_on_ticks_spacing = earliest_departure_time; } go_on_ticks = std::min(go_on_ticks_spacing, go_on_ticks_waiting); go_on_ticks = std::max(earliest_departure_time, go_on_ticks); running_late = wait_for_time && (go_on_ticks_waiting < go_on_ticks_spacing); if(running_late) { go_on_ticks = earliest_departure_time; } } } // loading is finished => maybe drive on bool can_go = false; can_go = loading_level >= loading_limit && (now >= go_on_ticks || !wait_for_time); //can_go = can_go || (now >= go_on_ticks_waiting && !wait_for_time); // This is pre-14 August 2016 code can_go = can_go || (now >= go_on_ticks && !wait_for_time); can_go = can_go || running_late; can_go = can_go || no_load; can_go = can_go && state != WAITING_FOR_CLEARANCE && state != WAITING_FOR_CLEARANCE_ONE_MONTH && state != WAITING_FOR_CLEARANCE_TWO_MONTHS; can_go = can_go && now > earliest_departure_time; if(can_go) { if(withdraw && (loading_level==0 || goods_catg_index.empty())) { // destroy when empty self_destruct(); return; } // add available capacity after loading(!) to statistics for (unsigned i = 0; i<vehicle_count; i++) { book(get_vehicle(i)->get_cargo_max()-get_vehicle(i)->get_total_cargo(), CONVOI_CAPACITY); } // Advance schedule advance_schedule(); state = ROUTING_1; //dbg->message("void convoi_t::hat_gehalten(halthandle_t halt)", "Convoy %s departing from stop %s at step %i. Its departure time is calculated as %ll", get_name(), halt.is_bound() ? halt->get_name() : "unknown", welt->get_steps(), go_on_ticks); } // reset the wait_lock if(state == ROUTING_1) { wait_lock = 0; } else if(state != WAITING_FOR_CLEARANCE && state != WAITING_FOR_CLEARANCE_ONE_MONTH && state != WAITING_FOR_CLEARANCE_TWO_MONTHS) // Do not add extra delay if the convoy has already decided to depart and is just waiting for clearance. { if (loading_limit > 0 && !wait_for_time) { wait_lock = (sint32) ((earliest_departure_time - now) / 2ll); } else { wait_lock = (sint32) ((go_on_ticks - now) / 2ll); } // The random extra wait here is designed to avoid processing every convoy at once wait_lock += (sint32)(self.get_id()) % 1024; if (wait_lock < 0 ) { wait_lock = 0; } else if(wait_lock > 8192 && go_on_ticks == WAIT_INFINITE) { // This is needed because the above calculation (from Standard) produces excessively // large numbers on occasions due to the conversion in Extended of certain values // (karte_t::ticks and go_on_ticks) to sint64. It would be better ultimately to fix that, // but this seems to work for now. wait_lock = 8192; } } } sint64 convoi_t::calc_sale_value() const { sint64 result = 0; for(uint i=0; i<vehicle_count; i++) { result += vehicle[i]->calc_sale_value(); } return result; } /** * Calculate loading_level and loading_limit. This depends on current state (loading or not). */ void convoi_t::calc_loading() { int fracht_max = 0; int fracht_menge = 0; int seats_max = 0; int seats_menge = 0; for(unsigned i=0; i<vehicle_count; i++) { const vehicle_t* v = vehicle[i]; if ( v->get_cargo_type() == goods_manager_t::passengers ) { seats_max += v->get_cargo_max(); seats_menge += v->get_total_cargo(); } else { fracht_max += v->get_cargo_max(); fracht_menge += v->get_total_cargo(); } } if (seats_max) { fracht_max += seats_max; fracht_menge += seats_menge; } loading_level = fracht_max > 0 ? (fracht_menge*100)/fracht_max : 100; loading_limit = 0; // will be set correctly from hat_gehalten() routine free_seats = seats_max > seats_menge ? seats_max - seats_menge : 0; // since weight has changed invalidate_weight_summary(); } // return the current average speed uint32 convoi_t::get_average_kmh() { halthandle_t halt = haltestelle_t::get_halt(schedule->get_current_entry().pos, owner); id_pair idp(last_stop_id, halt.get_id()); average_tpl<uint32>* avr = get_average_journey_times().access(idp); return avr ? avr->get_average() : get_vehicle_summary().max_speed; } /** * Schedule convoi for self destruction. Will be executed * upon next sync step */ void convoi_t::self_destruct() { line_update_pending = linehandle_t(); // does not bother to add it to a new line anyway ... // convois in depot are not contained in the map array! if(state==INITIAL) { destroy(); } else { state = SELF_DESTRUCT; wait_lock = 0; } } /** * Helper method to remove convois from the map that cannot * removed normally (i.e. by sending to a depot) anymore. * This is a workaround for bugs in the game. */ void convoi_t::destroy() { // can be only done here, with a valid convoihandle ... if(front()) { front()->set_convoi(NULL); } if( state == INITIAL ) { // in depot => not on map for( uint8 i = vehicle_count; i-- != 0; ) { vehicle[i]->set_flag( obj_t::not_on_map ); } } state = SELF_DESTRUCT; if(schedule!=NULL && !schedule->is_editing_finished()) { destroy_win((ptrdiff_t)schedule); } if( line.is_bound() ) { // needs to be done here to remove correctly ware catg from lines unset_line(); delete schedule; schedule = NULL; } // pay the current value, remove monthly maint waytype_t wt = front() ? front()->get_desc()->get_waytype() : ignore_wt; owner->book_new_vehicle( calc_sale_value(), get_pos().get_2d(), wt); for( uint8 i = vehicle_count; i-- != 0; ) { if( !vehicle[i]->get_flag( obj_t::not_on_map ) ) { // remove from rails/roads/crossings grund_t *gr = welt->lookup(vehicle[i]->get_pos()); vehicle[i]->set_last( true ); vehicle[i]->leave_tile(); if( gr && gr->ist_uebergang() ) { crossing_t* cr = gr->find<crossing_t>(); if(cr) { cr->release_crossing(vehicle[i]); } } vehicle[i]->set_flag( obj_t::not_on_map ); } player_t::add_maintenance(owner, -vehicle[i]->get_desc()->get_maintenance(), vehicle[i]->get_desc()->get_waytype()); vehicle[i]->discard_cargo(); vehicle[i]->cleanup(owner); delete vehicle[i]; } vehicle_count = 0; delete this; } /** * Debug info nach stderr */ void convoi_t::dump() const { dbg->debug("convoi::dump()", "\nvehicle_count = %d\n" "wait_lock = %d\n" "owner_n = %d\n" "akt_speed = %d\n" "sp_soll = %d\n" "state = %d\n" "statename = %s\n" "alte_direction = %d\n" "jahresgewinn = %ld\n" // %lld crashes mingw now, cast gewinn to long ... "name = '%s'\n" "line_id = '%d'\n" "schedule = '%p'", (int)vehicle_count, (int)wait_lock, (int)welt->sp2num(owner), (int)akt_speed, (int)sp_soll, (int)state, (const char *)(state_names[state]), (int)alte_direction, (long)(jahresgewinn/100), (const char *)name_and_id, line.is_bound() ? line.get_id() : 0, (const void *)schedule ); } void convoi_t::book(sint64 amount, convoi_cost_t cost_type) { assert( cost_type<MAX_CONVOI_COST); if(cost_type != CONVOI_AVERAGE_SPEED && cost_type != CONVOI_COMFORT) { // Summative types financial_history[0][cost_type] += amount; } else { // Average types if(rolling_average_count[cost_type] == 65535) { rolling_average_count[cost_type] /= 2; rolling_average[cost_type] /= 2; } rolling_average[cost_type] += (uint32)amount; rolling_average_count[cost_type] ++; const sint64 tmp = (sint64)rolling_average[cost_type] / (sint64)rolling_average_count[cost_type]; financial_history[0][cost_type] = tmp; } if (line.is_bound()) { line->book(amount, simline_t::convoi_to_line_catgory(cost_type) ); } } void convoi_t::init_financial_history() { for (int j = 0; j<MAX_CONVOI_COST; j++) { for (size_t k = MAX_MONTHS; k-- != 0;) { financial_history[k][j] = 0; } } } sint32 convoi_t::get_running_cost() const { sint32 running_cost = 0; for( unsigned i = 0; i < get_vehicle_count(); i++ ) { running_cost += vehicle[i]->get_running_cost(welt); } return running_cost; } sint32 convoi_t::get_per_kilometre_running_cost() const { sint32 running_cost = 0; for (unsigned i = 0; i<get_vehicle_count(); i++) { sint32 vehicle_running_cost = vehicle[i]->get_desc()->get_running_cost(welt); running_cost += vehicle_running_cost; } return running_cost; } uint32 convoi_t::get_fixed_cost() const { uint32 maint = 0; for (unsigned i = 0; i<get_vehicle_count(); i++) { maint += vehicle[i]->get_fixed_cost(welt); } return maint; } sint64 convoi_t::get_purchase_cost() const { sint64 purchase_cost = 0; for( unsigned i = 0; i < get_vehicle_count(); i++ ) { purchase_cost += vehicle[i]->get_desc()->get_value(); } return purchase_cost; } void convoi_t::clear_average_speed() { financial_history[0][CONVOI_AVERAGE_SPEED] = 0; financial_history[1][CONVOI_AVERAGE_SPEED] = 0; arrival_to_first_stop.clear(); } /** * set line * since convoys must operate on a copy of the route's schedule, we apply a fresh copy */ void convoi_t::set_line(linehandle_t org_line) { // to remove a convoi from a line, call unset_line(); passing a NULL is not allowed! bool need_to_reset_average_speed = false; if(!org_line.is_bound()) { return; } if(line.is_bound()) { unset_line(); need_to_reset_average_speed = true; } else { need_to_reset_average_speed = !schedule || !schedule->matches(welt, org_line->get_schedule()); // originally a lineless convoy -> unregister itself from stops as it now belongs to a line unregister_stops(); } if (need_to_reset_average_speed) { clear_average_speed(); } line_update_pending = org_line; check_pending_updates(); } /** * unset line * removes convoy from route without destroying its schedule * => no need to recalculate connections! */ void convoi_t::unset_line() { if( line.is_bound() ) { DBG_DEBUG("convoi_t::unset_line()", "removing old destinations from line=%d, schedule=%p",line.get_id(),schedule); line->remove_convoy(self); line = linehandle_t(); line_update_pending = linehandle_t(); } } // matches two halts; if the pos is not identical, maybe the halt still is the same bool convoi_t::matches_halt( const koord3d pos1, const koord3d pos2 ) { halthandle_t halt1 = haltestelle_t::get_halt(pos1, owner ); return pos1==pos2 || (halt1.is_bound() && halt1==haltestelle_t::get_halt( pos2, owner )); } // updates a line schedule and tries to find the best next station to go void convoi_t::check_pending_updates() { if( line_update_pending.is_bound() ) { // create dummy schedule if( schedule==NULL ) { schedule = create_schedule(); } schedule_t* new_fpl = line_update_pending->get_schedule(); new_fpl->set_current_stop(0); // A line should never have current_stop != 0 - this seems to happen on occasions, so reset it here before it causes trouble. uint8 current_stop = schedule->get_current_stop(); // save current position of schedule bool is_same = false; bool is_depot = false; koord3d current = koord3d::invalid, depot = koord3d::invalid; if (schedule->empty() || new_fpl->empty()) { // There was no entry or is no entry: go to the first stop current_stop = 0; } else { // something to check for ... current = schedule->get_current_entry().pos; if( current_stop<new_fpl->get_count() && current==new_fpl->entries[current_stop].pos ) { // next pos is the same => keep the convoi state is_same = true; } else { // check depot first (must also keept this state) is_depot = (welt->lookup(current) && welt->lookup(current)->get_depot() != NULL); if(is_depot) { // depot => current_stop+1 (depot will be restored later before this) depot = current; schedule->remove(); if(schedule->empty()) { goto end_check; } current = schedule->get_current_entry().pos; } /* there could be only one entry that matches best: * we try first same sequence as in old schedule; * if not found, we try for same nextnext station * (To detect also places, where only the platform * changed, we also compare the halthandle) */ if(current_stop > schedule->entries.get_count() - 1) { current_stop = schedule->entries.get_count() - 1; } uint8 index = current_stop; bool reverse = reverse_schedule; koord3d next[4]; for( uint8 i=0; i<4; i++ ) { next[i] = schedule->entries[index].pos; schedule->increment_index(&index, &reverse); } const int weights[4] = {3, 4, 2, 1}; int how_good_matching = 0; const uint8 new_count = new_fpl->get_count(); for( uint8 i=0; i<new_count; i++ ) { index = i; reverse = reverse_schedule; int quality = 0; for( uint8 j=0; j<4; j++ ) { quality += matches_halt(next[j],new_fpl->entries[index].pos) * weights[j]; new_fpl->increment_index(&index, &reverse); } if( quality>how_good_matching ) { // better match than previous: but depending of distance, the next number will be different index = i; reverse = reverse_schedule; for( uint8 j=0; j<4; j++ ) { if( matches_halt(next[j], new_fpl->entries[index].pos) ) if( new_fpl->entries[index].pos==next[j] ) { current_stop = index; break; } new_fpl->increment_index(&index, &reverse); } how_good_matching = quality; } } if(how_good_matching==0) { // nothing matches => take the one from the line current_stop = new_fpl->get_current_stop(); } // if we go to same, then we do not need route recalculation ... is_same = current_stop < new_fpl->get_count() && matches_halt(current,new_fpl->entries[current_stop].pos); } } end_check: // we may need to update the line and connection tables if( !line.is_bound() ) { line_update_pending->add_convoy(self); } line = line_update_pending; line_update_pending = linehandle_t(); // destroy old schedule and all related windows if(!schedule->is_editing_finished()) { schedule->copy_from( new_fpl ); schedule->set_current_stop(current_stop); // set new schedule current position to best match schedule->start_editing(); } else { schedule->copy_from( new_fpl ); schedule->set_current_stop(current_stop); // set new schedule current position to one before best match } if(is_depot) { // next was depot. restore it schedule->insert(welt->lookup(depot), 0, 0, 0, false, owner == welt->get_active_player()); // Insert will move the pointer past the inserted item; move back to it schedule->advance_reverse(); } if (state != INITIAL) { // remove wrong freight check_freight(); if(is_same || is_depot) { /* same destination * We are already there => keep current state */ } else { // need re-routing state = EDIT_SCHEDULE; } // make this change immediately if( !is_loading() ) { wait_lock = 0; } } } } /** * Register the convoy with the stops in the schedule */ void convoi_t::register_stops() { if(schedule) { FOR(minivec_tpl<schedule_entry_t>, const &i, schedule->entries) { halthandle_t const halt = haltestelle_t::get_halt(i.pos, get_owner()); if(halt.is_bound()) { halt->add_convoy(self); } } } } /** * Unregister the convoy from the stops in the schedule */ void convoi_t::unregister_stops() { if( schedule ) { FOR(minivec_tpl<schedule_entry_t>, const& i, schedule->entries) { halthandle_t const halt = haltestelle_t::get_halt(i.pos, get_owner()); if( halt.is_bound() ) { halt->remove_convoy(self); } } } } bool convoi_t::check_destination_reverse(route_t* current_route, route_t* target_rt) { route_t next_route; if(!current_route) { current_route = &route; } bool success = target_rt; if(!target_rt) { uint8 index = schedule->get_current_stop(); koord3d start_pos = schedule->entries[index].pos; bool rev = get_reverse_schedule(); schedule->increment_index(&index, &rev); const koord3d next_ziel = schedule->entries[index].pos; success = next_route.calc_route(welt, start_pos, next_ziel, front(), speed_to_kmh(get_min_top_speed()), get_highest_axle_load(), has_tall_vehicles(), get_tile_length(), welt->get_settings().get_max_route_steps(), get_weight_summary().weight / 1000) == route_t::valid_route; target_rt = &next_route; } if(success) { ribi_t::ribi old_dir = front()->calc_direction(current_route->at(current_route->get_count() - 2), current_route->back()); ribi_t::ribi new_dir = front()->calc_direction(target_rt->at(0), target_rt->at(1)); return old_dir & ribi_t::backward(new_dir); } else { return false; } } // set next stop before breaking will occur (or route search etc.) // currently only used for tracks void convoi_t::set_next_stop_index(uint16 n) { // stop at station or signals, not at waypoints if(n == INVALID_INDEX && !route.empty()) { // Find out if this schedule entry is a stop or a waypoint, waypoint: // do not brake at non-reversing waypoints bool reverse_waypoint = false; koord3d route_end = route.back(); bool update_line = false; if(front()->get_typ() != obj_t::air_vehicle) { const int count = schedule->get_count(); for(int i = 0; i < count; i ++) { schedule_entry_t &entries = schedule->entries[i]; if(entries.pos == route_end) { if(entries.reverse == -1) { grund_t* gr = world()->lookup(entries.pos); if (gr && gr->get_depot()) { schedule->set_reverse(1, i); } else { entries.reverse = check_destination_reverse() ? 1 : 0; schedule->set_reverse(entries.reverse, i); if (line.is_bound()) { schedule_t* line_schedule = line->get_schedule(); if (line_schedule->get_count() > i) { schedule_entry_t &line_entry = line_schedule->entries[i]; line_entry.reverse = entries.reverse; update_line = true; } } } } reverse_waypoint = entries.reverse == 1; break; } } if (update_line) { simlinemgmt_t::update_line(line); } } grund_t const* const gr = welt->lookup(route_end); if(gr && (gr->is_halt() || reverse_waypoint)) { if (front()->get_typ() != obj_t::rail_vehicle || (static_cast<const rail_vehicle_t *>(front())->get_working_method() != one_train_staff)) { n = route.get_count() - 1; } } } next_stop_index = n + 1; } /* including this route_index, the route was reserved the last time * currently only used for tracks */ void convoi_t::set_next_reservation_index(uint16 n) { // stop at station or signals, not at waypoints if( n==INVALID_INDEX ) { n = route.get_count()-1; } next_reservation_index = n; } /* * the current state saved as color * Meanings are BLACK (ok), WHITE (no convois), YELLOW (no vehicle moved), RED (last month income minus), DARK_PURPLE (convoy has overcrowded vehicles), BLUE (at least one convoi vehicle is obsolete) */ PIXVAL convoi_t::get_status_color() const { if(state==INITIAL) { // in depot/under assembly return SYSCOL_TEXT_HIGHLIGHT; } else if (skinverwaltung_t::alerts && (state == WAITING_FOR_CLEARANCE_ONE_MONTH || state == CAN_START_ONE_MONTH || get_state() == EMERGENCY_STOP || get_state() == WAITING_FOR_LOADING_THREE_MONTHS || get_state() == WAITING_FOR_LOADING_FOUR_MONTHS)) { // Display symbol if pakset has alert symbols. return COL_WARNING; } else if (state == WAITING_FOR_CLEARANCE_TWO_MONTHS || state == CAN_START_TWO_MONTHS || get_state() == NO_ROUTE || get_state() == NO_ROUTE_TOO_COMPLEX || get_state() == OUT_OF_RANGE) { // ok, not performing best return COL_DANGER; } else if((financial_history[0][CONVOI_OPERATIONS]|financial_history[1][CONVOI_OPERATIONS])==0) { // nothing moved return COL_CAUTION; } else if(get_overcrowded() > 0) { // Overcrowded return color_idx_to_rgb(COL_DARK_PURPLE); } else if(has_obsolete) { return SYSCOL_OBSOLETE; } // normal state return SYSCOL_TEXT; } uint8 convoi_t::get_catering_level(uint8 type) const { uint8 max_catering_level = 0; uint8 current_catering_level; //for(sint16 i = vehicle.get_size() - 1; i >= 0; i --) for(uint8 i = 0; i < vehicle_count; i ++) { vehicle_t* v = get_vehicle(i); if(v == NULL) { continue; } current_catering_level = v->get_desc()->get_catering_level(); if(current_catering_level > max_catering_level && v->get_desc()->get_freight_type()->get_catg_index() == type) { max_catering_level = current_catering_level; } } return max_catering_level; } /** * True if this convoy has the same vehicles as the other * @author isidoro * @author neroden (fixed) */ bool convoi_t::has_same_vehicles(convoihandle_t other) const { if (!other.is_bound()) { return false; } if (get_vehicle_count()!=other->get_vehicle_count()) { return false; } // We must compare both in the 'same direction' and in the 'reverse direction'. // We cannot use the 'reverse' flag to tell the difference. bool forward_compare_good = true; for (int i=0; i<get_vehicle_count(); i++) { if (get_vehicle(i)->get_desc()!=other->get_vehicle(i)->get_desc()) { forward_compare_good = false; break; } } if (forward_compare_good) { return true; } bool reverse_compare_good = true; for (int i=0, j=get_vehicle_count()-1; i<get_vehicle_count(); i++, j--) { if (get_vehicle(j)->get_desc()!=other->get_vehicle(i)->get_desc()) { reverse_compare_good = false; break; } } if (reverse_compare_good) { return true; } return false; } /* * Will find a depot for the vehicle "master". */ class depot_finder_t : public test_driver_t { private: vehicle_t *master; uint16 traction_type; public: depot_finder_t( convoihandle_t cnv, uint16 tt ) { master = cnv->get_vehicle(0); assert(master!=NULL); traction_type = tt; }; virtual waytype_t get_waytype() const { return master->get_waytype(); }; virtual bool check_next_tile( const grund_t* gr) const { return master->check_next_tile(gr); }; virtual bool is_target( const grund_t* gr, const grund_t* ) { return gr->get_depot() && gr->get_depot()->get_owner() == master->get_owner() && gr->get_depot()->get_tile()->get_desc()->get_enabled() & traction_type; }; virtual ribi_t::ribi get_ribi( const grund_t* gr) const { return master->get_ribi(gr); }; virtual int get_cost( const grund_t* gr, const sint32, koord from_pos) { return master->get_cost(gr, 0, from_pos); }; }; void convoi_t::set_depot_when_empty(bool new_dwe) { if(loading_level > 0) { depot_when_empty = new_dwe; } else if(new_dwe) { go_to_depot(); } } /** * Convoy is sent to depot. Return value, success or not. */ bool convoi_t::go_to_depot(bool show_success, bool use_home_depot) { if(!schedule->is_editing_finished()) { return false; } if (schedule) { old_schedule = schedule->copy(); } // limit update to certain states that are considered to be safe for schedule updates int state = get_state(); if(state==convoi_t::EDIT_SCHEDULE) { DBG_MESSAGE("convoi_t::go_to_depot()","convoi state %i => cannot change schedule ... ", state ); return false; } // Identify this convoi's traction types. We want to match at least one. uint16 traction_types = 0; uint16 shifter; if(replace) { ITERATE_PTR(replace->get_replacing_vehicles(), i) { if(replace->get_replacing_vehicle(i)->get_power() == 0) { continue; } shifter = 1 << replace->get_replacing_vehicle(i)->get_engine_type(); traction_types |= shifter; } } else { for(uint8 i = 0; i < vehicle_count; i ++) { if(vehicle[i]->get_desc()->get_power() == 0) { continue; } shifter = 1 << vehicle[i]->get_desc()->get_engine_type(); traction_types |= shifter; } } air_vehicle_t* aircraft = NULL; if(get_vehicle(0)->get_typ() == obj_t::air_vehicle) { // Flying aircraft cannot find a depot in the normal way, so go to the home depot. aircraft = (air_vehicle_t*)get_vehicle(0); if(!aircraft->is_on_ground()) { use_home_depot = true; } } const uint32 range = (uint32)get_min_range(); const uint32 distance_to_last_stop_km = ((front()->get_last_stop_pos() != koord3d::invalid && (!welt->lookup(front()->get_pos()) || !welt->lookup(front()->get_pos())->get_depot()) ? shortest_distance(front()->get_last_stop_pos().get_2d(), front()->get_pos().get_2d()) : 0) * welt->get_settings().get_meters_per_tile()) / 1000u; bool home_depot_valid = false; if (use_home_depot) { // Check for a valid home depot. It is quite easy to get savegames with // invalid home depot coordinates. const grund_t* test_gr = welt->lookup(get_home_depot()); if (test_gr) { depot_t* test_depot = test_gr->get_depot(); if (test_depot) { // It's a depot -- is it suitable? home_depot_valid = test_depot->is_suitable_for(get_vehicle(0), traction_types); } } if(range == 0 || ((shortest_distance(get_pos().get_2d(), get_home_depot().get_2d()) * (uint32)welt->get_settings().get_meters_per_tile()) / 1000) + distance_to_last_stop_km > range) { home_depot_valid = false; } // The home depot seems OK, but what if we can't get there? // Don't consider it a valid home depot if we already failed to get there. if (home_depot_valid && (state == NO_ROUTE || state == NO_ROUTE_TOO_COMPLEX || state == OUT_OF_RANGE)) { if (schedule) { const schedule_entry_t & current_entry = schedule->get_current_entry(); if ( current_entry.pos == get_home_depot() ) { // We were already trying to get there... and failed. home_depot_valid = false; } } } } koord3d depot_pos; route_t route; bool home_depot_found = false; bool other_depot_found = false; if (use_home_depot && home_depot_valid) { // The home depot is OK, use it. depot_pos = get_home_depot(); home_depot_found = true; } else { // See if we're already sitting on top of a depot. // (The route finder won't find a depot if we're standing on top of it, believe it or not.) bool current_location_valid = false; const grund_t* test_gr = welt->lookup( get_vehicle(0)->get_pos() ); if (test_gr) { depot_t* test_depot = test_gr->get_depot(); if (test_depot) { // It's a depot -- is it suitable? current_location_valid = test_depot->is_suitable_for(get_vehicle(0), traction_types); } } if (current_location_valid) { depot_pos = get_vehicle(0)->get_pos(); other_depot_found = true; } else { // OK, we're not standing on a depot. Find a route to a depot. depot_finder_t finder(self, traction_types); route.find_route(welt, get_vehicle(0)->get_pos(), &finder, speed_to_kmh(get_min_top_speed()), ribi_t::all, get_highest_axle_load(), get_tile_length(), get_weight_summary().weight / 1000, 0x7FFFFFFF, has_tall_vehicles()); if (!route.empty()) { depot_pos = route.at(route.get_count() - 1); if(range == 0 || ((shortest_distance(get_pos().get_2d(), depot_pos.get_2d()) * (uint32)welt->get_settings().get_meters_per_tile()) / 1000) + distance_to_last_stop_km <= range) { other_depot_found = true; } } } } if(((aircraft && !aircraft->is_on_ground()) || use_home_depot) && home_depot_valid) { // Flying aircraft cannot find a route using the normal means: send to their home depot instead. aircraft->calc_route(get_pos(), home_depot, speed_to_kmh(get_min_top_speed()), has_tall_vehicles(), &route); if(!route.empty()) { depot_pos = route.at(route.get_count() - 1); if(range == 0 || ((shortest_distance(get_pos().get_2d(), depot_pos.get_2d()) * (uint32)welt->get_settings().get_meters_per_tile()) / 1000) + distance_to_last_stop_km <= range) { home_depot_found = true; } } } bool transport_success = false; if (home_depot_found || other_depot_found) { if ( get_vehicle(0)->get_pos() == depot_pos ) { // We're already there. Just enter the depot (speed things up!) const grund_t* my_gr = welt->lookup(depot_pos); if (my_gr) { depot_t* my_depot = my_gr->get_depot(); if (my_depot) { enter_depot(my_depot); transport_success = true; } } } else { schedule_t* f = schedule->copy(); bool schedule_insertion_succeeded = f->insert(welt->lookup(depot_pos)); // Insert will move the pointer past the inserted item; move back to it f->advance_reverse(); // We still have to call set_schedule bool schedule_setting_succeeded = set_schedule(f); transport_success = schedule_insertion_succeeded && schedule_setting_succeeded; } } // show result char txt[255]; bool success = false; if (home_depot_found && transport_success) { sprintf(txt, translator::translate("The convoy has been sent\nto its home depot.\n%s\n"), get_name()); success = true; } else if (other_depot_found && transport_success) { sprintf(txt, translator::translate("Convoi has been sent\nto the nearest depot\nof appropriate type.\n%s\n"), get_name()); success = true; } else if (!home_depot_found && !other_depot_found) { sprintf(txt, translator::translate("No suitable depot found!\nYou need to send the\nconvoi to the depot\nmanually.\n%s\n"), get_name()); success = false; } else if (!transport_success) { sprintf(txt, translator::translate("Depot found but could not be inserted in schedule. This is a bug!%s\n"), get_name()); dbg->warning("convoi_t::go_to_depot()", "Depot found but could not be inserted in schedule for convoy %s", get_name()); success = false; } if ( (!success || show_success) && get_owner() == welt->get_active_player()) { create_win(new news_img(txt), w_time_delete, magic_none); } return success; } bool convoi_t::has_no_cargo() const { if (loading_level==0) { return true; } if (loading_level!=100) { return false; } /* a convoy with max capacity of zero, has always loading_level==100 */ for(unsigned i=0; i<vehicle_count; i++) { if (vehicle[i]->get_cargo_max()>0) { return false; } } return true; } // returns tiles needed for this convoi uint16 convoi_t::get_tile_length() const { uint16 carunits=0; for(sint8 i=0; i<vehicle_count-1; i++) { carunits += vehicle[i]->get_desc()->get_length(); } // the last vehicle counts differently in stations and for reserving track // (1) add 8 = 127/256 tile to account for the driving in stations in north/west direction // see at the end of vehicle_t::hop() // (2) for length of convoi for loading in stations the length of the last vehicle matters // see convoi_t::hat_gehalten carunits += max(CARUNITS_PER_TILE/2, vehicle[vehicle_count-1]->get_desc()->get_length()); uint16 tiles = (carunits + CARUNITS_PER_TILE - 1) / CARUNITS_PER_TILE; return tiles; } uint16 convoi_t::get_true_tile_length() const { uint16 carunits = 0; for (sint8 i = 0; i < vehicle_count; i++) { carunits += vehicle[i]->get_desc()->get_length(); } uint16 tiles = (carunits + CARUNITS_PER_TILE - 1) / CARUNITS_PER_TILE; return tiles; } // if withdraw and empty, then self destruct void convoi_t::set_withdraw(bool new_withdraw) { withdraw = new_withdraw; if( withdraw && (loading_level==0 || goods_catg_index.empty())) { // test if convoi in depot and not driving grund_t *gr = welt->lookup( get_pos()); if( gr && gr->get_depot() && state == INITIAL ) { #if 1 // do not touch line bound convois in depots withdraw = false; no_load = false; #else // disassemble also line bound convois in depots gr->get_depot()->disassemble_convoi(self, true); #endif } else { self_destruct(); } } } /** * conditions for a city car to overtake another overtaker. * The city car is not overtaking/being overtaken. */ bool convoi_t::can_overtake(overtaker_t *other_overtaker, sint32 other_speed, sint16 steps_other) { if(front()->get_waytype()!=road_wt) { return false; } grund_t *gr = welt->lookup(get_pos()); if( gr==NULL ) { // should never happen, since there is a vehicle in front of us ... return false; } strasse_t *str = (strasse_t*)gr->get_weg(road_wt); if( str==0 ) { // also this is not possible, since a car loads in front of is!?! return false; } overtaking_mode_t overtaking_mode = str->get_overtaking_mode(); if ( !other_overtaker->can_be_overtaken() && overtaking_mode > oneway_mode ) { return false; } if( overtaking_mode == prohibited_mode ){ // This road prohibits overtaking. return false; } if( other_speed == 0 ) { /* overtaking a loading convoi * => we can do a lazy check, since halts are always straight */ grund_t *gr = welt->lookup(get_pos()); if( gr==NULL ) { // should never happen, since there is a vehicle in front of us ... return false; } weg_t *str = gr->get_weg(road_wt); if( str==0 ) { // also this is not possible, since a car loads in front of is!?! return false; } // In this scope, variable "overtaking_mode" represents the strictest mode of tiles needed for overtaking. uint16 idx = front()->get_route_index(); const sint32 tiles = (steps_other-1)/(CARUNITS_PER_TILE*VEHICLE_STEPS_PER_CARUNIT) + get_tile_length() + 1; for (sint32 i = 0; i < tiles; i++) { grund_t *gr = welt->lookup(route.at(idx + i)); if (gr == NULL) { return false; } strasse_t *str = (strasse_t*)gr->get_weg(road_wt); if (str == 0) { return false; } // not overtaking on railroad crossings or normal crossings ... if (str->is_crossing()) { return false; } if( ribi_t::is_threeway(str->get_ribi()) && overtaking_mode > oneway_mode ) { // On one-way road, overtaking on threeway is allowed. return false; } const overtaking_mode_t mode_of_the_tile = str->get_overtaking_mode(); if( mode_of_the_tile>overtaking_mode ) { // update overtaking_mode to a stricter condition. overtaking_mode = mode_of_the_tile; } if( overtaking_mode==prohibited_mode ) { return false; } if( idx+(uint32)i==route.get_count()-1 && i<tiles-1 ) { // reach the end of route before examination of all tiles needed for overtaking. // convoy can stop on the passing lane only in halt_mode. if( overtaking_mode==halt_mode ) { set_tiles_overtaking(tiles); return true; } else { return false; } } if( overtaking_mode>oneway_mode ) { // Check for other vehicles on the next tile const uint8 top = gr->get_top(); for (uint8 j = 1; j < top; j++) { if (vehicle_base_t* const v = obj_cast<vehicle_base_t>(gr->obj_bei(j))) { // check for other traffic on the road const overtaker_t *ov = v->get_overtaker(); if (ov) { if (this != ov && other_overtaker != ov) { return false; } } else if (v->get_waytype() == road_wt && v->get_typ() != obj_t::pedestrian) { return false; } } } } } set_tiles_overtaking(tiles); return true; } // Around the end of route, overtaking moving convoi should not be allowed. if( get_route()->get_count() - front()->get_route_index() < 5 ) { return false; } // Do not overtake a vehicle which has higher max_power_speed than this. if( other_overtaker->get_max_power_speed() - this->get_max_power_speed() > kmh_to_speed(2) ) { return false; } // The flag whether the convoi is in traffic jam. When this is true, we must calculate overtaking in a different way. // On one-way road, other_speed is current speed. Otherwise, other_speed is the theoretical max power speed. bool in_congestion = false; int diff_speed = akt_speed - other_speed; if( diff_speed < kmh_to_speed(2) ) { // Overtaking in traffic jam is only accepted on one-way road. if( overtaking_mode <= oneway_mode ) { grund_t *gr = welt->lookup(get_pos()); strasse_t *str=(strasse_t *)gr->get_weg(road_wt); if( str==NULL ) { return false; }else if( akt_speed < fmin(get_max_power_speed(), str->get_max_speed())/2 && diff_speed >= kmh_to_speed(0) ){ //Warning: diff_speed == 0 is acceptable. We must consider the case diff_speed == 0. in_congestion = true; }else{ return false; } } else { return false; } } // Number of tiles overtaking will take int n_tiles = 0; // Distance it takes overtaking (unit: vehicle_steps) = my_speed * time_overtaking // time_overtaking = tiles_to_overtake/diff_speed // tiles_to_overtake = convoi_length + current pos within tile + (pos_other_convoi within tile + length of other convoi) - one tile int distance = 1; if( !in_congestion ) { distance = akt_speed*(front()->get_steps()+get_length_in_steps()+steps_other-VEHICLE_STEPS_PER_TILE)/diff_speed; } else { distance = get_max_power_speed()*(front()->get_steps()+get_length_in_steps()+steps_other-VEHICLE_STEPS_PER_TILE)/(get_max_power_speed()-other_speed); } int time_overtaking = 0; // Conditions for overtaking (originally): // Flat tiles, with no stops, no crossings, no signs, no change of road speed limit // First phase: no traffic except me and my overtaken car in the dangerous zone unsigned int route_index = front()->get_route_index()+1; koord3d pos = front()->get_pos(); koord3d pos_prev = (route_index > 2 ? route.at(route_index-2) : pos); koord3d pos_next; while( distance > 0 ) { if( route_index >= route.get_count() ) { return false; } pos_next = route.at(route_index++); grund_t *gr = welt->lookup(pos); // no ground, or slope => about if( gr==NULL ) { return false; } strasse_t *str = (strasse_t*)gr->get_weg(road_wt); if( str==NULL ) { return false; } overtaking_mode_t overtaking_mode_loop = str->get_overtaking_mode(); if( overtaking_mode_loop > oneway_mode && gr->get_weg_hang() != slope_t::flat ) { return false; } if( overtaking_mode_loop > twoway_mode ){ // Since the other vehicle is moving... return false; } // the only roadsign we must account for are choose points and traffic lights if( str->has_sign() ) { const roadsign_t *rs = gr->find<roadsign_t>(1); if(rs) { const roadsign_desc_t *rb = rs->get_desc(); if( rb->is_choose_sign() ) { // because we need to stop here ... return false; } //We consider traffic-lights on two-way road. if( rb->is_traffic_light() && overtaking_mode_loop >= twoway_mode ) { return false; } } } // not overtaking on railroad crossings or on normal crossings ... if( overtaking_mode_loop >= twoway_mode && (str->is_crossing() || ribi_t::is_threeway(str->get_ribi())) ) { return false; } // street gets too slow (TODO: should be able to be correctly accounted for) if( overtaking_mode_loop >= twoway_mode && akt_speed > kmh_to_speed(str->get_max_speed()) ) { return false; } int d = ribi_t::is_straight(str->get_ribi()) ? VEHICLE_STEPS_PER_TILE : vehicle_base_t::get_diagonal_vehicle_steps_per_tile(); distance -= d; time_overtaking += d; // Check for other vehicles const uint8 top = gr->get_top(); for( uint8 j=1; j<top; j++ ) { if (vehicle_base_t* const v = obj_cast<vehicle_base_t>(gr->obj_bei(j))) { // check for other traffic on the road const overtaker_t *ov = v->get_overtaker(); if(ov) { if(this!=ov && other_overtaker!=ov) { if( overtaking_mode_loop <= oneway_mode ) { //If ov goes same directory, should not return false ribi_t::ribi their_direction = ribi_t::backward( front()->calc_direction(pos_prev, pos_next) ); vehicle_base_t* const v = obj_cast<vehicle_base_t>(gr->obj_bei(j)); if (v && v->get_direction() == their_direction && v->get_overtaker()) { return false; } } else { return false; } } } else if( v->get_waytype()==road_wt && v->get_typ()!=obj_t::pedestrian ) { // sheeps etc. return false; } } } n_tiles++; pos_prev = pos; pos = pos_next; } // Second phase: only facing traffic is forbidden // Since street speed can change, we do the calculation with time. // Each empty tile will subtract tile_dimension/max_street_speed. // If time is exhausted, we are guaranteed that no facing traffic will // invade the dangerous zone. // Conditions for the street are milder: e.g. if no street, no facing traffic if(akt_speed == 0) { return false; } time_overtaking = (time_overtaking << 16)/ akt_speed; while( time_overtaking > 0 ) { if( route_index >= route.get_count() ) { return false; } pos_next = route.at(route_index++); grund_t *gr= welt->lookup(pos); if( gr==NULL ) { // will cause a route search, but is ok break; } weg_t *str = gr->get_weg(road_wt); if( str==NULL ) { break; } if( ribi_t::is_straight(str->get_ribi()) ) { // The code from Standard can produce a division be zero error. if (kmh_to_speed(str->get_max_speed()) > 0) { time_overtaking -= (VEHICLE_STEPS_PER_TILE << 16) / kmh_to_speed(str->get_max_speed()); } } else { time_overtaking -= (vehicle_base_t::get_diagonal_vehicle_steps_per_tile()<<16) / kmh_to_speed(str->get_max_speed()); } // Check for other vehicles in facing direction ribi_t::ribi their_direction = ribi_t::backward( front()->calc_direction(pos_prev, pos_next) ); const uint8 top = gr->get_top(); for( uint8 j=1; j<top; j++ ) { vehicle_base_t* const v = obj_cast<vehicle_base_t>(gr->obj_bei(j)); if (v && v->get_direction() == their_direction && v->get_overtaker()) { return false; } } pos_prev = pos; pos = pos_next; } set_tiles_overtaking( 1+n_tiles ); //The parameter about being overtaken is no longer meaningful on one-way road. if( overtaking_mode > oneway_mode ) { other_overtaker->set_tiles_overtaking( -1-(n_tiles*(akt_speed-diff_speed))/akt_speed ); } return true; } sint64 convoi_t::calc_remaining_loading_time() const { const uint32 reverse_delay = calc_reverse_delay(); uint32 loading_time = current_loading_time; const sint64 current_ticks = welt->get_ticks(); const grund_t* gr = welt->lookup(this->get_pos()); const sint64 time = arrival_time < WAIT_INFINITE ? arrival_time : welt->get_ticks(); if(gr && welt->get_ticks() - time > reverse_delay && gr->is_halt()) { // The reversing time must not be cumulative with the loading time, as // passengers can board trains etc. while they are changing direction. // Only do this where the reversing point is a stop, not a waypoint. if(reverse_delay <= loading_time) { loading_time -= reverse_delay; } else { loading_time = 0; } } sint32 remaining_ticks; if (go_on_ticks != WAIT_INFINITE && go_on_ticks >= current_ticks) { remaining_ticks = (sint32)(go_on_ticks - current_ticks); } else if (((time + current_loading_time) - reverse_delay) >= current_ticks) { remaining_ticks = (sint32)(((time + current_loading_time) - reverse_delay) - current_ticks); } else { remaining_ticks = 0; } uint32 ticks_left = 0; if(remaining_ticks >= 0) { ticks_left = remaining_ticks; } return ticks_left; } /** * Format remaining loading time from go_on_ticks */ void convoi_t::snprintf_remaining_loading_time(char *p, size_t size) const { sint64 ticks_left = calc_remaining_loading_time(); welt->sprintf_ticks(p, size, ticks_left); } /** * Format remaining loading time from go_on_ticks */ void convoi_t::snprintf_remaining_reversing_time(char *p, size_t size) const { welt->sprintf_ticks(p, size, wait_lock); } void convoi_t::snprintf_remaining_emergency_stop_time(char *p, size_t size) const { welt->sprintf_ticks(p, size, wait_lock); } uint32 convoi_t::calc_highest_axle_load() { uint32 heaviest = 0; for(uint8 i = 0; i < vehicle_count; i ++) { const uint32 tmp = vehicle[i]->get_desc()->get_axle_load(); if(tmp > heaviest) { heaviest = tmp; } } return heaviest; } uint32 convoi_t::calc_longest_min_loading_time() { uint32 longest = 0; for(int i = 0; i < vehicle_count; i ++) { const uint32 tmp = vehicle[i]->get_desc()->get_min_loading_time(); if(tmp > longest) { longest = tmp; } } return longest; } uint32 convoi_t::calc_longest_max_loading_time() { uint32 longest = 0; for(int i = 0; i < vehicle_count; i ++) { const uint32 tmp = vehicle[i]->get_desc()->get_max_loading_time(); if(tmp > longest) { longest = tmp; } } return longest; } void convoi_t::calc_min_range() { uint16 min = 0; for(int i = 0; i < vehicle_count; i ++) { const uint16 range = vehicle[i]->get_desc()->get_range(); if(range > 0 && min == 0) { min = range; } else if(range > 0 && range < min) { min = range; } } min_range = min; } void convoi_t::calc_direction_steps() { const waytype_t wt = vehicle[0]->get_waytype(); const sint32 top_speed_kmh = speed_to_kmh(get_min_top_speed()); const sint32 corner_force_divider = (wt != air_wt) ? welt->get_settings().get_corner_force_divider(wt) : 0; const sint32 max_limited_radius = ((top_speed_kmh * top_speed_kmh) * corner_force_divider) / 87; const sint16 max_tile_steps = (max_limited_radius / welt->get_settings().get_meters_per_tile()) * 2; // This must be multiplied by two because each diagonal step takes two tiles. for(int i = 0; i < vehicle_count; i ++) { vehicle[i]->set_direction_steps(max_tile_steps); } } // Bernd Gabriel, 18.06.2009: extracted from new_month() bool convoi_t::calc_obsolescence(uint16 timeline_year_month) { // convoi has obsolete vehicles? for(int j = get_vehicle_count(); --j >= 0; ) { if (vehicle[j]->get_desc()->is_obsolete(timeline_year_month)) { return true; } } return false; } uint16 convoi_t::get_average_age() { if (!get_vehicle_count()) { return 0; } uint32 total_age = 0; for (int j = get_vehicle_count(); --j >= 0; ) { total_age += welt->get_current_month() - (uint32)vehicle[j]->get_purchase_time(); } return total_age / get_vehicle_count(); } void convoi_t::clear_replace() { if(replace) { replace->decrement_convoys(self); replace = NULL; } } void convoi_t::set_replace(replace_data_t *new_replace) { if(new_replace != NULL && replace != new_replace) { new_replace->increment_convoys(self); } if(replace != NULL) { replace->decrement_convoys(self); } replace = new_replace; } void convoi_t::apply_livery_scheme() { const livery_scheme_t* const scheme = welt->get_settings().get_livery_scheme(livery_scheme_index); if(!scheme) { return; } const uint16 date = welt->get_timeline_year_month(); for (int i = 0; i < vehicle_count; i++) { vehicle_t& v = *vehicle[i]; const char* liv = scheme->get_latest_available_livery(date, v.get_desc()); if(liv) { // Only change the livery if there is an available scheme livery. v.set_current_livery(liv); } } } uint16 convoi_t::get_livery_scheme_index() const { if(line.is_bound()) { return line->get_livery_scheme_index(); } else { return livery_scheme_index; } } uint32 convoi_t::calc_reverse_delay() const { if (front()->get_waytype() == road_wt) { return welt->get_settings().get_road_reverse_time(); } uint32 reverse_delay; uint8 last_loco = get_front_loco_count() - 1; switch (get_terminal_shunt_mode()) { case change_direction: // Multiple unit or similar: quick reverse reverse_delay = welt->get_settings().get_unit_reverse_time(); break; case shunting_loco: // Locomotives need turntable. if (!(front()->get_desc()->is_bidirectional()) || (vehicle[last_loco]->get_desc()->get_basic_constraint_next(vehicle[last_loco]->is_reversed()) & vehicle_desc_t::can_be_head)==0) { reverse_delay = welt->get_settings().get_turntable_reverse_time()*check_need_turntable(); } else { // Loco hauled, no turntable. reverse_delay = welt->get_settings().get_hauled_reverse_time(); } break; case rearrange: // Goods train with brake van - longer reverse time. reverse_delay = (welt->get_settings().get_hauled_reverse_time() * 14) / 10; break; case wye: default: reverse_delay = welt->get_settings().get_hauled_reverse_time(); break; } return reverse_delay; } void convoi_t::book_waiting_times() { halthandle_t halt; halt.set_id(last_stop_id); if(!halt.is_bound()) { return; } const sint64 current_time = welt->get_ticks(); uint16 waiting_minutes; const uint16 airport_wait = front()->get_typ() == obj_t::air_vehicle ? welt->get_settings().get_min_wait_airport() : 0; for(uint8 i = 0; i < vehicle_count; i++) { const uint8 classes_to_check = vehicle[i]->get_desc()->get_number_of_classes(); for (uint8 j = 0; j < classes_to_check; j++) { FOR(slist_tpl< ware_t>, const& iter, vehicle[i]->get_cargo(j)) { if (iter.get_last_transfer().get_id() == halt.get_id()) { waiting_minutes = max(get_waiting_minutes(current_time - iter.arrival_time), airport_wait); // Only times of one minute or larger are registered, to avoid registering zero wait-time when a passenger // alights a convoy and then immediately re-boards that same convoy. if (waiting_minutes > 0) { #ifdef MULTI_THREAD pthread_mutex_lock(&step_convois_mutex); #endif halt->add_waiting_time(waiting_minutes, iter.get_zwischenziel(), iter.get_desc()->get_catg_index(), j); #ifdef MULTI_THREAD int error = pthread_mutex_unlock(&step_convois_mutex); assert(error == 0); (void)error; #endif } } } } } } void convoi_t::book_departure_time(sint64 time) { halthandle_t halt; halt.set_id(last_stop_id); if(halt.is_bound()) { // Only book a departure time if this convoy is at a station/stop. departure_data_t dep; dep.departure_time = time; uint8 schedule_entry = schedule->get_current_stop(); bool rev_rev = !reverse_schedule; // decrement(see negation of reverse_schedule) index until previous halt schedule->increment_index_until_next_halt(front()->get_owner(), &schedule_entry, &rev_rev); departure_point_t departure_point(schedule_entry, !rev_rev); departures.set(departure_point, dep); if((schedule->entries[schedule_entry].minimum_loading > 0 || schedule->entries[schedule_entry].wait_for_time) && schedule->get_spacing() > 0 && line.is_bound()) { line->book(1, LINE_DEPARTURES); } // Set the departure time from the current location (which is no longer an estimate). halt->set_estimated_departure_time(self.get_id(), time); // Estimate arrival and departure times at and from the subsequent stops on the schedule. bool rev = reverse_schedule; const uint8 count = schedule->is_mirrored() ? schedule->get_count() * 2 : schedule->get_count(); sint64 journey_time_ticks = 0; sint64 eta = time; sint64 etd = eta; vector_tpl<uint16> halts_already_processed; const uint32 reverse_delay = calc_reverse_delay(); schedule->increment_index_until_next_halt(front()->get_owner(), &schedule_entry, &rev); for(uint8 i = 0; i < count; i++) { uint32 journey_time_tenths_minutes = (uint32)journey_times_between_schedule_points.get(departure_point).get_average(); if(journey_time_tenths_minutes == 0) { // Journey time uninitialised - use average or estimated average speed instead. uint8 next_schedule_entry = schedule_entry; schedule->increment_index_until_next_halt(front()->get_owner(), &next_schedule_entry, &rev); const koord3d stop1_pos = schedule->entries[schedule_entry].pos; const koord3d stop2_pos = schedule->entries[next_schedule_entry].pos; const uint16 distance = shortest_distance(stop1_pos.get_2d(), stop2_pos.get_2d()); const uint32 current_average_speed = (uint32)(get_finance_history(1, convoi_t::CONVOI_AVERAGE_SPEED) > 0 ? get_finance_history(1, convoi_t::CONVOI_AVERAGE_SPEED) : (speed_to_kmh(get_min_top_speed()) >> 1)); journey_time_tenths_minutes = welt->travel_time_tenths_from_distance(distance, current_average_speed); } journey_time_ticks = welt->get_seconds_to_ticks(journey_time_tenths_minutes * 6); eta = etd; eta += journey_time_ticks; etd += journey_time_ticks; halt = haltestelle_t::get_halt(schedule->entries[schedule_entry].pos, owner); if(halt.is_bound() && !halts_already_processed.is_contained(halt.get_id())) { sint64 earliest_departure_time = eta + current_loading_time; if(schedule->entries[schedule_entry].reverse == 1) { // Add reversing time if this must reverse. earliest_departure_time += reverse_delay; } halt->set_estimated_arrival_time(self.get_id(), eta); const sint64 max_waiting_time = schedule->get_current_entry().waiting_time_shift ? welt->ticks_per_world_month >> (16ll - (sint64)schedule->get_current_entry().waiting_time_shift) : WAIT_INFINITE; if((schedule->entries[schedule_entry].minimum_loading > 0 || schedule->entries[schedule_entry].wait_for_time) && schedule->get_spacing() > 0) { sint64 spacing_multiplier = 1; // This may not be the next convoy on this line to depart from this forthcoming stop, so the spacing may have to be multiplied. FOR(const haltestelle_t::arrival_times_map, const& iter, halt->get_estimated_convoy_departure_times()) { const uint16 id = iter.key; convoihandle_t tmp_cnv; tmp_cnv.set_id(id); if(tmp_cnv.is_bound() && tmp_cnv->get_line() == get_line()) { // This is on the same line. Any earlier departure from the target stop is therefore relevant. if(iter.value < earliest_departure_time) { spacing_multiplier ++; } } } // Add spacing time. const sint64 spacing_ticks = welt->ticks_per_world_month / (sint64)schedule->get_spacing(); // There is a departure from each spaced stop once every this number of ticks const sint64 spacing_shift = (sint64)schedule->get_current_entry().spacing_shift * welt->ticks_per_world_month / (sint64)welt->get_settings().get_spacing_shift_divisor(); // Use earliest departure time (ready to depart exactly at the scheduled departure time?) const sint64 spacing_ticks_remainder = (earliest_departure_time + spacing_shift) % spacing_ticks; if(spacing_multiplier == 0 && spacing_ticks_remainder == 0) { // The loading and reversing will be added back later etd = eta; } else { // Calculate the departure time based on the spacing const sint64 tmp_etd = ((spacing_ticks - spacing_ticks_remainder) * spacing_multiplier) + earliest_departure_time; // The loading time and reverse delay will be added later etd = tmp_etd - current_loading_time; if (schedule->entries[schedule_entry].reverse == 1) { etd -= reverse_delay; } } } else if(schedule->entries[schedule_entry].minimum_loading > 0 && schedule->get_spacing() == 0) { if(schedule->get_current_entry().waiting_time_shift) { etd += max_waiting_time; } else { // Add loose estimate for loading to the % etd += seconds_to_ticks(900, welt->get_settings().get_meters_per_tile()); // 15 minutes. } } etd += current_loading_time; } if(schedule->entries[schedule_entry].reverse == 1) { // Add reversing time if this must reverse. etd += reverse_delay; } if(halt.is_bound() && !halts_already_processed.is_contained(halt.get_id())) { halt->set_estimated_departure_time(self.get_id(), etd); halts_already_processed.append(halt.get_id()); } schedule->increment_index_until_next_halt(front()->get_owner(), &schedule_entry, &rev); departure_point.entry = schedule_entry; departure_point.reversed = rev; } } else { dbg->warning("void convoi_t::book_departure_time(sint64 time)", "Cannot find last halt to set departure time"); } } uint16 convoi_t::get_waiting_minutes(uint32 waiting_ticks) { // Waiting time is reduced (2* ...) instead of (3 * ...) because, in real life, people // can organise their journies according to timetables, so waiting is more efficient. // NOTE: distance_per_tile is now a percentage figure rather than a floating point - divide by an extra factor of 100. //return (2 *welt->get_settings().get_distance_per_tile() * waiting_ticks) / 40960; // Note: waiting times now in *tenths* of minutes (hence difference in arithmetic) //uint16 test_minutes_1 = ((float)1 / (1 / (waiting_ticks / 4096.0) * 20) *welt->get_settings().get_distance_per_tile() * 600.0F); //uint16 test_minutes_2 = (2 *welt->get_settings().get_distance_per_tile() * waiting_ticks) / 409.6; //return (welt->get_settings().get_meters_per_tile() * waiting_ticks) / (409600L/2); // Feb 2012: Waiting times no longer reduced by 1/3, since connections can now be optimised by players in ways not previously possible, // and since many players run very high frequency networks so waiting times rarely need reducing. (Carl Baker) return (welt->get_settings().get_meters_per_tile() * waiting_ticks) / (409600L/3); //const uint32 value = (2 *welt->get_settings().get_distance_per_tile() * waiting_ticks) / 409.6F; //return value <= 65535 ? value : 65535; //Old method (both are functionally equivalent, except for reduction in time. Would be fully equivalent if above was 3 * ...): //return ((float)1 / (1 / (waiting_ticks / 4096.0) * 20) *welt->get_settings().get_distance_per_tile() * 60.0F); } uint32 convoi_t::calc_current_loading_time(uint16 load_charge) { if(longest_max_loading_time == longest_min_loading_time || load_charge == 0) { return longest_min_loading_time; } sint32 total_capacity = 0; for(uint8 i = 0; i < vehicle_count; i ++) { total_capacity += (sint32)vehicle[i]->get_desc()->get_total_capacity(); total_capacity += (sint32)vehicle[i]->get_desc()->get_overcrowded_capacity(); } // Multiply this by 2, as goods/passengers can both board and alight, so // the maximum load charge is twice the capacity: all alighting, then all // boarding. total_capacity *= 2; const sint32 percentage = ((sint32)load_charge * 100) / total_capacity; const sint32 difference = abs((((sint32)longest_max_loading_time - (sint32)longest_min_loading_time)) * percentage) / (sint32)100; return (uint32)(difference + (sint32)longest_min_loading_time); } obj_t::typ convoi_t::get_depot_type() const { const waytype_t wt = front()->get_waytype(); switch(wt) { case road_wt: return obj_t::strassendepot; case track_wt: return obj_t::bahndepot; case water_wt: return obj_t::schiffdepot; case monorail_wt: return obj_t::monoraildepot; case maglev_wt: return obj_t::maglevdepot; case tram_wt: return obj_t::tramdepot; case narrowgauge_wt: return obj_t::narrowgaugedepot; case air_wt: return obj_t::airdepot; default: dbg->error("obj_t::typ convoi_t::get_depot_type() const", "Invalid waytype: cannot find correct depot type"); return obj_t::strassendepot; }; } void convoi_t::emergency_go_to_depot(bool show_success) { // First try going to a depot the normal way. if(!go_to_depot(false)) { // Teleport to depot if cannot get there by normal means. depot_t* dep = welt->lookup(home_depot) ? welt->lookup(home_depot)->get_depot() : NULL; if(!dep) { dep = depot_t::find_depot(this->get_pos(), get_depot_type(), get_owner(), true); } if(dep) { // Only do this if a depot can be found, or else a crash will result. // Give a different message than the usual depot arrival message. cbuffer_t buf; #ifdef MULTI_THREAD pthread_mutex_lock(&step_convois_mutex); #endif if (show_success) { buf.printf(translator::translate("No route to depot for convoy %s: teleported to depot!"), get_name()); const vehicle_t* v = front(); welt->get_message()->add_message(buf, v->get_pos().get_2d(), message_t::warnings, PLAYER_FLAG | get_owner()->get_player_nr(), IMG_EMPTY); } enter_depot(dep); #ifdef MULTI_THREAD int error = pthread_mutex_unlock(&step_convois_mutex); assert(error == 0); (void)error; #endif // Do NOT do the convoi_arrived here: it's done in enter_depot! state = INITIAL; schedule->set_current_stop(0); } else { // We can't send it to a depot, because there are no appropriate depots. Destroy it! cbuffer_t buf; #ifdef MULTI_THREAD pthread_mutex_lock(&step_convois_mutex); #endif buf.printf( translator::translate("No route and no depot for convoy %s: convoy has been sold!"), get_name() ); const vehicle_t* v = front(); welt->get_message()->add_message(buf, v->get_pos().get_2d(),message_t::warnings, PLAYER_FLAG|get_owner()->get_player_nr(), IMG_EMPTY); // The player can engineer this deliberately by blowing up depots and tracks, so it isn't always a game error. // But it usually is an error, so report it as one. dbg->error("void convoi_t::emergency_go_to_depot()", "Could not find a depot to which to send convoy %i", self.get_id() ); destroy(); #ifdef MULTI_THREAD int error = pthread_mutex_unlock(&step_convois_mutex); assert(error == 0); (void)error; #endif } } } journey_times_map& convoi_t::get_average_journey_times() { if(line.is_bound()) { return line->get_average_journey_times(); } else { return average_journey_times; } } void convoi_t::clear_departures() { departures.clear(); departures_already_booked.clear(); journey_times_between_schedule_points.clear(); journey_times_history.clear(); clear_estimated_times(); } sint64 convoi_t::get_stat_converted(int month, convoi_cost_t cost_type) const { sint64 value = financial_history[month][cost_type]; switch(cost_type) { case CONVOI_REVENUE: case CONVOI_OPERATIONS: case CONVOI_PROFIT: case CONVOI_REFUNDS: case CONVOI_WAYTOLL: value = convert_money(value); break; default: ; } return value; } // BG, 31.12.2012: virtual methods of lazy_convoy_t: // Bernd Gabriel, Dec, 25 2009 sint16 convoi_t::get_current_friction() { return get_vehicle_count() > 0 ? get_friction_of_waytype(front()->get_waytype()) : 0; } void convoi_t::update_vehicle_summary(vehicle_summary_t &vehicle) { vehicle.clear(); uint32 count = get_vehicle_count(); if (count > 0) { for (const_iterator i = begin(); i != end(); ++i ) { vehicle.add_vehicle(*(*i)->get_desc()); } vehicle.update_summary(get_vehicle(count-1)->get_desc()->get_length()); } } void convoi_t::update_adverse_summary(adverse_summary_t &adverse) { adverse.clear(); uint16 count = get_vehicle_count(); if (count > 0) { for (const_iterator i = begin(); i != end(); ++i ) { adverse.add_vehicle(**i); } adverse.fr /= count; } } void convoi_t::update_freight_summary(freight_summary_t &freight) { freight.clear(); for (const_iterator i = begin(); i != end(); ++i ) { freight.add_vehicle(*(*i)->get_desc()); } } void convoi_t::update_weight_summary(weight_summary_t &weight) { weight.weight = 0; sint64 sin = 0; for (const_iterator i = begin(); i != end(); ++i ) { const vehicle_t &v = **i; sint32 kgs = v.get_total_weight(); weight.weight += kgs; sin += kgs * v.get_frictionfactor(); } weight.weight_cos = weight.weight; weight.weight_sin = (sin + 500) / 1000; } float32e8_t convoi_t::get_brake_summary(/*const float32e8_t &speed*/ /* in m/s */) { float32e8_t force = 0, br = get_adverse_summary().br; for (const_iterator i = begin(); i != end(); ++i ) { vehicle_t &v = **i; const uint16 bf = v.get_desc()->get_brake_force(); if (bf != BRAKE_FORCE_UNKNOWN) { force += bf * (uint32) 1000; } else { // Usual brake deceleration is about -0.5 .. -1.5 m/s² depending on vehicle and ground. // With F=ma, a = F/m follows that brake force in N is ~= 1/2 weight in kg force += br * v.get_total_weight(); } } return force; } float32e8_t convoi_t::get_force_summary(const float32e8_t &speed /* in m/s */) { sint64 force = 0; sint32 v = speed; for (const_iterator i = begin(); i != end(); ++i ) { force += (*i)->get_desc()->get_effective_force_index(v); } //for (array_tpl<vehicle_t*>::iterator i = vehicle.begin(), n = i + get_vehicle_count(); i != n; ++i) // force += (*i)->get_desc()->get_effective_force_index(v); return power_index_to_power(force, welt->get_settings().get_global_force_factor_percent()); } float32e8_t convoi_t::get_power_summary(const float32e8_t &speed /* in m/s */) { sint64 power = 0; sint32 v = speed; for (const_iterator i = begin(); i != end(); ++i ) { power += (*i)->get_desc()->get_effective_power_index(v); } return power_index_to_power(power, welt->get_settings().get_global_power_factor_percent()); } // BG, 31.12.2012: end of virtual methods of lazy_convoy_t void convoi_t::clear_estimated_times() { if(!schedule) { return; } halthandle_t halt; uint8 entry = schedule->get_current_stop(); bool rev = reverse_schedule; for(int i = 0; i < schedule->get_count(); i++) { halt = haltestelle_t::get_halt(schedule->entries[entry].pos, owner); if(halt.is_bound()) { halt->clear_estimated_timings(self.get_id()); } schedule->increment_index(&entry, &rev); } } void convoi_t::calc_classes_carried() { if (welt->is_destroying()) { // Some of the data below may already have been destroyed // if the world is shutting down return; } passenger_classes_carried.clear(); mail_classes_carried.clear(); for (const_iterator i = begin(); i != end(); ++i) { const vehicle_t &v = **i; for (uint8 j = 0; j < max(goods_manager_t::passengers->get_number_of_classes(), goods_manager_t::mail->get_number_of_classes()); j++) { if (v.get_desc()->get_freight_type()->get_catg_index() == goods_manager_t::INDEX_PAS) { if (v.get_fare_capacity(j) > 0) { passenger_classes_carried.append_unique(j); } } if (v.get_desc()->get_freight_type()->get_catg_index() == goods_manager_t::INDEX_MAIL) { if (v.get_fare_capacity(j) > 0) { mail_classes_carried.append_unique(j); } } } } } uint16 convoi_t::get_total_cargo_by_fare_class(uint8 catg, uint8 g_class) const { if ((catg == goods_manager_t::INDEX_PAS && g_class >= goods_manager_t::passengers->get_number_of_classes()) || (catg == goods_manager_t::INDEX_MAIL && g_class >= goods_manager_t::mail->get_number_of_classes())) { return 0; } else if (catg != goods_manager_t::INDEX_PAS && catg != goods_manager_t::INDEX_MAIL && g_class > 0) { return 0; // freight does not have classes } uint16 sum = 0; const uint8 classes = catg == goods_manager_t::INDEX_PAS ? goods_manager_t::passengers->get_number_of_classes() : goods_manager_t::mail->get_number_of_classes(); for (const_iterator i = begin(); i != end(); ++i) { const vehicle_t &v = **i; if (v.get_cargo_type()->get_catg_index() != catg) { continue; } if (catg == goods_manager_t::INDEX_PAS || catg == goods_manager_t::INDEX_MAIL) { for (uint8 c = 0; c < classes; c++) { if (v.get_reassigned_class(c) == g_class) { sum += v.get_total_cargo_by_class(c); } } } else { sum += v.get_total_cargo_by_class(0); } } return sum; } uint16 convoi_t::get_unique_fare_capacity(uint8 catg, uint8 g_class) const { if ((catg == goods_manager_t::INDEX_PAS && g_class >= goods_manager_t::passengers->get_number_of_classes()) || (catg == goods_manager_t::INDEX_MAIL && g_class >= goods_manager_t::mail->get_number_of_classes())) { return 0; } else if(catg != goods_manager_t::INDEX_PAS && catg != goods_manager_t::INDEX_MAIL && g_class>0){ return 0; // freight does not have classes } uint16 sum = 0; for (const_iterator i = begin(); i != end(); ++i) { const vehicle_t &v = **i; if (v.get_cargo_type()->get_catg_index() != catg) { continue; } sum += v.get_fare_capacity(g_class); } return sum; } bool convoi_t::carries_this_or_lower_class(uint8 catg, uint8 g_class) const { if (catg != goods_manager_t::INDEX_PAS && catg != goods_manager_t::INDEX_MAIL) { return true; } // Passengers may board vehicles of a lower, but not a higher, class if (catg == goods_manager_t::INDEX_PAS) { FOR(minivec_tpl<uint8>, i, passenger_classes_carried) { if (i <= g_class) { return true; } } } else { FOR(minivec_tpl<uint8>, i, mail_classes_carried) { if (i <= g_class) { return true; } } } return false; } /* * Functions to yield lane space to vehicles on passing lane. * More natural movement controll is desired! * @author THLeaderH */ void convoi_t::yield_lane_space() { // we do not allow lane yielding when the end of route is close. if( akt_speed > kmh_to_speed(20) && front()->get_route_index() < get_route()->get_count() - 4u ) { yielding_quit_index = front()->get_route_index() + 3u; } } bool convoi_t::calc_lane_affinity(uint8 lane_affinity_sign) { if( lane_affinity_sign!=0 && lane_affinity_sign<4 ) { uint16 test_index = front()->get_route_index(); while( test_index < route.get_count() ) { grund_t *gr = welt->lookup(route.at(test_index)); if( !gr ) { // way (weg) not existent (likely destroyed) return false; } strasse_t *str = (strasse_t *)gr->get_weg(road_wt); if( !str || gr->get_top() > 250 || str->get_overtaking_mode() > oneway_mode ) { // too many cars here or no street or not one-way road return false; } ribi_t::ribi str_ribi = str->get_ribi_unmasked(); if( str_ribi == ribi_t::all || ribi_t::is_threeway(str_ribi) ) { // It's a intersection. if( test_index == 0 || test_index == route.get_count() - 1 ) { // cannot calculate prev_dir or next_dir return false; } ribi_t::ribi prev_dir = vehicle_base_t::calc_direction(welt->lookup(route.at(test_index-1))->get_pos(),welt->lookup(route.at(test_index))->get_pos()); ribi_t::ribi next_dir = vehicle_base_t::calc_direction(welt->lookup(route.at(test_index))->get_pos(),welt->lookup(route.at(test_index+1))->get_pos()); ribi_t::ribi str_left = (ribi_t::rotate90l(prev_dir) & str_ribi) == 0 ? prev_dir : ribi_t::rotate90l(prev_dir); ribi_t::ribi str_right = (ribi_t::rotate90(prev_dir) & str_ribi) == 0 ? prev_dir : ribi_t::rotate90(prev_dir); if( next_dir == str_left && (lane_affinity_sign & 1) != 0 ) { // fix to left lane if( welt->get_settings().is_drive_left() ) { lane_affinity = -1; } else { lane_affinity = 1; } lane_affinity_end_index = test_index; return true; } else if( next_dir == str_right && (lane_affinity_sign & 2) != 0 ) { // fix to right lane if( welt->get_settings().is_drive_left() ) { lane_affinity = 1; } else { lane_affinity = -1; } lane_affinity_end_index = test_index; return true; } else { return false; } } test_index++; } } return false; } void convoi_t::reflesh(sint8 prev_tiles_overtaking, sint8 current_tiles_overtaking) { if( front() && front()->get_waytype()==road_wt && (prev_tiles_overtaking==0)^(current_tiles_overtaking==0) ){ for(uint8 i=0; i<vehicle_count; i++) { road_vehicle_t* rv = dynamic_cast<road_vehicle_t*>(vehicle[i]); if(rv && !rv->get_flag(obj_t::dirty) ) { rv->mark_image_dirty( rv->get_image(), 0 ); rv->set_flag( obj_t::dirty ); } } } } bool convoi_t::all_vehicles_are_buildable() const { for (uint32 i = 0; i < vehicle_count; i++) { if(get_vehicle(i)->get_desc()->is_available_only_as_upgrade()) { return false; } if(!welt->get_settings().get_allow_buying_obsolete_vehicles() && get_vehicle(i)->get_desc()->is_obsolete(welt->get_timeline_year_month())) { return false; } } return true; } // count the number of the front side powered chunk uint8 convoi_t::get_front_loco_count() const { uint8 loco_count = 0; bool this_group_has_power = false; for (uint32 i = 0; i < vehicle_count; ++i) { if (vehicle[i]->get_desc()->get_power()) { this_group_has_power = true; } // not a locomotive group if (loco_count && (vehicle[i]->get_desc()->get_capacity() || vehicle[i]->get_desc()->get_overcrowded_capacity())) { return loco_count; } if ((vehicle[i]->get_desc()->get_basic_constraint_next(vehicle[i]->is_reversed()) & vehicle_desc_t::can_be_tail) && this_group_has_power) { // seems independent locomotive group. check next group... loco_count = i+1; this_group_has_power = false; } } return loco_count; } uint8 convoi_t::get_terminal_shunt_mode() const { if (!back()->get_desc()->is_bidirectional()) { return wye; } const bool need_turn_table = !front()->get_desc()->is_bidirectional(); if (front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { if (!need_turn_table && back()->get_desc()->get_basic_constraint_next(back()->is_reversed()) & vehicle_desc_t::can_be_head) { return change_direction; // has a cab on both side. = no shunting } if (check_new_tail(get_front_loco_count())==0) { // can not headshunt because convoy does not have a new tail car candidate return wye; } // well, determine the headshunting type... // check loco's next side uint8 next_loco = get_front_loco_count(); if (vehicle[next_loco]->get_desc()->get_basic_constraint_prev(vehicle[next_loco]->is_reversed()) & vehicle_desc_t::can_be_tail) { // Both sides of remain coaces/wagons are can be at the tail end return shunting_loco; } else { // It is necessary to shunt unpowerd vehicles(wagon/coach) formation return rearrange; } } else { return wye; } return wye; } // Find the next "tail" vehicle other than the locomotive, and return that car's current position(number from front). // Pass the number of locomotives in the argument. // If it returns 0, it indicates that there is no existence. @Ranran uint8 convoi_t::check_new_tail(uint8 start = 1) const { for (uint32 i = start; i < vehicle_count; ++i) { if (!vehicle[i]->get_desc()->is_bidirectional()) { continue; } if (vehicle[i]->get_desc()->get_basic_constraint_prev(vehicle[i]->is_reversed()) & vehicle_desc_t::can_be_tail) { return i; } } return 0; } // calculation(auto remove) algorithm is based on tool_change_depot_t::init - "r" uint8 convoi_t::calc_auto_removal_length(uint8 car_no) const { uint8 len = 0; int nr = car_no; // check rear side while (nr < get_vehicle_count()) { const vehicle_desc_t *info = vehicle[nr]->get_desc(); len += info->get_length(); nr++; if (info->get_trailer_count() != 1) { break; } } // check front side nr = car_no; while (nr > 0) { const vehicle_desc_t *info = vehicle[nr-1]->get_desc(); if (info->get_trailer_count() != 1) { return len; } len += info->get_length(); nr--; } return len; } uint8 convoi_t::get_auto_removal_vehicle_count(uint8 car_no) const { uint8 cnt = 0; int nr = car_no; // check rear side while (nr < get_vehicle_count()) { const vehicle_desc_t *info = vehicle[nr]->get_desc(); cnt++; nr++; if (info->get_trailer_count() != 1) { break; } } // check front side nr = car_no; while (nr > 0) { const vehicle_desc_t *info = vehicle[nr - 1]->get_desc(); if (info->get_trailer_count() != 1) { return cnt; } cnt++; nr--; } return cnt; } // Currently this is used to determine if neighboring vehicles are in intermediate side each other. // They are considered identical groups when reversing convoy. uint8 convoi_t::check_couple_constraint_level(uint8 car_no, bool rear_side) const { uint8 constraint_level = free; if (car_no == 0 && !rear_side) { if (vehicle[0]->get_desc()->get_basic_constraint_prev(vehicle[0]->is_reversed()) & vehicle_desc_t::unconnectable) { return unconnectable; } return free; } if (car_no > vehicle_count - 2 && rear_side) { if (vehicle[vehicle_count-1]->get_desc()->get_basic_constraint_next(vehicle[vehicle_count - 1]->is_reversed()) & vehicle_desc_t::unconnectable) { return unconnectable; } return free; } const uint8 a = rear_side ? car_no : car_no - 1; const uint8 b = rear_side ? car_no + 1 : car_no; const uint8 end_a = vehicle[a]->get_desc()->get_basic_constraint_next(vehicle[a]->is_reversed()); const uint8 end_b = vehicle[b]->get_desc()->get_basic_constraint_prev(vehicle[b]->is_reversed()); if (end_a & vehicle_desc_t::unknown_constraint || end_b & vehicle_desc_t::unknown_constraint) { return free; } if (!end_a && !end_b) { constraint_level = both_intermediate; }else if ((end_a & vehicle_desc_t::can_be_head || end_a & vehicle_desc_t::can_be_tail) && (end_b & vehicle_desc_t::can_be_head || end_b & vehicle_desc_t::can_be_tail)) { constraint_level = head_and_tail; } else { constraint_level = half_intermediate; } if (end_a & vehicle_desc_t::intermediate_unique) { constraint_level = one_sided_partner; } if (end_b & vehicle_desc_t::intermediate_unique) { constraint_level = constraint_level == one_sided_partner ? unique_partner : one_sided_partner; } return constraint_level; } // return powered vehicle count if the front side locomotives need a turntable. Also supports double heading. // 0 = turtable is not necessary uint8 convoi_t::check_need_turntable() const { if (get_terminal_shunt_mode() == wye || get_terminal_shunt_mode() == change_direction) { return 0; } uint8 one_directional_powered_veh = 0; if (front()->get_waytype() == track_wt || front()->get_waytype() == tram_wt || front()->get_waytype() == narrowgauge_wt || front()->get_waytype() == maglev_wt || front()->get_waytype() == monorail_wt) { for (uint32 i = 0; i < get_front_loco_count(); ++i) { if (!vehicle[i]->get_desc()->is_bidirectional() && vehicle[i]->get_desc()->get_power()) { one_directional_powered_veh++; } } } return one_directional_powered_veh; } sint16 convoi_t::get_car_numbering(uint8 car_no) const { // Currently does not distinguish the last (pushing) locomotive or brake van. // memo: If want to mark the brake van, check the rear group if shunt_mode = rearrange. @Ranran car_no++; if (car_no > vehicle_count) { return 0; } uint8 loco_cnt = 0; uint8 normal_car_cnt = 0; // It also serves as a flag that the locomotive counting is over for (uint8 veh = 0; veh < car_no; veh++) { if (vehicle[veh]->get_number_of_accommodation_classes()) { normal_car_cnt++; } else { // Check the front side connection.. // It is the same group if each other's intermediate side. if (normal_car_cnt || get_front_loco_count() <= veh) { // NOTE: unpowered chunk is not considered locomotive group normal_car_cnt++; } else { loco_cnt++; } } } if (loco_cnt == car_no) { if (reversed && !check_need_turntable()) { return -(get_front_loco_count()-car_no+1); } return -loco_cnt; } return reversed ? vehicle_count - car_no + 1 : normal_car_cnt; } bool convoi_t::check_way_constraints_of_all_vehicles(const weg_t& way) const { for (uint32 i = 0; i < vehicle_count; i++) { if (!get_vehicle(i)->check_way_constraints(way)) { return false; } } return true; }
//remember to add the library // lib_deps = // WiFiConnector #include <Arduino.h> #include <ESP8266WiFi.h> #include <WiFiConnector.h> #include <ESP8266WebServer.h> #ifndef WIFI_SSID #define WIFI_SSID "ssid" #define WIFI_PASSPHRASE "password" #endif WiFiConnector wifi(WIFI_SSID, WIFI_PASSPHRASE); ESP8266WebServer server(80); void init_hardware() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); delay(10); Serial.println(); Serial.println("BEGIN"); } void init_webserver() { server.on ( "/", []() { static String responseHTML = F("" "<!doctype html>" "<html>" " <head>" " <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js'></script>" "" "" "<script type=\"text/javascript\">" " angular.module(\"NatApp\", [])" " .controller(\"CMMCController\", function($scope, $http, $interval) { " " var successCallback = function(response) { " " $scope.millis = response.data.millis; " " }; " " var errorCallback = function(response) { " " console.log(\"error\", response); " " }; " " var polling = function() { " " $http({ " " method: 'GET', " " url: '/millis' " " }).then(successCallback, errorCallback); " " }; " " " " $interval(polling, 500); " " });" "</script>" " </head>" " <body ng-app=\"NatApp\">" "<div ng-controller=\"CMMCController\">" " <h1>CMMC Controller: </h1>" " <h2><span>millis() = {{ millis }}</span> </h2>" "</div>" " </body>" "</html>"); server.send (200, "text/html", responseHTML.c_str() ); }); server.on ( "/millis", []() { char buff[100]; String ms = String(millis()); sprintf(buff, "{\"millis\": %s }", ms.c_str()); server.send ( 200, "text/plain", buff ); }); } void init_wifi() { wifi.init(); wifi.on_connecting([&](const void* message) { Serial.print("."); delay(500); }); wifi.on_connected([&](const void* message) { // Print the IP address Serial.print("WIFI CONNECTED => "); Serial.println(WiFi.localIP()); init_webserver(); server.begin(); Serial.println("SERVER Started."); }); wifi.on_disconnected([&](const void* message) { server.close(); }); } void setup() { init_hardware(); init_wifi(); wifi.connect(); } void loop() { wifi.loop(); server.handleClient(); }
/* Copyright 2007-2015 QReal Research Group * * 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 "playToneGenerator.h" #include "generatorBase/generatorCustomizer.h" using namespace generatorBase::simple; using namespace qReal; PlayToneGenerator::PlayToneGenerator(const qrRepo::RepoApi &repo , GeneratorCustomizer &customizer , const Id &id , QObject *parent) : BindingGenerator(repo, customizer, id, "playTone.t", QList<Binding *>() << Binding::createConverting("@@FREQUENCY@@", "Frequency" , customizer.factory()->intPropertyConverter(id, "Frequency")) << Binding::createConverting("@@DURATION@@", "Duration" , customizer.factory()->intPropertyConverter(id, "Duration")) << Binding::createConverting("@@VOLUME@@", "Volume" , customizer.factory()->intPropertyConverter(id, "Volume")) << Binding::createConverting("@@WAIT_FOR_COMPLETION@@", "WaitForCompletion" , customizer.factory()->boolPropertyConverter(id, "WaitForCompletion", false)) , parent) { }
/* * Copyright (C) 2018 by Author: Aroudj, Samir * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #include "App/TSR.h" #include "Platform/ResourceManagement/MemoryManager.h" #include "Platform/Utilities/HelperFunctions.h" using namespace Platform; using namespace std; #ifdef MEMORY_MANAGEMENT const uint32 ResourceManagement::DEFAULT_POOL_BUCKET_NUMBER = 5; const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_CAPACITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 1024, 1024, 1024, 1024, 1024 }; const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_GRANULARITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 16, 32, 64, 128, 256 }; #endif /// MEMORY_MANAGEMENT #ifdef _WINDOWS int32 WINAPI WinMain(HINSTANCE applicationHandle, HINSTANCE unused, LPSTR commandLineArguments, int32 windowShowState) { #else int main(int argumentCount, const char *commandLineArguments[]) { #endif // _WINDOWS // do cool stuff { vector<string> arguments; #ifdef _WINDOWS Utilities::getCommandLineArguments(arguments, commandLineArguments); #else Utilities::getCommandLineArguments(arguments, commandLineArguments, argumentCount); #endif // _WINDOWS TSR application ( #ifdef _WINDOWS applicationHandle, #endif // _WINDOWS arguments ); application.run(); } #ifdef MEMORY_MANAGEMENT ResourceManagement::MemoryManager::shutDown(); #endif /// MEMORY_MANAGEMENT return 0; }
#ifndef SYNOPSIS_H #define SYNOPSIS_H #include <stdlib.h> #include <iostream> #define TRANS_FAULT_AMNT 7 #define PERM_FAULT_AMNT 7 extern int DRAMMODULES; class Synopsis{ public: int dram_module; int sim_num; // the simulation number int sim_stat; //The status of a simulation instance. 0 - no faults, 1 - Failure, 2 - faults but corrected/detected int trans_faults[TRANS_FAULT_AMNT]; // transient fault count for each type of transient fault int perm_faults[PERM_FAULT_AMNT]; // permanent fault count for each type of permanent fault int the_straw; Synopsis(void); static void init_file(const char* filename); void print_to_csv(void); static void file_closure(void); static FILE* csv_fp; }; #endif
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cbn/model/DescribeFlowlogsRequest.h> using AlibabaCloud::Cbn::Model::DescribeFlowlogsRequest; DescribeFlowlogsRequest::DescribeFlowlogsRequest() : RpcServiceRequest("cbn", "2017-09-12", "DescribeFlowlogs") { setMethod(HttpRequest::Method::Post); } DescribeFlowlogsRequest::~DescribeFlowlogsRequest() {} long DescribeFlowlogsRequest::getResourceOwnerId()const { return resourceOwnerId_; } void DescribeFlowlogsRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::string DescribeFlowlogsRequest::getClientToken()const { return clientToken_; } void DescribeFlowlogsRequest::setClientToken(const std::string& clientToken) { clientToken_ = clientToken; setParameter("ClientToken", clientToken); } std::string DescribeFlowlogsRequest::getCenId()const { return cenId_; } void DescribeFlowlogsRequest::setCenId(const std::string& cenId) { cenId_ = cenId; setParameter("CenId", cenId); } std::string DescribeFlowlogsRequest::getDescription()const { return description_; } void DescribeFlowlogsRequest::setDescription(const std::string& description) { description_ = description; setParameter("Description", description); } int DescribeFlowlogsRequest::getPageNumber()const { return pageNumber_; } void DescribeFlowlogsRequest::setPageNumber(int pageNumber) { pageNumber_ = pageNumber; setParameter("PageNumber", std::to_string(pageNumber)); } std::string DescribeFlowlogsRequest::getRegionId()const { return regionId_; } void DescribeFlowlogsRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } int DescribeFlowlogsRequest::getPageSize()const { return pageSize_; } void DescribeFlowlogsRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter("PageSize", std::to_string(pageSize)); } std::string DescribeFlowlogsRequest::getProjectName()const { return projectName_; } void DescribeFlowlogsRequest::setProjectName(const std::string& projectName) { projectName_ = projectName; setParameter("ProjectName", projectName); } std::string DescribeFlowlogsRequest::getLogStoreName()const { return logStoreName_; } void DescribeFlowlogsRequest::setLogStoreName(const std::string& logStoreName) { logStoreName_ = logStoreName; setParameter("LogStoreName", logStoreName); } std::string DescribeFlowlogsRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void DescribeFlowlogsRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string DescribeFlowlogsRequest::getOwnerAccount()const { return ownerAccount_; } void DescribeFlowlogsRequest::setOwnerAccount(const std::string& ownerAccount) { ownerAccount_ = ownerAccount; setParameter("OwnerAccount", ownerAccount); } long DescribeFlowlogsRequest::getOwnerId()const { return ownerId_; } void DescribeFlowlogsRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string DescribeFlowlogsRequest::getFlowLogId()const { return flowLogId_; } void DescribeFlowlogsRequest::setFlowLogId(const std::string& flowLogId) { flowLogId_ = flowLogId; setParameter("FlowLogId", flowLogId); } std::string DescribeFlowlogsRequest::getFlowLogName()const { return flowLogName_; } void DescribeFlowlogsRequest::setFlowLogName(const std::string& flowLogName) { flowLogName_ = flowLogName; setParameter("FlowLogName", flowLogName); } std::string DescribeFlowlogsRequest::getStatus()const { return status_; } void DescribeFlowlogsRequest::setStatus(const std::string& status) { status_ = status; setParameter("Status", status); }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <pthread.h> #include <fcntl.h> #include <fstream> #include <iostream> #include <string> #include <unordered_map> #include <vector> #include <memory> #include <nlohmann/json.hpp> #include "eluvio/argutils.h" #include "eluvio/fixup-cpp.h" #include "eluvio/utils.h" #include "eluvio/el_cgo_interface.h" #include "eluvio/el_constants.h" using nlohmann::json; /* clang++ -std=c++14 -stdlib=libstdc++ -I ../include -I /home/jan/SSD2/elv-debug/dist/linux-glibc.2.27/include -g -c -emit-llvm -O0 tagger.cpp -fno-use-cxa-atexit -o tagger.bc */ /* * Outputs the data from key "image" */ int taggit(int outsz, char *outbuf, char* qlibid, char* qhash) { // ************************************* // THIS IS DUP'd FROM AVMASTER2000.CPP // JUST A PLACEHOLDER // ************************************* return -1; } /* * Dispatch content requests * * Arguments: * qlibid - content library ID * qhash - content 'hash' * URL path (e.g.: "/html") * * Example URLs: * http://localhost:8008/qlibs/ilibXXX/q/hq__XXX/rep/video * http://localhost:8008/qlibs/ilibXXX/q/hq__XXX/rep/html * http://localhost:8008/qlibs/ilibXXX/q/hq__XXX/rep/image */ extern "C" int tagger(int outsz, char *outbuf, const char *argbuf) { int res = -1; ArgumentBuffer argBuf(argbuf); int argc = argBuf.Count(); // argc should be 3 if (argc < 3) return -1; printf("argc=%d lib=%s url=%s\n", argc, argBuf[0], argBuf[2]); char *qlibid = argBuf[0]; char *qhash = argBuf[1]; // char* pMetaRequest = argBuf[2]; // int szUrl = 4*1024; // char url[szUrl]; // /*FIXME: Need a way to get the url instead of localhost:8008 */ // snprintf(url, szUrl, "http://localhost:8008/qlibs/%s/q/%s/meta/%s",qlibid,qhash,pMetaRequest); // if (strcmp(pMetaRequest, "/tag") == 0){ // really need to return error if not matching any // return taggit(outsz, outbuf, qlibid, qhash); // } return taggit(outsz, outbuf, ; }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <unordered_map> // template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, // class Alloc = allocator<pair<const Key, T>>> // class unordered_multimap // iterator insert(const_iterator p, const value_type& x); #if _LIBCPP_DEBUG >= 1 #define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0)) #endif #include <unordered_map> #include <cassert> #include "../../../min_allocator.h" int main() { { typedef std::unordered_multimap<double, int> C; typedef C::iterator R; typedef C::value_type P; C c; C::const_iterator e = c.end(); R r = c.insert(e, P(3.5, 3)); assert(c.size() == 1); assert(r->first == 3.5); assert(r->second == 3); r = c.insert(c.end(), P(3.5, 4)); assert(c.size() == 2); assert(r->first == 3.5); assert(r->second == 4); r = c.insert(c.end(), P(4.5, 4)); assert(c.size() == 3); assert(r->first == 4.5); assert(r->second == 4); r = c.insert(c.end(), P(5.5, 4)); assert(c.size() == 4); assert(r->first == 5.5); assert(r->second == 4); } #if __cplusplus >= 201103L { typedef std::unordered_multimap<double, int, std::hash<double>, std::equal_to<double>, min_allocator<std::pair<const double, int>>> C; typedef C::iterator R; typedef C::value_type P; C c; C::const_iterator e = c.end(); R r = c.insert(e, P(3.5, 3)); assert(c.size() == 1); assert(r->first == 3.5); assert(r->second == 3); r = c.insert(c.end(), P(3.5, 4)); assert(c.size() == 2); assert(r->first == 3.5); assert(r->second == 4); r = c.insert(c.end(), P(4.5, 4)); assert(c.size() == 3); assert(r->first == 4.5); assert(r->second == 4); r = c.insert(c.end(), P(5.5, 4)); assert(c.size() == 4); assert(r->first == 5.5); assert(r->second == 4); } #endif #if _LIBCPP_DEBUG >= 1 { typedef std::unordered_multimap<double, int> C; typedef C::iterator R; typedef C::value_type P; C c; C c2; C::const_iterator e = c2.end(); P v(3.5, 3); R r = c.insert(e, v); assert(false); } #endif }
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Lightmap only shader // // $Header: $ // $NoKeywords: $ //=============================================================================// #include "BaseVSShader.h" #include "lightmappedgeneric_decal.inc" #include "mathlib/bumpvects.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" BEGIN_VS_SHADER( LightmappedGeneric_Decal, "Help for LightmappedGeneric_Decal" ) BEGIN_SHADER_PARAMS END_SHADER_PARAMS // Set up anything that is necessary to make decisions in SHADER_FALLBACK. SHADER_INIT_PARAMS() { if ( g_pHardwareConfig->SupportsBorderColor() ) { params[FLASHLIGHTTEXTURE]->SetStringValue( "effects/flashlight_border" ); } else { params[FLASHLIGHTTEXTURE]->SetStringValue( "effects/flashlight001" ); } // No texture means no self-illum or env mask in base alpha if ( !params[BASETEXTURE]->IsDefined() ) { CLEAR_FLAGS( MATERIAL_VAR_SELFILLUM ); CLEAR_FLAGS( MATERIAL_VAR_BASEALPHAENVMAPMASK ); } SET_FLAGS( MATERIAL_VAR_DECAL ); SET_FLAGS( MATERIAL_VAR_NO_DEBUG_OVERRIDE ); SET_FLAGS2( MATERIAL_VAR2_LIGHTING_LIGHTMAP ); } SHADER_FALLBACK { return 0; } SHADER_INIT { LoadTexture( FLASHLIGHTTEXTURE, TEXTUREFLAGS_SRGB ); if (params[BASETEXTURE]->IsDefined()) { LoadTexture( BASETEXTURE ); if ( !params[BASETEXTURE]->GetTextureValue()->IsTranslucent() ) { CLEAR_FLAGS( MATERIAL_VAR_SELFILLUM ); CLEAR_FLAGS( MATERIAL_VAR_BASEALPHAENVMAPMASK ); } } // Don't alpha test if the alpha channel is used for other purposes if (IS_FLAG_SET(MATERIAL_VAR_SELFILLUM) || IS_FLAG_SET(MATERIAL_VAR_BASEALPHAENVMAPMASK) ) { CLEAR_FLAGS( MATERIAL_VAR_ALPHATEST ); } } void DrawDecal( IMaterialVar **params, IShaderDynamicAPI *pShaderAPI, IShaderShadow *pShaderShadow ) { if( IsSnapshotting() ) { // Be sure not to write to dest alpha pShaderShadow->EnableAlphaWrites( false ); pShaderShadow->EnableTexture( SHADER_SAMPLER0, true ); pShaderShadow->EnableTexture( SHADER_SAMPLER1, true ); pShaderShadow->EnableTexture( SHADER_SAMPLER2, true ); pShaderShadow->EnableTexture( SHADER_SAMPLER3, true ); SetNormalBlendingShadowState( BASETEXTURE, true ); int pTexCoords[3] = { 2, 2, 1 }; pShaderShadow->VertexShaderVertexFormat( VERTEX_POSITION | VERTEX_COLOR, 3, pTexCoords, 0 ); lightmappedgeneric_decal_Static_Index vshIndex; pShaderShadow->SetVertexShader( "LightmappedGeneric_Decal", vshIndex.GetIndex() ); pShaderShadow->SetPixelShader( "LightmappedGeneric_Decal" ); FogToFogColor(); } else { BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME ); // Load the z^2 components of the lightmap coordinate axes only // This is (N dot basis)^2 Vector vecZValues( g_localBumpBasis[0].z, g_localBumpBasis[1].z, g_localBumpBasis[2].z ); vecZValues *= vecZValues; Vector4D basis[3]; basis[0].Init( vecZValues.x, vecZValues.x, vecZValues.x, 0.0f ); basis[1].Init( vecZValues.y, vecZValues.y, vecZValues.y, 0.0f ); basis[2].Init( vecZValues.z, vecZValues.z, vecZValues.z, 0.0f ); pShaderAPI->SetPixelShaderConstant( 0, (float*)basis, 3 ); pShaderAPI->BindStandardTexture( SHADER_SAMPLER1, TEXTURE_LIGHTMAP_BUMPED ); SetVertexShaderTextureTransform( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, BASETEXTURETRANSFORM ); SetModulationPixelShaderDynamicState( 3 ); lightmappedgeneric_decal_Dynamic_Index vshIndex; vshIndex.SetDOWATERFOG( pShaderAPI->GetSceneFogMode() == MATERIAL_FOG_LINEAR_BELOW_FOG_Z ); pShaderAPI->SetVertexShaderIndex( vshIndex.GetIndex() ); } Draw(); } SHADER_DRAW { if( UsingFlashlight( params ) ) { DrawFlashlight_dx80( params, pShaderAPI, pShaderShadow, false, -1, -1, -1, FLASHLIGHTTEXTURE, FLASHLIGHTTEXTUREFRAME, true, false, 0, -1, -1 ); } else { DrawDecal( params, pShaderAPI, pShaderShadow ); } } END_SHADER
// // main.cpp // tests // // Created by bwk on 11.05.15. // Copyright (c) 2015 php. All rights reserved. // // This tells Catch to provide a main() - only do this in one cpp file #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp>
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <numeric> // UNSUPPORTED: c++98, c++03, c++11, c++14 // template<class InputIterator, class OutputIterator, class T> // OutputIterator exclusive_scan(InputIterator first, InputIterator last, // OutputIterator result, T init); // #include <numeric> #include <vector> #include <cassert> #include "test_iterators.h" template <class Iter1, class T, class Iter2> void test(Iter1 first, Iter1 last, T init, Iter2 rFirst, Iter2 rLast) { std::vector<typename std::iterator_traits<Iter1>::value_type> v; // Not in place std::exclusive_scan(first, last, std::back_inserter(v), init); assert(std::equal(v.begin(), v.end(), rFirst, rLast)); // In place v.clear(); v.assign(first, last); std::exclusive_scan(v.begin(), v.end(), v.begin(), init); assert(std::equal(v.begin(), v.end(), rFirst, rLast)); } template <class Iter> void test() { int ia[] = {1, 3, 5, 7, 9}; const int pRes[] = {0, 1, 4, 9, 16}; const unsigned sa = sizeof(ia) / sizeof(ia[0]); static_assert(sa == sizeof(pRes) / sizeof(pRes[0])); // just to be sure for (unsigned int i = 0; i < sa; ++i ) test(Iter(ia), Iter(ia + i), 0, pRes, pRes + i); } int triangle(int n) { return n*(n+1)/2; } // Basic sanity void basic_tests() { { std::vector<int> v(10); std::fill(v.begin(), v.end(), 3); std::exclusive_scan(v.begin(), v.end(), v.begin(), 50); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 50 + (int) i * 3); } { std::vector<int> v(10); std::iota(v.begin(), v.end(), 0); std::exclusive_scan(v.begin(), v.end(), v.begin(), 30); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 30 + triangle(i-1)); } { std::vector<int> v(10); std::iota(v.begin(), v.end(), 1); std::exclusive_scan(v.begin(), v.end(), v.begin(), 40); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 40 + triangle(i)); } } int main() { basic_tests(); // All the iterator categories test<input_iterator <const int*> >(); test<forward_iterator <const int*> >(); test<bidirectional_iterator<const int*> >(); test<random_access_iterator<const int*> >(); test<const int*>(); test< int*>(); }
/* Copyright (c) 2017-2020, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "../core/Core.hpp" #include "Federate.hpp" #include "helics/helics_enums.h" #include <memory> #include <string> namespace helics { class FilterOperations; class FilterOperator; class CoreApp; /** a set of common defined filters*/ enum class filter_types { custom = helics_filter_type_custom, delay = helics_filter_type_delay, random_delay = helics_filter_type_random_delay, random_drop = helics_filter_type_random_drop, reroute = helics_filter_type_reroute, clone = helics_filter_type_clone, firewall = helics_filter_type_firewall, unrecognized = 7 }; #define EMPTY_STRING std::string() /** get the filter type from a string*/ HELICS_CXX_EXPORT filter_types filterTypeFromString(const std::string& filterType) noexcept; /** class for managing a particular filter*/ class HELICS_CXX_EXPORT Filter { protected: Core* corePtr = nullptr; //!< the Core to use Federate* fed = nullptr; //!< pointer to fed interface_handle handle; //!< the handle as generated by the Federate bool cloning = false; bool disableAssign = false; //!< disable assignment for the object std::string name; //!< The name of the filter private: std::shared_ptr<FilterOperations> filtOp; //!< a class running any specific operation of the Filter public: /** default constructor*/ Filter() = default; /** construct through a federate*/ explicit Filter(Federate* ffed, const std::string& filtName = EMPTY_STRING); /** construct from handle*/ Filter(Federate* ffed, const std::string& filtName, interface_handle ihandle); /** construct through a federate*/ Filter(interface_visibility locality, Federate* ffed, const std::string& filtName = EMPTY_STRING); /** construct through a core object*/ explicit Filter(Core* cr, const std::string& filtName = EMPTY_STRING); /** virtual destructor*/ virtual ~Filter() = default; Filter(Filter&& filt) = default; /** copy the filter, a copied filter will point to the same object*/ Filter(const Filter& filt) = default; Filter& operator=(Filter&& filt) = default; /** copy the filter, a copied filter will point to the same object as the original*/ Filter& operator=(const Filter& filt) = default; /** check if the Filter links to a valid filter*/ bool isValid() const { return handle.isValid(); } /** check if the filter is a cloning filter*/ bool isCloningFilter() const { return cloning; } /** set a message operator to process the message*/ void setOperator(std::shared_ptr<FilterOperator> mo); /** get the underlying core handle for use with a core*/ interface_handle getHandle() const { return handle; } /** implicit conversion operator for extracting the handle*/ operator interface_handle() const { return handle; } /** get the name for the filter*/ const std::string& getName() const { return name; } /** get the full global key for the filter*/ const std::string& getKey() const; /** get the specified input type of the filter*/ const std::string& getInjectionType() const; /** get the specified output type of the filter*/ const std::string& getExtractionType() const; /** get the interface information field of the publication*/ const std::string& getInfo() const; /** set the interface information field of the publication*/ void setInfo(const std::string& info); /** set a property on a filter @param property the name of the property of the filter to change @param val the numerical value of the property */ virtual void set(const std::string& property, double val); /** set a string property on a filter @param property the name of the property of the filter to change @param val the numerical value of the property */ virtual void setString(const std::string& property, const std::string& val); /** add a sourceEndpoint to the list of endpoint to clone*/ virtual void addSourceTarget(const std::string& sourceName); /** add a destination endpoint to the list of endpoints to clone*/ virtual void addDestinationTarget(const std::string& destinationName); /** alias for addSourceTarget*/ void addTarget(const std::string& target) { addSourceTarget(target); } /** remove a sourceEndpoint to the list of endpoint to clone*/ virtual void removeTarget(const std::string& sourceName); /** set an interface option for a filter*/ void setOption(int32_t option, int32_t value); /** close a filter during an active simulation @details it is not necessary to call this function unless you are continuing the simulation after the close*/ void close(); /** get the current value of a flag for the handle*/ int32_t getOption(int32_t option) const; protected: /** set a filter operations object */ void setFilterOperations(std::shared_ptr<FilterOperations> filterOps); /** add a defined operation to a filter*/ friend void addOperations(Filter* filt, filter_types type, Core* cptr); }; /** class used to clone message for delivery to other endpoints*/ class HELICS_CXX_EXPORT CloningFilter: public Filter { public: /** default constructor*/ CloningFilter() = default; /** construct from a core object */ explicit CloningFilter(Core* cr, const std::string& filtName = EMPTY_STRING); /** construct from a Federate */ explicit CloningFilter(Federate* ffed, const std::string& filtName = EMPTY_STRING); /** construct from a Federate */ CloningFilter(interface_visibility locality, Federate* ffed, const std::string& filtName = EMPTY_STRING); /** constructor used by FilterFederateManager*/ CloningFilter(Federate* ffed, const std::string& filtName, interface_handle handle); /** move the filter to a new cloning filter*/ CloningFilter(CloningFilter&& filt) = default; /** copy the filter, a copied filter will point to the same object*/ CloningFilter(const CloningFilter& filt) = default; /** move assign the cloning filter*/ CloningFilter& operator=(CloningFilter&& filt) = default; /** copy the filter, a copied filter will point to the same object as the original*/ CloningFilter& operator=(const CloningFilter& filt) = default; /** destructor */ ~CloningFilter() = default; /** add a delivery address this is the name of an endpoint to deliver the message to*/ void addDeliveryEndpoint(const std::string& endpoint); /** remove a delivery address this is the name of an endpoint to deliver the message to*/ void removeDeliveryEndpoint(const std::string& endpoint); virtual void setString(const std::string& property, const std::string& val) override; private: friend class FilterFederateManager; }; /** create a filter @param type the type of filter to create @param fed the federate to create the filter through @param name the name of the filter (optional) @return a unique pointer to a destination Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT Filter& make_filter(filter_types type, Federate* fed, const std::string& name = EMPTY_STRING); /** create a filter @param locality the visibility of the filter global or local @param type the type of filter to create @param fed the federate to create the filter through @param name the name of the filter (optional) @return a unique pointer to a destination Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT Filter& make_filter(interface_visibility locality, filter_types type, Federate* fed, const std::string& name = EMPTY_STRING); /** create a filter @param type the type of filter to create @param cr the core to create the filter through @param name the name of the filter (optional) @return a unique pointer to a source Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT std::unique_ptr<Filter> make_filter(filter_types type, Core* cr, const std::string& name = EMPTY_STRING); /** create a filter @param type the type of filter to create @param cr the core to create the filter through @param name the name of the filter (optional) @return a unique pointer to a source Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT std::unique_ptr<Filter> make_filter(filter_types type, CoreApp& cr, const std::string& name = EMPTY_STRING); /** create a filter @param type the type of filter to create @param fed the federate to create the filter through @param delivery the endpoint to deliver the cloned message to @param name the name of the filter (optional) @return a unique pointer to a destination Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT CloningFilter& make_cloning_filter(filter_types type, Federate* fed, const std::string& delivery, const std::string& name = EMPTY_STRING); /** create a cloning filter with a specified visibility @param locality can be global or local @param type the type of filter to create @param fed the federate to create the filter through @param delivery the endpoint to deliver the cloned message to @param name the name of the filter (optional) @return a unique pointer to a destination Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT CloningFilter& make_cloning_filter(interface_visibility locality, filter_types type, Federate* fed, const std::string& delivery, const std::string& name = EMPTY_STRING); /** create a cloning filter with a delivery location @param type the type of filter to create @param cr the core to create the filter through @param delivery the endpoint to deliver the cloned message to @param name the name of the filter (optional) @return a unique pointer to a source Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT std::unique_ptr<CloningFilter> make_cloning_filter(filter_types type, Core* cr, const std::string& delivery, const std::string& name = EMPTY_STRING); /** create a cloning filter with a delivery location @param type the type of filter to create @param cr the core to create the filter through @param delivery the endpoint to deliver the cloned message to @param name the name of the filter (optional) @return a unique pointer to a source Filter object, note destroying the object does not deactivate the filter */ HELICS_CXX_EXPORT std::unique_ptr<CloningFilter> make_cloning_filter(filter_types type, CoreApp& cr, const std::string& delivery, const std::string& name = EMPTY_STRING); } // namespace helics
// based on ex15.15 #include <string> #include <iostream> class Quote { public: Quote() = default; Quote(const std::string &book, double pri) : bookNo(book), price(pri) { } virtual ~Quote() = default; std::string isbn() const { return bookNo; } virtual double net_price(std::size_t n) const { return n * price; } virtual std::ostream &debug(std::ostream &os) const { os << "Quote::bookNo " << bookNo << " Quote::price " << price; return os; } protected: double price = 0.0; private: std::string bookNo; }; class Disc_quote : public Quote { public: Disc_quote() = default; Disc_quote(const std::string &book, double pri, std::size_t qty, double disc) : Quote(book, pri), quantity(qty), discount(disc) { } double net_price(std::size_t n) const = 0; std::ostream &debug(std::ostream &os) const override { Quote::debug(os) << " Disc_quote::quantity " << quantity << " Disc_quote::discount " << discount; return os; } protected: std::size_t quantity = 0; double discount = 0.0; }; class Bulk_quote : public Disc_quote { public: Bulk_quote() = default; Bulk_quote(const std::string &book, double pri, std::size_t qty, double disc) : Disc_quote(book, pri, qty, disc) { } double net_price(std::size_t n) const override { if (n >= quantity) return n * price * (1 - discount); else return n * price; } }; class Limit_quote : public Disc_quote { public: Limit_quote() = default; Limit_quote(const std::string &book, double pri, std::size_t qty, double disc) : Disc_quote(book, pri, qty, disc) { } double net_price(std::size_t n) const override { if (n <= quantity) return n * price * (1 - discount); else return (n - quantity) * price + quantity * price * (1 - discount); } }; double print_total(std::ostream &os, const Quote &item, size_t n) { double ret = item.net_price(n); os << "ISBN: " << item.isbn() << " # sold: " << n << " total due: " << ret << std::endl; return ret; } int main() { Disc_quote disc("abc", 5.5, 10, 0.2); // Error, instantiate abstract class return 0; }
#include "mouse_event.h" namespace Echo { MouseEvent::MouseEvent() { } MouseEvent::~MouseEvent() { } void MouseEvent::bindMethods() { CLASS_BIND_METHOD(MouseEvent, getScreenPosition, DEF_METHOD("getScreenPosition")); CLASS_BIND_METHOD(MouseEvent, getWorldPosition, DEF_METHOD("getWorldPosition")); CLASS_BIND_METHOD(MouseEvent, getLocalPosition, DEF_METHOD("getLocalPosition")); } }
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) 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. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/odeconfig.h> #include "config.h" #include "pr.h" #include "joint_internal.h" //**************************************************************************** // Prismatic and Rotoide dxJointPR::dxJointPR( dxWorld *w ) : dxJoint( w ) { // Default Position // Z^ // | Body 1 P R Body2 // |+---------+ _ _ +-----------+ // || |----|----(_)--------+ | // |+---------+ - +-----------+ // | // X.-----------------------------------------> Y // N.B. X is comming out of the page dSetZero( anchor2, 4 ); dSetZero( axisR1, 4 ); axisR1[0] = 1; dSetZero( axisR2, 4 ); axisR2[0] = 1; dSetZero( axisP1, 4 ); axisP1[1] = 1; dSetZero( qrel, 4 ); dSetZero( offset, 4 ); limotR.init( world ); limotP.init( world ); } dReal dJointGetPRPosition( dJointID j ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); dVector3 q; // get the offset in global coordinates dMultiply0_331( q, joint->node[0].body->posr.R, joint->offset ); if ( joint->node[1].body ) { dVector3 anchor2; // get the anchor2 in global coordinates dMultiply0_331( anchor2, joint->node[1].body->posr.R, joint->anchor2 ); q[0] = (( joint->node[0].body->posr.pos[0] + q[0] ) - ( joint->node[1].body->posr.pos[0] + anchor2[0] ) ); q[1] = (( joint->node[0].body->posr.pos[1] + q[1] ) - ( joint->node[1].body->posr.pos[1] + anchor2[1] ) ); q[2] = (( joint->node[0].body->posr.pos[2] + q[2] ) - ( joint->node[1].body->posr.pos[2] + anchor2[2] ) ); } else { //N.B. When there is no body 2 the joint->anchor2 is already in // global coordinates q[0] = (( joint->node[0].body->posr.pos[0] + q[0] ) - ( joint->anchor2[0] ) ); q[1] = (( joint->node[0].body->posr.pos[1] + q[1] ) - ( joint->anchor2[1] ) ); q[2] = (( joint->node[0].body->posr.pos[2] + q[2] ) - ( joint->anchor2[2] ) ); if ( joint->flags & dJOINT_REVERSE ) { q[0] = -q[0]; q[1] = -q[1]; q[2] = -q[2]; } } dVector3 axP; // get prismatic axis in global coordinates dMultiply0_331( axP, joint->node[0].body->posr.R, joint->axisP1 ); return dCalcVectorDot3( axP, q ); } dReal dJointGetPRPositionRate( dJointID j ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); // get axis1 in global coordinates dVector3 ax1; dMultiply0_331( ax1, joint->node[0].body->posr.R, joint->axisP1 ); if ( joint->node[1].body ) { dVector3 lv2; dBodyGetRelPointVel( joint->node[1].body, joint->anchor2[0], joint->anchor2[1], joint->anchor2[2], lv2 ); return dCalcVectorDot3( ax1, joint->node[0].body->lvel ) - dCalcVectorDot3( ax1, lv2 ); } else { dReal rate = dCalcVectorDot3( ax1, joint->node[0].body->lvel ); return ( (joint->flags & dJOINT_REVERSE) ? -rate : rate); } } dReal dJointGetPRAngle( dJointID j ) { dxJointPR* joint = ( dxJointPR* )j; dAASSERT( joint ); checktype( joint, PR ); if ( joint->node[0].body ) { dReal ang = getHingeAngle( joint->node[0].body, joint->node[1].body, joint->axisR1, joint->qrel ); if ( joint->flags & dJOINT_REVERSE ) return -ang; else return ang; } else return 0; } dReal dJointGetPRAngleRate( dJointID j ) { dxJointPR* joint = ( dxJointPR* )j; dAASSERT( joint ); checktype( joint, PR ); if ( joint->node[0].body ) { dVector3 axis; dMultiply0_331( axis, joint->node[0].body->posr.R, joint->axisR1 ); dReal rate = dCalcVectorDot3( axis, joint->node[0].body->avel ); if ( joint->node[1].body ) rate -= dCalcVectorDot3( axis, joint->node[1].body->avel ); if ( joint->flags & dJOINT_REVERSE ) rate = -rate; return rate; } else return 0; } void dxJointPR::getSureMaxInfo( SureMaxInfo* info ) { info->max_m = 6; } void dxJointPR::getInfo1( dxJoint::Info1 *info ) { info->nub = 4; info->m = 4; // see if we're at a joint limit. limotP.limit = 0; if (( limotP.lostop > -dInfinity || limotP.histop < dInfinity ) && limotP.lostop <= limotP.histop ) { // measure joint position dReal pos = dJointGetPRPosition( this ); limotP.testRotationalLimit( pos ); // N.B. The function is ill named } // powered needs an extra constraint row if ( limotP.limit || limotP.fmax > 0 ) info->m++; // see if we're at a joint limit. limotR.limit = 0; if (( limotR.lostop >= -M_PI || limotR.histop <= M_PI ) && limotR.lostop <= limotR.histop ) { dReal angle = getHingeAngle( node[0].body, node[1].body, axisR1, qrel ); limotR.testRotationalLimit( angle ); } // powered morit or at limits needs an extra constraint row if ( limotR.limit || limotR.fmax > 0 ) info->m++; } void dxJointPR::getInfo2( dReal worldFPS, dReal worldERP, const Info2Descr *info ) { int s = info->rowskip; int s2 = 2 * s; int s3 = 3 * s; //int s4= 4*s; dReal k = worldFPS * worldERP; dVector3 q; // plane space of axP and after that axR // pull out pos and R for both bodies. also get the `connection' // vector pos2-pos1. dReal *pos1, *pos2 = 0, *R1, *R2 = 0; pos1 = node[0].body->posr.pos; R1 = node[0].body->posr.R; if ( node[1].body ) { pos2 = node[1].body->posr.pos; R2 = node[1].body->posr.R; } else { // pos2 = 0; // N.B. We can do that to be safe but it is no necessary // R2 = 0; // N.B. We can do that to be safe but it is no necessary } dVector3 axP; // Axis of the prismatic joint in global frame dMultiply0_331( axP, R1, axisP1 ); // distance between the body1 and the anchor2 in global frame // Calculated in the same way as the offset dVector3 wanchor2 = {0,0,0}, dist; if ( node[1].body ) { // Calculate anchor2 in world coordinate dMultiply0_331( wanchor2, R2, anchor2 ); dist[0] = wanchor2[0] + pos2[0] - pos1[0]; dist[1] = wanchor2[1] + pos2[1] - pos1[1]; dist[2] = wanchor2[2] + pos2[2] - pos1[2]; } else { if (flags & dJOINT_REVERSE ) { dist[0] = pos1[0] - anchor2[0]; // Invert the value dist[1] = pos1[1] - anchor2[1]; dist[2] = pos1[2] - anchor2[2]; } else { dist[0] = anchor2[0] - pos1[0]; dist[1] = anchor2[1] - pos1[1]; dist[2] = anchor2[2] - pos1[2]; } } // ====================================================================== // Work on the Rotoide part (i.e. row 0, 1 and maybe 4 if rotoide powered // Set the two rotoide rows. The rotoide axis should be the only unconstrained // rotational axis, the angular velocity of the two bodies perpendicular to // the rotoide axis should be equal. Thus the constraint equations are // p*w1 - p*w2 = 0 // q*w1 - q*w2 = 0 // where p and q are unit vectors normal to the rotoide axis, and w1 and w2 // are the angular velocity vectors of the two bodies. dVector3 ax1; dMultiply0_331( ax1, node[0].body->posr.R, axisR1 ); dCalcVectorCross3( q , ax1, axP ); info->J1a[0] = axP[0]; info->J1a[1] = axP[1]; info->J1a[2] = axP[2]; info->J1a[s+0] = q[0]; info->J1a[s+1] = q[1]; info->J1a[s+2] = q[2]; if ( node[1].body ) { info->J2a[0] = -axP[0]; info->J2a[1] = -axP[1]; info->J2a[2] = -axP[2]; info->J2a[s+0] = -q[0]; info->J2a[s+1] = -q[1]; info->J2a[s+2] = -q[2]; } // Compute the right hand side of the constraint equation set. Relative // body velocities along p and q to bring the rotoide back into alignment. // ax1,ax2 are the unit length rotoide axes of body1 and body2 in world frame. // We need to rotate both bodies along the axis u = (ax1 x ax2). // if `theta' is the angle between ax1 and ax2, we need an angular velocity // along u to cover angle erp*theta in one step : // |angular_velocity| = angle/time = erp*theta / stepsize // = (erp*fps) * theta // angular_velocity = |angular_velocity| * (ax1 x ax2) / |ax1 x ax2| // = (erp*fps) * theta * (ax1 x ax2) / sin(theta) // ...as ax1 and ax2 are unit length. if theta is smallish, // theta ~= sin(theta), so // angular_velocity = (erp*fps) * (ax1 x ax2) // ax1 x ax2 is in the plane space of ax1, so we project the angular // velocity to p and q to find the right hand side. dVector3 ax2; if ( node[1].body ) { dMultiply0_331( ax2, R2, axisR2 ); } else { ax2[0] = axisR2[0]; ax2[1] = axisR2[1]; ax2[2] = axisR2[2]; } dVector3 b; dCalcVectorCross3( b, ax1, ax2 ); info->c[0] = k * dCalcVectorDot3( b, axP ); info->c[1] = k * dCalcVectorDot3( b, q ); // ========================== // Work on the Prismatic part (i.e row 2,3 and 4 if only the prismatic is powered // or 5 if rotoide and prismatic powered // two rows. we want: vel2 = vel1 + w1 x c ... but this would // result in three equations, so we project along the planespace vectors // so that sliding along the prismatic axis is disregarded. for symmetry we // also substitute (w1+w2)/2 for w1, as w1 is supposed to equal w2. // p1 + R1 dist' = p2 + R2 anchor2' ## OLD ## p1 + R1 anchor1' = p2 + R2 dist' // v1 + w1 x R1 dist' + v_p = v2 + w2 x R2 anchor2'## OLD v1 + w1 x R1 anchor1' = v2 + w2 x R2 dist' + v_p // v_p is speed of prismatic joint (i.e. elongation rate) // Since the constraints are perpendicular to v_p we have: // p dot v_p = 0 and q dot v_p = 0 // ax1 dot ( v1 + w1 x dist = v2 + w2 x anchor2 ) // q dot ( v1 + w1 x dist = v2 + w2 x anchor2 ) // == // ax1 . v1 + ax1 . w1 x dist = ax1 . v2 + ax1 . w2 x anchor2 ## OLD ## ax1 . v1 + ax1 . w1 x anchor1 = ax1 . v2 + ax1 . w2 x dist // since a . (b x c) = - b . (a x c) = - (a x c) . b // and a x b = - b x a // ax1 . v1 - ax1 x dist . w1 - ax1 . v2 - (- ax1 x anchor2 . w2) = 0 // ax1 . v1 + dist x ax1 . w1 - ax1 . v2 - anchor2 x ax1 . w2 = 0 // Coeff for 1er line of: J1l => ax1, J2l => -ax1 // Coeff for 2er line of: J1l => q, J2l => -q // Coeff for 1er line of: J1a => dist x ax1, J2a => - anchor2 x ax1 // Coeff for 2er line of: J1a => dist x q, J2a => - anchor2 x q dCalcVectorCross3(( info->J1a ) + s2, dist, ax1 ); dCalcVectorCross3(( info->J1a ) + s3, dist, q ); info->J1l[s2+0] = ax1[0]; info->J1l[s2+1] = ax1[1]; info->J1l[s2+2] = ax1[2]; info->J1l[s3+0] = q[0]; info->J1l[s3+1] = q[1]; info->J1l[s3+2] = q[2]; if ( node[1].body ) { // ax2 x anchor2 instead of anchor2 x ax2 since we want the negative value dCalcVectorCross3(( info->J2a ) + s2, ax2, wanchor2 ); // since ax1 == ax2 // The cross product is in reverse order since we want the negative value dCalcVectorCross3(( info->J2a ) + s3, q, wanchor2 ); info->J2l[s2+0] = -ax1[0]; info->J2l[s2+1] = -ax1[1]; info->J2l[s2+2] = -ax1[2]; info->J2l[s3+0] = -q[0]; info->J2l[s3+1] = -q[1]; info->J2l[s3+2] = -q[2]; } // We want to make correction for motion not in the line of the axisP // We calculate the displacement w.r.t. the anchor pt. // // compute the elements 2 and 3 of right hand side. // we want to align the offset point (in body 2's frame) with the center of body 1. // The position should be the same when we are not along the prismatic axis dVector3 err; dMultiply0_331( err, R1, offset ); err[0] = dist[0] - err[0]; err[1] = dist[1] - err[1]; err[2] = dist[2] - err[2]; info->c[2] = k * dCalcVectorDot3( ax1, err ); info->c[3] = k * dCalcVectorDot3( q, err ); int row = 4; if ( node[1].body || !(flags & dJOINT_REVERSE) ) { row += limotP.addLimot ( this, worldFPS, info, 4, axP, 0 ); } else { dVector3 rAxP; rAxP[0] = -axP[0]; rAxP[1] = -axP[1]; rAxP[2] = -axP[2]; row += limotP.addLimot ( this, worldFPS, info, 4, rAxP, 0 ); } limotR.addLimot ( this, worldFPS, info, row, ax1, 1 ); } // compute initial relative rotation body1 -> body2, or env -> body1 void dxJointPR::computeInitialRelativeRotation() { if ( node[0].body ) { if ( node[1].body ) { dQMultiply1( qrel, node[0].body->q, node[1].body->q ); } else { // set joint->qrel to the transpose of the first body q qrel[0] = node[0].body->q[0]; for ( int i = 1; i < 4; i++ ) qrel[i] = -node[0].body->q[i]; // WARNING do we need the - in -joint->node[0].body->q[i]; or not } } } void dJointSetPRAnchor( dJointID j, dReal x, dReal y, dReal z ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); setAnchors( joint, x, y, z, joint->offset, joint->anchor2 ); } void dJointSetPRAxis1( dJointID j, dReal x, dReal y, dReal z ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); setAxes( joint, x, y, z, joint->axisP1, 0 ); joint->computeInitialRelativeRotation(); } void dJointSetPRAxis2( dJointID j, dReal x, dReal y, dReal z ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); setAxes( joint, x, y, z, joint->axisR1, joint->axisR2 ); joint->computeInitialRelativeRotation(); } void dJointSetPRParam( dJointID j, int parameter, dReal value ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); if (( parameter & 0xff00 ) == 0x100 ) { joint->limotR.set( parameter & 0xff, value ); // Take only lower part of the } // parameter alue else { joint->limotP.set( parameter, value ); } } void dJointGetPRAnchor( dJointID j, dVector3 result ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); dUASSERT( result, "bad result argument" ); checktype( joint, PR ); if ( joint->node[1].body ) getAnchor2( joint, result, joint->anchor2 ); else { result[0] = joint->anchor2[0]; result[1] = joint->anchor2[1]; result[2] = joint->anchor2[2]; } } void dJointGetPRAxis1( dJointID j, dVector3 result ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); dUASSERT( result, "bad result argument" ); checktype( joint, PR ); getAxis( joint, result, joint->axisP1 ); } void dJointGetPRAxis2( dJointID j, dVector3 result ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); dUASSERT( result, "bad result argument" ); checktype( joint, PR ); getAxis( joint, result, joint->axisR1 ); } dReal dJointGetPRParam( dJointID j, int parameter ) { dxJointPR* joint = ( dxJointPR* ) j; dUASSERT( joint, "bad joint argument" ); checktype( joint, PR ); if (( parameter & 0xff00 ) == 0x100 ) { return joint->limotR.get( parameter & 0xff ); } else { return joint->limotP.get( parameter ); } } void dJointAddPRTorque( dJointID j, dReal torque ) { dxJointPR* joint = ( dxJointPR* ) j; dVector3 axis; dAASSERT( joint ); checktype( joint, PR ); if ( joint->flags & dJOINT_REVERSE ) torque = -torque; getAxis( joint, axis, joint->axisR1 ); axis[0] *= torque; axis[1] *= torque; axis[2] *= torque; if ( joint->node[0].body != 0 ) dBodyAddTorque( joint->node[0].body, axis[0], axis[1], axis[2] ); if ( joint->node[1].body != 0 ) dBodyAddTorque( joint->node[1].body, -axis[0], -axis[1], -axis[2] ); } dJointType dxJointPR::type() const { return dJointTypePR; } size_t dxJointPR::size() const { return sizeof( *this ); } void dxJointPR::setRelativeValues() { dVector3 anchor; dJointGetPRAnchor(this, anchor); setAnchors( this, anchor[0], anchor[1], anchor[2], offset, anchor2 ); dVector3 axis; dJointGetPRAxis1(this, axis); setAxes( this, axis[0], axis[1], axis[2], axisP1, 0 ); dJointGetPRAxis2(this, axis); setAxes( this, axis[0], axis[1], axis[2], axisR1, axisR2 ); computeInitialRelativeRotation(); }
#include <microscopes/irm/model.hpp> #include <microscopes/common/relation/dataview.hpp> #include <microscopes/common/random_fwd.hpp> #include <microscopes/models/distributions.hpp> #include <random> #include <iostream> using namespace std; using namespace distributions; using namespace microscopes::common; using namespace microscopes::common::relation; using namespace microscopes::models; using namespace microscopes::irm; using namespace microscopes::io; static inline hyperparam_bag_t crp_hp(float alpha) { CRP m; m.set_alpha(alpha); return util::protobuf_to_string(m); } static inline hyperparam_bag_t beta_bernoulli_hp(float alpha, float beta) { distributions_hypers<BetaBernoulli>::message_type m_feature_hp; m_feature_hp.set_alpha(1.0); m_feature_hp.set_beta(1.0); return util::protobuf_to_string(m_feature_hp); } static inline hyperparam_bag_t nich_hp(float mu=0., float kappa=1., float sigmasq=1., float nu=1.) { distributions_hypers<NormalInverseChiSq>::message_type m; m.set_mu(mu); m.set_kappa(kappa); m.set_sigmasq(sigmasq); m.set_nu(nu); return util::protobuf_to_string(m); } static inline bool almost_eq(float a, float b) { return fabs(a - b) <= 1e-5; } template <typename T> static void assert_vectors_equal(const vector<T> &as, const vector<T> &bs) { MICROSCOPES_CHECK(as.size() == bs.size(), "size"); for (size_t i = 0; i < as.size(); i++) MICROSCOPES_CHECK(as[i] == bs[i], "element"); } template <typename T> static void assert_sets_equal(const set<T> &as, const set<T> &bs) { assert_vectors_equal(vector<T>(as.begin(), as.end()), vector<T>(bs.begin(), bs.end())); } static void test1() { random_device rd; rng_t r(rd()); const size_t n = 3; // 1 domain, // 1 binary relation const model_definition defn( {n}, {relation_definition( {0, 0}, make_shared<distributions_model<BetaBernoulli>>())}); // create fake, absolutely meaningless data for our relation bool *friends = new bool[n*n]; bool *masks = new bool[n*n]; size_t present = 0; for (size_t u = 0; u < n; u++) { for (size_t m = 0; m < n; m++) { const size_t idx = u*n + m; // coin flip to see if this data is present if (bernoulli_distribution(0.2)(r)) { masks[idx] = false; // coin flip to see if friends friends[idx] = bernoulli_distribution(0.8)(r); present++; } else { masks[idx] = true; } } } cout << "present: " << present << endl; unique_ptr<dataview> view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(friends), masks, {n, n}, runtime_type(TYPE_B))); auto s = state<>::initialize( defn, {crp_hp(5.0)}, {beta_bernoulli_hp(2., 2.)}, {{}}, {view.get()}, r); // peek @ suffstats size_t sum = 0; for (auto ident : s->suffstats_identifiers(0)) sum += s->get_suffstats_count(0, ident); MICROSCOPES_CHECK(sum == present, "suff stats don't match up"); const size_t gid = s->remove_value(0, 0, {view.get()}, r); s->add_value(0, gid, 0, {view.get()}, r); sum = 0; for (auto ident : s->suffstats_identifiers(0)) sum += s->get_suffstats_count(0, ident); MICROSCOPES_CHECK(sum == present, "suff stats don't match up"); cout << "test1 completed" << endl; } static void test2() { random_device rd; rng_t r(rd()); // 10 users, 100 movies const vector<size_t> domains({10, 100}); const model_definition defn( domains, {relation_definition({0,1}, make_shared<distributions_model<BetaBernoulli>>())}); // create fake, absolutely meaningless data for our relation bool *likes = new bool[domains[0]*domains[1]]; bool *masks = new bool[domains[0]*domains[1]]; size_t present = 0; for (size_t u = 0; u < domains[0]; u++) { for (size_t m = 0; m < domains[1]; m++) { const size_t idx = u*domains[1] + m; // coin flip to see if this data is present if (bernoulli_distribution(0.2)(r)) { masks[idx] = false; // coin flip to see if user likes likes[idx] = bernoulli_distribution(0.8)(r); present++; } else { masks[idx] = true; } } } cout << "present: " << present << endl; unique_ptr<dataview> view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(likes), masks, domains, runtime_type(TYPE_B))); auto s = state<3>::initialize( defn, {crp_hp(2.0), crp_hp(20.0)}, {beta_bernoulli_hp(2., 2.)}, {{}, {}}, {view.get()}, r); size_t sum = 0; for (auto ident : s->suffstats_identifiers(0)) sum += s->get_suffstats_count(0, ident); MICROSCOPES_CHECK(sum == present, "suff stats don't match up"); // score the 1st data point const size_t gid = s->remove_value(0, 0, {view.get()}, r); s->create_group(0); const auto scores = s->score_value(0, 0, {view.get()}, r); //cout << "scores: " << scores << endl; s->add_value(0, gid, 0, {view.get()}, r); // remove the data for (size_t u = 0; u < domains[0]; u++) s->remove_value(0, u, {view.get()}, r); // peek @ suffstats sum = 0; for (auto ident : s->suffstats_identifiers(0)) sum += s->get_suffstats_count(0, ident); MICROSCOPES_CHECK(!sum, "suff stats don't match up"); delete [] likes; delete [] masks; cout << "test2 completed" << endl; } template <typename T> static pair<unique_ptr<typename T::result_type[]>, unique_ptr<bool []>> binary_relation_generate( size_t domain0, size_t domain1, float p0, T sampler, rng_t &r) { typedef typename T::result_type value_type; unique_ptr<value_type[]> data(new value_type[domain0*domain1]); unique_ptr<bool[]> mask(new bool[domain0*domain1]); for (size_t x = 0; x < domain0; x++) { for (size_t y = 0; y < domain1; y++) { const size_t idx = x*domain1 + y; if (bernoulli_distribution(p0)(r)) { mask[idx] = false; data[idx] = sampler(r); } else { mask[idx] = true; } } } return make_pair(move(data), move(mask)); } static void test3() { random_device rd; rng_t r(rd()); const vector<size_t> domains({10, 5}); const model_definition defn( domains, {relation_definition({0,1}, make_shared<distributions_model<BetaBernoulli>>()), relation_definition({1,1}, make_shared<distributions_model<BetaBernoulli>>())}); auto rel0 = binary_relation_generate( domains[0], domains[1], 0.2, bernoulli_distribution(0.8), r); auto rel1 = binary_relation_generate( domains[1], domains[1], 0.3, bernoulli_distribution(0.7), r); shared_ptr<dataview> rel0view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(rel0.first.get()), rel0.second.get(), {domains[0], domains[1]}, runtime_type(TYPE_B))); shared_ptr<dataview> rel1view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(rel1.first.get()), rel1.second.get(), {domains[1], domains[1]}, runtime_type(TYPE_B))); auto s = state<2>::initialize( defn, {crp_hp(2.0), crp_hp(20.0)}, {beta_bernoulli_hp(2., 2.), beta_bernoulli_hp(2., 3.)}, {{}, {}}, {rel0view.get(), rel1view.get()}, r); microscopes::irm::model<2> s0(s, 0, {rel0view, rel1view}); microscopes::irm::model<2> s1(s, 1, {rel0view, rel1view}); for (size_t i = 0; i < s0.nentities(); i++) { s0.remove_value(i, r); auto scores = s0.score_value(i, r); const auto choice = scores.first[util::sample_discrete_log(scores.second, r)]; s0.add_value(choice, i, r); } for (size_t i = 0; i < s1.nentities(); i++) { s1.remove_value(i, r); auto scores = s1.score_value(i, r); const auto choice = scores.first[util::sample_discrete_log(scores.second, r)]; s1.add_value(choice, i, r); } cout << "test3 completed" << endl; } static void test4() { random_device rd; rng_t r(rd()); const vector<size_t> domains({10, 5, 3}); const model_definition defn( domains, {relation_definition({0,1}, make_shared<distributions_model<BetaBernoulli>>()), relation_definition({2,1}, make_shared<distributions_model<NormalInverseChiSq>>()), relation_definition({0,2}, make_shared<distributions_model<BetaBernoulli>>())}); auto rel0 = binary_relation_generate( domains[0], domains[1], 0.2, bernoulli_distribution(0.8), r); auto rel1 = binary_relation_generate( domains[2], domains[1], 0.3, normal_distribution<float>(), r); auto rel2 = binary_relation_generate( domains[0], domains[2], 0.1, bernoulli_distribution(0.2), r); shared_ptr<dataview> rel0view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(rel0.first.get()), rel0.second.get(), {domains[0], domains[1]}, runtime_type(TYPE_B))); shared_ptr<dataview> rel1view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(rel1.first.get()), rel1.second.get(), {domains[2], domains[1]}, runtime_type(TYPE_F32))); shared_ptr<dataview> rel2view( new row_major_dense_dataview( reinterpret_cast<uint8_t*>(rel2.first.get()), rel2.second.get(), {domains[0], domains[2]}, runtime_type(TYPE_B))); auto s = state<5>::initialize( defn, {crp_hp(2.0), crp_hp(20.0), crp_hp(10.0)}, {beta_bernoulli_hp(2., 2.), nich_hp(), beta_bernoulli_hp(2., 3.)}, {{}, {}, {}}, {rel0view.get(), rel1view.get(), rel2view.get()}, r); const auto raw = s->serialize(); const auto s1 = state<5>::deserialize(defn, raw); MICROSCOPES_CHECK(s->ndomains() == s1->ndomains(), "ndomains"); for (size_t i = 0; i < s->ndomains(); i++) { assert_vectors_equal(s->assignments(i), s1->assignments(i)); assert_vectors_equal(s->groups(i), s1->groups(i)); assert_sets_equal(s->empty_groups(i), s1->empty_groups(i)); } MICROSCOPES_CHECK(s->nrelations() == s1->nrelations(), "nrelations"); for (size_t i = 0; i < s->nrelations(); i++) { assert_vectors_equal(s->suffstats_identifiers(i), s1->suffstats_identifiers(i)); for (auto ident : s->suffstats_identifiers(i)) { MICROSCOPES_CHECK(s->get_suffstats_count(i, ident) == s1->get_suffstats_count(i, ident), "ss count"); if (i == 1) { // nich MICROSCOPES_CHECK( s->get_suffstats_mutator(i, ident, "count").accessor().get<int>() == s1->get_suffstats_mutator(i, ident, "count").accessor().get<int>(), "count"); MICROSCOPES_CHECK( almost_eq( s->get_suffstats_mutator(i, ident, "mean").accessor().get<float>(), s1->get_suffstats_mutator(i, ident, "mean").accessor().get<float>()), "mean"); MICROSCOPES_CHECK( almost_eq( s->get_suffstats_mutator(i, ident, "count_times_variance").accessor().get<float>(), s1->get_suffstats_mutator(i, ident, "count_times_variance").accessor().get<float>()), "count_times_variance"); } else { // bb MICROSCOPES_CHECK( s->get_suffstats_mutator(i, ident, "heads").accessor().get<int>() == s1->get_suffstats_mutator(i, ident, "heads").accessor().get<int>(), "heads"); } } } cout << "test4 completed" << endl; } int main(void) { test1(); test2(); test3(); test4(); return 0; }
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct BASE_HACKSHEILD_PARAMVtbl { bool (WINAPIV *IsLogPass)(struct BASE_HACKSHEILD_PARAM *_this); bool (WINAPIV *OnCheckSession_FirstVerify)(struct BASE_HACKSHEILD_PARAM *_this, int); void (WINAPIV *OnConnect)(struct BASE_HACKSHEILD_PARAM *_this, int); void (WINAPIV *OnLoop)(struct BASE_HACKSHEILD_PARAM *_this); void (WINAPIV *OnDisConnect)(struct BASE_HACKSHEILD_PARAM *_this); bool (WINAPIV *OnRecvSession)(struct BASE_HACKSHEILD_PARAM *_this, struct CHackShieldExSystem *, int, char, unsigned __int64, char *); }; END_ATF_NAMESPACE
//===-- lib/Semantics/mod-file.cpp ----------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "mod-file.h" #include "resolve-names.h" #include "flang/Common/restorer.h" #include "flang/Evaluate/tools.h" #include "flang/Parser/message.h" #include "flang/Parser/parsing.h" #include "flang/Semantics/scope.h" #include "flang/Semantics/semantics.h" #include "flang/Semantics/symbol.h" #include "flang/Semantics/tools.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <fstream> #include <set> #include <string_view> #include <vector> namespace Fortran::semantics { using namespace parser::literals; // The first line of a file that identifies it as a .mod file. // The first three bytes are a Unicode byte order mark that ensures // that the module file is decoded as UTF-8 even if source files // are using another encoding. struct ModHeader { static constexpr const char bom[3 + 1]{"\xef\xbb\xbf"}; static constexpr int magicLen{13}; static constexpr int sumLen{16}; static constexpr const char magic[magicLen + 1]{"!mod$ v1 sum:"}; static constexpr char terminator{'\n'}; static constexpr int len{magicLen + 1 + sumLen}; }; static std::optional<SourceName> GetSubmoduleParent(const parser::Program &); static SymbolVector CollectSymbols(const Scope &); static void PutEntity(llvm::raw_ostream &, const Symbol &); static void PutObjectEntity(llvm::raw_ostream &, const Symbol &); static void PutProcEntity(llvm::raw_ostream &, const Symbol &); static void PutPassName(llvm::raw_ostream &, const std::optional<SourceName> &); static void PutTypeParam(llvm::raw_ostream &, const Symbol &); static void PutEntity( llvm::raw_ostream &, const Symbol &, std::function<void()>, Attrs); static void PutInit(llvm::raw_ostream &, const Symbol &, const MaybeExpr &); static void PutInit(llvm::raw_ostream &, const MaybeIntExpr &); static void PutBound(llvm::raw_ostream &, const Bound &); static llvm::raw_ostream &PutAttrs(llvm::raw_ostream &, Attrs, const MaybeExpr & = std::nullopt, std::string before = ","s, std::string after = ""s); static llvm::raw_ostream &PutAttr(llvm::raw_ostream &, Attr); static llvm::raw_ostream &PutType(llvm::raw_ostream &, const DeclTypeSpec &); static llvm::raw_ostream &PutLower(llvm::raw_ostream &, const std::string &); static std::error_code WriteFile( const std::string &, const std::string &, bool = true); static bool FileContentsMatch( const std::string &, const std::string &, const std::string &); static std::string CheckSum(const std::string_view &); // Collect symbols needed for a subprogram interface class SubprogramSymbolCollector { public: SubprogramSymbolCollector(const Symbol &symbol, const Scope &scope) : symbol_{symbol}, scope_{scope} {} const SymbolVector &symbols() const { return need_; } const std::set<SourceName> &imports() const { return imports_; } void Collect(); private: const Symbol &symbol_; const Scope &scope_; bool isInterface_{false}; SymbolVector need_; // symbols that are needed SymbolSet needSet_; // symbols already in need_ SymbolSet useSet_; // use-associations that might be needed std::set<SourceName> imports_; // imports from host that are needed void DoSymbol(const Symbol &); void DoSymbol(const SourceName &, const Symbol &); void DoType(const DeclTypeSpec *); void DoBound(const Bound &); void DoParamValue(const ParamValue &); bool NeedImport(const SourceName &, const Symbol &); template <typename T> void DoExpr(evaluate::Expr<T> expr) { for (const Symbol &symbol : evaluate::CollectSymbols(expr)) { DoSymbol(symbol); } } }; bool ModFileWriter::WriteAll() { // this flag affects character literals: force it to be consistent auto restorer{ common::ScopedSet(parser::useHexadecimalEscapeSequences, false)}; WriteAll(context_.globalScope()); return !context_.AnyFatalError(); } void ModFileWriter::WriteAll(const Scope &scope) { for (const auto &child : scope.children()) { WriteOne(child); } } void ModFileWriter::WriteOne(const Scope &scope) { if (scope.kind() == Scope::Kind::Module) { auto *symbol{scope.symbol()}; if (!symbol->test(Symbol::Flag::ModFile)) { Write(*symbol); } WriteAll(scope); // write out submodules } } // Construct the name of a module file. Non-empty ancestorName means submodule. static std::string ModFileName(const SourceName &name, const std::string &ancestorName, const std::string &suffix) { std::string result{name.ToString() + suffix}; return ancestorName.empty() ? result : ancestorName + '-' + result; } // Write the module file for symbol, which must be a module or submodule. void ModFileWriter::Write(const Symbol &symbol) { auto *ancestor{symbol.get<ModuleDetails>().ancestor()}; auto ancestorName{ancestor ? ancestor->GetName().value().ToString() : ""s}; auto path{context_.moduleDirectory() + '/' + ModFileName(symbol.name(), ancestorName, context_.moduleFileSuffix())}; PutSymbols(DEREF(symbol.scope())); if (std::error_code error{ WriteFile(path, GetAsString(symbol), context_.debugModuleWriter())}) { context_.Say( symbol.name(), "Error writing %s: %s"_err_en_US, path, error.message()); } } // Return the entire body of the module file // and clear saved uses, decls, and contains. std::string ModFileWriter::GetAsString(const Symbol &symbol) { std::string buf; llvm::raw_string_ostream all{buf}; auto &details{symbol.get<ModuleDetails>()}; if (!details.isSubmodule()) { all << "module " << symbol.name(); } else { auto *parent{details.parent()->symbol()}; auto *ancestor{details.ancestor()->symbol()}; all << "submodule(" << ancestor->name(); if (parent != ancestor) { all << ':' << parent->name(); } all << ") " << symbol.name(); } all << '\n' << uses_.str(); uses_.str().clear(); all << useExtraAttrs_.str(); useExtraAttrs_.str().clear(); all << decls_.str(); decls_.str().clear(); auto str{contains_.str()}; contains_.str().clear(); if (!str.empty()) { all << "contains\n" << str; } all << "end\n"; return all.str(); } // Put out the visible symbols from scope. bool ModFileWriter::PutSymbols(const Scope &scope) { std::string buf; llvm::raw_string_ostream typeBindings{ buf}; // stuff after CONTAINS in derived type for (const Symbol &symbol : CollectSymbols(scope)) { PutSymbol(typeBindings, symbol); } if (auto str{typeBindings.str()}; !str.empty()) { CHECK(scope.IsDerivedType()); decls_ << "contains\n" << str; return true; } else { return false; } } // Emit a symbol to decls_, except for bindings in a derived type (type-bound // procedures, type-bound generics, final procedures) which go to typeBindings. void ModFileWriter::PutSymbol( llvm::raw_ostream &typeBindings, const Symbol &symbol) { std::visit(common::visitors{ [&](const ModuleDetails &) { /* should be current module */ }, [&](const DerivedTypeDetails &) { PutDerivedType(symbol); }, [&](const SubprogramDetails &) { PutSubprogram(symbol); }, [&](const GenericDetails &x) { if (symbol.owner().IsDerivedType()) { // generic binding for (const Symbol &proc : x.specificProcs()) { typeBindings << "generic::" << symbol.name() << "=>" << proc.name() << '\n'; } } else { PutGeneric(symbol); if (x.specific()) { PutSymbol(typeBindings, *x.specific()); } if (x.derivedType()) { PutSymbol(typeBindings, *x.derivedType()); } } }, [&](const UseDetails &) { PutUse(symbol); }, [](const UseErrorDetails &) {}, [&](const ProcBindingDetails &x) { bool deferred{symbol.attrs().test(Attr::DEFERRED)}; typeBindings << "procedure"; if (deferred) { typeBindings << '(' << x.symbol().name() << ')'; } PutPassName(typeBindings, x.passName()); auto attrs{symbol.attrs()}; if (x.passName()) { attrs.reset(Attr::PASS); } PutAttrs(typeBindings, attrs); typeBindings << "::" << symbol.name(); if (!deferred && x.symbol().name() != symbol.name()) { typeBindings << "=>" << x.symbol().name(); } typeBindings << '\n'; }, [&](const NamelistDetails &x) { decls_ << "namelist/" << symbol.name(); char sep{'/'}; for (const Symbol &object : x.objects()) { decls_ << sep << object.name(); sep = ','; } decls_ << '\n'; }, [&](const CommonBlockDetails &x) { decls_ << "common/" << symbol.name(); char sep = '/'; for (const auto &object : x.objects()) { decls_ << sep << object->name(); sep = ','; } decls_ << '\n'; if (symbol.attrs().test(Attr::BIND_C)) { PutAttrs(decls_, symbol.attrs(), x.bindName(), ""s); decls_ << "::/" << symbol.name() << "/\n"; } }, [](const HostAssocDetails &) {}, [](const MiscDetails &) {}, [&](const auto &) { PutEntity(decls_, symbol); }, }, symbol.details()); } void ModFileWriter::PutDerivedType(const Symbol &typeSymbol) { auto &details{typeSymbol.get<DerivedTypeDetails>()}; PutAttrs(decls_ << "type", typeSymbol.attrs()); if (const DerivedTypeSpec * extends{typeSymbol.GetParentTypeSpec()}) { decls_ << ",extends(" << extends->name() << ')'; } decls_ << "::" << typeSymbol.name(); auto &typeScope{*typeSymbol.scope()}; if (!details.paramNames().empty()) { char sep{'('}; for (const auto &name : details.paramNames()) { decls_ << sep << name; sep = ','; } decls_ << ')'; } decls_ << '\n'; if (details.sequence()) { decls_ << "sequence\n"; } bool contains{PutSymbols(typeScope)}; if (!details.finals().empty()) { const char *sep{contains ? "final::" : "contains\nfinal::"}; for (const auto &pair : details.finals()) { decls_ << sep << pair.second->name(); sep = ","; } if (*sep == ',') { decls_ << '\n'; } } decls_ << "end type\n"; } // Attributes that may be in a subprogram prefix static const Attrs subprogramPrefixAttrs{Attr::ELEMENTAL, Attr::IMPURE, Attr::MODULE, Attr::NON_RECURSIVE, Attr::PURE, Attr::RECURSIVE}; void ModFileWriter::PutSubprogram(const Symbol &symbol) { auto attrs{symbol.attrs()}; auto &details{symbol.get<SubprogramDetails>()}; Attrs bindAttrs{}; if (attrs.test(Attr::BIND_C)) { // bind(c) is a suffix, not prefix bindAttrs.set(Attr::BIND_C, true); attrs.set(Attr::BIND_C, false); } Attrs prefixAttrs{subprogramPrefixAttrs & attrs}; // emit any non-prefix attributes in an attribute statement attrs &= ~subprogramPrefixAttrs; std::string ssBuf; llvm::raw_string_ostream ss{ssBuf}; PutAttrs(ss, attrs); if (!ss.str().empty()) { decls_ << ss.str().substr(1) << "::" << symbol.name() << '\n'; } bool isInterface{details.isInterface()}; llvm::raw_ostream &os{isInterface ? decls_ : contains_}; if (isInterface) { os << "interface\n"; } PutAttrs(os, prefixAttrs, std::nullopt, ""s, " "s); os << (details.isFunction() ? "function " : "subroutine "); os << symbol.name() << '('; int n = 0; for (const auto &dummy : details.dummyArgs()) { if (n++ > 0) { os << ','; } if (dummy) { os << dummy->name(); } else { os << "*"; } } os << ')'; PutAttrs(os, bindAttrs, details.bindName(), " "s, ""s); if (details.isFunction()) { const Symbol &result{details.result()}; if (result.name() != symbol.name()) { os << " result(" << result.name() << ')'; } } os << '\n'; // walk symbols, collect ones needed for interface const Scope &scope{ details.entryScope() ? *details.entryScope() : DEREF(symbol.scope())}; SubprogramSymbolCollector collector{symbol, scope}; collector.Collect(); std::string typeBindingsBuf; llvm::raw_string_ostream typeBindings{typeBindingsBuf}; ModFileWriter writer{context_}; for (const Symbol &need : collector.symbols()) { writer.PutSymbol(typeBindings, need); } CHECK(typeBindings.str().empty()); os << writer.uses_.str(); for (const SourceName &import : collector.imports()) { decls_ << "import::" << import << "\n"; } os << writer.decls_.str(); os << "end\n"; if (isInterface) { os << "end interface\n"; } } static bool IsIntrinsicOp(const Symbol &symbol) { if (const auto *details{symbol.GetUltimate().detailsIf<GenericDetails>()}) { return details->kind().IsIntrinsicOperator(); } else { return false; } } static llvm::raw_ostream &PutGenericName( llvm::raw_ostream &os, const Symbol &symbol) { if (IsGenericDefinedOp(symbol)) { return os << "operator(" << symbol.name() << ')'; } else { return os << symbol.name(); } } void ModFileWriter::PutGeneric(const Symbol &symbol) { auto &details{symbol.get<GenericDetails>()}; PutGenericName(decls_ << "interface ", symbol) << '\n'; for (const Symbol &specific : details.specificProcs()) { decls_ << "procedure::" << specific.name() << '\n'; } decls_ << "end interface\n"; if (symbol.attrs().test(Attr::PRIVATE)) { PutGenericName(decls_ << "private::", symbol) << '\n'; } } void ModFileWriter::PutUse(const Symbol &symbol) { auto &details{symbol.get<UseDetails>()}; auto &use{details.symbol()}; uses_ << "use " << GetUsedModule(details).name(); PutGenericName(uses_ << ",only:", symbol); // Can have intrinsic op with different local-name and use-name // (e.g. `operator(<)` and `operator(.lt.)`) but rename is not allowed if (!IsIntrinsicOp(symbol) && use.name() != symbol.name()) { PutGenericName(uses_ << "=>", use); } uses_ << '\n'; PutUseExtraAttr(Attr::VOLATILE, symbol, use); PutUseExtraAttr(Attr::ASYNCHRONOUS, symbol, use); } // We have "USE local => use" in this module. If attr was added locally // (i.e. on local but not on use), also write it out in the mod file. void ModFileWriter::PutUseExtraAttr( Attr attr, const Symbol &local, const Symbol &use) { if (local.attrs().test(attr) && !use.attrs().test(attr)) { PutAttr(useExtraAttrs_, attr) << "::"; useExtraAttrs_ << local.name() << '\n'; } } // Collect the symbols of this scope sorted by their original order, not name. // Namelists are an exception: they are sorted after other symbols. SymbolVector CollectSymbols(const Scope &scope) { SymbolVector sorted; SymbolVector namelist; std::size_t commonSize{scope.commonBlocks().size()}; auto symbols{scope.GetSymbols()}; sorted.reserve(symbols.size() + commonSize); for (SymbolRef symbol : symbols) { if (!symbol->test(Symbol::Flag::ParentComp)) { if (symbol->has<NamelistDetails>()) { namelist.push_back(symbol); } else { sorted.push_back(symbol); } } } sorted.insert(sorted.end(), namelist.begin(), namelist.end()); for (const auto &pair : scope.commonBlocks()) { sorted.push_back(*pair.second); } std::sort(sorted.end() - commonSize, sorted.end()); return sorted; } void PutEntity(llvm::raw_ostream &os, const Symbol &symbol) { std::visit( common::visitors{ [&](const ObjectEntityDetails &) { PutObjectEntity(os, symbol); }, [&](const ProcEntityDetails &) { PutProcEntity(os, symbol); }, [&](const TypeParamDetails &) { PutTypeParam(os, symbol); }, [&](const auto &) { common::die("PutEntity: unexpected details: %s", DetailsToString(symbol.details()).c_str()); }, }, symbol.details()); } void PutShapeSpec(llvm::raw_ostream &os, const ShapeSpec &x) { if (x.lbound().isAssumed()) { CHECK(x.ubound().isAssumed()); os << ".."; } else { if (!x.lbound().isDeferred()) { PutBound(os, x.lbound()); } os << ':'; if (!x.ubound().isDeferred()) { PutBound(os, x.ubound()); } } } void PutShape( llvm::raw_ostream &os, const ArraySpec &shape, char open, char close) { if (!shape.empty()) { os << open; bool first{true}; for (const auto &shapeSpec : shape) { if (first) { first = false; } else { os << ','; } PutShapeSpec(os, shapeSpec); } os << close; } } void PutObjectEntity(llvm::raw_ostream &os, const Symbol &symbol) { auto &details{symbol.get<ObjectEntityDetails>()}; PutEntity( os, symbol, [&]() { PutType(os, DEREF(symbol.GetType())); }, symbol.attrs()); PutShape(os, details.shape(), '(', ')'); PutShape(os, details.coshape(), '[', ']'); PutInit(os, symbol, details.init()); os << '\n'; } void PutProcEntity(llvm::raw_ostream &os, const Symbol &symbol) { if (symbol.attrs().test(Attr::INTRINSIC)) { os << "intrinsic::" << symbol.name() << '\n'; return; } const auto &details{symbol.get<ProcEntityDetails>()}; const ProcInterface &interface{details.interface()}; Attrs attrs{symbol.attrs()}; if (details.passName()) { attrs.reset(Attr::PASS); } PutEntity( os, symbol, [&]() { os << "procedure("; if (interface.symbol()) { os << interface.symbol()->name(); } else if (interface.type()) { PutType(os, *interface.type()); } os << ')'; PutPassName(os, details.passName()); }, attrs); os << '\n'; } void PutPassName( llvm::raw_ostream &os, const std::optional<SourceName> &passName) { if (passName) { os << ",pass(" << *passName << ')'; } } void PutTypeParam(llvm::raw_ostream &os, const Symbol &symbol) { auto &details{symbol.get<TypeParamDetails>()}; PutEntity( os, symbol, [&]() { PutType(os, DEREF(symbol.GetType())); PutLower(os << ',', common::EnumToString(details.attr())); }, symbol.attrs()); PutInit(os, details.init()); os << '\n'; } void PutInit( llvm::raw_ostream &os, const Symbol &symbol, const MaybeExpr &init) { if (init) { if (symbol.attrs().test(Attr::PARAMETER) || symbol.owner().IsDerivedType()) { os << (symbol.attrs().test(Attr::POINTER) ? "=>" : "="); init->AsFortran(os); } } } void PutInit(llvm::raw_ostream &os, const MaybeIntExpr &init) { if (init) { init->AsFortran(os << '='); } } void PutBound(llvm::raw_ostream &os, const Bound &x) { if (x.isAssumed()) { os << '*'; } else if (x.isDeferred()) { os << ':'; } else { x.GetExplicit()->AsFortran(os); } } // Write an entity (object or procedure) declaration. // writeType is called to write out the type. void PutEntity(llvm::raw_ostream &os, const Symbol &symbol, std::function<void()> writeType, Attrs attrs) { writeType(); MaybeExpr bindName; std::visit(common::visitors{ [&](const SubprogramDetails &x) { bindName = x.bindName(); }, [&](const ObjectEntityDetails &x) { bindName = x.bindName(); }, [&](const ProcEntityDetails &x) { bindName = x.bindName(); }, [&](const auto &) {}, }, symbol.details()); PutAttrs(os, attrs, bindName); os << "::" << symbol.name(); } // Put out each attribute to os, surrounded by `before` and `after` and // mapped to lower case. llvm::raw_ostream &PutAttrs(llvm::raw_ostream &os, Attrs attrs, const MaybeExpr &bindName, std::string before, std::string after) { attrs.set(Attr::PUBLIC, false); // no need to write PUBLIC attrs.set(Attr::EXTERNAL, false); // no need to write EXTERNAL if (bindName) { bindName->AsFortran(os << before << "bind(c, name=") << ')' << after; attrs.set(Attr::BIND_C, false); } for (std::size_t i{0}; i < Attr_enumSize; ++i) { Attr attr{static_cast<Attr>(i)}; if (attrs.test(attr)) { PutAttr(os << before, attr) << after; } } return os; } llvm::raw_ostream &PutAttr(llvm::raw_ostream &os, Attr attr) { return PutLower(os, AttrToString(attr)); } llvm::raw_ostream &PutType(llvm::raw_ostream &os, const DeclTypeSpec &type) { return PutLower(os, type.AsFortran()); } llvm::raw_ostream &PutLower(llvm::raw_ostream &os, const std::string &str) { for (char c : str) { os << parser::ToLowerCaseLetter(c); } return os; } struct Temp { Temp(int fd, std::string path) : fd{fd}, path{path} {} Temp(Temp &&t) : fd{std::exchange(t.fd, -1)}, path{std::move(t.path)} {} ~Temp() { if (fd >= 0) { llvm::sys::fs::file_t native{llvm::sys::fs::convertFDToNativeFile(fd)}; llvm::sys::fs::closeFile(native); llvm::sys::fs::remove(path.c_str()); } } int fd; std::string path; }; // Create a temp file in the same directory and with the same suffix as path. // Return an open file descriptor and its path. static llvm::ErrorOr<Temp> MkTemp(const std::string &path) { auto length{path.length()}; auto dot{path.find_last_of("./")}; std::string suffix{ dot < length && path[dot] == '.' ? path.substr(dot + 1) : ""}; CHECK(length > suffix.length() && path.substr(length - suffix.length()) == suffix); auto prefix{path.substr(0, length - suffix.length())}; int fd; llvm::SmallString<16> tempPath; if (std::error_code err{llvm::sys::fs::createUniqueFile( prefix + "%%%%%%" + suffix, fd, tempPath)}) { return err; } return Temp{fd, tempPath.c_str()}; } // Write the module file at path, prepending header. If an error occurs, // return errno, otherwise 0. static std::error_code WriteFile( const std::string &path, const std::string &contents, bool debug) { auto header{std::string{ModHeader::bom} + ModHeader::magic + CheckSum(contents) + ModHeader::terminator}; if (debug) { llvm::dbgs() << "Processing module " << path << ": "; } if (FileContentsMatch(path, header, contents)) { if (debug) { llvm::dbgs() << "module unchanged, not writing\n"; } return {}; } llvm::ErrorOr<Temp> temp{MkTemp(path)}; if (!temp) { return temp.getError(); } llvm::raw_fd_ostream writer(temp->fd, /*shouldClose=*/false); writer << header; writer << contents; writer.flush(); if (writer.has_error()) { return writer.error(); } if (debug) { llvm::dbgs() << "module written\n"; } return llvm::sys::fs::rename(temp->path, path); } // Return true if the stream matches what we would write for the mod file. static bool FileContentsMatch(const std::string &path, const std::string &header, const std::string &contents) { std::size_t hsize{header.size()}; std::size_t csize{contents.size()}; auto buf_or{llvm::MemoryBuffer::getFile(path)}; if (!buf_or) { return false; } auto buf = std::move(buf_or.get()); if (buf->getBufferSize() != hsize + csize) { return false; } if (!std::equal(header.begin(), header.end(), buf->getBufferStart(), buf->getBufferStart() + hsize)) { return false; } return std::equal(contents.begin(), contents.end(), buf->getBufferStart() + hsize, buf->getBufferEnd()); } // Compute a simple hash of the contents of a module file and // return it as a string of hex digits. // This uses the Fowler-Noll-Vo hash function. static std::string CheckSum(const std::string_view &contents) { std::uint64_t hash{0xcbf29ce484222325ull}; for (char c : contents) { hash ^= c & 0xff; hash *= 0x100000001b3; } static const char *digits = "0123456789abcdef"; std::string result(ModHeader::sumLen, '0'); for (size_t i{ModHeader::sumLen}; hash != 0; hash >>= 4) { result[--i] = digits[hash & 0xf]; } return result; } static bool VerifyHeader(llvm::ArrayRef<char> content) { std::string_view sv{content.data(), content.size()}; if (sv.substr(0, ModHeader::magicLen) != ModHeader::magic) { return false; } std::string_view expectSum{sv.substr(ModHeader::magicLen, ModHeader::sumLen)}; std::string actualSum{CheckSum(sv.substr(ModHeader::len))}; return expectSum == actualSum; } Scope *ModFileReader::Read(const SourceName &name, Scope *ancestor) { std::string ancestorName; // empty for module if (ancestor) { if (auto *scope{ancestor->FindSubmodule(name)}) { return scope; } ancestorName = ancestor->GetName().value().ToString(); } else { auto it{context_.globalScope().find(name)}; if (it != context_.globalScope().end()) { return it->second->scope(); } } parser::Parsing parsing{context_.allCookedSources()}; parser::Options options; options.isModuleFile = true; options.features.Enable(common::LanguageFeature::BackslashEscapes); options.searchDirectories = context_.searchDirectories(); auto path{ModFileName(name, ancestorName, context_.moduleFileSuffix())}; const auto *sourceFile{parsing.Prescan(path, options)}; if (parsing.messages().AnyFatalError()) { for (auto &msg : parsing.messages().messages()) { std::string str{msg.ToString()}; Say(name, ancestorName, parser::MessageFixedText{str.c_str(), str.size()}, path); } return nullptr; } CHECK(sourceFile); if (!VerifyHeader(sourceFile->content())) { Say(name, ancestorName, "File has invalid checksum: %s"_en_US, sourceFile->path()); return nullptr; } llvm::raw_null_ostream NullStream; parsing.Parse(NullStream); auto &parseTree{parsing.parseTree()}; if (!parsing.messages().empty() || !parsing.consumedWholeFile() || !parseTree) { Say(name, ancestorName, "Module file is corrupt: %s"_err_en_US, sourceFile->path()); return nullptr; } Scope *parentScope; // the scope this module/submodule goes into if (!ancestor) { parentScope = &context_.globalScope(); } else if (std::optional<SourceName> parent{GetSubmoduleParent(*parseTree)}) { parentScope = Read(*parent, ancestor); } else { parentScope = ancestor; } ResolveNames(context_, *parseTree); const auto &it{parentScope->find(name)}; if (it == parentScope->end()) { return nullptr; } auto &modSymbol{*it->second}; modSymbol.set(Symbol::Flag::ModFile); return modSymbol.scope(); } parser::Message &ModFileReader::Say(const SourceName &name, const std::string &ancestor, parser::MessageFixedText &&msg, const std::string &arg) { return context_ .Say(name, ancestor.empty() ? "Error reading module file for module '%s'"_err_en_US : "Error reading module file for submodule '%s' of module '%s'"_err_en_US, name, ancestor) .Attach(name, std::move(msg), arg); } // program was read from a .mod file for a submodule; return the name of the // submodule's parent submodule, nullptr if none. static std::optional<SourceName> GetSubmoduleParent( const parser::Program &program) { CHECK(program.v.size() == 1); auto &unit{program.v.front()}; auto &submod{std::get<common::Indirection<parser::Submodule>>(unit.u)}; auto &stmt{ std::get<parser::Statement<parser::SubmoduleStmt>>(submod.value().t)}; auto &parentId{std::get<parser::ParentIdentifier>(stmt.statement.t)}; if (auto &parent{std::get<std::optional<parser::Name>>(parentId.t)}) { return parent->source; } else { return std::nullopt; } } void SubprogramSymbolCollector::Collect() { const auto &details{symbol_.get<SubprogramDetails>()}; isInterface_ = details.isInterface(); for (const Symbol *dummyArg : details.dummyArgs()) { if (dummyArg) { DoSymbol(*dummyArg); } } if (details.isFunction()) { DoSymbol(details.result()); } for (const auto &pair : scope_) { const Symbol &symbol{*pair.second}; if (const auto *useDetails{symbol.detailsIf<UseDetails>()}) { if (useSet_.count(useDetails->symbol().GetUltimate()) > 0) { need_.push_back(symbol); } } } } void SubprogramSymbolCollector::DoSymbol(const Symbol &symbol) { DoSymbol(symbol.name(), symbol); } // Do symbols this one depends on; then add to need_ void SubprogramSymbolCollector::DoSymbol( const SourceName &name, const Symbol &symbol) { const auto &scope{symbol.owner()}; if (scope != scope_ && !scope.IsDerivedType()) { if (scope != scope_.parent()) { useSet_.insert(symbol); } if (NeedImport(name, symbol)) { imports_.insert(name); } return; } if (!needSet_.insert(symbol).second) { return; // already done } std::visit(common::visitors{ [this](const ObjectEntityDetails &details) { for (const ShapeSpec &spec : details.shape()) { DoBound(spec.lbound()); DoBound(spec.ubound()); } for (const ShapeSpec &spec : details.coshape()) { DoBound(spec.lbound()); DoBound(spec.ubound()); } if (const Symbol * commonBlock{details.commonBlock()}) { DoSymbol(*commonBlock); } }, [this](const CommonBlockDetails &details) { for (const auto &object : details.objects()) { DoSymbol(*object); } }, [](const auto &) {}, }, symbol.details()); if (!symbol.has<UseDetails>()) { DoType(symbol.GetType()); } if (!scope.IsDerivedType()) { need_.push_back(symbol); } } void SubprogramSymbolCollector::DoType(const DeclTypeSpec *type) { if (!type) { return; } switch (type->category()) { case DeclTypeSpec::Numeric: case DeclTypeSpec::Logical: break; // nothing to do case DeclTypeSpec::Character: DoParamValue(type->characterTypeSpec().length()); break; default: if (const DerivedTypeSpec * derived{type->AsDerived()}) { const auto &typeSymbol{derived->typeSymbol()}; if (const DerivedTypeSpec * extends{typeSymbol.GetParentTypeSpec()}) { DoSymbol(extends->name(), extends->typeSymbol()); } for (const auto &pair : derived->parameters()) { DoParamValue(pair.second); } for (const auto &pair : *typeSymbol.scope()) { const Symbol &comp{*pair.second}; DoSymbol(comp); } DoSymbol(derived->name(), derived->typeSymbol()); } } } void SubprogramSymbolCollector::DoBound(const Bound &bound) { if (const MaybeSubscriptIntExpr & expr{bound.GetExplicit()}) { DoExpr(*expr); } } void SubprogramSymbolCollector::DoParamValue(const ParamValue &paramValue) { if (const auto &expr{paramValue.GetExplicit()}) { DoExpr(*expr); } } // Do we need a IMPORT of this symbol into an interface block? bool SubprogramSymbolCollector::NeedImport( const SourceName &name, const Symbol &symbol) { if (!isInterface_) { return false; } else if (symbol.owner() != scope_.parent()) { // detect import from parent of use-associated symbol // can be null in the case of a use-associated derived type's parent type const auto *found{scope_.FindSymbol(name)}; CHECK(found || symbol.has<DerivedTypeDetails>()); return found && found->has<UseDetails>() && found->owner() != scope_; } else { return true; } } } // namespace Fortran::semantics
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd 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 "OgreBspResourceManager.h" #include "OgreBspLevel.h" #include "OgreQuake3ShaderManager.h" namespace Ogre { //----------------------------------------------------------------------- template<> BspResourceManager* Singleton<BspResourceManager>::ms_Singleton = 0; BspResourceManager* BspResourceManager::getSingletonPtr(void) { return ms_Singleton; } BspResourceManager& BspResourceManager::getSingleton(void) { assert( ms_Singleton ); return ( *ms_Singleton ); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- BspResourceManager::BspResourceManager() { mResourceType = "BspLevel"; // Also create related shader manager (singleton managed) mShaderMgr = OGRE_NEW Quake3ShaderManager(); ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); } //----------------------------------------------------------------------- BspResourceManager::~BspResourceManager() { OGRE_DELETE mShaderMgr; ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); } //----------------------------------------------------------------------- ResourcePtr BspResourceManager::load(const String& name, const String& group, bool isManual, ManualResourceLoader* loader, const NameValuePairList* loadParams) { // Only 1 BSP level allowed loaded at once removeAll(); return ResourceManager::load(name, group, isManual, loader, loadParams); } //----------------------------------------------------------------------- ResourcePtr BspResourceManager::load(DataStreamPtr& stream, const String& group) { // Only 1 BSP level allowed loaded at once removeAll(); ResourcePtr ret = create("bsplevel", group, true, 0); BspLevelPtr bspLevel = ret; bspLevel->load(stream); return ret; } //----------------------------------------------------------------------- Resource* BspResourceManager::createImpl(const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, const NameValuePairList* createParams) { return OGRE_NEW BspLevel(this, name, handle, group, isManual, loader); } }
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Volker Mosthaf $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FILTERING/TRANSFORMERS/SqrtMower.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> #include <cmath> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(SqrtMower, "$Id$") ///////////////////////////////////////////////////////////// SqrtMower* e_ptr = 0; SqrtMower* e_nullPointer = 0; START_SECTION((SqrtMower())) e_ptr = new SqrtMower; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~SqrtMower())) delete e_ptr; END_SECTION e_ptr = new SqrtMower(); START_SECTION((SqrtMower(const SqrtMower& source))) SqrtMower copy(*e_ptr); TEST_EQUAL(*e_ptr == copy, true) END_SECTION START_SECTION((SqrtMower& operator=(const SqrtMower& source))) SqrtMower copy; copy = *e_ptr; TEST_EQUAL(*e_ptr == copy, true) END_SECTION START_SECTION((template<typename SpectrumType> void filterSpectrum(SpectrumType& spectrum))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), 37.5) e_ptr->filterSpectrum(spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), sqrt(37.5)) END_SECTION START_SECTION((void filterPeakMap(PeakMap& exp))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); PeakMap pm; pm.addSpectrum(spec); TEST_REAL_SIMILAR((pm.begin()->begin() + 40)->getIntensity(), 37.5) e_ptr->filterPeakMap(pm); TEST_REAL_SIMILAR((pm.begin()->begin() + 40)->getIntensity(), sqrt(37.5)) END_SECTION START_SECTION((void filterPeakSpectrum(PeakSpectrum& spectrum))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), 37.5) e_ptr->filterPeakSpectrum(spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), sqrt(37.5)) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Interface/Application/GuiLogger.h> #include <Core/Logging/Log.h> using namespace SCIRun::Gui; using namespace SCIRun::Core::Logging; void GuiLogger::logInfo(const QString& message) { GuiLog::Instance().get()->info(message.toStdString()); if (LogSettings::Instance().verbose()) GeneralLog::Instance().get()->info(message.toStdString()); } void GuiLogger::logError(const QString& message) { GuiLog::Instance().get()->error(message.toStdString()); GeneralLog::Instance().get()->error(message.toStdString()); } CORE_SINGLETON_IMPLEMENTATION(GuiLog)
/*************************************************************************/ /* polygon_path_finder.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "polygon_path_finder.h" #include "core/math/geometry.h" bool PolygonPathFinder::_is_point_inside(const Vector2 &p_point) const { int crosses = 0; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; if (Geometry::segment_intersects_segment_2d(a, b, p_point, outside_point, nullptr)) { crosses++; } } return crosses & 1; } void PolygonPathFinder::setup(const Vector<Vector2> &p_points, const Vector<int> &p_connections) { ERR_FAIL_COND(p_connections.size() & 1); points.clear(); edges.clear(); //insert points int point_count = p_points.size(); points.resize(point_count + 2); bounds = Rect2(); for (int i = 0; i < p_points.size(); i++) { points.write[i].pos = p_points[i]; points.write[i].penalty = 0; outside_point.x = i == 0 ? p_points[0].x : (MAX(p_points[i].x, outside_point.x)); outside_point.y = i == 0 ? p_points[0].y : (MAX(p_points[i].y, outside_point.y)); if (i == 0) { bounds.position = points[i].pos; } else { bounds.expand_to(points[i].pos); } } outside_point.x += 20.451 + Math::randf() * 10.2039; outside_point.y += 21.193 + Math::randf() * 12.5412; //insert edges (which are also connetions) for (int i = 0; i < p_connections.size(); i += 2) { Edge e(p_connections[i], p_connections[i + 1]); ERR_FAIL_INDEX(e.points[0], point_count); ERR_FAIL_INDEX(e.points[1], point_count); points.write[p_connections[i]].connections.insert(p_connections[i + 1]); points.write[p_connections[i + 1]].connections.insert(p_connections[i]); edges.insert(e); } //fill the remaining connections based on visibility for (int i = 0; i < point_count; i++) { for (int j = i + 1; j < point_count; j++) { if (edges.has(Edge(i, j))) { continue; //if in edge ignore } Vector2 from = points[i].pos; Vector2 to = points[j].pos; if (!_is_point_inside(from * 0.5 + to * 0.5)) { //connection between points in inside space continue; } bool valid = true; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); if (e.points[0] == i || e.points[1] == i || e.points[0] == j || e.points[1] == j) { continue; } Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; if (Geometry::segment_intersects_segment_2d(a, b, from, to, nullptr)) { valid = false; break; } } if (valid) { points.write[i].connections.insert(j); points.write[j].connections.insert(i); } } } } Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector2 &p_to) { Vector<Vector2> path; Vector2 from = p_from; Vector2 to = p_to; Edge ignore_from_edge(-1, -1); Edge ignore_to_edge(-1, -1); if (!_is_point_inside(from)) { float closest_dist = 1e20f; Vector2 closest_point; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); Vector2 seg[2] = { points[e.points[0]].pos, points[e.points[1]].pos }; Vector2 closest = Geometry::get_closest_point_to_segment_2d(from, seg); float d = from.distance_squared_to(closest); if (d < closest_dist) { ignore_from_edge = E->get(); closest_dist = d; closest_point = closest; } } from = closest_point; }; if (!_is_point_inside(to)) { float closest_dist = 1e20f; Vector2 closest_point; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); Vector2 seg[2] = { points[e.points[0]].pos, points[e.points[1]].pos }; Vector2 closest = Geometry::get_closest_point_to_segment_2d(to, seg); float d = to.distance_squared_to(closest); if (d < closest_dist) { ignore_to_edge = E->get(); closest_dist = d; closest_point = closest; } } to = closest_point; }; //test direct connection { bool can_see_eachother = true; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); if (e.points[0] == ignore_from_edge.points[0] && e.points[1] == ignore_from_edge.points[1]) { continue; } if (e.points[0] == ignore_to_edge.points[0] && e.points[1] == ignore_to_edge.points[1]) { continue; } Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; if (Geometry::segment_intersects_segment_2d(a, b, from, to, nullptr)) { can_see_eachother = false; break; } } if (can_see_eachother) { path.push_back(from); path.push_back(to); return path; } } //add to graph int aidx = points.size() - 2; int bidx = points.size() - 1; points.write[aidx].pos = from; points.write[bidx].pos = to; points.write[aidx].distance = 0; points.write[bidx].distance = 0; points.write[aidx].prev = -1; points.write[bidx].prev = -1; points.write[aidx].penalty = 0; points.write[bidx].penalty = 0; for (int i = 0; i < points.size() - 2; i++) { bool valid_a = true; bool valid_b = true; points.write[i].prev = -1; points.write[i].distance = 0; if (!_is_point_inside(from * 0.5 + points[i].pos * 0.5)) { valid_a = false; } if (!_is_point_inside(to * 0.5 + points[i].pos * 0.5)) { valid_b = false; } for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); if (e.points[0] == i || e.points[1] == i) { continue; } Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; if (valid_a) { if (e.points[0] != ignore_from_edge.points[1] && e.points[1] != ignore_from_edge.points[1] && e.points[0] != ignore_from_edge.points[0] && e.points[1] != ignore_from_edge.points[0]) { if (Geometry::segment_intersects_segment_2d(a, b, from, points[i].pos, nullptr)) { valid_a = false; } } } if (valid_b) { if (e.points[0] != ignore_to_edge.points[1] && e.points[1] != ignore_to_edge.points[1] && e.points[0] != ignore_to_edge.points[0] && e.points[1] != ignore_to_edge.points[0]) { if (Geometry::segment_intersects_segment_2d(a, b, to, points[i].pos, nullptr)) { valid_b = false; } } } if (!valid_a && !valid_b) { break; } } if (valid_a) { points.write[i].connections.insert(aidx); points.write[aidx].connections.insert(i); } if (valid_b) { points.write[i].connections.insert(bidx); points.write[bidx].connections.insert(i); } } //solve graph Set<int> open_list; points.write[aidx].distance = 0; points.write[aidx].prev = aidx; for (Set<int>::Element *E = points[aidx].connections.front(); E; E = E->next()) { open_list.insert(E->get()); points.write[E->get()].distance = from.distance_to(points[E->get()].pos); points.write[E->get()].prev = aidx; } bool found_route = false; while (true) { if (open_list.size() == 0) { printf("open list empty\n"); break; } //check open list int least_cost_point = -1; float least_cost = 1e30; //this could be faster (cache previous results) for (Set<int>::Element *E = open_list.front(); E; E = E->next()) { const Point &p = points[E->get()]; float cost = p.distance; cost += p.pos.distance_to(to); cost += p.penalty; if (cost < least_cost) { least_cost_point = E->get(); least_cost = cost; } } const Point &np = points[least_cost_point]; //open the neighbours for search for (Set<int>::Element *E = np.connections.front(); E; E = E->next()) { Point &p = points.write[E->get()]; float distance = np.pos.distance_to(p.pos) + np.distance; if (p.prev != -1) { //oh this was visited already, can we win the cost? if (p.distance > distance) { p.prev = least_cost_point; //reasign previous p.distance = distance; } } else { //add to open neighbours p.prev = least_cost_point; p.distance = distance; open_list.insert(E->get()); if (E->get() == bidx) { //oh my reached end! stop algorithm found_route = true; break; } } } if (found_route) { break; } open_list.erase(least_cost_point); } if (found_route) { int at = bidx; path.push_back(points[at].pos); do { at = points[at].prev; path.push_back(points[at].pos); } while (at != aidx); path.invert(); } for (int i = 0; i < points.size() - 2; i++) { points.write[i].connections.erase(aidx); points.write[i].connections.erase(bidx); points.write[i].prev = -1; points.write[i].distance = 0; } points.write[aidx].connections.clear(); points.write[aidx].prev = -1; points.write[aidx].distance = 0; points.write[bidx].connections.clear(); points.write[bidx].prev = -1; points.write[bidx].distance = 0; return path; } void PolygonPathFinder::_set_data(const Dictionary &p_data) { ERR_FAIL_COND(!p_data.has("points")); ERR_FAIL_COND(!p_data.has("connections")); ERR_FAIL_COND(!p_data.has("segments")); ERR_FAIL_COND(!p_data.has("bounds")); PoolVector<Vector2> p = p_data["points"]; Array c = p_data["connections"]; ERR_FAIL_COND(c.size() != p.size()); if (c.size()) { return; } int pc = p.size(); points.resize(pc + 2); PoolVector<Vector2>::Read pr = p.read(); for (int i = 0; i < pc; i++) { points.write[i].pos = pr[i]; PoolVector<int> con = c[i]; PoolVector<int>::Read cr = con.read(); int cc = con.size(); for (int j = 0; j < cc; j++) { points.write[i].connections.insert(cr[j]); } } if (p_data.has("penalties")) { PoolVector<float> penalties = p_data["penalties"]; if (penalties.size() == pc) { PoolVector<float>::Read pr2 = penalties.read(); for (int i = 0; i < pc; i++) { points.write[i].penalty = pr2[i]; } } } PoolVector<int> segs = p_data["segments"]; int sc = segs.size(); ERR_FAIL_COND(sc & 1); PoolVector<int>::Read sr = segs.read(); for (int i = 0; i < sc; i += 2) { Edge e(sr[i], sr[i + 1]); edges.insert(e); } bounds = p_data["bounds"]; } Dictionary PolygonPathFinder::_get_data() const { Dictionary d; PoolVector<Vector2> p; PoolVector<int> ind; Array connections; p.resize(MAX(0, points.size() - 2)); connections.resize(MAX(0, points.size() - 2)); ind.resize(edges.size() * 2); PoolVector<float> penalties; penalties.resize(MAX(0, points.size() - 2)); { PoolVector<Vector2>::Write wp = p.write(); PoolVector<float>::Write pw = penalties.write(); for (int i = 0; i < points.size() - 2; i++) { wp[i] = points[i].pos; pw[i] = points[i].penalty; PoolVector<int> c; c.resize(points[i].connections.size()); { PoolVector<int>::Write cw = c.write(); int idx = 0; for (Set<int>::Element *E = points[i].connections.front(); E; E = E->next()) { cw[idx++] = E->get(); } } connections[i] = c; } } { PoolVector<int>::Write iw = ind.write(); int idx = 0; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { iw[idx++] = E->get().points[0]; iw[idx++] = E->get().points[1]; } } d["bounds"] = bounds; d["points"] = p; d["penalties"] = penalties; d["connections"] = connections; d["segments"] = ind; return d; } bool PolygonPathFinder::is_point_inside(const Vector2 &p_point) const { return _is_point_inside(p_point); } Vector2 PolygonPathFinder::get_closest_point(const Vector2 &p_point) const { float closest_dist = 1e20f; Vector2 closest_point; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { const Edge &e = E->get(); Vector2 seg[2] = { points[e.points[0]].pos, points[e.points[1]].pos }; Vector2 closest = Geometry::get_closest_point_to_segment_2d(p_point, seg); float d = p_point.distance_squared_to(closest); if (d < closest_dist) { closest_dist = d; closest_point = closest; } } ERR_FAIL_COND_V(Math::is_equal_approx(closest_dist, 1e20f), Vector2()); return closest_point; } Vector<Vector2> PolygonPathFinder::get_intersections(const Vector2 &p_from, const Vector2 &p_to) const { Vector<Vector2> inters; for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { Vector2 a = points[E->get().points[0]].pos; Vector2 b = points[E->get().points[1]].pos; Vector2 res; if (Geometry::segment_intersects_segment_2d(a, b, p_from, p_to, &res)) { inters.push_back(res); } } return inters; } Rect2 PolygonPathFinder::get_bounds() const { return bounds; } void PolygonPathFinder::set_point_penalty(int p_point, float p_penalty) { ERR_FAIL_INDEX(p_point, points.size() - 2); points.write[p_point].penalty = p_penalty; } float PolygonPathFinder::get_point_penalty(int p_point) const { ERR_FAIL_INDEX_V(p_point, points.size() - 2, 0); return points[p_point].penalty; } void PolygonPathFinder::_bind_methods() { ClassDB::bind_method(D_METHOD("setup", "points", "connections"), &PolygonPathFinder::setup); ClassDB::bind_method(D_METHOD("find_path", "from", "to"), &PolygonPathFinder::find_path); ClassDB::bind_method(D_METHOD("get_intersections", "from", "to"), &PolygonPathFinder::get_intersections); ClassDB::bind_method(D_METHOD("get_closest_point", "point"), &PolygonPathFinder::get_closest_point); ClassDB::bind_method(D_METHOD("is_point_inside", "point"), &PolygonPathFinder::is_point_inside); ClassDB::bind_method(D_METHOD("set_point_penalty", "idx", "penalty"), &PolygonPathFinder::set_point_penalty); ClassDB::bind_method(D_METHOD("get_point_penalty", "idx"), &PolygonPathFinder::get_point_penalty); ClassDB::bind_method(D_METHOD("get_bounds"), &PolygonPathFinder::get_bounds); ClassDB::bind_method(D_METHOD("_set_data"), &PolygonPathFinder::_set_data); ClassDB::bind_method(D_METHOD("_get_data"), &PolygonPathFinder::_get_data); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data"); } PolygonPathFinder::PolygonPathFinder() { }
#include <iostream> using namespace std; int main(void) { short a, b; cin >> a >> b; if ((a + b) % 2 == 0) cout << "Bino"; else cout << "Cino"; cout << endl; return 0; }
#include "ledplayer.h" LEDPlayer::LEDStatus::LEDStatus(const int& cc, const int& a) { colorCode = cc; alpha = a; } LEDPlayer::LEDStatus& LEDPlayer::LEDStatus::operator=(const LEDPlayer::LEDStatus& ls) { colorCode = ls.colorCode; alpha = ls.alpha; return *this; } LEDPlayer::Frame::Frame(const size_t& _start, const bool& _fade, const json& _status) { start = _start; fade = _fade; status.reserve(_status.size()); for (auto& ls : _status) status.push_back(LEDStatus((int)ls["colorCode"], (int)ls["alpha"])); } LEDPlayer::Frame& LEDPlayer::Frame::operator=(const LEDPlayer::Frame& f) { start = f.start; fade = f.fade; status = f.status; return *this; } void LEDPlayer::load(const json& pl) { playList.reserve(pl.size()); for (auto& f : pl) { Frame frame(f["start"], f["fade"], f["status"]); if (frame.status.size() != len) { cout << name << endl; cout << "Frame status length: " << frame.status.size(); cout << "Frame time: " << frame.start << endl; cout << "Expected Frame status length: " << len << endl; continue; } playList.push_back(frame); } playList[playList.size() - 1].fade = false; } LEDPlayer::Frame LEDPlayer::getFrame(const size_t& time) { frameId = getFrameId(time); return playList[frameId].fade ? getFadeFrame(time) : playList[frameId]; } bool LEDPlayer::isFinished() const { return playList.size() - 1 == frameId; } size_t LEDPlayer::getFrameId(const size_t& time) const { const size_t totalFrame = playList.size(); if (totalFrame == 0) return 0; if (time > playList[playList.size() - 1].start) return playList.size() - 1; if (time == 0) return 0; if (time >= playList[frameId].start) { if (frameId < playList.size() - 1) if (time < playList[frameId + 1].start) return frameId; if (frameId < playList.size() - 2) if (time >= playList[frameId + 1].start && time < playList[frameId + 2].start) return frameId + 1; } size_t first = 0; size_t last = totalFrame - 1; while (first <= last) { const size_t mid = (first + last) >> 1; if (time > playList[mid].start) first = mid + 1; else if (time == playList[mid].start) return mid; else last = mid - 1; } if (time < playList[first].start) --first; return first; } LEDPlayer::Frame LEDPlayer::getFadeFrame(const size_t& time) const { const size_t firstTime = playList[frameId].start; const size_t secondTime = playList[frameId + 1].start; const float rate = (float)(time - firstTime) / (float)(secondTime - firstTime); Frame f; f.start = time; f.fade = true; for (int i = 0; i < len; ++i) { const int cc = rgbHexInterpolate(playList[frameId].status[i].colorCode, playList[frameId + 1].status[i].colorCode, rate); const int a = (int)round((1 - rate) * double(playList[frameId].status[i].alpha) + rate * double(playList[frameId + 1].status[i].alpha)); f.status.push_back(LEDStatus(cc, a)); } return f; } int LEDPlayer::getFrameNum() const { return playList.size(); } size_t LEDPlayer::getEndTime() const { return playList[playList.size() - 1].start; }
/*********************************************************\ * File: Script.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] extern "C" { #include <Lua/lua.h> #include <Lua/lualib.h> #include <Lua/lauxlib.h> } #include <PLCore/Log/Log.h> #include <PLCore/File/File.h> #include "PLScriptLua/LuaContext.h" #include "PLScriptLua/RTTIObjectPointer.h" #include "PLScriptLua/RTTIObjectMethodPointer.h" #include "PLScriptLua/Script.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLScriptLua { //[-------------------------------------------------------] //[ RTTI interface ] //[-------------------------------------------------------] pl_implement_class(Script) //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Default constructor */ Script::Script() : m_pLuaState(nullptr), m_bFunctionResult(false), m_nCurrentArgument(0) { // Add a context reference LuaContext::AddContextReference(); } /** * @brief * Destructor */ Script::~Script() { // Clear the script Clear(); // Remove all global functions RemoveAllGlobalFunctions(); // Release a context reference LuaContext::ReleaseContextReference(); } /** * @brief * Returns the Lua state */ lua_State *Script::GetLuaState() const { return m_pLuaState; } /** * @brief * Writes the current Lua stack content into the log */ void Script::LuaStackDump() { // Is there a Lua state? if (m_pLuaState) { // Get the number of elements on the Lua stack const int nNumOfStackElements = lua_gettop(m_pLuaState); // Write this number into the log LogOutput(Log::Info, String("Number of elements on the Lua stack: ") + nNumOfStackElements); // Iterate through the Lua stack for (int i=1; i<=nNumOfStackElements; i++) { const int nLuaType = lua_type(m_pLuaState, i); String sValue; switch (nLuaType) { case LUA_TNIL: sValue = "nil"; break; case LUA_TNUMBER: sValue = lua_tonumber(m_pLuaState, i); break; case LUA_TBOOLEAN: sValue = lua_toboolean(m_pLuaState, i) ? "true" : "false"; break; case LUA_TSTRING: sValue = lua_tostring(m_pLuaState, i); break; case LUA_TTABLE: sValue = "Table"; break; case LUA_TFUNCTION: sValue = lua_iscfunction(m_pLuaState, i) ? "C-function" : "Lua-function"; break; case LUA_TUSERDATA: sValue = "User data"; break; case LUA_TTHREAD: sValue = "Thread"; break; case LUA_TLIGHTUSERDATA: sValue = "Light user data"; break; default: sValue = "?"; break; } LogOutput(Log::Info, String("Lua stack element ") + (i-1) + ": \"" + sValue + "\" (Lua type name: \"" + lua_typename(m_pLuaState, nLuaType) + "\")"); } } } //[-------------------------------------------------------] //[ Public virtual PLCore::Script functions ] //[-------------------------------------------------------] bool Script::IsGlobalFunction(const String &sName, const String &sNamespace) { bool bIsGlobalFunction = false; // By default, the global script function does not exist // Is there a Lua state? If so, get a nested Lua table if (m_pLuaState && GetNestedTable(sNamespace)) { // Table key lua_pushstring(m_pLuaState, sName); // Push the function name onto the Lua stack // This function pops the key from the stack - this gets the function lua_gettable(m_pLuaState, -2); // Is it a function? bIsGlobalFunction = lua_isfunction(m_pLuaState, -1); // Pop the function from the Lua state stack lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } // Done return bIsGlobalFunction; } bool Script::AddGlobalFunction(const String &sFunction, const DynFunc &cDynFunc, const String &sNamespace) { // Is there a Lua state? if (m_pLuaState) { // Error! return false; } else { // Add the global function GlobalFunction *psGlobalFunction = new GlobalFunction; psGlobalFunction->pScript = this; psGlobalFunction->sFunction = sFunction; psGlobalFunction->pDynFunc = cDynFunc.Clone(); psGlobalFunction->sNamespace = sNamespace; m_lstGlobalFunctions.Add(psGlobalFunction); // Done return true; } } bool Script::RemoveAllGlobalFunctions() { // Is there a Lua state? if (m_pLuaState) { // Error! return false; } else { // Destroy the global functions for (uint32 i=0; i<m_lstGlobalFunctions.GetNumOfElements(); i++) { delete m_lstGlobalFunctions[i]->pDynFunc; delete m_lstGlobalFunctions[i]; } m_lstGlobalFunctions.Clear(); // Done return true; } } String Script::GetSourceCode() const { return m_sSourceCode; } bool Script::SetSourceCode(const String &sSourceCode) { // Clear the previous script Clear(); // Backup the given source code m_sSourceCode = sSourceCode; // Is there source code? if (m_sSourceCode.GetLength()) { // Create the Lua state m_pLuaState = lua_open(); if (m_pLuaState) { // Open all standard Lua libraries into the given state luaL_openlibs(m_pLuaState); // Create the metatable for LuaUserData events LuaUserData::CreateMetatable(m_pLuaState); // Add the global functions for (uint32 i=0; i<m_lstGlobalFunctions.GetNumOfElements(); i++) { // Get the global function GlobalFunction *psGlobalFunction = m_lstGlobalFunctions[i]; // Create a nested Lua table if (CreateNestedTable(psGlobalFunction->sNamespace)) { // Table key lua_pushstring(m_pLuaState, psGlobalFunction->sFunction); // Push the function name onto the Lua stack // Table value: Store a pointer to the global function in the c-closure lua_pushlightuserdata(m_pLuaState, psGlobalFunction); // Push a pointer to the global function onto the Lua stack lua_pushcclosure(m_pLuaState, &Script::LuaFunctionCallback, 1); // Push the function pointer onto the Lua stack // This function pops both the key and the value from the stack lua_settable(m_pLuaState, -3); // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } } // Load the script const int nResult = luaL_loadbuffer(m_pLuaState, sSourceCode, sSourceCode.GetLength(), Name.Get()); if (!nResult && !lua_pcall(m_pLuaState, 0, 0, 0)) { // Done return true; } else { // Error! // Write a log message String sErrorDescription; switch (nResult) { case LUA_ERRSYNTAX: sErrorDescription = " (Syntax error during pre-compilation)"; break; case LUA_ERRMEM: sErrorDescription = " (Memory allocation error)"; break; } LogOutput(Log::Error, "Failed to compile the script" + sErrorDescription); // Report Lua errors ReportErrors(); } } } else { // No script at all - done return true; } // Error! return false; } void Script::GetAssociatedFilenames(Array<String> &lstFilenames) { // We want to have a list of script filenames which were included within this script // -> It appears that there's no "easy" way in Lua to get this kind of information :/ // Contains "Application", "Interaction" and so on (no final filenames) Array<String> lstRequire; // Get a list of loaded "require"-files { // -> The files loaded within a Lua script by using "require" can be accessed by using the // global control table variable "_LOADED". See http://www.lua.org/pil/8.1.html for details. lua_getfield(m_pLuaState, LUA_REGISTRYINDEX, "_LOADED"); if (lua_istable(m_pLuaState, -1)) { lua_pushnil(m_pLuaState); while (lua_next(m_pLuaState, -2)) { if (lua_isstring(m_pLuaState, -2)) lstRequire.Add(lua_tostring(m_pLuaState, -2)); lua_pop(m_pLuaState, 1); } } // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } // Get the content of "package.path" used by "require" to search for a Lua loader // -> The content looks like "?.lua;C:\SomePath\?.lua;" const String sPackagePath = GetGlobalVariable("path", "package"); // Iterate over the "require"-list const String sToReplace = "?."; for (uint32 i=0; i<lstRequire.GetNumOfElements(); i++) { // Get the current "require" const String sRequire = lstRequire[i] + '.'; // Get the index of the first ";" within the package path int nPreviousIndex = 0; int nIndex = sPackagePath.IndexOf(';'); while (nIndex>-1) { // Get current package search path, we now have e.g. "C:\SomePath\?.lua" String sFilename = sPackagePath.GetSubstring(nPreviousIndex, nIndex-nPreviousIndex); // Replace "?." with the "require"-name sFilename.Replace(sToReplace, sRequire); // Does this file exist? if (File(sFilename).Exists()) { // We found a match! lstFilenames.Add(sFilename); // Get us out of the while-loop nIndex = -1; } else { // Get the index of the next ";" within the package path nPreviousIndex = nIndex + 1; nIndex = sPackagePath.IndexOf(';', nPreviousIndex); } } } } bool Script::Execute(const String &sSourceCode) { // Is there a Lua state? if (m_pLuaState) { // Execute const bool bResult = !luaL_dostring(m_pLuaState, sSourceCode.GetASCII()); // -> For now we don't want to bother the script API user with something // like garbage collection, so do this automatically // -> If this is not done, reuse of "RTTIObjectPointer"-instances (as well as derived classes of course) // will not work that well because unused stuff will not be removed automatically by Lua when not asking // Lua to do so lua_gc(m_pLuaState, LUA_GCSTEP, 1); // Done return bResult; } // Error! return false; } void Script::GetGlobalVariables(Array<String> &lstGlobalVariables, const String &sNamespace) { // Is there a Lua state? If so, get a nested Lua table if (m_pLuaState && GetNestedTable(sNamespace)) { // Push the first key onto the Lua stack lua_pushnil(m_pLuaState); // Iterate through the Lua table while (lua_next(m_pLuaState, 1) != 0) { // Lua stack content: The 'key' is at index -2 and the 'value' at index -1 // Check the 'key' type (at index -2) - must be a string if (lua_isstring(m_pLuaState, -2)) { // Check whether or not the 'value' (at index -1) is a global variable // (something like "_VERSION" is passing this test as well, but that's probably ok because it's just a Lua build in global variable) if (lua_isnumber(m_pLuaState, -1) || lua_isstring(m_pLuaState, -1)) { // Add the global variable to our list lstGlobalVariables.Add(lua_tostring(m_pLuaState, -2)); } } // Next, please (removes 'value'; keeps 'key' for next iteration) lua_pop(m_pLuaState, 1); } // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } } bool Script::IsGlobalVariable(const String &sName, const String &sNamespace) { bool bGlobalVariable = false; // Is there a Lua state? If so, get a nested Lua table if (m_pLuaState && GetNestedTable(sNamespace)) { // Table key lua_pushstring(m_pLuaState, sName); // Push the variable name onto the Lua stack // This function pops the key from the stack - this gets the variable lua_gettable(m_pLuaState, -2); // Check the type of the variable bGlobalVariable = (lua_isnumber(m_pLuaState, -1) || lua_isstring(m_pLuaState, -1)); // Pop the variable from the Lua state stack lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } // Done return bGlobalVariable; } ETypeID Script::GetGlobalVariableTypeID(const String &sName, const String &sNamespace) { ETypeID nType = TypeInvalid; // Is there a Lua state? If so, get a nested Lua table if (m_pLuaState && GetNestedTable(sNamespace)) { // Table key lua_pushstring(m_pLuaState, sName); // Push the variable name onto the Lua stack // This function pops the key from the stack - this gets the variable lua_gettable(m_pLuaState, -2); // Check the type of the variable if (lua_isboolean(m_pLuaState, -1)) nType = TypeBool; else if (lua_isnumber(m_pLuaState, -1)) nType = TypeDouble; else if (lua_isstring(m_pLuaState, -1)) nType = TypeString; else if (lua_isuserdata(m_pLuaState, -1)) nType = TypeObjectPtr; // [TODO] Do any type tests in here? // Pop the variable from the Lua state stack lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } // Done return nType; } String Script::GetGlobalVariable(const String &sName, const String &sNamespace) { String sValue; // Is there a Lua state? If so, get a nested Lua table if (m_pLuaState && GetNestedTable(sNamespace)) { // Table key lua_pushstring(m_pLuaState, sName); // Push the variable name onto the Lua stack // This function pops the key from the stack - this gets the variable lua_gettable(m_pLuaState, -2); // Get the value of the variable as string sValue = lua_tostring(m_pLuaState, -1); // Pop the variable from the Lua state stack lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } // Done return sValue; } void Script::SetGlobalVariable(const String &sName, const DynVar &cValue, const String &sNamespace) { // Is there a Lua state? if (m_pLuaState) { // Get the type of the variable because we don't want to change it's type int nTypeID = GetGlobalVariableTypeID(sName); if (nTypeID == TypeInvalid) { // Ok, this must be a new variable nTypeID = cValue.GetTypeID(); } // Create a nested Lua table if (CreateNestedTable(sNamespace)) { // Table key lua_pushstring(m_pLuaState, sName); // Push the variable name onto the Lua stack // Table value: Push the value of the variable onto the Lua stack switch (nTypeID) { case TypeVoid: return; // ? Yeah, that's really funny! case TypeBool: lua_pushboolean(m_pLuaState, cValue.GetBool()); break; case TypeDouble: lua_pushnumber (m_pLuaState, cValue.GetDouble()); break; case TypeFloat: lua_pushnumber (m_pLuaState, cValue.GetFloat()); break; case TypeInt: lua_pushinteger(m_pLuaState, cValue.GetInt()); break; case TypeInt16: lua_pushinteger(m_pLuaState, cValue.GetInt()); break; case TypeInt32: lua_pushinteger(m_pLuaState, cValue.GetInt()); break; case TypeInt64: lua_pushinteger(m_pLuaState, cValue.GetInt()); break; // [TODO] TypeInt64 is currently handled just as long case TypeInt8: lua_pushinteger(m_pLuaState, cValue.GetInt()); break; case TypeString: lua_pushstring (m_pLuaState, cValue.GetString()); break; case TypeUInt16: lua_pushinteger(m_pLuaState, cValue.GetUInt16()); break; case TypeUInt32: lua_pushinteger(m_pLuaState, cValue.GetUInt32()); break; case TypeUInt64: lua_pushinteger(m_pLuaState, static_cast<lua_Integer>(cValue.GetUInt64())); break; // [TODO] TypeUInt64 is currently handled just as long case TypeUInt8: lua_pushinteger(m_pLuaState, cValue.GetUInt8()); break; // [HACK] Currently, classes derived from "PLCore::Object" are just recognized as type "void*"... but "PLCore::Object*" type would be perfect case TypePtr: case TypeObjectPtr: RTTIObjectPointer::LuaStackPush(*this, reinterpret_cast<Object*>(cValue.GetUIntPtr())); break; default: lua_pushstring (m_pLuaState, cValue.GetString()); break; // Unknown type } // This function pops both the key and the value from the stack - this sets the variable lua_settable(m_pLuaState, -3); // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } } } bool Script::BeginCall(const String &sFunctionName, const String &sFunctionSignature, const String &sNamespace) { // Is there a Lua state? if (m_pLuaState) { // Get a nested Lua table if (GetNestedTable(sNamespace)) { // Table key lua_pushstring(m_pLuaState, sFunctionName); // Push the function name onto the Lua stack // Push the function to be called onto the Lua state stack lua_gettable(m_pLuaState, -2); if (lua_isfunction(m_pLuaState, -1)) { // Backup the name of the current function (we may need it for error log output) m_sCurrentFunction = sFunctionName; // Has the current function a result? m_bFunctionResult = !sFunctionSignature.Compare("void(", 0, 5); // Current argument is 0 m_nCurrentArgument = 0; // Done return true; } else { // Error! if (sNamespace.GetLength()) LogOutput(Log::Error, "The function '" + sFunctionName + "' was not found within the namespace '" + sNamespace + '\''); else LogOutput(Log::Error, "The function '" + sFunctionName + "' was not found"); } } else { // Error! LogOutput(Log::Error, "The namespace '" + sNamespace + "' of the function '" + sFunctionName + "' was not found"); } } // Error! return false; } void Script::PushArgument(bool bValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushboolean(m_pLuaState, bValue); m_nCurrentArgument++; } } void Script::PushArgument(float fValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushnumber(m_pLuaState, fValue); m_nCurrentArgument++; } } void Script::PushArgument(double fValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushnumber(m_pLuaState, fValue); m_nCurrentArgument++; } } void Script::PushArgument(int8 nValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushinteger(m_pLuaState, nValue); m_nCurrentArgument++; } } void Script::PushArgument(int16 nValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushinteger(m_pLuaState, nValue); m_nCurrentArgument++; } } void Script::PushArgument(int32 nValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushinteger(m_pLuaState, nValue); m_nCurrentArgument++; } } void Script::PushArgument(int64 nValue) { // Is there a Lua state? if (m_pLuaState) { // [TODO] There's no int64 support in Lua (?) lua_pushinteger(m_pLuaState, static_cast<lua_Integer>(nValue)); m_nCurrentArgument++; } } void Script::PushArgument(uint8 nValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushinteger(m_pLuaState, nValue); m_nCurrentArgument++; } } void Script::PushArgument(uint16 nValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushinteger(m_pLuaState, nValue); m_nCurrentArgument++; } } void Script::PushArgument(uint32 nValue) { // Is there a Lua state? if (m_pLuaState) { lua_pushinteger(m_pLuaState, nValue); m_nCurrentArgument++; } } void Script::PushArgument(uint64 nValue) { // Is there a Lua state? if (m_pLuaState) { // [TODO] There's no uint64 support in Lua (?) lua_pushinteger(m_pLuaState, static_cast<lua_Integer>(nValue)); m_nCurrentArgument++; } } void Script::PushArgument(const String &sString) { // Is there a Lua state? if (m_pLuaState) { lua_pushstring(m_pLuaState, sString); m_nCurrentArgument++; } } void Script::PushArgument(Object *pObject) { RTTIObjectPointer::LuaStackPush(*this, pObject); m_nCurrentArgument++; } void Script::PushArgument(Object &cObject) { RTTIObjectPointer::LuaStackPush(*this, &cObject); m_nCurrentArgument++; } bool Script::EndCall() { // Is there a Lua state? if (m_pLuaState) { // Do the call ('m_nCurrentArgument' arguments, 1 result) const int nResult = lua_pcall(m_pLuaState, m_nCurrentArgument, m_bFunctionResult, 0); // Perform an incremental step of garbage collection // -> For now we don't want to bother the script API user with something // like garbage collection, so do this automatically // -> If this is not done, reuse of "RTTIObjectPointer"-instances (as well as derived classes of course) // will not work that well because unused stuff will not be removed automatically by Lua when not asking // Lua to do so lua_gc(m_pLuaState, LUA_GCSTEP, 1); // Evaluate the result if (nResult) { // Write a log message String sErrorDescription; switch (nResult) { case LUA_ERRRUN: sErrorDescription = " (A runtime error)"; break; case LUA_ERRMEM: sErrorDescription = " (Memory allocation error)"; break; case LUA_ERRERR: sErrorDescription = " (Error while running the error handler function)"; break; } LogOutput(Log::Error, "Error running function '" + m_sCurrentFunction + '\'' + sErrorDescription); // Report Lua errors ReportErrors(); } else { // If there's no function result we need to pop the table from the Lua stack right now, else this is done within the "GetReturn()"-method if (!m_bFunctionResult) lua_pop(m_pLuaState, -1); // Done return true; } } // Error! return false; } bool Script::GetReturn(bool nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a boolean if (lua_isboolean(m_pLuaState, -1)) { // Get the result nValue = (lua_toboolean(m_pLuaState, -1) != 0); } else { // Error! nValue = false; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a boolean"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = false; } // Done return nValue; } float Script::GetReturn(float nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = static_cast<float>(lua_tonumber(m_pLuaState, -1)); } else { // Error! nValue = 0.0f; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0.0f; } // Done return nValue; } double Script::GetReturn(double nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = lua_tonumber(m_pLuaState, -1); } else { // Error! nValue = 0.0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0.0; } // Done return nValue; } int8 Script::GetReturn(int8 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = static_cast<uint8>(lua_tointeger(m_pLuaState, -1)); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } int16 Script::GetReturn(int16 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = static_cast<uint16>(lua_tointeger(m_pLuaState, -1)); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } int32 Script::GetReturn(int32 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the value nValue = static_cast<int32>(lua_tointeger(m_pLuaState, -1)); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } int64 Script::GetReturn(int64 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // [TODO] There's no int64 support in Lua (?) // Get the result nValue = lua_tointeger(m_pLuaState, -1); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } uint8 Script::GetReturn(uint8 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = static_cast<uint8>(lua_tointeger(m_pLuaState, -1)); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } uint16 Script::GetReturn(uint16 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = static_cast<uint16>(lua_tointeger(m_pLuaState, -1)); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } uint32 Script::GetReturn(uint32 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // Get the result nValue = static_cast<uint32>(lua_tointeger(m_pLuaState, -1)); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } uint64 Script::GetReturn(uint64 nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a number if (lua_isnumber(m_pLuaState, -1)) { // [TODO] There's no uint64 support in Lua (?) // Get the result nValue = lua_tointeger(m_pLuaState, -1); } else { // Error! nValue = 0; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a number"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = 0; } // Done return nValue; } String Script::GetReturn(String nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be a string if (lua_isstring(m_pLuaState, -1)) { // Get the result nValue = lua_tostring(m_pLuaState, -1); } else { // Error! nValue = ""; LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return a string"); } lua_pop(m_pLuaState, 1); // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = ""; } // Done return nValue; } Object *Script::GetReturn(Object *nValue) { // Is there a Lua state? if (m_pLuaState) { // Must be user data or nil if (lua_isuserdata(m_pLuaState, -1)) { // Get user data from the top of the Lua stack and removes it from the Lua stack // [TODO] Do any type tests in here? nValue = reinterpret_cast<RTTIObjectPointer*>(LuaUserData::PopUserDataFromLuaStack(m_pLuaState))->GetObject(); } else { // Nil is fine, too nValue = nullptr; if (!lua_isnil(m_pLuaState, -1)) { // Error! LogOutput(Log::Error, "Function '" + m_sCurrentFunction + "' must return user data"); } lua_pop(m_pLuaState, 1); } // Pop the table from the Lua stack lua_pop(m_pLuaState, -1); } else { // Error! nValue = nullptr; } // Done return nValue; } Object &Script::GetReturn(Object &nValue) { // ... please note that in here, we can't return a null pointer... Object *pObject = GetReturn(&nValue); return pObject ? *pObject : nValue; } //[-------------------------------------------------------] //[ Private static Lua callback functions ] //[-------------------------------------------------------] /* * @brief * Lua function callback */ int Script::LuaFunctionCallback(lua_State *pLuaState) { // Get the global function GlobalFunction *psGlobalFunction = reinterpret_cast<GlobalFunction*>(lua_touserdata(pLuaState, lua_upvalueindex(1))); // Call the dynamic function return psGlobalFunction ? RTTIObjectMethodPointer::CallDynFunc(*psGlobalFunction->pScript, *psGlobalFunction->pDynFunc, false) : 0; } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Copy constructor */ Script::Script(const Script &cSource) : m_pLuaState(nullptr), m_bFunctionResult(false), m_nCurrentArgument(0) { // No implementation because the copy constructor is never used } /** * @brief * Copy operator */ Script &Script::operator =(const Script &cSource) { // No implementation because the copy operator is never used return *this; } /** * @brief * Reports Lua errors */ void Script::ReportErrors() { // Output the Lua errors LogOutput(Log::Error, lua_tostring(m_pLuaState, -1)); // Pop the error value from the stack lua_pop(m_pLuaState, 1); } /** * @brief * Clears the script */ void Script::Clear() { // Is there a Lua state? if (m_pLuaState) { // Destroy all registered event user data (a kind of "disconnect all slots at once") DestroyEventUserData(); // Reset the source code m_sSourceCode = ""; // Verify the stack and write a warning into the log if the script stack is not empty if (lua_gettop(m_pLuaState)) { LogOutput(Log::Warning, "Script termination, but the stack is not empty"); LuaStackDump(); } // Clear all global variables while (true) { lua_pushnil(m_pLuaState); if (!lua_next(m_pLuaState, LUA_GLOBALSINDEX)) break; lua_pop(m_pLuaState, 1); lua_pushnil(m_pLuaState); lua_rawset(m_pLuaState, LUA_GLOBALSINDEX); } // Force the garbage collector to cleanup right now... because required stuff like the LuaUserData metatable are still there at the moment... lua_gc(m_pLuaState, LUA_GCCOLLECT, 0); // Destroy the metatable for LuaUserData events LuaUserData::DestroyMetatable(m_pLuaState); // Close the Lua state lua_close(m_pLuaState); m_pLuaState = nullptr; // Reset states m_sCurrentFunction = ""; m_bFunctionResult = false; m_nCurrentArgument = 0; } } /** * @brief * Creates a nested Lua table */ bool Script::CreateNestedTable(const String &sTableName) { // Is there a table name? if (sTableName.GetLength()) { // Loop through all components within the given nested Lua table name uint32 nPartBegin = 0; while (nPartBegin<=sTableName.GetLength()) { // Find the next "." within the given nested Lua table name int nPartEnd = sTableName.IndexOf(".", nPartBegin); if (nPartEnd < 0) nPartEnd = sTableName.GetLength(); // Get the current Lua table name const String sSubTableName = sTableName.GetSubstring(nPartBegin, nPartEnd - nPartBegin); // Each table must have a name! if (!sSubTableName.GetLength()) return false; // Error! // Does the Lua table already exist within the current Lua table? if (nPartBegin) { // We're already within a Lua table lua_pushstring(m_pLuaState, sSubTableName); lua_gettable(m_pLuaState, -2); if (!lua_isnil(m_pLuaState, -1)) lua_remove(m_pLuaState, -2); } else { // Currently we're in global space lua_pushstring(m_pLuaState, sSubTableName); lua_gettable(m_pLuaState, LUA_GLOBALSINDEX); } // Lua table found? if (lua_isnil(m_pLuaState, -1)) { // Nope, create a new one // Pop nil from the Lua stack lua_pop(m_pLuaState, 1); // Create new Lua table on the Lua stack lua_newtable(m_pLuaState); lua_pushstring(m_pLuaState, sSubTableName); lua_pushvalue(m_pLuaState, -2); // Pushes a copy of the element at the given valid index onto the stack if (nPartBegin) { // We're already within a Lua table lua_settable(m_pLuaState, -4); lua_remove(m_pLuaState, -2); } else { // Currently we're in global space lua_settable(m_pLuaState, LUA_GLOBALSINDEX); } } // Skip "." nPartBegin = nPartEnd + 1; } } else { // No table name given, so just push the global Lua table onto the stack lua_getglobal(m_pLuaState, "_G"); if (!lua_istable(m_pLuaState, -1)) return false; // Error! } // Done return true; } /** * @brief * Gets a nested Lua table */ bool Script::GetNestedTable(const String &sTableName) { // Is there a table name? if (sTableName.GetLength()) { // Loop through all components within the given nested Lua table name uint32 nPartBegin = 0; while (nPartBegin<=sTableName.GetLength()) { // Find the next "." within the given nested Lua table name int nPartEnd = sTableName.IndexOf(".", nPartBegin); if (nPartEnd < 0) nPartEnd = sTableName.GetLength(); // Get the current Lua table name const String sSubTableName = sTableName.GetSubstring(nPartBegin, nPartEnd - nPartBegin); // Each table must have a name! if (!sSubTableName.GetLength()) return false; // Error! // Does the Lua table already exist within the current Lua table? if (nPartBegin) { // We're already within a Lua table lua_pushstring(m_pLuaState, sSubTableName); lua_gettable(m_pLuaState, -2); if (!lua_isnil(m_pLuaState, -1)) lua_remove(m_pLuaState, -2); } else { // Currently we're in global space lua_pushstring(m_pLuaState, sSubTableName); lua_gettable(m_pLuaState, LUA_GLOBALSINDEX); } // Lua table found? if (lua_isnil(m_pLuaState, -1)) { // Nope, don't create a new one in here // Pop nil from the Lua stack lua_pop(m_pLuaState, 1); // Cleanup the Lua stack if (nPartBegin) { // We're already within a Lua table // Pop the table from the Lua stack lua_pop(m_pLuaState, 1); } else { // Currently we're in global space } // Error! return false; } // Skip "." nPartBegin = nPartEnd + 1; } } else { // No table name given, so just push the global Lua table onto the stack lua_getglobal(m_pLuaState, "_G"); if (!lua_istable(m_pLuaState, -1)) return false; // Error! } // Done return true; } /** * @brief * Returns event user data key */ String Script::GetEventUserDataKey(DynEvent *pDynEvent, const void *pLuaPointer) const { return String(pDynEvent) + String(const_cast<void*>(pLuaPointer)); } /** * @brief * Returns event user data */ Script::EventUserData *Script::GetEventUserData(DynEvent *pDynEvent, const void *pLuaPointer) const { return m_mapEventUserData.Get(GetEventUserDataKey(pDynEvent, pLuaPointer)); } /** * @brief * Adds event user data */ void Script::AddEventUserData(DynEvent *pDynEvent, const void *pLuaPointer, EventUserData *pEventUserData) { m_mapEventUserData.Add(GetEventUserDataKey(pDynEvent, pLuaPointer), pEventUserData); } /** * @brief * Destroys all registered event user data (a kind of "disconnect all slots at once") */ void Script::DestroyEventUserData() { // Iterate through the map content Iterator<String> cKeyIterator = m_mapEventUserData.GetKeyIterator(); while (cKeyIterator.HasNext()) { // Get the event user data instance EventUserData *pEventUserData = m_mapEventUserData.Get(cKeyIterator.Next()); // Destroy the event user data delete pEventUserData->pDynEventHandler; luaL_unref(m_pLuaState, LUA_REGISTRYINDEX, pEventUserData->nLuaFunctionReference); delete pEventUserData; } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLScriptLua
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #ifndef INOU_H #define INOU_H #include "lgraph.hpp" #include "options.hpp" // Abstract class that any inou block must support class Inou { private: protected: public: Inou() { } virtual std::vector<LGraph *> tolg() = 0; // Output modules like to verilog target virtual void fromlg(std::vector<const LGraph *> &out) = 0; // Set the options/arguments for the pass virtual void set(const std::string &key, const std::string &value) = 0; }; #endif
// 692. Top K Frequent Words // Given a non-empty list of words, return the k most frequent elements. // Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. // Example 1: // Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 // Output: ["i", "love"] // Explanation: "i" and "love" are the two most frequent words. // Note that "i" comes before "love" due to a lower alphabetical order. // Example 2: // Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 // Output: ["the", "is", "sunny", "day"] // Explanation: "the", "is", "sunny" and "day" are the four most frequent words, // with the number of occurrence being 4, 3, 2 and 1 respectively. // Note: // You may assume k is always valid, 1 ≤ k ≤ number of unique elements. // Input words contain only lowercase letters. // Follow up: // Try to solve it in O(n log k) time and O(n) extra space. class Solution { public: struct CMP{ bool operator()(pair<string, int> a, pair<string, int> b){ if(a.second!=b.second){ return a.second > b.second; } else{ return a.first < b.first; } } }; vector<string> topKFrequent(vector<string>& words, int k) { unordered_map<string, int> m; for(int i=0;i<words.size();i++){ m[words[i]]++; } priority_queue<pair<string,int>, vector<pair<string,int>>, CMP> pq; for(auto it:m){ pq.push(make_pair(it.first,it.second)); if(pq.size()>k){ pq.pop(); } } vector<string> res; while(!pq.empty()){ res.push_back(pq.top().first); pq.pop(); } reverse(res.begin(), res.end()); return res; } };
//STARTHEADER // $Id: ClusterSequencePassiveArea.hh 2687 2011-11-14 11:17:51Z soyez $ // // Copyright (c) 2005-2011, Matteo Cacciari, Gavin P. Salam and Gregory Soyez // //---------------------------------------------------------------------- // This file is part of FastJet. // // FastJet is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // The algorithms that underlie FastJet have required considerable // development and are described in hep-ph/0512210. If you use // FastJet as part of work towards a scientific publication, please // include a citation to the FastJet paper. // // FastJet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FastJet. If not, see <http://www.gnu.org/licenses/>. //---------------------------------------------------------------------- //ENDHEADER #ifndef __FASTJET_CLUSTERSEQUENCEPASSIVEAREA_HH__ #define __FASTJET_CLUSTERSEQUENCEPASSIVEAREA_HH__ #include "fastjet/PseudoJet.hh" #include "fastjet/ClusterSequence1GhostPassiveArea.hh" #include<iostream> #include<vector> FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh //using namespace std; /// @ingroup sec_area_classes /// \class ClusterSequencePassiveArea /// Like ClusterSequence with computation of the passive jet area /// /// Class that behaves essentially like ClusterSequence except /// that it also provides access to the area of a jet (which /// will be a random quantity... Figure out what to do about seeds /// later...) /// /// This class should not be used directly. Rather use /// ClusterSequenceArea with the appropriate AreaDefinition class ClusterSequencePassiveArea : public ClusterSequence1GhostPassiveArea { public: /// constructor based on JetDefinition and PassiveAreaSpec template<class L> ClusterSequencePassiveArea (const std::vector<L> & pseudojets, const JetDefinition & jet_def_in, const GhostedAreaSpec & area_spec, const bool & writeout_combinations = false) ; /// return an empty area that's appropriate to the passive area /// determination carried out virtual double empty_area(const Selector & selector) const; private: /// does the initialisation and running specific to the passive /// areas class void _initialise_and_run_PA (const JetDefinition & jet_def_in, const GhostedAreaSpec & area_spec, const bool & writeout_combinations = false); }; template<class L> ClusterSequencePassiveArea::ClusterSequencePassiveArea (const std::vector<L> & pseudojets, const JetDefinition & jet_def_in, const GhostedAreaSpec & area_spec, const bool & writeout_combinations) { // transfer the initial jets (type L) into our own array _transfer_input_jets(pseudojets); // run the clustering for passive areas _initialise_and_run_PA(jet_def_in, area_spec, writeout_combinations); } FASTJET_END_NAMESPACE #endif // __FASTJET_CLUSTERSEQUENCEPASSIVEAREA_HH__
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkScalableAffineTransform_hxx #define itkScalableAffineTransform_hxx #include "itkNumericTraits.h" #include "itkScalableAffineTransform.h" #include "vnl/algo/vnl_matrix_inverse.h" namespace itk { /** Constructor with default arguments */ template< typename TScalar, unsigned int NDimensions > ScalableAffineTransform< TScalar, NDimensions > ::ScalableAffineTransform(): Superclass(Self::ParametersDimension) { for ( unsigned int i = 0; i < NDimensions; i++ ) { m_Scale[i] = 1; m_MatrixScale[i] = 1; } } /** Constructor with default arguments */ template< typename TScalar, unsigned int NDimensions > ScalableAffineTransform< TScalar, NDimensions > ::ScalableAffineTransform(unsigned int , unsigned int parametersDimension): Superclass(parametersDimension) { for ( unsigned int i = 0; i < NDimensions; i++ ) { m_Scale[i] = 1; m_MatrixScale[i] = 1; } } template< typename TScalar, unsigned int NDimensions > ScalableAffineTransform< TScalar, NDimensions > ::ScalableAffineTransform(unsigned int parametersDimension): Superclass(parametersDimension) { for ( unsigned int i = 0; i < NDimensions; i++ ) { m_Scale[i] = 1; m_MatrixScale[i] = 1; } } /** Constructor with default arguments */ template< typename TScalar, unsigned int NDimensions > ScalableAffineTransform< TScalar, NDimensions > ::ScalableAffineTransform(const MatrixType & matrix, const OutputVectorType & offset): Superclass(matrix, offset) { for ( unsigned int i = 0; i < NDimensions; i++ ) { m_Scale[i] = 1; m_MatrixScale[i] = 1; } } /** Destructor */ template< typename TScalar, unsigned int NDimensions > ScalableAffineTransform< TScalar, NDimensions > ::~ScalableAffineTransform() { } /** Print self */ template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); unsigned int i; os << indent << "Scale : "; for ( i = 0; i < NDimensions; i++ ) { os << m_Scale[i] << " "; } os << std::endl; os << indent << "MatrixScale : "; for ( i = 0; i < NDimensions; i++ ) { os << m_MatrixScale[i] << " "; } os << std::endl; } // Set the parameters in order to fit an Identity transform template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::SetIdentity(void) { for ( unsigned int i = 0; i < NDimensions; i++ ) { m_Scale[i] = 1; m_MatrixScale[i] = 1; } this->Superclass::SetIdentity(); } /** Set the scale of the transformation */ template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::SetScale(const InputVectorType & scale) { unsigned int i; for ( i = 0; i < NDimensions; i++ ) { m_Scale[i] = scale[i]; } this->ComputeMatrix(); this->Modified(); } template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::SetScale(const double scale[NDimensions]) { unsigned int i; for ( i = 0; i < NDimensions; i++ ) { m_Scale[i] = scale[i]; } this->ComputeMatrix(); this->Modified(); } // Get an inverse of this transform template< typename TScalar, unsigned int NDimensions > bool ScalableAffineTransform< TScalar, NDimensions > ::GetInverse(Self *inverse) const { return this->Superclass::GetInverse(inverse); } // Return an inverse of this transform template< typename TScalar, unsigned int NDimensions > typename ScalableAffineTransform< TScalar, NDimensions > ::InverseTransformBasePointer ScalableAffineTransform< TScalar, NDimensions > ::GetInverseTransform() const { Pointer inv = New(); return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } /** Set the scale of the transformation */ template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::ComputeMatrix() { bool scaleChanged = false; for ( unsigned int i = 0; i < NDimensions; i++ ) { if ( m_Scale[i] != m_MatrixScale[i] ) { scaleChanged = true; } } if ( scaleChanged ) { MatrixType mat; typename MatrixType::InternalMatrixType & imat = mat.GetVnlMatrix(); for ( unsigned int i = 0; i < NDimensions; i++ ) { if ( m_MatrixScale[i] != 0 && m_Scale[i] != 0 ) { imat.put(i, i, m_Scale[i] / m_MatrixScale[i] * this->GetMatrix()[i][i]); m_MatrixScale[i] = m_Scale[i]; } else { m_Scale[i] = 1; m_MatrixScale[i] = 1; imat.put(i, i, this->GetMatrix()[i][i]); } } Superclass::SetVarMatrix(mat); } } #if !defined(ITK_LEGACY_REMOVE) template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::SetMatrixComponent(const MatrixType & matrix) { this->SetMatrix(matrix); } template< typename TScalar, unsigned int NDimensions > const typename ScalableAffineTransform< TScalar, NDimensions >::MatrixType & ScalableAffineTransform< TScalar, NDimensions > ::GetMatrixComponent() const { return this->GetMatrix(); } template< typename TScalar, unsigned int NDimensions > void ScalableAffineTransform< TScalar, NDimensions > ::SetOffsetComponent(const OffsetType & offset) { this->SetTranslation(offset); } template< typename TScalar, unsigned int NDimensions > const typename ScalableAffineTransform< TScalar, NDimensions >::OffsetType & ScalableAffineTransform< TScalar, NDimensions > ::GetOffsetComponent(void) const { return this->GetTranslation(); } #endif } // namespace #endif
#include <catch.hpp> #include <mw/mmr/MMR.h> #include <mw/mmr/backends/VectorBackend.h> using namespace mmr; TEST_CASE("mmr::MMR") { auto pBackend = std::make_shared<VectorBackend>(); MMR mmr(pBackend); std::vector<uint8_t> leaf0({ 0, 1, 2 }); std::vector<uint8_t> leaf1({ 1, 2, 3 }); std::vector<uint8_t> leaf2({ 2, 3, 4 }); std::vector<uint8_t> leaf3({ 3, 4, 5 }); std::vector<uint8_t> leaf4({ 4, 5, 6 }); mmr.Add(leaf0); mmr.Add(leaf1); mmr.Add(leaf2); mmr.Add(leaf3); REQUIRE(mmr.GetLeaf(LeafIndex::At(0)) == Leaf::Create(LeafIndex::At(0), std::vector<uint8_t>(leaf0))); REQUIRE(mmr.GetLeaf(LeafIndex::At(1)) == Leaf::Create(LeafIndex::At(1), std::vector<uint8_t>(leaf1))); REQUIRE(mmr.GetLeaf(LeafIndex::At(2)) == Leaf::Create(LeafIndex::At(2), std::vector<uint8_t>(leaf2))); REQUIRE(mmr.GetLeaf(LeafIndex::At(3)) == Leaf::Create(LeafIndex::At(3), std::vector<uint8_t>(leaf3))); REQUIRE(mmr.GetNumLeaves() == 4); REQUIRE(mmr.GetNumNodes() == 7); REQUIRE(mmr.Root() == mw::Hash::FromHex("675996c8bbfce6319dd00588ebd289d555eedfa60aa17a9a83cc7da80888a97e")); mmr.Add(leaf4); REQUIRE(mmr.GetLeaf(LeafIndex::At(4)) == Leaf::Create(LeafIndex::At(4), std::vector<uint8_t>(leaf4))); REQUIRE(mmr.GetNumLeaves() == 5); REQUIRE(mmr.GetNumNodes() == 8); REQUIRE(mmr.Root() == mw::Hash::FromHex("2657bf9ad4d4269ba1cfa872b325497fcff937c6b96df336e4ba29842a80232d")); mmr.Rewind(4); REQUIRE(mmr.GetNumLeaves() == 4); REQUIRE(mmr.GetNumNodes() == 7); REQUIRE(mmr.Root() == mw::Hash::FromHex("675996c8bbfce6319dd00588ebd289d555eedfa60aa17a9a83cc7da80888a97e")); } TEST_CASE("mmr::MMRCache") { auto pBackend = std::make_shared<VectorBackend>(); std::shared_ptr<MMR> mmr = std::make_shared<MMR>(pBackend); MMRCache cache(mmr); std::vector<uint8_t> leaf0({ 0, 1, 2 }); std::vector<uint8_t> leaf1({ 1, 2, 3 }); std::vector<uint8_t> leaf2({ 2, 3, 4 }); std::vector<uint8_t> leaf3({ 3, 4, 5 }); std::vector<uint8_t> leaf4({ 4, 5, 6 }); cache.Add(leaf0); cache.Add(leaf1); cache.Add(leaf2); cache.Add(leaf3); REQUIRE(cache.GetLeaf(LeafIndex::At(0)) == Leaf::Create(LeafIndex::At(0), std::vector<uint8_t>(leaf0))); REQUIRE(cache.GetLeaf(LeafIndex::At(1)) == Leaf::Create(LeafIndex::At(1), std::vector<uint8_t>(leaf1))); REQUIRE(cache.GetLeaf(LeafIndex::At(2)) == Leaf::Create(LeafIndex::At(2), std::vector<uint8_t>(leaf2))); REQUIRE(cache.GetLeaf(LeafIndex::At(3)) == Leaf::Create(LeafIndex::At(3), std::vector<uint8_t>(leaf3))); REQUIRE(cache.GetNumLeaves() == 4); REQUIRE(cache.Root() == mw::Hash::FromHex("675996c8bbfce6319dd00588ebd289d555eedfa60aa17a9a83cc7da80888a97e")); cache.Add(leaf4); REQUIRE(cache.GetLeaf(LeafIndex::At(4)) == Leaf::Create(LeafIndex::At(4), std::vector<uint8_t>(leaf4))); REQUIRE(cache.GetNumLeaves() == 5); REQUIRE(cache.Root() == mw::Hash::FromHex("2657bf9ad4d4269ba1cfa872b325497fcff937c6b96df336e4ba29842a80232d")); cache.Rewind(4); REQUIRE(cache.GetNumLeaves() == 4); REQUIRE(cache.Root() == mw::Hash::FromHex("675996c8bbfce6319dd00588ebd289d555eedfa60aa17a9a83cc7da80888a97e")); cache.Flush(0, nullptr); }
// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/algorithms/outcome_sampling_mccfr.h" #include <cmath> #include <numeric> #include <random> #include "open_spiel/abseil-cpp/absl/random/discrete_distribution.h" #include "open_spiel/algorithms/cfr.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace algorithms { // Serialization of the MCCFR solver is in agreement with de/serialization of // regular CFR solvers, i.e. take a look at the PartiallyDeserializedCFRSolver() // method for more info. constexpr const int kSerializationVersion = 1; constexpr const char* kSerializeSolverRNGSectionHeader = "[SolverRNG]"; constexpr const char* kSerializeSolverEpsilonSectionHeader = "[SolverEpsilon]"; constexpr const char* kSerializeSolverDefaultPolicySectionHeader = "[SolverDefaultPolicy]"; OutcomeSamplingMCCFRSolver::OutcomeSamplingMCCFRSolver(const Game& game, double epsilon, int seed) : OutcomeSamplingMCCFRSolver(game, std::make_shared<UniformPolicy>(), epsilon, seed) {} OutcomeSamplingMCCFRSolver::OutcomeSamplingMCCFRSolver( const Game& game, std::shared_ptr<Policy> default_policy, double epsilon, int seed) : OutcomeSamplingMCCFRSolver( game.shared_from_this(), default_policy, epsilon, std::mt19937(seed >= 0 ? seed : std::mt19937::default_seed)) {} OutcomeSamplingMCCFRSolver::OutcomeSamplingMCCFRSolver( std::shared_ptr<const Game> game, std::shared_ptr<Policy> default_policy, double epsilon, std::mt19937 rng) : game_(game), epsilon_(epsilon), rng_(rng), dist_(0.0, 1.0), default_policy_(default_policy) { if (game_->GetType().dynamics != GameType::Dynamics::kSequential) { SpielFatalError( "MCCFR requires sequential games. If you're trying to run it " "on a simultaneous (or normal-form) game, please first transform it " "using turn_based_simultaneous_game."); } } void OutcomeSamplingMCCFRSolver::RunIteration(std::mt19937* rng) { // for (Player update_player = Player{0}; update_player < game_->NumPlayers(); // ++update_player) { for (Player p = Player{0}; p < game_->NumPlayers(); ++p) { std::unique_ptr<State> state = game_->NewInitialState(); SampleEpisode(state.get(), p, rng, 1.0, 1.0, 1.0); } } std::string OutcomeSamplingMCCFRSolver::Serialize(int double_precision, std::string delimiter) const { SPIEL_CHECK_GE(double_precision, -1); std::string str = ""; // Meta section absl::StrAppend(&str, "# Automatically generated by OpenSpiel " "OutcomeSamplingMCCFRSolver::Serialize\n"); absl::StrAppend(&str, kSerializeMetaSectionHeader, "\n"); absl::StrAppend(&str, "Version: ", kSerializationVersion, "\n"); absl::StrAppend(&str, "\n"); // Game section absl::StrAppend(&str, kSerializeGameSectionHeader, "\n"); absl::StrAppend(&str, game_->Serialize(), "\n"); // Internal solver state section absl::StrAppend(&str, kSerializeSolverTypeSectionHeader, "\n"); absl::StrAppend(&str, "OutcomeSamplingMCCFRSolver", "\n"); absl::StrAppend(&str, kSerializeSolverSpecificStateSectionHeader, "\n"); // RNG section absl::StrAppend(&str, kSerializeSolverRNGSectionHeader, "\n"); std::ostringstream rng_stream; rng_stream << rng_; absl::StrAppend(&str, rng_stream.str(), "\n"); // Epsilon section absl::StrAppend(&str, kSerializeSolverEpsilonSectionHeader, "\n"); absl::StrAppend(&str, epsilon_, "\n"); // Default policy section absl::StrAppend(&str, kSerializeSolverDefaultPolicySectionHeader, "\n"); absl::StrAppend(&str, default_policy_->Serialize(double_precision, delimiter), "\n"); // Info state values table section absl::StrAppend(&str, kSerializeSolverValuesTableSectionHeader, "\n"); SerializeCFRInfoStateValuesTable(info_states_, &str, double_precision, delimiter); return str; } std::vector<double> OutcomeSamplingMCCFRSolver::SamplePolicy( const CFRInfoStateValues& info_state) const { std::vector<double> policy = info_state.current_policy; for (int i = 0; i < policy.size(); ++i) { policy[i] = epsilon_ * 1.0 / policy.size() + (1 - epsilon_) * policy[i]; } return policy; } double OutcomeSamplingMCCFRSolver::Baseline( const State& state, const CFRInfoStateValues& info_state, int aidx) const { // Default to vanilla outcome sampling. return 0; } // Applies Eq. 9 of Schmid et al. '19 double OutcomeSamplingMCCFRSolver::BaselineCorrectedChildValue( const State& state, const CFRInfoStateValues& info_state, int sampled_aidx, int aidx, double child_value, double sample_prob) const { double baseline = Baseline(state, info_state, aidx); if (aidx == sampled_aidx) { return baseline + (child_value - baseline) / sample_prob; } else { return baseline; } } double OutcomeSamplingMCCFRSolver::SampleEpisode( State* state, Player update_player, std::mt19937* rng, double my_reach, double opp_reach, double sample_reach) { if (state->IsTerminal()) { return state->PlayerReturn(update_player); } else if (state->IsChanceNode()) { std::pair<Action, double> outcome_and_prob = SampleAction(state->ChanceOutcomes(), dist_(*rng)); SPIEL_CHECK_PROB(outcome_and_prob.second); SPIEL_CHECK_GT(outcome_and_prob.second, 0); state->ApplyAction(outcome_and_prob.first); return SampleEpisode(state, update_player, rng, my_reach, outcome_and_prob.second * opp_reach, outcome_and_prob.second * sample_reach); } else if (state->IsSimultaneousNode()) { SpielFatalError( "Simultaneous moves not supported. Use " "TurnBasedSimultaneousGame to convert the game first."); } SPIEL_CHECK_PROB(sample_reach); int player = state->CurrentPlayer(); std::string is_key = state->InformationStateString(player); std::vector<Action> legal_actions = state->LegalActions(); // The insert here only inserts the default value if the key is not found, // otherwise returns the entry in the map. auto iter_and_result = info_states_.insert( {is_key, CFRInfoStateValues(legal_actions, kInitialTableValues)}); CFRInfoStateValues info_state_copy = iter_and_result.first->second; info_state_copy.ApplyRegretMatching(); const std::vector<double>& sample_policy = (player == update_player ? SamplePolicy(info_state_copy) : info_state_copy.current_policy); absl::discrete_distribution<int> action_dist(sample_policy.begin(), sample_policy.end()); int sampled_aidx = action_dist(*rng); SPIEL_CHECK_PROB(sample_policy[sampled_aidx]); SPIEL_CHECK_GT(sample_policy[sampled_aidx], 0); state->ApplyAction(legal_actions[sampled_aidx]); double child_value = SampleEpisode( state, update_player, rng, player == update_player ? my_reach * info_state_copy.current_policy[sampled_aidx] : my_reach, player == update_player ? opp_reach : opp_reach * info_state_copy.current_policy[sampled_aidx], sample_reach * sample_policy[sampled_aidx]); // Compute each of the child estimated values. std::vector<double> child_values(legal_actions.size(), 0); for (int aidx = 0; aidx < legal_actions.size(); ++aidx) { child_values[aidx] = BaselineCorrectedChildValue(*state, info_state_copy, sampled_aidx, aidx, child_value, sample_policy[aidx]); } // Compute the value of this history for this policy. double value_estimate = 0; for (int aidx = 0; aidx < legal_actions.size(); ++aidx) { value_estimate += info_state_copy.current_policy[sampled_aidx] * child_values[aidx]; } if (player == update_player) { // Now the regret and avg strategy updates. CFRInfoStateValues& info_state = info_states_[is_key]; info_state.ApplyRegretMatching(); // Estimate for the counterfactual value of the policy. double cf_value = value_estimate * opp_reach / sample_reach; // Update regrets. // // Note: different from Chapter 4 of Lanctot '13 thesis, the utilities // coming back from the recursion are already multiplied by the players' // tail reaches and divided by the sample tail reach. So when adding regrets // to the table, we need only multiply by the opponent reach and divide by // the sample reach to this point. for (int aidx = 0; aidx < legal_actions.size(); ++aidx) { // Estimate for the counterfactual value of the policy replaced by always // choosing sampled_aidx at this information state. double cf_action_value = child_values[aidx] * opp_reach / sample_reach; info_state.cumulative_regrets[aidx] += (cf_action_value - cf_value); } // Update the average policy. for (int aidx = 0; aidx < legal_actions.size(); ++aidx) { double increment = my_reach * info_state.current_policy[aidx] / sample_reach; SPIEL_CHECK_FALSE(std::isnan(increment) || std::isinf(increment)); info_state.cumulative_policy[aidx] += increment; } } return value_estimate; } std::unique_ptr<OutcomeSamplingMCCFRSolver> DeserializeOutcomeSamplingMCCFRSolver(const std::string& serialized, std::string delimiter) { auto partial = PartiallyDeserializeCFRSolver(serialized); SPIEL_CHECK_EQ(partial.solver_type, "OutcomeSamplingMCCFRSolver"); enum Section { kInvalid = -1, kRNG = 0, kEpsilon = 1, kDefaultPolicy = 2 }; std::array<std::string, 3> section_strings = {"", "", ""}; Section current_section = kInvalid; std::vector<absl::string_view> lines = absl::StrSplit(partial.solver_specific_state, '\n'); for (int i = 0; i < lines.size(); i++) { if (lines[i] == kSerializeSolverRNGSectionHeader) { SPIEL_CHECK_EQ(current_section, kInvalid); current_section = kRNG; } else if (lines[i] == kSerializeSolverEpsilonSectionHeader) { SPIEL_CHECK_EQ(current_section, kRNG); current_section = kEpsilon; } else if (lines[i] == kSerializeSolverDefaultPolicySectionHeader) { SPIEL_CHECK_EQ(current_section, kEpsilon); current_section = kDefaultPolicy; } else { SPIEL_CHECK_NE(current_section, kInvalid); absl::StrAppend(&section_strings[current_section], lines[i], "\n"); } } // Remove trailing newline characters for (int i = 0; i < section_strings.size(); i++) { section_strings[i].erase(section_strings[i].length() - 1); } // Do the actual deserialization for all internal state values std::mt19937 rng = std::mt19937(); std::istringstream rng_stream(section_strings[kRNG]); rng_stream >> rng; // First scalar is epsilon, second is update_player std::string epsilon = section_strings[kEpsilon]; auto solver = std::make_unique<OutcomeSamplingMCCFRSolver>( partial.game, DeserializePolicy(section_strings[kDefaultPolicy]), std::stod(epsilon), rng); DeserializeCFRInfoStateValuesTable(partial.serialized_cfr_values_table, &solver->InfoStateValuesTable(), delimiter); return solver; } } // namespace algorithms } // namespace open_spiel
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. *------------------------------------------------------------------------- * * main.cpp * main function file for gs_cgroup utility * * IDENTIFICATION * src/bin/gs_cgroup/main.cpp * * ------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <libcgroup.h> #include "securec.h" #include "cgutil.h" #include "pg_config.h" #include "getopt_long.h" extern int CheckBackendEnv(const char* input_env_value); /* global variable to describe Cgroup configuration file */ gscgroup_grp_t* cgutil_vaddr[GSCGROUP_ALLNUM] = {NULL}; /* global variable of gs_cgroup options */ cgutil_opt_t cgutil_opt = {0}; /* the cpu count */ int cgutil_cpucnt = 0; /* global variable to indicate the user of Cgroup configuration file */ struct passwd* cgutil_passwd_user = NULL; /* global variable for version info */ static char* cgutil_version = NULL; /* all cores for OS */ char cgutil_allset[CPUSET_LEN]; /* memory set for OS */ char cgutil_mems[CPUSET_LEN]; char* current_nodegroup = NULL; #define MAX_PATH_LEN 1024 /* the max length of the file path */ #define MAX_BUF_SIZE 2048 /* the max size of the buffer */ #define STATIC_CONFIG_FILE "cluster_static_config" /* the name of cluster static config file */ #define PROG_NAME "gs_cgroup" /* * function name: usage * description : gs_cgroup usage function * */ static void usage(void) { fprintf(stdout, "\ngs_cgroup is used to manage the Gauss Cgroups on each node.\n" "Usage:\n gs_cgroup [OPTION]...\n\n" "OPTIONS:\n" " -a [--abort] : the abort exception flag, should be used with '-E data'.\n" " -b pct : backend group percentage\n" " -B name : specify the group name together with '-u'\n" " -c : create default control groups, \n" " with '-S' and '-G' to create specified class groups and workload groups;\n" " with '-N' to create control group of the specified logical cluster.\n" " -d : drop all control groups, with '-S' and '-G' to drop specified groups\n" " with '-N' to drop control group of the specified logical cluster.\n" " -D mpoint : specify a mount point instead of default point: \"/dev/cgroup/subsystem\"\n" " -E data : Exception data with the following format string: \n" " blocktime=value (unit is second) \n" " elapsedtime=value (unit is second) \n" " allcputime=value (unit is second) \n" " qualificationtime=value (unit is second) \n" " cpuskewpercent=value (0 ~ 100) \n" " spillsize=value (unit is MB) \n" " broadcastsize=value (unit is MB) \n" " these strings can be joined with ',' sperator.\n" " -h [--help] : help information\n" " -H : GAUSSHOME PATH for the specified user\n" " -f : to specify cpu cores to use like this: a or a-b.\n" " the argument is only used on Gaussdb:user group.\n" " --fixed : allocate cpu cores by percentage for different groups.\n" " -g pct : workload group percentage\n" " -G name : specify the group name together with '-c', '-d', '-u' or '-E' \n" " and '-S' option; ',' operator is used to join multiple groups.\n" " -m : mount cgroups\n" " -M : umount cgroups\n" " -N [--group] name : specify the name of logical cluster.\n" " -p : display the default cgroups configuration information.\n" " with '-N' to display the control group configuration of the specified logical cluster.\n" " -P : display all cgroups tree information of whole cluster.\n" " --penalty : the penalty exception flag, should be used with '-E data'.\n" " -r data : blkio bps read\n" " --recover : recover the group configure to last change by normal user.\n" " with '-N' to recover control group of the specified logical cluster.\n" " --refresh : refresh the cgroup group based on the configuration file.\n" " with '-N' to refresh control group of the specified logical cluster.\n" " --revert : revert the group to default.\n" " -R data : blkio iops read\n" " -s pct : class group percentage\n" " -S name : specify the Class name together with '-c', '-d', '-u' or '-E' option\n" " if the class name is \"default\", it will be treated as \"DefaultClass\". \n" " if this option is not set, class name will be 'DefaultClass' while with '-E'.\n" " -t pct : top group percentage\n" " -T name : specify the Top group name together with '-u' option\n" " -u : modify the information of a specified class group with '-S', \n" " or a specified top group with '-T', \n" " or a specified workload group with '-G'.\n" " with '-N' to update control group of the specified logical cluster.\n" " -U name : the user name of database\n" " -V [--version] : show the version.\n" " -w data : blkio bps write\n" " -W data : blkio iops write\n" "\n" "Examples:\n" "Root user can execute:\n" "gs_cgroup -U name -H path -c : create the default control groups.\n" "gs_cgroup -U name -d : drop all control groups.\n" "gs_cgroup -m: mount cgroup\n" "gs_cgroup -M: umount cgroup\n" "\n" "Non-root user can execute:\n" "gs_cgroup -p: display the control groups configuration information.\n" "gs_cgroup -c -S class: create the default control groups for class\n" "gs_cgroup -d -S class: drop all control groups of class\n" "gs_cgroup -c -S class -G wg1: create wg1 groups for class.\n" "gs_cgroup -d -S class -G wg2 : \n" " drop wg2 groups of class, its child group is moved to its level.\n" "gs_cgroup -u -T Gaussdb -t 70: \n" " update CPU percentage of Gaussdb cgroup as 70%%.\n" "gs_cgroup -u -f 2-8 -T Gaussdb: \n" " update the CPU cores of Gaussdb:user cgroup as 2~8.\n" "gs_cgroup -u --fixed -S class1 -s 40: \n" " update the CPU cores percentage of class1 group as 40%% of the Top group: Class\n" "gs_cgroup -u -S class -r \"major:minor value\": \n" " update the BLKIO Readbps throttle value of class cgroup.\n" " The major:minor value can be retrieved by following steps: \n" " a. run \"df\" command to find the disk which will be controlled;\n" " b. run \"ls -l device\" to find the major and minor value of the disk;\n" " device can't include the device number, such as sdd is correct rather than sdd1;\n" " it may display: brw-rw---- 1 root disk 8, 48 Mar 10 05:44 device\n" " so the major:minor value is \"8:48\";\n" "gs_cgroup -S class -G wg -E \"blocktime=5,elapsedtime=5\" -a\n" "gs_cgroup -S class -G wg -E \"spillsize=256,broadcastsize=100\" -a\n" "gs_cgroup -c -N ngname: create control groups for the logical cluster ngname.\n" "gs_cgroup -c -N ngname -S class -G wg1: create wg1 groups for class in the logical cluster ngname.\n" "gs_cgroup -d -N ngname -S class: drop class control groups in the logical cluster ngname.\n" "gs_cgroup -p -N ngname: display the control groups configuration information of the logical cluster ngname.\n" "\n"); (void)fflush(stdout); } /* * @Description: if more than one level of cgroup is specified, the reduntant groups are set to NULL * @IN bkd: check if backend group is being updated * @IN grp: check if workload group is being updated * @IN cls: check if class group is being updated * @IN top: check if top group is being updated * @See also: */ void check_group_name_redundant(int bkd, int grp, int cls, int top) { if (bkd) { cgutil_opt.wdname[0] = '\0'; cgutil_opt.clsname[0] = '\0'; cgutil_opt.topname[0] = '\0'; } /* clsname must be left */ else if (grp) { cgutil_opt.bkdname[0] = '\0'; cgutil_opt.topname[0] = '\0'; } else if (cls) { cgutil_opt.bkdname[0] = '\0'; if (cgutil_opt.uflag) cgutil_opt.wdname[0] = '\0'; cgutil_opt.topname[0] = '\0'; } else if (top) { cgutil_opt.bkdname[0] = '\0'; cgutil_opt.wdname[0] = '\0'; cgutil_opt.clsname[0] = '\0'; } } /* * @Description: check percentage for different groups and cpusets. * @IN bkd: check if backend group is being updated * @IN grp: check if workload group is being updated * @IN cls: check if class group is being updated * @IN top: check if top group is being updated * @Return: -1: abnormal 0: normal * @See also: */ static int check_percentage_value(int bkd, int grp, int cls, int top) { /* fixed mode */ if (cgutil_opt.fixed) { /* * it is not allowed if more than one group percentage is specified when updating * cpuset by percentage */ if (bkd + cls + top + grp > 1) { fprintf(stderr, "ERROR: redundant options of cpu core percentage. \n"); return -1; } else if (bkd + cls + top + grp == 0) { return 0; } check_group_name_redundant(bkd, grp, cls, top); /* check backend percentage, cpuset percentage range is 1-100 */ if (cgutil_opt.uflag && bkd) { if (cgutil_opt.bkdpct > 100 || cgutil_opt.bkdpct < 0) { fprintf(stderr, "ERROR: invalid value for cpu core percentage. " "its range should be 0-100. \n"); return -1; } cgutil_opt.setspct = cgutil_opt.bkdpct; cgutil_opt.bkdpct = 0; } /* check group percentage */ if (cgutil_opt.uflag && grp) { if (cgutil_opt.grppct > 100 || cgutil_opt.grppct < 0) { fprintf(stderr, "ERROR: invalid value for cpu core percentage. " "its range should be 0-100. \n"); return -1; } cgutil_opt.setspct = cgutil_opt.grppct; cgutil_opt.grppct = 0; } /* check class percentage */ if (cgutil_opt.uflag && cls) { if (cgutil_opt.clspct > 100 || cgutil_opt.clspct < 0) { fprintf(stderr, "ERROR: invalid value for cpu core percentage. " "its range should be 0-100. \n"); return -1; } cgutil_opt.setspct = cgutil_opt.clspct; cgutil_opt.clspct = 0; cgutil_opt.clssetpct = 1; } /* check top group percentage */ if (cgutil_opt.uflag && top) { if (cgutil_opt.toppct > 100 || cgutil_opt.toppct < 0) { fprintf(stderr, "ERROR: invalid value for cpu core percentage. " "its range should be 0-100. \n"); return -1; } cgutil_opt.setspct = cgutil_opt.toppct; cgutil_opt.toppct = 0; } // if user set core percentage is 0, set a flag to show that user set if (cgutil_opt.setspct == 0) cgutil_opt.setfixed = 1; } else { if ((cgutil_opt.cflag || cgutil_opt.uflag) && bkd && (cgutil_opt.bkdpct >= 100 || cgutil_opt.bkdpct < 1)) { fprintf(stderr, "ERROR: invalid value for backend group dynamic percentage. " "its range should be 1 ~ 99!\n"); return -1; } /* check backend percentage */ if ((cgutil_opt.cflag || cgutil_opt.uflag) && grp && (cgutil_opt.grppct >= 100 || cgutil_opt.grppct < 1)) { fprintf(stderr, "ERROR: invalid value for workload group dynamic percentage. " "its range should be 1 ~ 99!\n"); return -1; } /* check group percentage */ if ((cgutil_opt.cflag || cgutil_opt.uflag) && cls && (cgutil_opt.clspct >= 100 || (cgutil_opt.clspct < 1))) { fprintf(stderr, "ERROR: invalid value for class group dynamic percentage. " "its range should be 1 ~ 99!\n"); return -1; } /* check class percentage */ if ((cgutil_opt.cflag || cgutil_opt.uflag) && top && (cgutil_opt.toppct >= 100 || cgutil_opt.toppct < 1)) { fprintf(stderr, "ERROR: invalid value for top group dynamic percentage. " "its range should be 1 ~ 99!\n"); return -1; } } return 0; } /* * @Description: check if the node group is valid. * @Return: -1: abnormal 0: normal * @See also: */ static int check_node_group_name() { char path[MAX_PATH_LEN]; struct stat stat_buf; /* get the static configuration file */ errno_t sret; sret = memset_s(&stat_buf, sizeof(stat_buf), 0, sizeof(stat_buf)); securec_check_errno(sret, , -1); char* exec_path = gs_getenv_r("GAUSSHOME"); if (NULL == exec_path) { fprintf(stderr, "ERROR: Get GAUSSHOME failed, please check.\n"); return -1; } if (CheckBackendEnv(exec_path) != 0) { return -1; } sret = snprintf_s(path, MAX_PATH_LEN, MAX_PATH_LEN - 1, "%s/%s/%s_%s%s", exec_path, GSCGROUP_CONF_DIR, GSCFG_PREFIX, cgutil_passwd_user->pw_name, GSCFG_SUFFIX); securec_check_intval(sret, , -1); /* check if the file access */ if (stat(path, &stat_buf) != 0) { fprintf(stderr, "ERROR: the file %s doesn't exist.\n", path); return -1; } return 0; } /* * @Description: check input for security * @IN input: input string * @Return: void * @See also: */ static void check_input_for_security(char* input) { char* danger_token[] = {"|", ";", "&", "$", "<", ">", "`", "\\", "!", "\n", NULL}; for (int i = 0; danger_token[i] != NULL; ++i) { if (strstr(input, danger_token[i]) != NULL) { printf("invalid token \"%s\"\n", danger_token[i]); exit(1); } } } /* * @Description: check iops and bps values. * @IN void * @Return: 1: valid 0: invalid * @See also: */ static int check_bps_or_iops_value(void) { if (cgutil_opt.bpsread[0] || cgutil_opt.iopsread[0] || cgutil_opt.bpswrite[0] || cgutil_opt.iopswrite[0]) return 1; return 0; } /* * @Description: Check whether the name of class, * Class group and Workload group is valid. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_name_valid(void) { int namelen = GPNAME_LEN / 2 - 1; /* max name length */ errno_t sret; /* check class name and class exception data */ if (*cgutil_opt.clsname == '\0' && *cgutil_opt.edata) { fprintf(stdout, "NOTICE: if not specify class name but exceptional data is valid, " "class name will be \"%s\"!\n", GSCGROUP_DEFAULT_CLASS); sret = snprintf_s(cgutil_opt.clsname, GPNAME_LEN, GPNAME_LEN - 1, "%s", GSCGROUP_DEFAULT_CLASS); securec_check_intval(sret, , -1); } /* check class name length */ if (strlen(cgutil_opt.clsname) > (size_t)namelen) { *cgutil_opt.clsname = '\0'; fprintf(stderr, "ERROR: The name of Class group is beyond " "its dedicated size which is %d bytes.\n", namelen); return -1; } /* check workload group name length */ if (strlen(cgutil_opt.wdname) > (size_t)namelen - 3) { *cgutil_opt.wdname = '\0'; fprintf(stderr, "ERROR: The name of Workload group is beyond " "its dedicated size which is %d bytes.\n", namelen - 3); return -1; } return 0; } /* * @Description: check input values. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_input_valid(void) { /* check group name with flag '--fixed' */ if (*cgutil_opt.clsname == '\0' && *cgutil_opt.wdname == '\0' && *cgutil_opt.bkdname == '\0' && *cgutil_opt.topname == '\0' && cgutil_opt.fixed) { fprintf(stderr, "ERROR: Please specify a group name with flag \"--fixed\"\n"); return -1; } /* check flag '--fixed' and '-u' */ if (cgutil_opt.fixed && 0 == cgutil_opt.uflag) { fprintf(stderr, "ERROR: Please specify \'--fixed\' flag together with \'-u\' flag.\n"); return -1; } /* check group name with flag '-f' */ if ((*cgutil_opt.clsname || *cgutil_opt.wdname || *cgutil_opt.bkdname || (*cgutil_opt.topname && (0 != strncmp(cgutil_opt.topname, GSCGROUP_TOP_DATABASE, sizeof(GSCGROUP_TOP_DATABASE))))) && *cgutil_opt.sets) { fprintf(stderr, "ERROR: Only specify \'-f\' option on Gaussdb Group.\n"); return -1; } /* users cannot use -f and --fixed at the same time */ if (cgutil_opt.fixed && *cgutil_opt.sets) { fprintf(stderr, "ERROR: Please specify one option from \'-f\',\'--fixed\'.\n"); return -1; } /* get current mount points */ if (cgexec_get_mount_points() < 0) { return -1; } /* check '-c', '-d', '-u' flag */ if ((cgutil_opt.cflag && cgutil_opt.dflag) || (cgutil_opt.cflag && cgutil_opt.uflag) || (cgutil_opt.uflag && cgutil_opt.dflag)) { fprintf(stderr, "ERROR: please only specify one option from '-c', '-d' and '-u'.\n"); return -1; } /* check '-e' flag */ if (IS_EXCEPT_FLAG(cgutil_opt.eflag, EXCEPT_ERROR)) { fprintf(stderr, "ERROR: abort and penalty cannot be specified together!\n"); return -1; } /* check exception data from '-e' flag */ if (cgutil_opt.clsname[0] == '\0' && IS_EXCEPT_FLAG(cgutil_opt.eflag, EXCEPT_PENALTY)) { fprintf(stderr, "ERROR: you must specify a class name with penalty!\n"); return -1; } /* set default exception data without '--penalty', '--abort' and '-a' flag */ if (*cgutil_opt.edata && IS_EXCEPT_FLAG(cgutil_opt.eflag, EXCEPT_NONE)) { cgutil_opt.eflag = EXCEPT_FLAG(EXCEPT_PENALTY); fprintf(stdout, "NOTICE: if do not specify exceptional action, default is penalty!\n"); } /* check '--refresh', '--revert' and '--recover' flag */ if ((cgutil_opt.cflag || cgutil_opt.dflag || cgutil_opt.uflag) && (cgutil_opt.refresh || cgutil_opt.revert || cgutil_opt.recover)) { fprintf(stderr, "ERROR: you cannot specify option '-c', '-u' or '-d' with " "'--refresh' or '--revert' or '--recover'!\n"); return -1; } /* check '--recover' flag */ if ((geteuid() == 0) && cgutil_opt.recover) { fprintf(stderr, "ERROR: you cannpt specify option '--recover' by root user!\n"); return -1; } return 0; } /* * @Description: check io values. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_io_value(void) { /* check exception data */ if (!(cgutil_opt.cflag || cgutil_opt.dflag || cgutil_opt.uflag || *cgutil_opt.edata)) { fprintf(stderr, "ERROR: please specify one option from '-c', '-d', '-u', '-E' " "when using class name!\n"); return -1; } /* check group percentage with '-u' flag */ if (cgutil_opt.uflag == 0 || cgutil_opt.clspct || cgutil_opt.grppct) return 0; /* check io values with '--fixed' flag */ if (cgutil_opt.fixed && cgutil_opt.setspct == 0 && cgutil_opt.setfixed == 0 && !check_bps_or_iops_value()) { fprintf(stderr, "ERROR: please specified the fixed percent or IO values " "when updating fixed values!\n"); return -1; } return 0; } /* * @Description: check user info with flags. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_user_process(void) { /* check root user process */ if ((geteuid() == 0) && ((cgutil_opt.cflag || cgutil_opt.display || cgutil_opt.uflag || cgutil_opt.dflag) && cgutil_opt.user[0] == '\0')) { fprintf(stderr, "ERROR: you must specify the user name with '-c', '-d', '-p' or '-u' " "while running as root user.\n"); return -1; } /* check non-root user process */ if (geteuid() && cgutil_opt.user[0] != '\0') { fprintf(stderr, "ERROR: you can't specify the user name while running as non-root user.\n"); return -1; } /* check user info for '-P' flag */ if (0 == geteuid() && cgutil_opt.ptree && '\0' == *cgutil_opt.user) { fprintf(stderr, "ERROR: you must specify the user name when running as root user " "to display the cgroup tree.\n"); return -1; } /* check non-root user info for '-M' flag */ if ((cgutil_opt.mflag || cgutil_opt.umflag) && geteuid()) { fprintf(stderr, "ERROR: you must run mount or umount cgroup by root user!\n"); return -1; } return 0; } /* * @Description: check all flags. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_flag_process(void) { /* create flag process */ if (cgutil_opt.cflag) { /* check top and backend group name */ if (cgutil_opt.topname[0] != '\0' || cgutil_opt.bkdname[0] != '\0') { fprintf(stderr, "ERROR: you can't specify the Top group or backend group" " during creating cgroup!\n"); return -1; } /* check workload group name and class name */ if (cgutil_opt.wdname[0] != '\0' && cgutil_opt.clsname[0] == '\0') { fprintf(stderr, "ERROR: You can' specify the group name without" " specifying the class name during creating cgroup!\n"); return -1; } if (*cgutil_opt.wdname && NULL != strchr(cgutil_opt.wdname, ':')) { fprintf(stderr, "ERROR, workload group cannot be named with ':'. \n"); return -1; } } /* delete flag process */ if (cgutil_opt.dflag) { /* check top and backend group name */ if (cgutil_opt.topname[0] != '\0' || cgutil_opt.bkdname[0] != '\0') { fprintf(stderr, "ERROR: you can't specify the Top group or backend group" " during dropping cgroup!\n"); return -1; } } /* update flag process */ if (cgutil_opt.uflag && ('\0' == cgutil_opt.topname[0] && '\0' == cgutil_opt.bkdname[0] && '\0' == cgutil_opt.clsname[0])) { fprintf(stderr, "ERROR: please specify the Group name when updating!\n"); return -1; } return 0; } /* * @Description: check group names. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_group_name_process(int top, int bkd) { /* class group name special process */ if (cgutil_opt.clsname[0] != '\0') { if (-1 == check_io_value()) { return -1; } } /* check class name and percentage */ if (cgutil_opt.clspct && '\0' == cgutil_opt.clsname[0]) { fprintf(stderr, "ERROR: please specify the Class name " "together with Class percent!\n"); return -1; } /* check workload group name and percentage */ if (cgutil_opt.grppct && '\0' == cgutil_opt.wdname[0]) { fprintf(stderr, "ERROR: please specify the Workload name " "together with Workload percent!\n"); return -1; } /* workload group name special process */ if (cgutil_opt.wdname[0] != '\0') { if ((NULL == strchr(cgutil_opt.wdname, ':') && 0 == strcmp(cgutil_opt.wdname, GSCGROUP_TOP_WORKLOAD)) || (NULL != strchr(cgutil_opt.wdname, ':') && 0 == strncmp(cgutil_opt.wdname, GSCGROUP_TOP_WORKLOAD, sizeof(GSCGROUP_TOP_WORKLOAD) - 1))) { fprintf(stderr, "ERROR: can't do any operation on %s group!\n", GSCGROUP_TOP_WORKLOAD); return -1; } } /* check timeshare group name */ if (cgutil_opt.wdname[0] && (0 == strcmp(cgutil_opt.wdname, GSCGROUP_RUSH_TIMESHARE) || 0 == strcmp(cgutil_opt.wdname, GSCGROUP_HIGH_TIMESHARE) || 0 == strcmp(cgutil_opt.wdname, GSCGROUP_MEDIUM_TIMESHARE) || 0 == strcmp(cgutil_opt.wdname, GSCGROUP_LOW_TIMESHARE))) { fprintf(stderr, "ERROR: can't specify the name of Workload group the same as " "the name of default Timeshare Group!\n"); return -1; } /* top group name special process */ if (cgutil_opt.topname[0] != '\0') { if (!cgutil_opt.uflag) { fprintf(stderr, "ERROR: please specify the option '-u' when using top name!\n"); return -1; } /* check top percentage with '-f' flag */ if (!cgutil_opt.fixed && !*cgutil_opt.sets && !cgutil_opt.toppct) { fprintf(stderr, "ERROR: please specify the top dynamic percent when using top name!\n"); return -1; } else if (cgutil_opt.fixed && !(cgutil_opt.setspct || cgutil_opt.toppct || top || cgutil_opt.bpsread[0] || cgutil_opt.iopsread[0] || cgutil_opt.bpswrite[0] || cgutil_opt.iopswrite[0])) { fprintf(stderr, "ERROR: please specify the cpu core percent or IO values " "when updating fixed values!\n"); return -1; } } /* backend group name special process */ if (cgutil_opt.bkdname[0] != '\0') { if (!cgutil_opt.uflag) { fprintf(stderr, "ERROR: please specify the option '-u' " "when using backend name!\n"); return -1; } /* check backend percent with '--fixed' flag */ if (cgutil_opt.fixed && !(cgutil_opt.setspct || cgutil_opt.bkdpct || bkd || cgutil_opt.bpsread[0] || cgutil_opt.iopsread[0] || cgutil_opt.bpswrite[0] || cgutil_opt.iopswrite[0])) { fprintf(stderr, "ERROR: please specified the cpu core percent or IO values " "when updating fixed values!\n"); return -1; } } /* check backend name and percentage */ if (cgutil_opt.bkdpct && '\0' == cgutil_opt.bkdname[0]) { fprintf(stderr, "ERROR: please specify the backend name " "together with backend percent!\n"); return -1; } /* check backend name and percentage */ if (cgutil_opt.toppct && '\0' == cgutil_opt.topname[0]) { fprintf(stderr, "ERROR: please specify the top cgroup name " "together with top percent!\n"); return -1; } /* Check if the node group has been created or will be created */ if ('\0' != cgutil_opt.nodegroup[0]) { if ((cgutil_opt.clsname[0] != '\0' || cgutil_opt.wdname[0] != '\0' || cgutil_opt.refresh) && -1 == check_node_group_name()) { fprintf(stderr, "ERROR: please check if the node group exists!\n"); return -1; } /* can't run command by root user */ if (geteuid() == 0) { fprintf(stderr, "ERROR: please execute command by non-root user " "when the node group is specified!\n"); return -1; } if (0 == strcmp(cgutil_opt.nodegroup, GSCGROUP_TOP_CLASS) || 0 == strcmp(cgutil_opt.nodegroup, GSCGROUP_TOP_BACKEND)) { fprintf(stderr, "ERROR: the name of logical cluster can't be 'Class' or 'Backend'.\n"); return -1; } if (!cgutil_opt.cflag && !cgutil_opt.dflag && !cgutil_opt.uflag && !cgutil_opt.display && !cgutil_opt.recover && !cgutil_opt.refresh && ('\0' == *cgutil_opt.edata)) { fprintf(stderr, "ERROR: please specify logical cluster with -c/-d/-u/--recover/--refresh option!\n"); return -1; } } /* Check if the rename flag is set together with nodegroup */ if (cgutil_opt.rename && '\0' == cgutil_opt.nodegroup[0]) { fprintf(stderr, "ERROR: please specify the rename flag together with nodegroup name!\n"); return -1; } /* set the name when there is no rename flag */ if (!cgutil_opt.rename && '\0' != cgutil_opt.nodegroup[0]) current_nodegroup = cgutil_opt.nodegroup; return 0; } /* * @Description: check user name. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int check_user_name(void) { /* user name is valid */ if (cgutil_opt.user[0]) { /* check it's root user */ if (0 == strcmp(cgutil_opt.user, "root")) { fprintf(stderr, "ERROR: can't specify the user name as root.\n"); return -1; } else /* get the user id and group id */ { cgutil_passwd_user = getpwnam(cgutil_opt.user); if (NULL == cgutil_passwd_user) { fprintf(stderr, "ERROR: can't get the uid and gid of %s.\n" "HINT: please check the specified user name.\n", cgutil_opt.user); return -1; } } } else { /* save current user info */ cgutil_passwd_user = getpwuid(geteuid()); if (NULL == cgutil_passwd_user) { fprintf(stderr, "ERROR: can't get the cgutil_passwd_user.\n" "HINT: please check the running user!\n"); return -1; } } return 0; } /* * @Description: check all input whether is valid. * @IN bkd: backend group id * @IN grp: group id * @IN cls: class id * @IN top: top group id * @Return: -1: abnormal 0: normal * @See also: */ static int check_input_isvalid(int bkd, int grp, int cls, int top) { /* check list */ if (check_name_valid() == -1 || check_input_valid() == -1 || check_user_name() == -1 || check_percentage_value(bkd, grp, cls, top) == -1 || check_group_name_process(top, bkd) == -1 || check_user_process() == -1 || check_flag_process() == -1) { return -1; } return 0; } /* * @Description: check cpuset value is valid. * @IN cpuset: cpuset value * @Return: -1: abnormal 0: normal * @See also: */ static int check_cpuset_value_valid(char* cpuset) { char* bad = NULL; int a = -1; int b = -1; char* p = NULL; if (*cpuset == '-') { fprintf(stderr, "ERROR: please specify the cpuset with a valid value.\n"); return -1; } p = strchr(cpuset, '-'); /* check "cpuset" value is like this: a-b */ if (p == NULL) { a = (int)strtol(cpuset, &bad, 10); if ((bad != NULL) && *bad) { fprintf(stderr, "ERROR: please specify the cpuset with \"a-b\" or \"a\"!\n"); return -1; } b = a; } else { *p++ = '\0'; a = (int)strtol(cpuset, &bad, 10); if ((bad != NULL) && *bad) { fprintf(stderr, "ERROR: please specify the cpuset with a valid value.\n"); return -1; } b = (int)strtol(p, &bad, 10); if ((bad != NULL) && *bad) { fprintf(stderr, "ERROR: please specify the cpuset with a valid value.\n"); return -1; } } if ((a < 0) || (b < 0) || (a > b) || (b >= cgutil_cpucnt)) { fprintf(stderr, "ERROR: please specify the cpuset with a valid value.\n"); return -1; } int rcs = sprintf_s(cgutil_opt.sets, CPUSET_LEN, "%d-%d", a, b); securec_check_intval(rcs, , -1); return 0; } /* * @Description: check config flag. * @IN void * @Return: 1: OK 0: Not OK * @See also: */ static int check_config_flag(void) { if (cgutil_opt.cflag || (cgutil_opt.dflag && (*cgutil_opt.clsname || *cgutil_opt.nodegroup)) || cgutil_opt.uflag || cgutil_opt.display || (*cgutil_opt.edata && *cgutil_opt.clsname) || cgutil_opt.refresh || cgutil_opt.upgrade || cgutil_opt.revert || cgutil_opt.recover) return 1; return 0; } /* * @Description: initialize cgroup config. * @IN void * @Return: -1: abnormal 0: normal * @See also: */ static int initialize_cgroup_config(void) { char* hpath = NULL; errno_t sret; /* retrieve the information of configure file; if it doesn't, create one */ if (check_config_flag() > 0) { if (geteuid() == 0) { if ('\0' == cgutil_opt.hpath[0]) { fprintf(stderr, "ERROR: you need specify the GAUSSHOME path " "when runing as root user!\n"); return -1; } } else { if (NULL == (hpath = gs_getenv_r("GAUSSHOME"))) { fprintf(stderr, "ERROR: environment variable $GAUSSHOME is not set!\n"); return -1; } if (CheckBackendEnv(hpath) != 0) { return -1; } sret = snprintf_s(cgutil_opt.hpath, sizeof(cgutil_opt.hpath), sizeof(cgutil_opt.hpath) - 1, "%s", hpath); securec_check_intval(sret, , -1); } if (-1 == cgconf_parse_config_file()) { if (cgutil_opt.dflag && '\0' != cgutil_opt.nodegroup[0]) { fprintf(stderr, "WARNING: failed to parse the node group configure file!\n"); } else { fprintf(stderr, "FATAL: failed to parse the configure file!\n"); return -1; } } } return 0; } /* * @Description: check and get group percent. * @IN percent: input percent * @IN gtype: group type: class, workload or top * @Return: -1: abnormal 0: normal * @See also: */ static int check_and_get_group_percent(char* percent, char* gtype) { char* bad = NULL; if (strcmp(gtype, "top") == 0) { cgutil_opt.toppct = (int)strtol(percent, &bad, 10); } else if (strcmp(gtype, "class") == 0) { cgutil_opt.clspct = (int)strtol(percent, &bad, 10); } else if (strcmp(gtype, "workload") == 0) { cgutil_opt.grppct = (int)strtol(percent, &bad, 10); } else if (strcmp(gtype, "backend") == 0) { cgutil_opt.bkdpct = (int)strtol(percent, &bad, 10); } else { return -1; } if ((bad != NULL) && *bad) { fprintf(stderr, "ERROR: incorrect %s percent %s!\n", gtype, percent); return -1; } return 0; } /* * function name: parse_options * description : parse the option of gs_cgroup utility * arguments : as main function arguments * return value : * -1: abnormal * 0: normal */ static struct option long_options[] = {{"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {"abort", no_argument, NULL, 'a'}, {"group", required_argument, NULL, 'N'}, {"penalty", no_argument, NULL, 1}, {"upgrade", no_argument, NULL, 2}, {"refresh", no_argument, NULL, 3}, {"revert", no_argument, NULL, 4}, {"fixed", no_argument, NULL, 5}, {"recover", no_argument, NULL, 6}, {"rename", no_argument, NULL, 7}, {NULL, 0, NULL, 0}}; static int parse_options(int argc, char** argv) { int c; int option_index; int bkd = 0; int grp = 0; int cls = 0; int top = 0; int last = 0; errno_t sret; sret = memset_s(&cgutil_opt, sizeof(cgutil_opt_t), 0, sizeof(cgutil_opt_t)); securec_check_errno(sret, , -1); /* option parse */ while ((c = getopt_long( argc, argv, "ab:B:cdD:E:f:hH:g:G:mMN:pPr:R:s:S:t:T:uU:Vw:W:", long_options, &option_index)) != -1) { switch (c) { case 'a': /* abort */ if (IS_EXCEPT_FLAG(cgutil_opt.eflag, EXCEPT_NONE)) cgutil_opt.eflag = EXCEPT_FLAG(EXCEPT_ABORT); else cgutil_opt.eflag = EXCEPT_FLAG(EXCEPT_ERROR); break; case 'b': /* backend group percentage */ if (check_and_get_group_percent(optarg, "backend") == -1) return -1; bkd = 1; break; case 'B': /* backend group name */ sret = strncpy_s(cgutil_opt.bkdname, GPNAME_LEN, optarg, GPNAME_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.bkdname); break; case 'c': /* create group */ cgutil_opt.cflag = 1; break; case 'd': /* drop group */ cgutil_opt.dflag = 1; break; case 'D': /* mount point */ cgutil_opt.mpflag = 1; sret = strncpy_s(cgutil_opt.mpoint, MAXPGPATH, optarg, MAXPGPATH - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.mpoint); last = strlen(cgutil_opt.mpoint) - 1; if ('/' == cgutil_opt.mpoint[last]) cgutil_opt.mpoint[last] = '\0'; break; case 'E': /* Exceptional data */ sret = strncpy_s(cgutil_opt.edata, EXCEPT_LEN, optarg, EXCEPT_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.edata); break; case 'h': /* help */ usage(); exit(0); case 'H': /* GAUSSHOME path */ sret = strncpy_s(cgutil_opt.hpath, MAXPGPATH, optarg, MAXPGPATH - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.hpath); break; case 'f': /* core numbers */ if (check_cpuset_value_valid(optarg) == -1) return -1; break; case 'g': /* workload group percentage */ if (check_and_get_group_percent(optarg, "workload") == -1) return -1; grp = 1; break; case 'G': /* workload group name for "gpname:gplevel" */ sret = strncpy_s(cgutil_opt.wdname, GPNAME_LEN, optarg, GPNAME_LEN - 1 - 2); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.wdname); break; case 'm': /* mount cgroup */ cgutil_opt.mflag = 1; break; case 'M': /* umount cgroup */ cgutil_opt.umflag = 1; break; case 'N': /* Nodegroup information */ sret = strncpy_s(cgutil_opt.nodegroup, GPNAME_LEN, optarg, GPNAME_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.nodegroup); break; case 'p': /* display gscgroup.cfg information */ cgutil_opt.display = 1; break; case 'P': /* display Cgroup tree information */ cgutil_opt.ptree = 1; break; case 'r': /* IO bps read */ sret = strncpy_s(cgutil_opt.bpsread, IODATA_LEN, optarg, IODATA_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.bpsread); if (*cgutil_opt.bpsread == '\0') fprintf(stdout, "NOTICE: invalid IO value for '-r' flag!\n"); break; case 'R': /* IO iops read */ sret = strncpy_s(cgutil_opt.iopsread, IODATA_LEN, optarg, IODATA_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.iopsread); if (*cgutil_opt.iopsread == '\0') fprintf(stdout, "NOTICE: invalid IO value for '-R' flag!\n"); break; case 's': /* Class group percentage */ if (check_and_get_group_percent(optarg, "class") == -1) return -1; cls = 1; break; case 'S': /* Class group name */ if (strchr(optarg, ':') != NULL) { fprintf(stderr, "ERROR, class cannot be named with ':'. \n"); return -1; } sret = strncpy_s(cgutil_opt.clsname, GPNAME_LEN, optarg, GPNAME_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.clsname); break; case 't': /* Top group percentage */ if (check_and_get_group_percent(optarg, "top") == -1) return -1; top = 1; break; case 'T': /* Top group name */ sret = strncpy_s(cgutil_opt.topname, GPNAME_LEN, optarg, GPNAME_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.topname); break; case 'u': /* update flag */ cgutil_opt.uflag = 1; break; case 'U': /* user name */ sret = strncpy_s(cgutil_opt.user, USERNAME_LEN, optarg, USERNAME_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.user); break; case 'V': /* version */ cgutil_version = DEF_GS_VERSION; return 0; case 'w': /* IO bps write */ sret = strncpy_s(cgutil_opt.bpswrite, IODATA_LEN, optarg, IODATA_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.bpswrite); break; case 'W': /* IO iops write */ sret = strncpy_s(cgutil_opt.iopswrite, IODATA_LEN, optarg, IODATA_LEN - 1); securec_check_errno(sret, , -1); check_input_for_security(cgutil_opt.iopswrite); break; case 1: if (IS_EXCEPT_FLAG(cgutil_opt.eflag, EXCEPT_NONE)) cgutil_opt.eflag = EXCEPT_FLAG(EXCEPT_PENALTY); else cgutil_opt.eflag = EXCEPT_FLAG(EXCEPT_ERROR); break; case 2: cgutil_opt.upgrade = 1; break; case 3: cgutil_opt.refresh = 1; break; case 4: cgutil_opt.revert = 1; break; case 5: cgutil_opt.fixed = 1; break; case 6: cgutil_opt.recover = 1; break; case 7: cgutil_opt.rename = 1; break; default: fprintf(stderr, "ERROR: incorrect option: %s\n.", optarg); usage(); return -1; } } return check_input_isvalid(bkd, grp, cls, top); } /* * function name: main * description : main entry of gs_cgroup utility * arguments : main function default arguments */ int main(int argc, char** argv) { char* cpuset = NULL; int ret = 0; if (argc < 2) { usage(); exit(-1); } // log output redirect init_log(PROG_NAME); /* print the log about arguments of gs_cgroup */ char arguments[MAX_BUF_SIZE] = {0x00}; for (int i = 0; i < argc; i++) { errno_t rc = strcat_s(arguments, MAX_BUF_SIZE, argv[i]); size_t len = strlen(arguments); if (rc != EOK || len >= (MAX_BUF_SIZE - 2)) break; arguments[len] = ' '; arguments[len + 1] = '\0'; } write_log("The gs_cgroup run with the following arguments: [%s].\n", arguments); /* get the cpu count value */ cgutil_cpucnt = gsutil_get_cpu_count(); if (cgutil_cpucnt == -1) { fprintf(stderr, "get cpu core range failed, please check if \"/proc/cpuinfo\"" " or \"/sys/devices/system\" is acceptable. \n"); exit(-1); } int rc = sprintf_s(cgutil_allset, sizeof(cgutil_allset), "%d-%d", 0, cgutil_cpucnt - 1); securec_check_intval(rc, , -1); /* parse the options */ ret = parse_options(argc, argv); if (-1 == ret) { fprintf(stderr, "HINT: please run 'gs_cgroup -h' to display the usage!\n"); exit(-1); } if (cgutil_version != NULL) { fprintf(stdout, "gs_cgroup %s\n", cgutil_version); return 0; } if (geteuid() == 0 && cgutil_opt.mflag) { cgexec_mount_cgroups(); } if (geteuid() == 0 && cgutil_opt.umflag && !cgutil_opt.dflag) { cgexec_umount_cgroups(); exit(0); } /* retrieve the information of configure file; if it doesn't, create one */ if (initialize_cgroup_config() == -1) return -1; /* check upgrade flag */ if (cgutil_opt.upgrade) { cgutil_opt.refresh = 1; /* maybe we need not do upgrade */ if (cgexec_check_mount_for_upgrade() == -1) { goto error; } } if (cgutil_opt.cflag) { /* run as root user */ if (geteuid() == 0 && cgutil_opt.upgrade == 0) { /* check if cgroups have been mounted if it doesn't specify mflag */ if (-1 == (ret = cgexec_mount_root_cgroup())) { goto error; } } } /* initialize libcgroup */ ret = cgroup_init(); if (ret) { fprintf(stderr, "FATAL: libcgroup initialization failed: %s\n" "please run 'gs_cgroup -m' to " "mount cgroup by root user!\n", cgroup_strerror(ret)); goto error; } /* get memory set */ if (-1 == cgexec_get_cgroup_cpuset_info(TOPCG_ROOT, &cpuset)) { fprintf(stderr, "ERROR: failed to get cpusets and mems during initialization.\n"); goto error; } rc = snprintf_s(cgutil_allset, CPUSET_LEN, CPUSET_LEN - 1, "%s", cpuset); securec_check_intval(rc, , -1); free(cpuset); cpuset = NULL; /* create/delete/update operation */ if (cgutil_opt.cflag) { if (cgexec_create_groups() == -1) { goto error; } } else if (cgutil_opt.dflag) { if (cgexec_drop_groups() == -1) { goto error; } } else if (cgutil_opt.uflag) { if (cgexec_update_groups() == -1) { goto error; } } else if (cgutil_opt.revert) { if (cgexec_revert_groups() == -1) { goto error; } } /* refresh current groups */ if (cgutil_opt.refresh) { if (cgexec_refresh_groups() == -1) { goto error; } } /* recover the last changes of groups */ if (cgutil_opt.recover) { if (cgexec_recover_groups() == -1) { goto error; } } /* process the exceptional data */ if (*cgutil_opt.edata && *cgutil_opt.clsname && -1 == cgexcp_class_exception()) goto error; /* display the cgroup configuration file information */ if (cgutil_opt.display) cgconf_display_groups(); /* display the cgroup tree information */ if (cgutil_opt.ptree) { if (cgptree_display_cgroups() == -1) { goto error; } } if (cgutil_vaddr[0] != NULL) (void)munmap(cgutil_vaddr[0], GSCGROUP_ALLNUM * sizeof(gscgroup_grp_t)); return 0; error: if (cgutil_vaddr[0] != NULL) (void)munmap(cgutil_vaddr[0], GSCGROUP_ALLNUM * sizeof(gscgroup_grp_t)); write_log("gs_cgroup execution error.\n"); exit(-1); } #ifdef ENABLE_UT void cgroup_set_default_group() { errno_t sret; char tmpstr[GPNAME_LEN]; cgutil_vaddr[TOPCG_ROOT]->used = 1; cgutil_vaddr[TOPCG_ROOT]->gid = TOPCG_ROOT; cgutil_vaddr[TOPCG_ROOT]->gtype = GROUP_TOP; sret = strncpy_s(cgutil_vaddr[TOPCG_ROOT]->grpname, GPNAME_LEN, GSCGROUP_ROOT, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TOPCG_ROOT]->ginfo.top.percent = 100 * DEFAULT_IO_WEIGHT / MAX_IO_WEIGHT; cgutil_vaddr[TOPCG_ROOT]->ainfo.weight = DEFAULT_IO_WEIGHT; cgutil_vaddr[TOPCG_ROOT]->percent = 1000; /* set root group as default cpu set */ (void)sprintf_s(cgutil_vaddr[TOPCG_ROOT]->cpuset, CPUSET_LEN, "%s", cgutil_allset); cgutil_vaddr[TOPCG_BACKEND]->used = 1; cgutil_vaddr[TOPCG_BACKEND]->gid = TOPCG_BACKEND; cgutil_vaddr[TOPCG_BACKEND]->gtype = GROUP_TOP; sret = strncpy_s(cgutil_vaddr[TOPCG_BACKEND]->grpname, GPNAME_LEN, GSCGROUP_TOP_BACKEND, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TOPCG_BACKEND]->ginfo.top.percent = TOP_BACKEND_PERCENT; cgutil_vaddr[TOPCG_BACKEND]->ainfo.shares = DEFAULT_CPU_SHARES * TOP_BACKEND_PERCENT / 10; cgutil_vaddr[TOPCG_BACKEND]->ainfo.weight = IO_WEIGHT_CALC(MAX_IO_WEIGHT, TOP_BACKEND_PERCENT); cgutil_vaddr[TOPCG_BACKEND]->percent = cgutil_vaddr[TOPCG_GAUSSDB]->percent * TOP_BACKEND_PERCENT / 100; /* set root group as gaussdb group cpu set */ if (*cgutil_vaddr[TOPCG_BACKEND]->cpuset == '\0') (void)sprintf_s(cgutil_vaddr[TOPCG_BACKEND]->cpuset, CPUSET_LEN, "%s", cgutil_vaddr[TOPCG_GAUSSDB]->cpuset); cgutil_vaddr[TOPCG_CLASS]->used = 1; cgutil_vaddr[TOPCG_CLASS]->gid = TOPCG_CLASS; cgutil_vaddr[TOPCG_CLASS]->gtype = GROUP_TOP; sret = strncpy_s(cgutil_vaddr[TOPCG_CLASS]->grpname, GPNAME_LEN, GSCGROUP_TOP_CLASS, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TOPCG_CLASS]->ginfo.top.percent = TOP_CLASS_PERCENT; cgutil_vaddr[TOPCG_CLASS]->ainfo.shares = DEFAULT_CPU_SHARES * TOP_CLASS_PERCENT / 10; cgutil_vaddr[TOPCG_CLASS]->ainfo.weight = IO_WEIGHT_CALC(MAX_IO_WEIGHT, TOP_CLASS_PERCENT); cgutil_vaddr[TOPCG_CLASS]->percent = cgutil_vaddr[TOPCG_GAUSSDB]->percent * TOP_CLASS_PERCENT / 100; /* set root group as gaussdb group cpu set */ if (*cgutil_vaddr[TOPCG_CLASS]->cpuset == '\0') (void)sprintf_s(cgutil_vaddr[TOPCG_CLASS]->cpuset, CPUSET_LEN, "%s", cgutil_vaddr[TOPCG_GAUSSDB]->cpuset); cgutil_vaddr[BACKENDCG_START_ID]->used = 1; cgutil_vaddr[BACKENDCG_START_ID]->gid = BACKENDCG_START_ID; cgutil_vaddr[BACKENDCG_START_ID]->gtype = GROUP_BAKWD; cgutil_vaddr[BACKENDCG_START_ID]->ginfo.cls.tgid = TOPCG_BACKEND; cgutil_vaddr[BACKENDCG_START_ID]->ginfo.cls.percent = DEFAULT_BACKEND_PERCENT; sret = strncpy_s(cgutil_vaddr[BACKENDCG_START_ID]->grpname, GPNAME_LEN, GSCGROUP_DEFAULT_BACKEND, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[BACKENDCG_START_ID]->ainfo.shares = DEFAULT_CPU_SHARES * DEFAULT_BACKEND_PERCENT / 10; cgutil_vaddr[BACKENDCG_START_ID]->ainfo.weight = IO_WEIGHT_CALC(MAX_IO_WEIGHT, DEFAULT_BACKEND_PERCENT); cgutil_vaddr[BACKENDCG_START_ID]->percent = cgutil_vaddr[TOPCG_BACKEND]->percent * DEFAULT_BACKEND_PERCENT / 100; /* set root group as backend group cpu set */ if (*cgutil_vaddr[BACKENDCG_START_ID]->cpuset == '\0') (void)sprintf_s( cgutil_vaddr[BACKENDCG_START_ID]->cpuset, CPUSET_LEN, "%s", cgutil_vaddr[TOPCG_BACKEND]->cpuset); cgutil_vaddr[BACKENDCG_START_ID + 1]->used = 1; cgutil_vaddr[BACKENDCG_START_ID + 1]->gid = BACKENDCG_START_ID + 1; cgutil_vaddr[BACKENDCG_START_ID + 1]->gtype = GROUP_BAKWD; cgutil_vaddr[BACKENDCG_START_ID + 1]->ginfo.cls.tgid = TOPCG_BACKEND; cgutil_vaddr[BACKENDCG_START_ID + 1]->ginfo.cls.percent = VACUUM_PERCENT; sret = strncpy_s(cgutil_vaddr[BACKENDCG_START_ID + 1]->grpname, GPNAME_LEN, GSCGROUP_VACUUM, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[BACKENDCG_START_ID + 1]->ainfo.shares = DEFAULT_CPU_SHARES * VACUUM_PERCENT / 10; cgutil_vaddr[BACKENDCG_START_ID + 1]->ainfo.weight = IO_WEIGHT_CALC(MAX_IO_WEIGHT, VACUUM_PERCENT); cgutil_vaddr[BACKENDCG_START_ID + 1]->percent = cgutil_vaddr[TOPCG_BACKEND]->percent * VACUUM_PERCENT / 100; /* set root group as backend group cpu set */ if (*cgutil_vaddr[BACKENDCG_START_ID + 1]->cpuset == '\0') (void)sprintf_s( cgutil_vaddr[BACKENDCG_START_ID + 1]->cpuset, CPUSET_LEN, "%s", cgutil_vaddr[TOPCG_BACKEND]->cpuset); cgutil_vaddr[CLASSCG_START_ID]->used = 1; cgutil_vaddr[CLASSCG_START_ID]->gid = CLASSCG_START_ID; cgutil_vaddr[CLASSCG_START_ID]->gtype = GROUP_CLASS; cgutil_vaddr[CLASSCG_START_ID]->ginfo.cls.tgid = TOPCG_CLASS; cgutil_vaddr[CLASSCG_START_ID]->ginfo.cls.maxlevel = 1; /* initialized value */ cgutil_vaddr[CLASSCG_START_ID]->ginfo.cls.percent = DEFAULT_CLASS_PERCENT; cgutil_vaddr[CLASSCG_START_ID]->ginfo.cls.rempct = 100; /* initialized value */ sret = strncpy_s(cgutil_vaddr[CLASSCG_START_ID]->grpname, GPNAME_LEN, GSCGROUP_DEFAULT_CLASS, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[CLASSCG_START_ID]->ainfo.shares = DEFAULT_CPU_SHARES * DEFAULT_CLASS_PERCENT / 10; cgutil_vaddr[CLASSCG_START_ID]->ainfo.weight = IO_WEIGHT_CALC(MAX_IO_WEIGHT, DEFAULT_CLASS_PERCENT); /* it has only this class, so it has all resource */ cgutil_vaddr[CLASSCG_START_ID]->percent = cgutil_vaddr[TOPCG_CLASS]->percent; cgutil_vaddr[CLASSCG_START_ID]->except[EXCEPT_PENALTY].skewpercent = DEFAULT_CPUSKEWPCT; cgutil_vaddr[CLASSCG_START_ID]->except[EXCEPT_PENALTY].qualitime = DEFAULT_QUALITIME; cgutil_vaddr[WDCG_START_ID]->used = 1; cgutil_vaddr[WDCG_START_ID]->gid = WDCG_START_ID; cgutil_vaddr[WDCG_START_ID]->gtype = GROUP_DEFWD; cgutil_vaddr[WDCG_START_ID]->ginfo.wd.cgid = CLASSCG_START_ID; cgutil_vaddr[WDCG_START_ID]->ginfo.wd.wdlevel = 1; sret = snprintf_s(tmpstr, sizeof(tmpstr), sizeof(tmpstr) - 1, "%s:%d", GSCGROUP_TOP_WORKLOAD, 1); securec_check_intval(sret, , ); sret = strncpy_s(cgutil_vaddr[WDCG_START_ID]->grpname, GPNAME_LEN, tmpstr, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[WDCG_START_ID]->ainfo.shares = MAX_CLASS_CPUSHARES * TOPWD_PERCENT / 100; cgutil_vaddr[WDCG_START_ID]->ainfo.weight = IO_WEIGHT_CALC(MAX_IO_WEIGHT, TOPWD_PERCENT); cgutil_vaddr[TSCG_START_ID]->used = 1; cgutil_vaddr[TSCG_START_ID]->gid = TSCG_START_ID; cgutil_vaddr[TSCG_START_ID]->gtype = GROUP_TSWD; cgutil_vaddr[TSCG_START_ID]->ginfo.ts.cgid = CLASSCG_START_ID; cgutil_vaddr[TSCG_START_ID]->ginfo.ts.rate = TS_LOW_RATE; sret = strncpy_s(cgutil_vaddr[TSCG_START_ID]->grpname, GPNAME_LEN, GSCGROUP_LOW_TIMESHARE, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TSCG_START_ID]->ainfo.shares = DEFAULT_CPU_SHARES * TS_LOW_RATE; cgutil_vaddr[TSCG_START_ID]->ainfo.weight = MIN_IO_WEIGHT * TS_LOW_RATE; /* medium group of default group */ cgutil_vaddr[TSCG_START_ID + 1]->used = 1; cgutil_vaddr[TSCG_START_ID + 1]->gid = TSCG_START_ID + 1; cgutil_vaddr[TSCG_START_ID + 1]->gtype = GROUP_TSWD; cgutil_vaddr[TSCG_START_ID + 1]->ginfo.ts.cgid = CLASSCG_START_ID; cgutil_vaddr[TSCG_START_ID + 1]->ginfo.ts.rate = TS_MEDIUM_RATE; sret = strncpy_s(cgutil_vaddr[TSCG_START_ID + 1]->grpname, GPNAME_LEN, GSCGROUP_MEDIUM_TIMESHARE, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TSCG_START_ID + 1]->ainfo.shares = DEFAULT_CPU_SHARES * TS_MEDIUM_RATE; cgutil_vaddr[TSCG_START_ID + 1]->ainfo.weight = MIN_IO_WEIGHT * TS_MEDIUM_RATE; /* high group of default group */ cgutil_vaddr[TSCG_START_ID + 2]->used = 1; cgutil_vaddr[TSCG_START_ID + 2]->gid = TSCG_START_ID + 2; cgutil_vaddr[TSCG_START_ID + 2]->gtype = GROUP_TSWD; cgutil_vaddr[TSCG_START_ID + 2]->ginfo.ts.cgid = CLASSCG_START_ID; cgutil_vaddr[TSCG_START_ID + 2]->ginfo.ts.rate = TS_HIGH_RATE; sret = strncpy_s(cgutil_vaddr[TSCG_START_ID + 2]->grpname, GPNAME_LEN, GSCGROUP_HIGH_TIMESHARE, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TSCG_START_ID + 2]->ainfo.shares = DEFAULT_CPU_SHARES * TS_HIGH_RATE; cgutil_vaddr[TSCG_START_ID + 2]->ainfo.weight = MIN_IO_WEIGHT * TS_HIGH_RATE; /* rush group of default group */ cgutil_vaddr[TSCG_START_ID + 3]->used = 1; cgutil_vaddr[TSCG_START_ID + 3]->gid = TSCG_START_ID + 3; cgutil_vaddr[TSCG_START_ID + 3]->gtype = GROUP_TSWD; cgutil_vaddr[TSCG_START_ID + 3]->ginfo.ts.cgid = CLASSCG_START_ID; cgutil_vaddr[TSCG_START_ID + 3]->ginfo.ts.rate = TS_RUSH_RATE; sret = strncpy_s(cgutil_vaddr[TSCG_START_ID + 3]->grpname, GPNAME_LEN, GSCGROUP_RUSH_TIMESHARE, GPNAME_LEN - 1); securec_check_errno(sret, , ); cgutil_vaddr[TSCG_START_ID + 3]->ainfo.shares = DEFAULT_CPU_SHARES * TS_RUSH_RATE; cgutil_vaddr[TSCG_START_ID + 3]->ainfo.weight = MIN_IO_WEIGHT * TS_RUSH_RATE; } extern void cgconf_generate_default_config_file(void* vaddr); extern int cgexec_update_remain_cgroup_cpuset(int cls, char* cpuset, unsigned char update); extern int cgexec_check_cpuset_value(const char* clsset, const char* grpset); extern int cgexec_update_class_cpuset(int cls, char* cpuset); extern int cgexec_update_top_group_cpuset(int top, char* cpuset); extern void cgexec_update_fixed_config(int high, int extended); void cgroup_unit_test_case() { char* argv[] = {"gs_cgroup", "-D", "/dev/cgroups/test", "--upgrade"}; int argc = sizeof(argv) / sizeof(*argv); int sret = 0; cgutil_opt.mpflag = 1; (void)cgexec_mount_root_cgroup(); (void)cgexec_umount_root_cgroup(); (void)parse_options(argc, argv); for (int i = 0; i < GSCGROUP_ALLNUM; ++i) { if (NULL == (cgutil_vaddr[i] = (gscgroup_grp_t*)malloc(sizeof(gscgroup_grp_t)))) { fprintf(stderr, "ERROR: failed to allocate memory for gsgroup!\n"); for (int index = 0; index < i; ++index) { free(cgutil_vaddr[index]); cgutil_vaddr[index] = NULL; } return; } } cgroup_set_default_group(); for (int i = 0; i < GSCGROUP_ALLNUM; ++i) { free(cgutil_vaddr[i]); cgutil_vaddr[i] = NULL; } gscgroup_grp_t vaddr[GSCGROUP_ALLNUM]; cgconf_generate_default_config_file(vaddr); sret = memset_s(&cgutil_opt, sizeof(cgutil_opt), 0, sizeof(cgutil_opt)); securec_check_c(sret, "\0", "\0"); sret = snprintf_s(cgutil_opt.sets, sizeof(cgutil_opt.sets), sizeof(cgutil_opt.sets) - 1, "%s", "2-8"); securec_check_ss_c(sret, "\0", "\0"); cgconf_set_class_group(1); sret = snprintf_s(cgutil_opt.wdname, sizeof(cgutil_opt.wdname), sizeof(cgutil_opt.wdname) - 1, "%s", "wg1"); securec_check_ss_c(sret, "\0", "\0"); cgconf_set_class_group(1); cgconf_set_workload_group(1, 2); cgutil_opt.fixed = 1; cgutil_is_sles11_sp2 = 0; check_percentage_value(1, 1, 1, 1); cgutil_opt.display = 1; cgutil_opt.user[0] = '\0'; check_user_process(); cgutil_opt.display = 0; cgutil_opt.ptree = 1; check_user_process(); cgutil_opt.ptree = 0; cgutil_opt.cflag = 1; cgutil_opt.fixed = 0; sret = snprintf_s(cgutil_opt.topname, sizeof(cgutil_opt.topname), sizeof(cgutil_opt.topname) - 1, "%s", "Gaussdb"); securec_check_ss_c(sret, "\0", "\0"); check_flag_process(); cgutil_opt.topname[0] = '\0'; sret = snprintf_s(cgutil_opt.wdname, sizeof(cgutil_opt.wdname), sizeof(cgutil_opt.wdname) - 1, "%s", "wg1"); securec_check_ss_c(sret, "\0", "\0"); check_flag_process(); sret = snprintf_s(cgutil_opt.wdname, sizeof(cgutil_opt.wdname), sizeof(cgutil_opt.wdname) - 1, "%s", "class1:wg1"); securec_check_ss_c(sret, "\0", "\0"); check_flag_process(); cgutil_opt.cflag = 0; cgutil_opt.dflag = 1; sret = snprintf_s(cgutil_opt.topname, sizeof(cgutil_opt.topname), sizeof(cgutil_opt.topname) - 1, "%s", "Gaussdb"); securec_check_ss_c(sret, "\0", "\0"); check_flag_process(); cgutil_opt.topname[0] = '\0'; sret = snprintf_s(cgutil_opt.user, sizeof(cgutil_opt.user), sizeof(cgutil_opt.user) - 1, "%s", "root"); securec_check_ss_c(sret, "\0", "\0"); check_user_name(); sret = snprintf_s(cgutil_opt.user, sizeof(cgutil_opt.user), sizeof(cgutil_opt.user) - 1, "%s", "xxx"); securec_check_ss_c(sret, "\0", "\0"); check_user_name(); cgutil_opt.user[0] = '\0'; check_and_get_group_percent(NULL, "abc"); cgexec_check_cpuset_value("1-2", "3-4"); cgexec_update_remain_cgroup_cpuset(1, "3-4", 1); cgexec_update_remain_cgroup_cpuset(1, "3-4", 0); cgexec_update_class_cpuset(1, "3-4"); cgexec_update_top_group_cpuset(TOPCG_ROOT, "3-4"); cgexec_update_top_group_cpuset(TOPCG_GAUSSDB, "3-4"); cgexec_update_top_group_cpuset(TOPCG_BACKEND, "3-4"); cgexec_update_top_group_cpuset(TOPCG_CLASS, "3-4"); cgexec_update_top_group_cpuset(-1, "3-4"); cgutil_opt.mpflag = 1; cgexec_check_mount_for_upgrade(); cgutil_opt.mpflag = 0; cgutil_opt.cflag = 0; cgutil_opt.cflag = 1; sret = snprintf_s( cgutil_opt.mpoints[0], sizeof(cgutil_opt.mpoints[0]), sizeof(cgutil_opt.mpoints[0]) - 1, "%s", "/dev/abc"); securec_check_ss_c(sret, "\0", "\0"); cgexec_umount_root_cgroup(); sret = memset_s(cgutil_vaddr[CLASSCG_START_ID]->except, EXCEPT_ALL_KINDS * sizeof(except_data_t), 0, EXCEPT_ALL_KINDS * sizeof(except_data_t)); securec_check_c(sret, "\0", "\0"); cgexec_create_groups(); sret = snprintf_s(cgutil_opt.clsname, sizeof(cgutil_opt.clsname), sizeof(cgutil_opt.clsname) - 1, "%s", "class2"); securec_check_ss_c(sret, "\0", "\0"); cgconf_set_class_group(31); sret = snprintf_s(cgutil_opt.clsname, sizeof(cgutil_opt.clsname), sizeof(cgutil_opt.clsname) - 1, "%s", "class3"); securec_check_ss_c(sret, "\0", "\0"); cgconf_set_class_group(32); sret = snprintf_s(cgutil_opt.clsname, sizeof(cgutil_opt.clsname), sizeof(cgutil_opt.clsname) - 1, "%s", "class4"); securec_check_ss_c(sret, "\0", "\0"); cgconf_set_class_group(33); sret = snprintf_s(cgutil_vaddr[TOPCG_CLASS]->cpuset, CPUSET_LEN, CPUSET_LEN - 1, "%s", "0-47"); securec_check_ss_c(sret, "\0", "\0"); sret = snprintf_s(cgutil_vaddr[31]->cpuset, CPUSET_LEN, CPUSET_LEN - 1, "%s", "0-46"); securec_check_ss_c(sret, "\0", "\0"); sret = snprintf_s(cgutil_vaddr[32]->cpuset, CPUSET_LEN, CPUSET_LEN - 1, "%s", "0-30"); securec_check_ss_c(sret, "\0", "\0"); sret = snprintf_s(cgutil_vaddr[33]->cpuset, CPUSET_LEN, CPUSET_LEN - 1, "%s", "0-0"); securec_check_ss_c(sret, "\0", "\0"); cgexec_update_fixed_config(TOPCG_CLASS, 0); cgconf_reset_class_group(31); cgconf_reset_class_group(32); cgconf_reset_class_group(33); } #endif
// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // XFAIL: arm-linux-gnueabi // XFAIL: armv7l-unknown-linux-gnueabihf // Test use-after-free report in the case when access is at the right border of // the allocation. #include <stdlib.h> int main() { volatile char *x = (char*)malloc(sizeof(char)); free((void*)x); *x = 42; // CHECK: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}} // CHECK: {{0x.* at pc 0x.* bp 0x.* sp 0x.*}} // CHECK: {{WRITE of size 1 at 0x.* thread T0}} // CHECK: {{ #0 0x.* in main .*use-after-free-right.cc:}}[[@LINE-4]] // CHECK: {{0x.* is located 0 bytes inside of 1-byte region .0x.*,0x.*}} // CHECK: {{freed by thread T0 here:}} // CHECK-Linux: {{ #0 0x.* in .*free}} // CHECK-Linux: {{ #1 0x.* in main .*use-after-free-right.cc:}}[[@LINE-10]] // CHECK-Darwin: {{ #0 0x.* in wrap_free}} // CHECK-Darwin: {{ #1 0x.* in main .*use-after-free-right.cc:}}[[@LINE-13]] // CHECK: {{previously allocated by thread T0 here:}} // CHECK-Linux: {{ #0 0x.* in .*malloc}} // CHECK-Linux: {{ #1 0x.* in main .*use-after-free-right.cc:}}[[@LINE-19]] // CHECK-Darwin: {{ #0 0x.* in wrap_malloc.*}} // CHECK-Darwin: {{ #1 0x.* in main .*use-after-free-right.cc:}}[[@LINE-22]] }
#include <iostream> using namespace std; int main() { int a, i, fib, fib_1; cout << "Ingrese el n-esimo termino de la sucesion de Fibonnacci que quiere imprimir: "; cin >> a; /* fib_1 = 1; cout << fib_1 << endl; */ a = a - 1; fib = 1; fib_1 = 1; for (i = 2; i <= a; i++) { fib = fib + fib_1; fib_1 = fib - fib_1; } cout << fib << endl; } /* 1 --- 1 2 ---- 1+0 1 3 ---- 1+1 2 4 ---- 2+1 3 5 ---- 3+2 5 6 ---- 5+3 8 */ /* typedef unsigned long long Millies struct Timer { } Timer timer () { return {}; } void timerStart(timer& t) { } void timerStop(timer& t) { } unsigned long long timerElapsedTime(timer& t) { } */
/** @file A brief file description @section license License 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. */ /**************************************************************************** ink_string.c String and text processing routines for libinktomi.a. ****************************************************************************/ #include <assert.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "inktomi++.h" /* MAGIC_EDITING_TAG */ #define INK_MAX_STRING_ARRAY_SIZE 128 /*---------------------------------------------------------------------------* char *ink_strncpy(char *dest, char *src, int n) This routine is a safer version of strncpy which always NUL terminates the destination string. Note that this routine has the SAME semantics as strncpy, such as copying exactly n bytes, padding dest with NULs is necessary. Use ink_string_copy for a non-padding version. *---------------------------------------------------------------------------*/ char * ink_strncpy(char *dest, const char *src, int n) { if (likely(src && dest)) { if (n > 1) strncpy(dest, src, (n - 1)); if (n > 0) dest[n - 1] = '\0'; } return (dest); } /* End ink_strncpy */ /*---------------------------------------------------------------------------* char *ink_string_concatenate_strings(char *dest, ...) This routine concatenates a variable number of strings into the buffer <dest>, returning the pointer to <dest>. The sequence of strings must end with NULL. *---------------------------------------------------------------------------*/ char * ink_string_concatenate_strings(char *dest, ...) { va_list ap; register char *s, *d; va_start(ap, dest); d = dest; while (1) { s = va_arg(ap, char *); if (s == NULL) break; while (*s) *d++ = *s++; } *d++ = '\0'; va_end(ap); return (dest); } /* End ink_string_concatenate_strings */ /*---------------------------------------------------------------------------* char *ink_string_concatenate_strings_n(char *dest, int n, ...) This routine concatenates a variable number of strings into the buffer <dest>, returning the pointer to <dest>. The sequence of strings must end with NULL. A NUL will always be placed after <dest>, and no more than <n> - 1 characters will ever be written to <dest>. *---------------------------------------------------------------------------*/ char * ink_string_concatenate_strings_n(char *dest, int n, ...) { va_list ap; register char *s, *d; va_start(ap, n); d = dest; while (n > 1) { s = va_arg(ap, char *); if (s == NULL) break; while (*s && (n > 1)) { *d++ = *s++; n--; } } if (n >= 1) *d = '\0'; va_end(ap); return (dest); } /* End ink_string_concatenate_strings_n */ /*---------------------------------------------------------------------------* char *ink_string_append(char *dest, char *src, int n) This routine appends <src> to the end of <dest>, but it insures the string pointed to by <dest> never grows beyond <n> characters, including the terminating NUL. A NUL is always written if n > 0. *---------------------------------------------------------------------------*/ char * ink_string_append(char *dest, char *src, int n) { char *d, *s, *last_valid_char; ink_assert(src != NULL); ink_assert(dest != NULL); ink_assert(n >= 0); if (n == 0) return (dest); last_valid_char = dest + n - 1; /* Scan For End Of Dest */ for (d = dest; (d <= last_valid_char) && (*d != '\0'); d++); /* If At End Of String, NUL Terminate & Exit */ if (d > last_valid_char) { dest[n - 1] = '\0'; return (dest); } /* Append src To String */ s = src; while ((d < last_valid_char) && (*s != '\0')) *d++ = *s++; /* If At End Of String, NUL Terminate & Exit */ if (d > last_valid_char) dest[n - 1] = '\0'; else *d = '\0'; return (dest); } /* End ink_string_append */ /*---------------------------------------------------------------------------* char *ink_string_duplicate(char *ptr) This routine allocates memory for the string <ptr>, and copies the string into the new buffer. The pointer to the new buffer is returned. *---------------------------------------------------------------------------*/ char * ink_string_duplicate(char *ptr) { char *n = NULL; if (likely(ptr)) { const size_t nSize = strlen(ptr) + 1; n = (char *) ink_malloc(nSize); ink_strncpy(n, ptr, nSize); } return (n); } /* End ink_string_duplicate */ /*---------------------------------------------------------------------------* char *ink_string_find_dotted_extension(char *str, char *ext, int max_ext_len) This routine takes a string <str>, copies the period-separated extension to <ext> (up to <max_ext_len - 1> characters) NUL terminates <ext>, and returns a pointer into the string <str> where the '.' of the extension begins, or NULL if there is no extension. *---------------------------------------------------------------------------*/ char * ink_string_find_dotted_extension(char *str, char *ext, int max_ext_len) { char *p = NULL; if (ext) { *ext = '\0'; if (str) { for (p = (str + strlen(str)) - 1; p >= str; p--) if (*p == '.') break; if (p <= str) return (NULL); ink_string_copy(ext, (p + 1), max_ext_len); } } return (p); } /* End ink_string_find_dotted_extension */ /*---------------------------------------------------------------------------* char *ink_string_mpath(int nstrings, char *str1, bool free1, char *str2, bool free2, ...); This routine joins multiple path components together to make a new path. Each component can optionally start with a / in which case all the preceeding components are ignored. Each component can optionally be free()d. Space is malloc()d to hold the resulting path. *---------------------------------------------------------------------------*/ char * ink_string_mpath(int nstrings, ...) { va_list ap; char *e[INK_MAX_STRING_ARRAY_SIZE]; bool f[INK_MAX_STRING_ARRAY_SIZE]; size_t s[INK_MAX_STRING_ARRAY_SIZE]; int slash = 0; size_t ts = 0; char *ns = NULL; char *p; int i; if (likely(nstrings < INK_MAX_STRING_ARRAY_SIZE)) { va_start(ap, nstrings); for (i = 0; i < nstrings; i++) { e[i] = va_arg(ap, char *); f[i] = va_arg(ap, int); } for (i = nstrings - 1; i >= 0; i--) { if (!e[i]) continue; s[i] = strlen(e[i]); ts += s[i] + 1; if (e[i][0] == '/') { slash = i; break; } } if ((slash == nstrings - 1) && f[slash]) { for (i = 0; i < nstrings - 1; i++) { if (f[i]) xfree(e[i]); } va_end(ap); return e[slash]; } else { const size_t nsSize = ts + 1; p = (ns = (char *) xmalloc(nsSize)); ink_assert(ns); for (i = slash; i < nstrings - 1; i++) { ink_strncpy(p, e[i], (nsSize - (p - ns))); p += s[i]; *p++ = '/'; } ink_strncpy(p, e[nstrings - 1], (nsSize - (p - ns))); } for (i = 0; i < nstrings; i++) { if (f[i]) xfree(e[i]); } va_end(ap); } return ns; } /*---------------------------------------------------------------------------* char *ink_string_mcopy(char *source); This simply makes a copy of a string into freshly malloc()ed space. *---------------------------------------------------------------------------*/ char * ink_string_mcopy(char *source) { char *n = NULL; if (likely(source)) { const size_t nSize = strlen(source) + 1; n = (char *) xmalloc(nSize); ink_strncpy(n, source, nSize); } return n; } /*---------------------------------------------------------------------------* char *ink_string_mjoin(int nstrings, char *str1, bool free1, char *str2, bool free2, ...); This routine joins multiple strings components together to make a new string. Each component can optionally be free()d. Space is malloc()d to hold the resulting path. *---------------------------------------------------------------------------*/ char * ink_string_mjoin(int nstrings, ...) { va_list ap; char *e[INK_MAX_STRING_ARRAY_SIZE]; bool f[INK_MAX_STRING_ARRAY_SIZE]; size_t s[INK_MAX_STRING_ARRAY_SIZE]; int slash = 0; size_t ts = 0; char *ns = NULL; char *p; int i; if (likely(nstrings < INK_MAX_STRING_ARRAY_SIZE)) { va_start(ap, nstrings); for (i = 0; i < nstrings; i++) { e[i] = va_arg(ap, char *); f[i] = va_arg(ap, int); if (e[i]) { s[i] = strlen(e[i]); ts += s[i]; } } const size_t nsSize = ts + 1; p = (ns = (char *) xmalloc(nsSize)); for (i = slash; i < nstrings - 1; i++) { ink_strncpy(p, e[i], (nsSize - (p - ns))); p += s[i]; } ink_strncpy(p, e[nstrings - 1], (nsSize - (p - ns))); for (i = 0; i < nstrings; i++) { if (f[i]) xfree(e[i]); } va_end(ap); } return ns; } char * ink_strtok_r(char *s1, const char *s2, char **lasts) { return strtok_r(s1, s2, lasts); } // XXX/lomew this might not be portable. If not check in configure // and always squash if no iconv available. #include <iconv.h> /* * This is a front-end to iconv(3). * * latin-1 is a subset of utf-8 so the output string len you pass * can be the same as the input string len. */ void ink_utf8_to_latin1(const char *in, int inlen, char *out, int *outlen) { size_t inbytesleft, outbytesleft; iconv_t ic; // XXX/lomew should have a configure test for the first arg ic = iconv_open("8859-1", "UTF-8"); // solaris if (ic == (iconv_t) - 1) { ic = iconv_open("iso-8859-1", "UTF-8"); // linux if (ic == (iconv_t) - 1) { goto strip; } } inbytesleft = inlen; outbytesleft = *outlen; if (iconv(ic, (char **) &in, &inbytesleft, &out, &outbytesleft) == (size_t) - 1) { iconv_close(ic); goto strip; } *outlen -= outbytesleft; iconv_close(ic); return; strip: /* Strip out chars with the high bit set. This only happens if iconv can't convert. */ inbytesleft = inlen; outbytesleft = *outlen; while (inbytesleft && outbytesleft) { if (!(*in & 0x80)) { *out++ = *in; outbytesleft--; } in++; inbytesleft--; } *outlen -= outbytesleft; }
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ // // Created by mmoiseev on 06/14/19. // #include <systemc.h> // Array of modular interface instances struct mod_if : public sc_module//, sc_interface { sc_in_clk clk{"clk"}; sc_in<bool> rst; sc_in<bool> a {"a"}; sc_out<bool> b {"b"}; sc_signal<bool> s {"s"}; sc_uint<2> var; SC_HAS_PROCESS(mod_if); /*explicit mod_if(const sc_module_name& name) : sc_module(name) { SC_METHOD(metProc); sensitive << a << s; //SC_CTHREAD(thrProc, clk.pos()); //async_reset_signal_is(rst, 1); }*/ mod_if() : sc_module(sc_module_name("mod_if_name")) { SC_METHOD(metProc); sensitive << a << s; //SC_CTHREAD(thrProc, clk.pos()); //async_reset_signal_is(rst, 1); } void metProc() { var = a.read(); b = s.read() && var; } void thrProc() { sc_uint<3> i = 0; wait(); while (1) { s = i++; wait(); } } bool func() { return s.read(); } }; SC_MODULE(top) { sc_in_clk clk{"clk"}; sc_in<bool> rst; sc_signal<bool> a[2]; // no name constructor leads to incorrect elabDB mod_if minst; //mod_if minst[2]; SC_CTOR(top) { // for (int i = 0; i < 2; i++) { // minst[i].rst(rst); // minst[i].clk(clk); // minst[i].a(a[i]); // minst[i].b(a[i]); // } minst.rst(rst); minst.clk(clk); minst.a(a[0]); minst.b(a[0]); //SC_METHOD(top_method); //sensitive << minst[0].s << minst[1].s; } void top_method() { // bool c = minst[0].s.read() || minst[1].func(); } }; SC_MODULE(tb) { sc_clock clk {"clk", sc_time(1, SC_NS)}; sc_signal<bool> rst {"rst"}; top top_inst{"top_inst"}; SC_CTOR(tb) { top_inst.clk(clk); top_inst.rst(rst); } }; int sc_main(int argc, char **argv) { cout << "test_modular_iface_proc\n"; tb tb_inst{"tb_inst"}; sc_start(); return 0; }
#include <mysql/mysql.h> #include <stdio.h> #include <string> #include <string.h> #include <stdlib.h> #include <list> #include <pthread.h> #include <iostream> #include "sqlConnectionPool.h" using namespace std; ConnectionPool::ConnectionPool() { m_CurConn = 0; m_FreeConn = 0; } ConnectionPool *ConnectionPool::GetInstance() { static ConnectionPool connPool; return &connPool; } //构造初始化 void ConnectionPool::init(string url, string User, string PassWord, string DBName, int Port, int MaxConn, int close_log ,int log_level) { m_url = url; m_Port = Port; m_User = User; m_PassWord = PassWord; m_DatabaseName = DBName; m_close_log = close_log; m_log_level = log_level; //创建连接池 for (int i = 0; i < MaxConn; i++) { MYSQL *con = NULL; con = mysql_init(con); if (con == NULL) { LOG_ERROR("MySQL Init Error"); exit(1); } con = mysql_real_connect(con, url.c_str(), User.c_str(), PassWord.c_str(), DBName.c_str(), Port, NULL, 0); if (con == NULL) { LOG_ERROR("MySQL Login Error"); exit(1); } connList.push_back(con); ++m_FreeConn; } //创造一个拥有m_FreeConn数量的信号量,用于互斥访问mysql连接 reserve = Sem(m_FreeConn); m_MaxConn = m_FreeConn; } //当有请求时,从数据库连接池中返回一个可用连接,更新使用和空闲连接数 MYSQL *ConnectionPool::GetConnection() { MYSQL *con = NULL; if (0 == connList.size()) return NULL; reserve.wait(); lock.lock(); con = connList.front(); connList.pop_front(); --m_FreeConn; ++m_CurConn; lock.unlock(); return con; } //释放当前使用的连接 bool ConnectionPool::ReleaseConnection(MYSQL *con) { if (NULL == con) return false; lock.lock(); connList.push_back(con); ++m_FreeConn; --m_CurConn; lock.unlock(); reserve.post(); return true; } //销毁数据库连接池 void ConnectionPool::DestroyPool() { lock.lock(); if (connList.size() > 0) { list<MYSQL *>::iterator it; for (it = connList.begin(); it != connList.end(); ++it) { MYSQL *con = *it; mysql_close(con); } m_CurConn = 0; m_FreeConn = 0; connList.clear(); } lock.unlock(); } //当前空闲的连接数 int ConnectionPool::GetFreeConn() { return this->m_FreeConn; } ConnectionPool::~ConnectionPool() { DestroyPool(); } ConnectionRAII::ConnectionRAII(MYSQL **SQL, ConnectionPool *connPool) { *SQL = connPool->GetConnection(); conRAII = *SQL; poolRAII = connPool; } ConnectionRAII::~ConnectionRAII() { poolRAII->ReleaseConnection(conRAII); }
#pragma once #include "../../../JObject.hpp" class JArray; namespace android::service::autofill { class Validators : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit Validators(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} Validators(QJniObject obj); // Constructors // Methods static JObject and_(JArray arg0); static JObject not_(JObject arg0); static JObject or_(JArray arg0); }; } // namespace android::service::autofill
// // Created by 陈广祥 on 2019-09-19. // #include <sstream> #include "TxtPlugin.h" #include "PlainTextFormat.h" #include "TxtReader.h" #include "TxtChapterDetector.h" static const std::string TAG = "TxtPlugin"; TxtPlugin::TxtPlugin() : mTxtReaderPtr(nullptr) { } TxtPlugin::~TxtPlugin() { if (mTxtReaderPtr != nullptr) { delete mTxtReaderPtr; mTxtReaderPtr = nullptr; } } bool TxtPlugin::readEncodingInternal(std::string &outEncoding) { return detectEncoding(outEncoding); } bool TxtPlugin::readLanguageInternal(std::string &outLanguage) { return detectLanguage(outLanguage); } bool TxtPlugin::readChaptersInternal(std::string &chapterPattern, std::vector<TextChapter> &chapterList) { std::string encoding; bool result = readEncoding(encoding); // 如果文件地址为空,或者地址是目录 if (mFilePtr == nullptr || mFilePtr->isDirectory()) { return false; } if (result) { // 创建章节探测器,进行章节探测。 TxtChapterDetector(chapterPattern).detector(*mFilePtr, encoding, chapterList); } return result; } bool TxtPlugin::readChapterContentInternal(TextChapter &inChapter, TextContent &outContent) { // TODO:对于文本独有的数据信息,如何进行缓存?就是解析 format 的情况,看下效率吧,如果效率特别高,不缓存也没问题(暂时不考虑) File chapterFile(inChapter.url); // 如果参数信息未初始化 if (!mFormat.hasInitialized()) { // 调用探测器进行探测 PlainTextDetector detector; detector.detect(chapterFile, mFormat); } // 如果无法探测到信息,直接 return if (!mFormat.hasInitialized()) { return false; } std::string bookEncoding; readEncoding(bookEncoding); // 创建文本阅读器 if (mTxtReaderPtr == nullptr) { mTxtReaderPtr = new TxtReader(mFormat, bookEncoding); } // 读取内容 return mTxtReaderPtr->readContent(inChapter, outContent); }
#include <iostream> #include <queue> #include <cstring> #define nullptr 0 using namespace std; struct edge { int to, val, next; }e[40010]; int head[1010], tot = 0; void add_edge(int from, int to, int val) { e[++tot].to = to; e[tot].val = val; e[tot].next = head[from]; head[from] = tot; } bool in_que[1010]; int dist[1010]; int cnt[1010]; bool spfa(int type, int n) //1 for negative circle, 2 for dist { queue<int> q; memset(cnt, 0, sizeof(cnt)); memset(in_que, false, sizeof(in_que)); memset(dist, 0x3f, sizeof(dist)); if (type == 1) { for (int i = 1; i <= n; i++) { q.push(i); in_que[i] = true; dist[i] = 0; } } else { q.push(1); in_que[1] = true; dist[1] = 0; } while (!q.empty()) { int u = q.front(); q.pop(); in_que[u] = false; for (int i = head[u]; i; i = e[i].next) { int j = e[i].to; if (dist[j] > dist[u] + e[i].val) { dist[j] = dist[u] + e[i].val; cnt[j] = cnt[u] + 1; if (cnt[j] >= n) return false; if (!in_que[j]) { q.push(j); in_que[j] = true; } } } } if (dist[n] > 0x3f3f3f3f / 2) return false; else return true; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); int n, ml, md; cin >> n >> ml >> md; for (int i = 2; i <= n; i++) add_edge(i, i - 1, 0); for (int i = 1; i <= ml; i++) { int a, b, v; cin >> a >> b >> v; add_edge(a, b, v); } for (int i = 1; i <= md; i++) { int a, b, v; cin >> a >> b >> v; add_edge(b, a, -v); } if (!spfa(1, n)) cout << -1 << '\n'; else { if (!spfa(2, n)) cout << -2 << '\n'; else cout << dist[n] << '\n'; } return 0; }
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/merkle.h" #include "merkleblock.h" #include "serialize.h" #include "streams.h" #include "uint256.h" #include "arith_uint256.h" #include "version.h" #include "test/test_coinvest.h" #include "test/test_random.h" #include <vector> #include <boost/assign/list_of.hpp> #include <boost/test/unit_test.hpp> class CPartialMerkleTreeTester : public CPartialMerkleTree { public: // flip one bit in one of the hashes - this should break the authentication void Damage() { unsigned int n = insecure_rand() % vHash.size(); int bit = insecure_rand() % 256; *(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7); } }; BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(pmt_test1) { seed_insecure_rand(false); static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095}; for (int i = 0; i < 12; i++) { unsigned int nTx = nTxCounts[i]; // build a block with some dummy transactions CBlock block; for (unsigned int j=0; j<nTx; j++) { CMutableTransaction tx; tx.nLockTime = j; // actual transaction data doesn't matter; just make the nLockTime's unique block.vtx.push_back(MakeTransactionRef(std::move(tx))); } // calculate actual merkle root and height uint256 merkleRoot1 = BlockMerkleRoot(block); std::vector<uint256> vTxid(nTx, uint256()); for (unsigned int j=0; j<nTx; j++) vTxid[j] = block.vtx[j]->GetHash(); int nHeight = 1, nTx_ = nTx; while (nTx_ > 1) { nTx_ = (nTx_+1)/2; nHeight++; } // check with random subsets with inclusion chances 1, 1/2, 1/4, ..., 1/128 for (int att = 1; att < 15; att++) { // build random subset of txid's std::vector<bool> vMatch(nTx, false); std::vector<uint256> vMatchTxid1; for (unsigned int j=0; j<nTx; j++) { bool fInclude = (insecure_rand() & ((1 << (att/2)) - 1)) == 0; vMatch[j] = fInclude; if (fInclude) vMatchTxid1.push_back(vTxid[j]); } // build the partial merkle tree CPartialMerkleTree pmt1(vTxid, vMatch); // serialize CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pmt1; // verify CPartialMerkleTree's size guarantees unsigned int n = std::min<unsigned int>(nTx, 1 + vMatchTxid1.size()*nHeight); BOOST_CHECK(ss.size() <= 10 + (258*n+7)/8); // deserialize into a tester copy CPartialMerkleTreeTester pmt2; ss >> pmt2; // extract merkle root and matched txids from copy std::vector<uint256> vMatchTxid2; std::vector<unsigned int> vIndex; uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex); // check that it has the same merkle root as the original, and a valid one BOOST_CHECK(merkleRoot1 == merkleRoot2); BOOST_CHECK(!merkleRoot2.IsNull()); // check that it contains the matched transactions (in the same order!) BOOST_CHECK(vMatchTxid1 == vMatchTxid2); // check that random bit flips break the authentication for (int j=0; j<4; j++) { CPartialMerkleTreeTester pmt3(pmt2); pmt3.Damage(); std::vector<uint256> vMatchTxid3; uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex); BOOST_CHECK(merkleRoot3 != merkleRoot1); } } } } BOOST_AUTO_TEST_CASE(pmt_malleability) { std::vector<uint256> vTxid = boost::assign::list_of (ArithToUint256(1))(ArithToUint256(2)) (ArithToUint256(3))(ArithToUint256(4)) (ArithToUint256(5))(ArithToUint256(6)) (ArithToUint256(7))(ArithToUint256(8)) (ArithToUint256(9))(ArithToUint256(10)) (ArithToUint256(9))(ArithToUint256(10)); std::vector<bool> vMatch = boost::assign::list_of(false)(false)(false)(false)(false)(false)(false)(false)(false)(true)(true)(false); CPartialMerkleTree tree(vTxid, vMatch); std::vector<unsigned int> vIndex; BOOST_CHECK(tree.ExtractMatches(vTxid, vIndex).IsNull()); } BOOST_AUTO_TEST_SUITE_END()
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkNrrdImageIO.h" #include "NrrdIO.h" #include "itkMetaDataObject.h" #include "itkIOCommon.h" #include "itkFloatingPointExceptions.h" namespace itk { #define KEY_PREFIX "NRRD_" NrrdImageIO::NrrdImageIO() { this->SetNumberOfDimensions(3); this->AddSupportedWriteExtension(".nrrd"); this->AddSupportedReadExtension(".nrrd"); this->AddSupportedWriteExtension(".nhdr"); this->AddSupportedReadExtension(".nhdr"); } NrrdImageIO::~NrrdImageIO() { } bool NrrdImageIO::SupportsDimension(unsigned long dim) { if ( 1 == this->GetNumberOfComponents() ) { return dim <= NRRD_DIM_MAX; } else { return dim <= NRRD_DIM_MAX - 1; } } void NrrdImageIO::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } ImageIOBase::IOComponentType NrrdImageIO::NrrdToITKComponentType(const int nrrdComponentType) const { switch ( nrrdComponentType ) { case nrrdTypeUnknown: case nrrdTypeBlock: return UNKNOWNCOMPONENTTYPE; break; case nrrdTypeChar: return CHAR; break; case nrrdTypeUChar: return UCHAR; break; case nrrdTypeShort: return SHORT; break; case nrrdTypeUShort: return USHORT; break; // "long" is a silly type because it basically guaranteed not to be // cross-platform across 32-vs-64 bit machines, but we'll use it // where possible. case nrrdTypeLLong: return (4 == sizeof(long) ) ? UNKNOWNCOMPONENTTYPE : LONG; break; case nrrdTypeULLong: return (4 == sizeof(long) ) ? UNKNOWNCOMPONENTTYPE : ULONG; break; case nrrdTypeInt: return INT; break; case nrrdTypeUInt: return UINT; break; case nrrdTypeFloat: return FLOAT; break; case nrrdTypeDouble: return DOUBLE; break; default: break; } // Strictly to avoid compiler warning regarding "control may reach end of // non-void function": return UNKNOWNCOMPONENTTYPE; } int NrrdImageIO::ITKToNrrdComponentType(const ImageIOBase::IOComponentType itkComponentType) const { switch ( itkComponentType ) { case UNKNOWNCOMPONENTTYPE: return nrrdTypeUnknown; break; case CHAR: return nrrdTypeChar; break; case UCHAR: return nrrdTypeUChar; break; case SHORT: return nrrdTypeShort; break; case USHORT: return nrrdTypeUShort; break; // "long" is a silly type because it basically guaranteed not to be // cross-platform across 32-vs-64 bit machines, but we can figure out // a cross-platform way of storing the information. case LONG: return (4 == sizeof(long) ) ? nrrdTypeInt : nrrdTypeLLong; break; case ULONG: return (4 == sizeof(long) ) ? nrrdTypeUInt : nrrdTypeULLong; break; case INT: return nrrdTypeInt; break; case UINT: return nrrdTypeUInt; break; case FLOAT: return nrrdTypeFloat; break; case DOUBLE: return nrrdTypeDouble; break; default: break; } // Strictly to avoid compiler warning regarding "control may reach end of // non-void function": return nrrdTypeUnknown; } bool NrrdImageIO::CanReadFile(const char *filename) { // Check the extension first to avoid opening files that do not // look like nrrds. The file must have an appropriate extension to be // recognized. std::string fname = filename; if ( fname == "" ) { itkDebugMacro(<< "No filename specified."); return false; } bool extensionFound = false; std::string::size_type nrrdPos = fname.rfind(".nrrd"); if ( ( nrrdPos != std::string::npos ) && ( nrrdPos == fname.length() - 5 ) ) { extensionFound = true; } std::string::size_type nhdrPos = fname.rfind(".nhdr"); if ( ( nhdrPos != std::string::npos ) && ( nhdrPos == fname.length() - 5 ) ) { extensionFound = true; } if ( !extensionFound ) { itkDebugMacro(<< "The filename extension is not recognized"); return false; } // We have the correct extension, so now check for the Nrrd magic "NRRD", // while ignoring the format version (the next four characters) std::ifstream inputStream; inputStream.open(filename, std::ios::in | std::ios::binary); if ( inputStream.fail() ) { return false; } char magic[5] = { '\0', '\0', '\0', '\0', '\0' }; inputStream.read( magic, 4 * sizeof( char ) ); if ( inputStream.eof() ) { inputStream.close(); return false; } if ( strcmp(magic, "NRRD") == 0 ) { inputStream.close(); return true; } inputStream.close(); return false; } void NrrdImageIO::ReadImageInformation() { // This method determines the following and sets the appropriate value in // the parent IO class: // // binary/ascii file type // endianness // pixel type // pixel component type // number of pixel components // number of image dimensions // image spacing // image origin // meta data dictionary information Nrrd * nrrd = nrrdNew(); NrrdIoState *nio = nrrdIoStateNew(); try { // nrrd causes exceptions on purpose, so mask them bool saveFPEState(FloatingPointExceptions::GetExceptionAction() ); FloatingPointExceptions::Disable(); // this is the mechanism by which we tell nrrdLoad to read // just the header, and none of the data nrrdIoStateSet(nio, nrrdIoStateSkipData, 1); if ( nrrdLoad(nrrd, this->GetFileName(), nio) != 0 ) { char *err = biffGetDone(NRRD); // don't use macro so that we can free err std::ostringstream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "ReadImageInformation: Error reading " << this->GetFileName() << ":\n" << err; ExceptionObject e_(__FILE__, __LINE__, message.str().c_str(), ITK_LOCATION); free( err ); throw e_; } // restore state FloatingPointExceptions::SetEnabled(saveFPEState); if ( nrrdTypeBlock == nrrd->type ) { itkExceptionMacro("ReadImageInformation: Cannot currently " "handle nrrdTypeBlock"); } if ( nio->endian == airEndianLittle ) { this->SetByteOrderToLittleEndian(); } else if ( nio->endian == airEndianBig ) { this->SetByteOrderToBigEndian(); } else { this->SetByteOrder(ImageIOBase::OrderNotApplicable); } if ( nio->encoding == nrrdEncodingAscii ) { this->SetFileTypeToASCII(); } else { this->SetFileTypeToBinary(); } // set type of pixel components; this is orthogonal to pixel type ImageIOBase::IOComponentType cmpType = this->NrrdToITKComponentType(nrrd->type); if ( UNKNOWNCOMPONENTTYPE == cmpType ) { itkExceptionMacro("Nrrd type " << airEnumStr(nrrdType, nrrd->type) << " could not be mapped to an ITK component type"); } this->SetComponentType(cmpType); // Set the number of image dimensions and bail if needed unsigned int domainAxisNum, domainAxisIdx[NRRD_DIM_MAX], rangeAxisNum, rangeAxisIdx[NRRD_DIM_MAX]; domainAxisNum = nrrdDomainAxesGet(nrrd, domainAxisIdx); rangeAxisNum = nrrdRangeAxesGet(nrrd, rangeAxisIdx); if ( nrrd->spaceDim && nrrd->spaceDim != domainAxisNum ) { itkExceptionMacro("ReadImageInformation: nrrd's #independent axes (" << domainAxisNum << ") doesn't match dimension of space" " in which orientation is defined (" << nrrd->spaceDim << "); not currently handled"); } // else nrrd->spaceDim == domainAxisNum when nrrd has orientation if ( 0 == rangeAxisNum ) { // we don't have any non-scalar data this->SetNumberOfDimensions(nrrd->dim); this->SetPixelType(ImageIOBase::SCALAR); this->SetNumberOfComponents(1); } else if ( 1 == rangeAxisNum ) { this->SetNumberOfDimensions(nrrd->dim - 1); unsigned int kind = nrrd->axis[rangeAxisIdx[0]].kind; unsigned int size = nrrd->axis[rangeAxisIdx[0]].size; // NOTE: it is the NRRD readers responsibility to make sure that // the size (#of components) associated with a specific kind is // matches the actual size of the axis. switch ( kind ) { case nrrdKindDomain: case nrrdKindSpace: case nrrdKindTime: itkExceptionMacro("ReadImageInformation: range axis kind (" << airEnumStr(nrrdKind, kind) << ") seems more " "like a domain axis than a range axis"); break; case nrrdKindStub: case nrrdKindScalar: this->SetPixelType(ImageIOBase::SCALAR); this->SetNumberOfComponents(size); break; case nrrdKind3Color: case nrrdKindRGBColor: this->SetPixelType(ImageIOBase::RGB); this->SetNumberOfComponents(size); break; case nrrdKind4Color: case nrrdKindRGBAColor: this->SetPixelType(ImageIOBase::RGBA); this->SetNumberOfComponents(size); break; case nrrdKindVector: case nrrdKind2Vector: case nrrdKind3Vector: case nrrdKind4Vector: case nrrdKindList: this->SetPixelType(ImageIOBase::VECTOR); this->SetNumberOfComponents(size); break; case nrrdKindPoint: this->SetPixelType(ImageIOBase::POINT); this->SetNumberOfComponents(size); break; case nrrdKindCovariantVector: case nrrdKind3Gradient: case nrrdKindNormal: case nrrdKind3Normal: this->SetPixelType(ImageIOBase::COVARIANTVECTOR); this->SetNumberOfComponents(size); break; case nrrdKind3DSymMatrix: // ImageIOBase::DIFFUSIONTENSOR3D is a subclass this->SetPixelType(ImageIOBase::SYMMETRICSECONDRANKTENSOR); this->SetNumberOfComponents(size); break; case nrrdKind3DMaskedSymMatrix: this->SetPixelType(ImageIOBase::SYMMETRICSECONDRANKTENSOR); // NOTE: we will crop out the mask in Read() below; this is the // one case where NumberOfComponents != size this->SetNumberOfComponents(size - 1); break; case nrrdKindComplex: this->SetPixelType(ImageIOBase::COMPLEX); this->SetNumberOfComponents(size); break; case nrrdKindHSVColor: case nrrdKindXYZColor: case nrrdKindQuaternion: case nrrdKind2DSymMatrix: case nrrdKind2DMaskedSymMatrix: case nrrdKind2DMatrix: case nrrdKind2DMaskedMatrix: case nrrdKind3DMatrix: // for all other Nrrd kinds, we punt and call it a vector this->SetPixelType(ImageIOBase::VECTOR); this->SetNumberOfComponents(size); break; default: itkExceptionMacro("ReadImageInformation: nrrdKind " << kind << " not known!"); break; } } else { itkExceptionMacro("ReadImageInformation: nrrd has " << rangeAxisNum << " dependent axis (not 1); not currently handled"); } double spacing; double spaceDir[NRRD_SPACE_DIM_MAX]; std::vector< double > spaceDirStd(domainAxisNum); int spacingStatus; int iFlipFactors[3]; // used to flip the measurement frame later on for ( unsigned int iI = 0; iI < 3; iI++ ) { iFlipFactors[iI] = 1; } for ( unsigned int axii = 0; axii < domainAxisNum; axii++ ) { unsigned int naxi = domainAxisIdx[axii]; this->SetDimensions(axii, nrrd->axis[naxi].size); spacingStatus = nrrdSpacingCalculate(nrrd, naxi, &spacing, spaceDir); switch ( spacingStatus ) { case nrrdSpacingStatusNone: // Let ITK's defaults stay // this->SetSpacing(axii, 1.0); break; case nrrdSpacingStatusScalarNoSpace: this->SetSpacing(axii, spacing); break; case nrrdSpacingStatusDirection: if ( AIR_EXISTS(spacing) ) { // only set info if we have something to set switch ( nrrd->space ) { // on read, convert non-LPS coords into LPS coords, when we can case nrrdSpaceRightAnteriorSuperior: spaceDir[0] *= -1; // R -> L spaceDir[1] *= -1; // A -> P iFlipFactors[0] = -1; iFlipFactors[1] = -1; break; case nrrdSpaceLeftAnteriorSuperior: spaceDir[0] *= -1; // R -> L iFlipFactors[0] = -1; break; case nrrdSpaceLeftPosteriorSuperior: // no change needed break; default: // we're not coming from a space for which the conversion // to LPS is well-defined break; } this->SetSpacing(axii, spacing); for ( unsigned int saxi = 0; saxi < nrrd->spaceDim; saxi++ ) { spaceDirStd[saxi] = spaceDir[saxi]; } this->SetDirection(axii, spaceDirStd); } break; default: case nrrdSpacingStatusUnknown: itkExceptionMacro("ReadImageInformation: Error interpreting " "nrrd spacing (nrrdSpacingStatusUnknown)"); break; case nrrdSpacingStatusScalarWithSpace: itkExceptionMacro("ReadImageInformation: Error interpreting " "nrrd spacing (nrrdSpacingStatusScalarWithSpace)"); break; } } // Figure out origin if ( nrrd->spaceDim ) { if ( AIR_EXISTS(nrrd->spaceOrigin[0]) ) { // only set info if we have something to set double spaceOrigin[NRRD_SPACE_DIM_MAX]; for ( unsigned int saxi = 0; saxi < nrrd->spaceDim; saxi++ ) { spaceOrigin[saxi] = nrrd->spaceOrigin[saxi]; } switch ( nrrd->space ) { // convert non-LPS coords into LPS coords, when we can case nrrdSpaceRightAnteriorSuperior: spaceOrigin[0] *= -1; // R -> L spaceOrigin[1] *= -1; // A -> P break; case nrrdSpaceLeftAnteriorSuperior: spaceOrigin[0] *= -1; // R -> L break; case nrrdSpaceLeftPosteriorSuperior: // no change needed break; default: // we're not coming from a space for which the conversion // to LPS is well-defined break; } for ( unsigned int saxi = 0; saxi < nrrd->spaceDim; saxi++ ) { this->SetOrigin(saxi, spaceOrigin[saxi]); } } } else { double spaceOrigin[NRRD_DIM_MAX]; int originStatus = nrrdOriginCalculate(nrrd, domainAxisIdx, domainAxisNum, nrrdCenterCell, spaceOrigin); for ( unsigned int saxi = 0; saxi < domainAxisNum; saxi++ ) { switch ( originStatus ) { case nrrdOriginStatusNoMin: case nrrdOriginStatusNoMaxOrSpacing: // only set info if we have something to set // this->SetOrigin(saxi, 0.0); break; case nrrdOriginStatusOkay: this->SetOrigin(saxi, spaceOrigin[saxi]); break; default: case nrrdOriginStatusUnknown: case nrrdOriginStatusDirection: itkExceptionMacro("ReadImageInformation: Error interpreting " "nrrd origin status"); break; } } } // Store key/value pairs in MetaDataDictionary char key[AIR_STRLEN_SMALL]; const char * val; char * keyPtr = NULL; char * valPtr = NULL; MetaDataDictionary & thisDic = this->GetMetaDataDictionary(); // Necessary to clear dict if ImageIO object is re-used thisDic.Clear(); std::string classname( this->GetNameOfClass() ); EncapsulateMetaData< std::string >(thisDic, ITK_InputFilterName, classname); for ( unsigned int kvpi = 0; kvpi < nrrdKeyValueSize(nrrd); kvpi++ ) { nrrdKeyValueIndex(nrrd, &keyPtr, &valPtr, kvpi); EncapsulateMetaData< std::string >( thisDic, std::string(keyPtr), std::string(valPtr) ); keyPtr = (char *)airFree(keyPtr); valPtr = (char *)airFree(valPtr); } // save in MetaDataDictionary those important nrrd fields that // (currently) have no ITK equivalent. NOTE that for the per-axis // information, we use the same axis index (axii) as in ITK, NOT // the original axis index in nrrd (axi). This is because in the // Read() method, non-scalar data is permuted to the fastest axis, // on the on the Write() side, its always written to the fastest axis, // so we might was well go with consistent and idiomatic indexing. NrrdAxisInfo *naxis; for ( unsigned int axii = 0; axii < domainAxisNum; axii++ ) { unsigned int axi = domainAxisIdx[axii]; naxis = nrrd->axis + axi; if ( AIR_EXISTS(naxis->thickness) ) { sprintf(key, "%s%s[%u]", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_thicknesses), axii); EncapsulateMetaData< double >(thisDic, std::string(key), naxis->thickness); } if ( naxis->center ) { sprintf(key, "%s%s[%u]", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_centers), axii); val = airEnumStr(nrrdCenter, naxis->center); EncapsulateMetaData< std::string >( thisDic, std::string(key), std::string(val) ); } if ( naxis->kind ) { sprintf(key, "%s%s[%u]", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_kinds), axii); val = airEnumStr(nrrdKind, naxis->kind); EncapsulateMetaData< std::string >( thisDic, std::string(key), std::string(val) ); } if ( airStrlen(naxis->label) ) { sprintf(key, "%s%s[%u]", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_labels), axii); EncapsulateMetaData< std::string >( thisDic, std::string(key), std::string(naxis->label) ); } } if ( airStrlen(nrrd->content) ) { sprintf( key, "%s%s", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_content) ); EncapsulateMetaData< std::string >( thisDic, std::string(key), std::string(nrrd->content) ); } if ( AIR_EXISTS(nrrd->oldMin) ) { sprintf( key, "%s%s", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_old_min) ); EncapsulateMetaData< double >(thisDic, std::string(key), nrrd->oldMin); } if ( AIR_EXISTS(nrrd->oldMax) ) { sprintf( key, "%s%s", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_old_max) ); EncapsulateMetaData< double >(thisDic, std::string(key), nrrd->oldMax); } if ( nrrd->space ) { sprintf( key, "%s%s", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_space) ); val = airEnumStr(nrrdSpace, nrrd->space); // keep everything consistent: so enter it as LPS in the meta data // dictionary in case it could get converted, otherwise leave it // as is switch ( nrrd->space ) { case nrrdSpaceRightAnteriorSuperior: case nrrdSpaceLeftAnteriorSuperior: case nrrdSpaceLeftPosteriorSuperior: // in all these cases we could convert EncapsulateMetaData< std::string >( thisDic, std::string(key), std::string( airEnumStr(nrrdSpace, nrrdSpaceLeftPosteriorSuperior) ) ); break; default: // we're not coming from a space for which the conversion // to LPS is well-defined EncapsulateMetaData< std::string >( thisDic, std::string(key), std::string(val) ); break; } } if ( AIR_EXISTS(nrrd->measurementFrame[0][0]) ) { sprintf( key, "%s%s", KEY_PREFIX, airEnumStr(nrrdField, nrrdField_measurement_frame) ); std::vector< std::vector< double > > msrFrame(domainAxisNum); // flip the measurement frame here if we have to // so that everything is consistent with the ITK LPS space directions // but only do this if we have a three dimensional space or smaller for ( unsigned int saxi = 0; saxi < domainAxisNum; saxi++ ) { msrFrame[saxi].resize(domainAxisNum); for ( unsigned int saxj = 0; saxj < domainAxisNum; saxj++ ) { if ( domainAxisNum <= 3 ) { msrFrame[saxi][saxj] = iFlipFactors[saxj] * nrrd->measurementFrame[saxi][saxj]; } else { msrFrame[saxi][saxj] = nrrd->measurementFrame[saxi][saxj]; } } } EncapsulateMetaData< std::vector< std::vector< double > > >(thisDic, std::string(key), msrFrame); } nrrd = nrrdNix(nrrd); nio = nrrdIoStateNix(nio); } catch (...) { // clean up from an exception nrrd = nrrdNix(nrrd); nio = nrrdIoStateNix(nio); // rethrow exception throw; } } void NrrdImageIO::Read(void *buffer) { Nrrd * nrrd = nrrdNew(); bool nrrdAllocated; // NOTE the main reason the logic becomes complicated here is that // ITK has to be the one to allocate the data segment ("buffer") if ( ImageIOBase::SYMMETRICSECONDRANKTENSOR == this->GetPixelType() ) { // It may be that this is coming from a nrrdKind3DMaskedSymMatrix, // in which case ITK's buffer has not been allocated for the // actual size of the data. The data will be allocated by nrrdLoad. nrrdAllocated = true; } else { // The data buffer has already been allocated for the correct size. // Hand the buffer off to the nrrd, setting just enough info so that // the nrrd knows the allocated data size (the axes may actually be out // of order in the case of non-scalar data. Internal to nrrdLoad(), the // given buffer will be re-used, instead of allocating new data. unsigned int baseDim; nrrdAllocated = false; nrrd->data = buffer; nrrd->type = this->ITKToNrrdComponentType(this->m_ComponentType); if ( ImageIOBase::SCALAR == this->m_PixelType ) { baseDim = 0; } else { baseDim = 1; nrrd->axis[0].size = this->GetNumberOfComponents(); } nrrd->dim = baseDim + this->GetNumberOfDimensions(); for ( unsigned int axi = 0; axi < this->GetNumberOfDimensions(); axi++ ) { nrrd->axis[axi + baseDim].size = this->GetDimensions(axi); } } // nrrd causes exceptions on purpose, so mask them bool saveFPEState(FloatingPointExceptions::GetExceptionAction() ); FloatingPointExceptions::Disable(); // Read in the nrrd. Yes, this means that the header is being read // twice: once by NrrdImageIO::ReadImageInformation, and once here if ( nrrdLoad(nrrd, this->GetFileName(), NULL) != 0 ) { char *err = biffGetDone(NRRD); // would be nice to free(err) itkExceptionMacro("Read: Error reading " << this->GetFileName() << ":\n" << err); } // restore state FloatingPointExceptions::SetEnabled(saveFPEState); unsigned int rangeAxisNum, rangeAxisIdx[NRRD_DIM_MAX]; rangeAxisNum = nrrdRangeAxesGet(nrrd, rangeAxisIdx); if ( rangeAxisNum > 1 ) { itkExceptionMacro("Read: handling more than one non-scalar axis " "not currently handled"); } if ( 1 == rangeAxisNum && 0 != rangeAxisIdx[0] ) { // the range (dependent variable) is not on the fastest axis, // so we have to permute axes to put it there, since that is // how we set things up in ReadImageInformation() above Nrrd * ntmp = nrrdNew(); unsigned int axmap[NRRD_DIM_MAX]; axmap[0] = rangeAxisIdx[0]; for ( unsigned int axi = 1; axi < nrrd->dim; axi++ ) { axmap[axi] = axi - ( axi <= rangeAxisIdx[0] ); } // The memory size of the input and output of nrrdAxesPermute is // the same; the existing nrrd->data is re-used. if ( nrrdCopy(ntmp, nrrd) || nrrdAxesPermute(nrrd, ntmp, axmap) ) { char *err = biffGetDone(NRRD); // would be nice to free(err) itkExceptionMacro("Read: Error permuting independent axis in " << this->GetFileName() << ":\n" << err); } nrrdNuke(ntmp); } if ( nrrdAllocated ) { // Now we have to get the data back into the given ITK buffer // In any case, the logic here has the luxury of assuming that the // *single* non-scalar axis is the *first* (fastest) axis. if ( nrrdKind3DMaskedSymMatrix == nrrd->axis[0].kind && ImageIOBase::SYMMETRICSECONDRANKTENSOR == this->GetPixelType() ) { // we crop out the mask and put the output in ITK-allocated "buffer" size_t size[NRRD_DIM_MAX], minIdx[NRRD_DIM_MAX], maxIdx[NRRD_DIM_MAX]; for ( unsigned int axi = 0; axi < nrrd->dim; axi++ ) { minIdx[axi] = ( 0 == axi ) ? 1 : 0; maxIdx[axi] = nrrd->axis[axi].size - 1; size[axi] = maxIdx[axi] - minIdx[axi] + 1; } Nrrd *ntmp = nrrdNew(); if ( nrrdCopy(ntmp, nrrd) || ( nrrdEmpty(nrrd), nrrdWrap_nva(nrrd, buffer, ntmp->type, ntmp->dim, size) ) || nrrdCrop(nrrd, ntmp, minIdx, maxIdx) ) { char *err = biffGetDone(NRRD); // would be nice to free(err) itkExceptionMacro("Read: Error copying, crapping or cropping:\n" << err); } nrrdNuke(ntmp); nrrdNix(nrrd); } else { // false alarm; we didn't need to allocate the data ourselves memcpy( buffer, nrrd->data, nrrdElementSize(nrrd) * nrrdElementNumber(nrrd) ); nrrdNuke(nrrd); } } else // { // "buffer" == nrrd->data was ITK-allocated; lose the nrrd struct nrrdNix(nrrd); } } bool NrrdImageIO::CanWriteFile(const char *name) { std::string filename = name; if ( filename == "" ) { return false; } std::string::size_type nrrdPos = filename.rfind(".nrrd"); if ( ( nrrdPos != std::string::npos ) && ( nrrdPos == filename.length() - 5 ) ) { return true; } std::string::size_type nhdrPos = filename.rfind(".nhdr"); if ( ( nhdrPos != std::string::npos ) && ( nhdrPos == filename.length() - 5 ) ) { return true; } return false; } void NrrdImageIO::WriteImageInformation(void) { // Nothing needs doing here. } void NrrdImageIO::Write(const void *buffer) { Nrrd * nrrd = nrrdNew(); NrrdIoState *nio = nrrdIoStateNew(); int kind[NRRD_DIM_MAX]; size_t size[NRRD_DIM_MAX]; unsigned int nrrdDim, baseDim, spaceDim; double spaceDir[NRRD_DIM_MAX][NRRD_SPACE_DIM_MAX]; double origin[NRRD_DIM_MAX]; spaceDim = this->GetNumberOfDimensions(); if ( this->GetNumberOfComponents() > 1 ) { size[0] = this->GetNumberOfComponents(); switch ( this->GetPixelType() ) { case ImageIOBase::RGB: kind[0] = nrrdKindRGBColor; break; case ImageIOBase::RGBA: kind[0] = nrrdKindRGBAColor; break; case ImageIOBase::POINT: kind[0] = nrrdKindPoint; break; case ImageIOBase::COVARIANTVECTOR: kind[0] = nrrdKindCovariantVector; break; case ImageIOBase::SYMMETRICSECONDRANKTENSOR: case ImageIOBase::DIFFUSIONTENSOR3D: kind[0] = nrrdKind3DSymMatrix; break; case ImageIOBase::COMPLEX: kind[0] = nrrdKindComplex; break; case ImageIOBase::VECTOR: case ImageIOBase::OFFSET: // HEY is this right? case ImageIOBase::FIXEDARRAY: // HEY is this right? default: kind[0] = nrrdKindVector; break; } // the range axis has no space direction for ( unsigned int saxi = 0; saxi < spaceDim; saxi++ ) { spaceDir[0][saxi] = AIR_NAN; } baseDim = 1; } else { baseDim = 0; } nrrdDim = baseDim + spaceDim; std::vector< double > spaceDirStd(spaceDim); unsigned int axi; for ( axi = 0; axi < spaceDim; axi++ ) { size[axi + baseDim] = this->GetDimensions(axi); kind[axi + baseDim] = nrrdKindDomain; origin[axi] = this->GetOrigin(axi); double spacing = this->GetSpacing(axi); spaceDirStd = this->GetDirection(axi); for ( unsigned int saxi = 0; saxi < spaceDim; saxi++ ) { spaceDir[axi + baseDim][saxi] = spacing * spaceDirStd[saxi]; } } if ( nrrdWrap_nva(nrrd, const_cast< void * >( buffer ), this->ITKToNrrdComponentType(m_ComponentType), nrrdDim, size) || ( 3 == spaceDim // special case: ITK is LPS in 3-D ? nrrdSpaceSet(nrrd, nrrdSpaceLeftPosteriorSuperior) : nrrdSpaceDimensionSet(nrrd, spaceDim) ) || nrrdSpaceOriginSet(nrrd, origin) ) { char *err = biffGetDone(NRRD); // would be nice to free(err) itkExceptionMacro("Write: Error wrapping nrrd for " << this->GetFileName() << ":\n" << err); } nrrdAxisInfoSet_nva(nrrd, nrrdAxisInfoKind, kind); nrrdAxisInfoSet_nva(nrrd, nrrdAxisInfoSpaceDirection, spaceDir); // Go through MetaDataDictionary and set either specific nrrd field // or a key/value pair MetaDataDictionary & thisDic = this->GetMetaDataDictionary(); std::vector< std::string > keys = thisDic.GetKeys(); std::vector< std::string >::const_iterator keyIt; const char * keyField, *field; for ( keyIt = keys.begin(); keyIt != keys.end(); ++keyIt ) { if ( !strncmp( KEY_PREFIX, ( *keyIt ).c_str(), strlen(KEY_PREFIX) ) ) { keyField = ( *keyIt ).c_str() + strlen(KEY_PREFIX); // only of one of these can succeed field = airEnumStr(nrrdField, nrrdField_thicknesses); if ( !strncmp( keyField, field, strlen(field) ) ) { if ( 1 == sscanf(keyField + strlen(field), "[%u]", &axi) && axi + baseDim < nrrd->dim ) { double thickness = 0.0; ExposeMetaData< double >(thisDic, *keyIt, thickness); nrrd->axis[axi + baseDim].thickness = thickness; } } field = airEnumStr(nrrdField, nrrdField_centers); if ( !strncmp( keyField, field, strlen(field) ) ) { if ( 1 == sscanf(keyField + strlen(field), "[%u]", &axi) && axi + baseDim < nrrd->dim ) { std::string value; ExposeMetaData< std::string >(thisDic, *keyIt, value); nrrd->axis[axi + baseDim].center = airEnumVal( nrrdCenter, value.c_str() ); } } field = airEnumStr(nrrdField, nrrdField_kinds); if ( !strncmp( keyField, field, strlen(field) ) ) { if ( 1 == sscanf(keyField + strlen(field), "[%u]", &axi) && axi + baseDim < nrrd->dim ) { std::string value; ExposeMetaData< std::string >(thisDic, *keyIt, value); nrrd->axis[axi + baseDim].kind = airEnumVal( nrrdKind, value.c_str() ); } } field = airEnumStr(nrrdField, nrrdField_labels); if ( !strncmp( keyField, field, strlen(field) ) ) { if ( 1 == sscanf(keyField + strlen(field), "[%u]", &axi) && axi + baseDim < nrrd->dim ) { std::string value; ExposeMetaData< std::string >(thisDic, *keyIt, value); nrrd->axis[axi + baseDim].label = airStrdup( value.c_str() ); } } field = airEnumStr(nrrdField, nrrdField_old_min); if ( !strncmp( keyField, field, strlen(field) ) ) { ExposeMetaData< double >(thisDic, *keyIt, nrrd->oldMin); } field = airEnumStr(nrrdField, nrrdField_old_max); if ( !strncmp( keyField, field, strlen(field) ) ) { ExposeMetaData< double >(thisDic, *keyIt, nrrd->oldMax); } field = airEnumStr(nrrdField, nrrdField_space); if ( !strncmp( keyField, field, strlen(field) ) ) { int space; std::string value; ExposeMetaData< std::string >(thisDic, *keyIt, value); space = airEnumVal( nrrdSpace, value.c_str() ); if ( nrrdSpaceDimension(space) == nrrd->spaceDim ) { // sanity check nrrd->space = space; } } field = airEnumStr(nrrdField, nrrdField_content); if ( !strncmp( keyField, field, strlen(field) ) ) { std::string value; ExposeMetaData< std::string >(thisDic, *keyIt, value); nrrd->content = airStrdup( value.c_str() ); } field = airEnumStr(nrrdField, nrrdField_measurement_frame); if ( !strncmp( keyField, field, strlen(field) ) ) { std::vector< std::vector< double > > msrFrame; ExposeMetaData< std::vector< std::vector< double > > >(thisDic, *keyIt, msrFrame); for ( unsigned int saxi = 0; saxi < nrrd->spaceDim; saxi++ ) { for ( unsigned int saxj = 0; saxj < nrrd->spaceDim; saxj++ ) { if ( saxi < msrFrame.size() && saxj < msrFrame[saxi].size() ) { nrrd->measurementFrame[saxi][saxj] = msrFrame[saxi][saxj]; } else { // there is a difference between the dimension of the // recorded measurement frame, and the actual dimension of // the ITK image, which (for now) determines nrrd->spaceDim. // We can't set this to AIR_NAN, because the coefficients of // the measurement frame have to all be equally existent. // If we used 0, it might not a flag that something is wrong. // So, we have to get creative. nrrd->measurementFrame[saxi][saxj] = 666666; } } } } } else { // not a NRRD field packed into meta data; just a regular key/value std::string value; ExposeMetaData< std::string >(thisDic, *keyIt, value); nrrdKeyValueAdd( nrrd, ( *keyIt ).c_str(), value.c_str() ); } } // set encoding for data: compressed (raw), (uncompressed) raw, or ascii if ( this->GetUseCompression() == true && nrrdEncodingGzip->available() ) { // this is necessarily gzip-compressed *raw* data nio->encoding = nrrdEncodingGzip; } else { Superclass::FileType fileType = this->GetFileType(); switch ( fileType ) { default: case TypeNotApplicable: case Binary: nio->encoding = nrrdEncodingRaw; break; case ASCII: nio->encoding = nrrdEncodingAscii; break; } } // set desired endianness of output Superclass::ByteOrder byteOrder = this->GetByteOrder(); switch ( byteOrder ) { default: case OrderNotApplicable: nio->endian = airEndianUnknown; break; case BigEndian: nio->endian = airEndianBig; break; case LittleEndian: nio->endian = airEndianLittle; break; } // Write the nrrd to file. if ( nrrdSave(this->GetFileName(), nrrd, nio) ) { char *err = biffGetDone(NRRD); // would be nice to free(err) itkExceptionMacro("Write: Error writing " << this->GetFileName() << ":\n" << err); } // Free the nrrd struct but don't touch nrrd->data nrrd = nrrdNix(nrrd); nio = nrrdIoStateNix(nio); } } // end namespace itk
#pragma once #include <functional> #include <optional> #include <type_traits> #include <boost/range.hpp> #include <boost/range/join.hpp> #include "all_type_variant.hpp" #include "constant_mappings.hpp" #include "storage/pos_lists/row_id_pos_list.hpp" #include "types.hpp" namespace opossum { // Generic class which handles the actual scanning of a sorted segment template <typename IteratorType, typename SearchValueType> class SortedSegmentSearch { public: SortedSegmentSearch(IteratorType begin, IteratorType end, const SortMode& sorted_by, const bool nullable, const PredicateCondition& predicate_condition, const SearchValueType& search_value) : _begin{begin}, _end{end}, _predicate_condition{predicate_condition}, _first_search_value{search_value}, _second_search_value{std::nullopt}, _nullable{nullable}, _is_ascending{sorted_by == SortMode::Ascending} {} // For SortedSegmentBetweenSearch SortedSegmentSearch(IteratorType begin, IteratorType end, const SortMode& sorted_by, const bool nullable, const PredicateCondition& predicate_condition, const SearchValueType& left_value, const SearchValueType& right_value) : _begin{begin}, _end{end}, _predicate_condition{predicate_condition}, _first_search_value{left_value}, _second_search_value{right_value}, _nullable{nullable}, _is_ascending{sorted_by == SortMode::Ascending} {} private: /** * _get_first_bound and _get_last_bound are used to retrieve the lower and upper bound in a sorted segment but are * independent of its sort order. _get_first_bound will always return the bound with the smaller offset and * _get_last_bound will return the bigger offset. * On a segment sorted in ascending sort order they would work analogously to lower_bound and upper_bound. For * descending sort orders, _get_first_bound will actually return an upper bound and _get_last_bound the lower one. * However, the first offset will always point to an entry matching the search value, whereas last offset points to * the entry behind the last matching one. */ IteratorType _get_first_bound(const SearchValueType& search_value, const IteratorType begin, const IteratorType end) const { if (_is_ascending) { return std::lower_bound(begin, end, search_value, [](const auto& segment_position, const auto& value) { return segment_position.value() < value; }); } else { return std::lower_bound(begin, end, search_value, [](const auto& segment_position, const auto& value) { return segment_position.value() > value; }); } } IteratorType _get_last_bound(const SearchValueType& search_value, const IteratorType begin, const IteratorType end) const { if (_is_ascending) { return std::upper_bound(begin, end, search_value, [](const auto& value, const auto& segment_position) { return segment_position.value() > value; }); } else { return std::upper_bound(begin, end, search_value, [](const auto& value, const auto& segment_position) { return segment_position.value() < value; }); } } // This function sets the offset(s) which delimit the result set based on the predicate condition and the sort order void _set_begin_and_end_positions_for_vs_value_scan() { if (_predicate_condition == PredicateCondition::Equals) { _begin = _get_first_bound(_first_search_value, _begin, _end); _end = _get_last_bound(_first_search_value, _begin, _end); return; } // clang-format off if (_is_ascending) { switch (_predicate_condition) { case PredicateCondition::GreaterThanEquals: _begin = _get_first_bound(_first_search_value, _begin, _end); return; case PredicateCondition::GreaterThan: _begin = _get_last_bound(_first_search_value, _begin, _end); return; case PredicateCondition::LessThanEquals: _end = _get_last_bound(_first_search_value, _begin, _end); return; case PredicateCondition::LessThan: _end = _get_first_bound(_first_search_value, _begin, _end); return; default: Fail("Unsupported predicate condition encountered"); } } else { switch (_predicate_condition) { case PredicateCondition::LessThanEquals: _begin = _get_first_bound(_first_search_value, _begin, _end); return; case PredicateCondition::LessThan: _begin = _get_last_bound(_first_search_value, _begin, _end); return; case PredicateCondition::GreaterThanEquals: _end = _get_last_bound(_first_search_value, _begin, _end); return; case PredicateCondition::GreaterThan: _end = _get_first_bound(_first_search_value, _begin, _end); return; default: Fail("Unsupported predicate condition encountered"); } } // clang-format on } // This function sets the offset(s) that delimit the result set based on the predicate condition and the sort order void _set_begin_and_end_positions_for_between_scan() { DebugAssert(_second_search_value, "Second Search Value must be set for between scan"); if (_begin == _end) return; auto first_value = _begin->value(); auto last_value = (_end - 1)->value(); auto predicate_condition = _predicate_condition; auto first_search_value = _first_search_value; auto second_search_value = *_second_search_value; // if descending: exchange predicate conditions, search values and first/last values if (!_is_ascending) { switch (_predicate_condition) { case PredicateCondition::BetweenLowerExclusive: predicate_condition = PredicateCondition::BetweenUpperExclusive; break; case PredicateCondition::BetweenUpperExclusive: predicate_condition = PredicateCondition::BetweenLowerExclusive; break; case PredicateCondition::BetweenInclusive: case PredicateCondition::BetweenExclusive: break; default: Fail("Unsupported predicate condition encountered"); } std::swap(first_value, last_value); std::swap(first_search_value, second_search_value); } // early out everything matches if (first_value > _first_search_value && last_value < *_second_search_value) return; // early out nothing matches if (first_value > *_second_search_value || last_value < _first_search_value) { _begin = _end; return; } // This implementation uses behaviour which resembles std::equal_range's // behaviour since it, too, calculates two different bounds. // However, equal_range is designed to compare to a single search value, // whereas in this case, the upper and lower search value (if given) will differ. switch (predicate_condition) { case PredicateCondition::BetweenInclusive: _begin = _get_first_bound(first_search_value, _begin, _end); _end = _get_last_bound(second_search_value, _begin, _end); return; case PredicateCondition::BetweenLowerExclusive: // upper inclusive _begin = _get_last_bound(first_search_value, _begin, _end); _end = _get_last_bound(second_search_value, _begin, _end); return; case PredicateCondition::BetweenUpperExclusive: _begin = _get_first_bound(first_search_value, _begin, _end); _end = _get_first_bound(second_search_value, _begin, _end); return; case PredicateCondition::BetweenExclusive: _begin = _get_last_bound(first_search_value, _begin, _end); _end = _get_first_bound(second_search_value, _begin, _end); return; default: Fail("Unsupported predicate condition encountered"); } } /* * NotEquals may result in two matching ranges (one below and one above the search_value) and needs special handling. * The function contains four early outs. These are all only for performance reasons and, if removed, would not * change the functionality. * * Note: All comments within this method are written from the point of ranges in ascending sort order. */ template <typename ResultConsumer> void _handle_not_equals(const ResultConsumer& result_consumer) { const auto first_bound = _get_first_bound(_first_search_value, _begin, _end); if (first_bound == _end) { // Neither the _search_value nor anything greater than it are found. Call the result_consumer on the whole range // and skip the call to _get_last_bound(). result_consumer(_begin, _end); return; } if (first_bound->value() != _first_search_value) { // If the first value >= _search_value is not equal to _search_value, then _search_value doesn't occur at all. // Call the result_consumer on the whole range and skip the call to _get_last_bound(). result_consumer(_begin, _end); return; } // At this point, first_bound points to the first occurrence of _search_value. const auto last_bound = _get_last_bound(_first_search_value, _begin, _end); if (last_bound == _end) { // If no value > _search_value is found, call the result_consumer from start to first occurrence and skip the // need for boost::join(). result_consumer(_begin, first_bound); return; } if (first_bound == _begin) { // If _search_value is right at the start, call the result_consumer from the first value > _search_value // to end and skip the need for boost::join(). result_consumer(last_bound, _end); return; } const auto range = boost::range::join(boost::make_iterator_range(_begin, first_bound), boost::make_iterator_range(last_bound, _end)); result_consumer(range.begin(), range.end()); } public: template <typename ResultConsumer> void scan_sorted_segment(const ResultConsumer& result_consumer) { if (_second_search_value) { if (_nullable) { // decrease the effective sort range by excluding null values _begin = std::lower_bound(_begin, _end, false, [](const auto& segment_position, const auto& _) { return segment_position.is_null(); }); } _set_begin_and_end_positions_for_between_scan(); result_consumer(_begin, _end); } else { // decrease the effective sort range by excluding null values _begin = std::lower_bound(_begin, _end, false, [](const auto& segment_position, const auto& _) { return segment_position.is_null(); }); if (_predicate_condition == PredicateCondition::NotEquals) { _handle_not_equals(result_consumer); } else { _set_begin_and_end_positions_for_vs_value_scan(); result_consumer(_begin, _end); } } } template <typename ResultIteratorType> void _write_rows_to_matches(ResultIteratorType begin, ResultIteratorType end, const ChunkID chunk_id, RowIDPosList& matches, const std::shared_ptr<const AbstractPosList>& position_filter) const { if (begin == end) return; // General note: If the predicate is NotEquals, there might be two ranges that match. // These two ranges might have been combined into a single one via boost::join(range_1, range_2). // See _handle_not_equals for further details. size_t output_idx = matches.size(); matches.resize(matches.size() + std::distance(begin, end)); /** * If the range of matches consists of continuous ChunkOffsets we can speed up the writing * by calculating the offsets based on the first offset instead of calling chunk_offset() * for every match. * ChunkOffsets in position_filter are not necessarily continuous. The same is true for * NotEquals because the result might consist of 2 ranges. */ if (position_filter || _predicate_condition == PredicateCondition::NotEquals) { for (; begin != end; ++begin) { matches[output_idx++] = RowID{chunk_id, begin->chunk_offset()}; } } else { const auto first_offset = begin->chunk_offset(); const auto distance = std::distance(begin, end); for (auto chunk_offset = 0; chunk_offset < distance; ++chunk_offset) { matches[output_idx++] = RowID{chunk_id, first_offset + chunk_offset}; } } } private: // _begin and _end will be modified to match the search range and will be passed to the ResultConsumer, except when // handling NotEquals (see _handle_not_equals). IteratorType _begin; IteratorType _end; const PredicateCondition _predicate_condition; const SearchValueType _first_search_value; const std::optional<SearchValueType> _second_search_value; const bool _nullable; const bool _is_ascending; }; } // namespace opossum
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // 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 "UNIX_SCSIMultipathConfigurationCapabilitiesProvider.h" UNIX_SCSIMultipathConfigurationCapabilitiesProvider::UNIX_SCSIMultipathConfigurationCapabilitiesProvider() { } UNIX_SCSIMultipathConfigurationCapabilitiesProvider::~UNIX_SCSIMultipathConfigurationCapabilitiesProvider() { } CIMInstance UNIX_SCSIMultipathConfigurationCapabilitiesProvider::constructInstance( const CIMName &className, const CIMNamespaceName &nameSpace, const UNIX_SCSIMultipathConfigurationCapabilities &_p) { CIMProperty p; CIMInstance inst(className); // Set path inst.setPath(CIMObjectPath(String(""), // hostname nameSpace, CIMName("UNIX_SCSIMultipathConfigurationCapabilities"), constructKeyBindings(_p))); //CIM_ManagedElement Properties if (_p.getInstanceID(p)) inst.addProperty(p); if (_p.getCaption(p)) inst.addProperty(p); if (_p.getDescription(p)) inst.addProperty(p); if (_p.getElementName(p)) inst.addProperty(p); //CIM_Capabilities Properties //CIM_SCSIMultipathConfigurationCapabilities Properties if (_p.getSupportedLoadBalanceTypes(p)) inst.addProperty(p); if (_p.getOtherSupportedLoadBalanceAlgorithmNames(p)) inst.addProperty(p); if (_p.getOtherSupportedLoadBalanceVendorNames(p)) inst.addProperty(p); if (_p.getCanSetTPGAccess(p)) inst.addProperty(p); if (_p.getCanOverridePaths(p)) inst.addProperty(p); if (_p.getExposesPathDeviceFiles(p)) inst.addProperty(p); if (_p.getDeviceNameFilespace(p)) inst.addProperty(p); if (_p.getOnlySupportsSpecifiedProducts(p)) inst.addProperty(p); if (_p.getMaximumWeight(p)) inst.addProperty(p); if (_p.getAutofailbackSupport(p)) inst.addProperty(p); if (_p.getAutoFailbackEnabled(p)) inst.addProperty(p); if (_p.getPollingRateMax(p)) inst.addProperty(p); if (_p.getCurrentPollingRate(p)) inst.addProperty(p); if (_p.getDefaultLoadBalanceType(p)) inst.addProperty(p); return inst; } Array<CIMKeyBinding> UNIX_SCSIMultipathConfigurationCapabilitiesProvider::constructKeyBindings(const UNIX_SCSIMultipathConfigurationCapabilities& _p) { Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding( PROPERTY_INSTANCE_ID, _p.getInstanceID(), CIMKeyBinding::STRING)); return keys; } #define UNIX_PROVIDER UNIX_SCSIMultipathConfigurationCapabilitiesProvider #define UNIX_PROVIDER_NAME "UNIX_SCSIMultipathConfigurationCapabilitiesProvider" #define CLASS_IMPLEMENTATION UNIX_SCSIMultipathConfigurationCapabilities #define CLASS_IMPLEMENTATION_NAME "UNIX_SCSIMultipathConfigurationCapabilities" #define BASE_CLASS_NAME "CIM_SCSIMultipathConfigurationCapabilities" #define NUMKEYS_CLASS_IMPLEMENTATION 0 #include "UNIXProviderBase.hpp"
// Copyright 2020 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <memory> #include <string> #include <tuple> #include <vector> #include "controller_interface/controller_interface.hpp" #include "controller_manager/controller_manager.hpp" #include "controller_manager_test_common.hpp" #include "lifecycle_msgs/msg/state.hpp" using test_controller::TEST_CONTROLLER_CLASS_NAME; using ::testing::_; using ::testing::Return; const auto controller_name1 = "test_controller1"; const auto controller_name2 = "test_controller2"; using strvec = std::vector<std::string>; class TestLoadController : public ControllerManagerFixture { protected: void _switch_test_controllers( const strvec & start_controllers, const strvec & stop_controllers, const std::future_status expected_future_status = std::future_status::timeout, const controller_interface::return_type expected_interface_status = controller_interface::return_type::OK) { // First activation not possible because controller not configured auto switch_future = std::async( std::launch::async, &controller_manager::ControllerManager::switch_controller, cm_, start_controllers, stop_controllers, STRICT, true, rclcpp::Duration(0, 0)); ASSERT_EQ(expected_future_status, switch_future.wait_for(std::chrono::milliseconds(100))) << "switch_controller should be blocking until next update cycle"; ControllerManagerRunner cm_runner(this); EXPECT_EQ(expected_interface_status, switch_future.get()); } }; TEST_F(TestLoadController, load_unknown_controller) { ASSERT_EQ(cm_->load_controller("unknown_controller_name", "unknown_controller_type"), nullptr); } TEST_F(TestLoadController, load_controller_failed_init) { ASSERT_EQ( cm_->load_controller( "test_controller_failed_init", test_controller_failed_init::TEST_CONTROLLER_FAILED_INIT_CLASS_NAME), nullptr); } TEST_F(TestLoadController, configuring_non_loaded_controller_fails) { // try configure non-loaded controller EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::ERROR); } class TestLoadedController : public TestLoadController { public: controller_interface::ControllerInterfaceSharedPtr controller_if{nullptr}; void SetUp() override { TestLoadController::SetUp(); controller_if = cm_->load_controller(controller_name1, TEST_CONTROLLER_CLASS_NAME); ASSERT_NE(controller_if, nullptr); } void start_test_controller( const std::future_status expected_future_status = std::future_status::timeout, const controller_interface::return_type expected_interface_status = controller_interface::return_type::OK) { _switch_test_controllers( strvec{controller_name1}, strvec{}, expected_future_status, expected_interface_status); } void stop_test_controller( const std::future_status expected_future_status = std::future_status::timeout, const controller_interface::return_type expected_interface_status = controller_interface::return_type::OK) { _switch_test_controllers( strvec{}, strvec{controller_name1}, expected_future_status, expected_interface_status); } }; TEST_F(TestLoadedController, load_and_configure_one_known_controller) { EXPECT_EQ(1u, cm_->get_loaded_controllers().size()); EXPECT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if->get_state().id()); cm_->configure_controller(controller_name1); EXPECT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); } TEST_F(TestLoadedController, can_start_configured_controller) { EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::OK); start_test_controller(); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if->get_state().id()); } TEST_F(TestLoadedController, can_stop_active_controller) { EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::OK); start_test_controller(); // Stop controller stop_test_controller(); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); } TEST_F(TestLoadedController, starting_and_stopping_a_controller) { ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if->get_state().id()); // Only testing with STRICT now for simplicity { // Test starting unconfigured controller, and starting configured afterwards start_test_controller(std::future_status::ready, controller_interface::return_type::ERROR); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if->get_state().id()); // Activate configured controller cm_->configure_controller(controller_name1); start_test_controller(); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if->get_state().id()); } { // Stop controller stop_test_controller(); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); } } TEST_F(TestLoadedController, can_not_configure_active_controller) { EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::OK); start_test_controller(); // Can not configure active controller EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::ERROR); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if->get_state().id()); } TEST_F(TestLoadedController, can_not_start_finalized_controller) { ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if->get_state().id()); // Shutdown controller on purpose for testing ASSERT_EQ(controller_if->shutdown().id(), lifecycle_msgs::msg::State::PRIMARY_STATE_FINALIZED); // Start controller start_test_controller(std::future_status::ready, controller_interface::return_type::ERROR); // Can not configure unconfigured controller EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::ERROR); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_FINALIZED, controller_if->get_state().id()); } TEST_F(TestLoadedController, inactive_controller_cannot_be_cleaned_up) { EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::OK); start_test_controller(); stop_test_controller(); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); std::shared_ptr<test_controller::TestController> test_controller = std::dynamic_pointer_cast<test_controller::TestController>(controller_if); size_t cleanup_calls = 0; test_controller->cleanup_calls = &cleanup_calls; // Configure from inactive state: controller can no be cleaned-up test_controller->simulate_cleanup_failure = true; EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::ERROR); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); EXPECT_EQ(0u, cleanup_calls); } TEST_F(TestLoadedController, inactive_controller_cannot_be_configured) { EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::OK); start_test_controller(); stop_test_controller(); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); std::shared_ptr<test_controller::TestController> test_controller = std::dynamic_pointer_cast<test_controller::TestController>(controller_if); size_t cleanup_calls = 0; test_controller->cleanup_calls = &cleanup_calls; // Configure from inactive state test_controller->simulate_cleanup_failure = false; EXPECT_EQ(cm_->configure_controller(controller_name1), controller_interface::return_type::OK); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); EXPECT_EQ(1u, cleanup_calls); } class SwitchTest : public TestLoadedController, public ::testing::WithParamInterface< std::tuple<controller_interface::return_type, int, strvec, strvec, std::string>> { }; const auto UNSPECIFIED = 0; const auto EMPTY_STR_VEC = strvec{}; const auto NONEXISTENT_CONTROLLER = strvec{"nonexistent_controller"}; const auto VALID_CONTROLLER = strvec{controller_name1}; const auto VALID_PLUS_NONEXISTENT_CONTROLLERS = strvec{controller_name1, "nonexistent_controller"}; TEST_P(SwitchTest, EmptyListOrNonExistentTest) { EXPECT_EQ(1u, cm_->get_loaded_controllers().size()); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if->get_state().id()); auto params = GetParam(); auto result = std::get<0>(params); auto strictness = std::get<1>(params); auto start_controllers = std::get<2>(params); auto stop_controllers = std::get<3>(params); auto error_message = std::get<4>(params); EXPECT_EQ( result, cm_->switch_controller( start_controllers, stop_controllers, strictness, true, rclcpp::Duration(0, 0))) << error_message; } INSTANTIATE_TEST_SUITE_P( EmptyListOrNonExistentTest, SwitchTest, ::testing::Values( // empty lists std::make_tuple( controller_interface::return_type::OK, UNSPECIFIED, EMPTY_STR_VEC, EMPTY_STR_VEC, "Switch with no controllers specified and strictness UNSPECIFIED didn't return OK"), std::make_tuple( controller_interface::return_type::OK, STRICT, EMPTY_STR_VEC, EMPTY_STR_VEC, "Switch with no controllers specified and strictness STRICT didn't return OK"), std::make_tuple( controller_interface::return_type::OK, BEST_EFFORT, EMPTY_STR_VEC, EMPTY_STR_VEC, "Switch with no controllers specified and strictness BEST_EFFORT didn't return OK"), // combination of empty and non-existent controller std::make_tuple( controller_interface::return_type::OK, UNSPECIFIED, NONEXISTENT_CONTROLLER, EMPTY_STR_VEC, "Switch with nonexistent start controller specified and strictness UNSPECIFIED didn't return " "OK"), std::make_tuple( controller_interface::return_type::ERROR, STRICT, NONEXISTENT_CONTROLLER, EMPTY_STR_VEC, "Switch with nonexistent start controller specified and strictness STRICT didn't return " "ERROR"), std::make_tuple( controller_interface::return_type::OK, BEST_EFFORT, NONEXISTENT_CONTROLLER, EMPTY_STR_VEC, "Switch with nonexistent start controller specified and strictness BEST_EFFORT didn't return " "OK"), std::make_tuple( controller_interface::return_type::OK, UNSPECIFIED, EMPTY_STR_VEC, NONEXISTENT_CONTROLLER, "Switch with nonexistent stop controller specified and strictness UNSPECIFIED didn't return " "OK"), std::make_tuple( controller_interface::return_type::ERROR, STRICT, EMPTY_STR_VEC, NONEXISTENT_CONTROLLER, "Switch with nonexistent stop controller specified and strictness STRICT didn't return " "ERROR"), std::make_tuple( controller_interface::return_type::OK, BEST_EFFORT, EMPTY_STR_VEC, NONEXISTENT_CONTROLLER, "Switch with nonexistent stop controller specified and strictness BEST_EFFORT didn't return " "OK"), std::make_tuple( controller_interface::return_type::OK, UNSPECIFIED, NONEXISTENT_CONTROLLER, NONEXISTENT_CONTROLLER, "Switch with nonexistent start and stop controllers specified, and strictness UNSPECIFIED, " "didn't return OK"), std::make_tuple( controller_interface::return_type::ERROR, STRICT, NONEXISTENT_CONTROLLER, NONEXISTENT_CONTROLLER, "Switch with nonexistent start and stop controllers specified, and strictness STRICT, didn't " "return ERROR"), std::make_tuple( controller_interface::return_type::OK, BEST_EFFORT, NONEXISTENT_CONTROLLER, NONEXISTENT_CONTROLLER, "Switch with nonexistent start and stop controllers specified, and strictness BEST_EFFORT, " "didn't return OK"), // valid controller used std::make_tuple( controller_interface::return_type::ERROR, STRICT, NONEXISTENT_CONTROLLER, VALID_CONTROLLER, "Switch with valid stopped controller and nonexistent start controller specified, and " "strictness STRICT, didn't return ERROR"), std::make_tuple( controller_interface::return_type::OK, BEST_EFFORT, NONEXISTENT_CONTROLLER, VALID_CONTROLLER, "Switch with valid stopped controller specified, nonexistent start controller and strictness " "BEST_EFFORT didn't return OK"), std::make_tuple( controller_interface::return_type::ERROR, STRICT, VALID_PLUS_NONEXISTENT_CONTROLLERS, EMPTY_STR_VEC, "Switch with valid and nonexistent start controller specified and strictness STRICT didn't " "return ERROR"), std::make_tuple( controller_interface::return_type::ERROR, STRICT, VALID_CONTROLLER, NONEXISTENT_CONTROLLER, "Switch with valid start controller and nonexistent controller specified, and strinctness " "STRICT, didn't return ERROR"))); class TestTwoLoadedControllers : public TestLoadController { public: controller_interface::ControllerInterfaceSharedPtr controller_if1{nullptr}; controller_interface::ControllerInterfaceSharedPtr controller_if2{nullptr}; void SetUp() override { TestLoadController::SetUp(); controller_if1 = cm_->load_controller(controller_name1, TEST_CONTROLLER_CLASS_NAME); ASSERT_NE(controller_if1, nullptr); EXPECT_EQ(1u, cm_->get_loaded_controllers().size()); controller_if2 = cm_->load_controller(controller_name2, TEST_CONTROLLER_CLASS_NAME); ASSERT_NE(controller_if2, nullptr); EXPECT_EQ(2u, cm_->get_loaded_controllers().size()); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if1->get_state().id()); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if2->get_state().id()); } void switch_test_controllers( const strvec & start_controllers, const strvec & stop_controllers, const std::future_status expected_future_status = std::future_status::timeout, const controller_interface::return_type expected_interface_status = controller_interface::return_type::OK) { _switch_test_controllers( start_controllers, stop_controllers, expected_future_status, expected_interface_status); } }; TEST_F(TestTwoLoadedControllers, load_and_configure_two_known_controllers) { cm_->configure_controller(controller_name1); EXPECT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if1->get_state().id()); cm_->configure_controller(controller_name2); EXPECT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if2->get_state().id()); } TEST_F(TestTwoLoadedControllers, switch_multiple_controllers) { // Only testing with STRICT now for simplicity // Test starting a stopped controller, and stopping afterwards cm_->configure_controller(controller_name1); // Start controller #1 RCLCPP_INFO(cm_->get_logger(), "Starting stopped controller #1"); switch_test_controllers(strvec{controller_name1}, strvec{}); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if1->get_state().id()); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if2->get_state().id()); // Stop controller 1, start controller 2 // Both fail because controller 2 because it is not configured and STRICT is used RCLCPP_INFO( cm_->get_logger(), "Stopping controller #1, starting unconfigured controller #2 fails (STRICT)"); switch_test_controllers( strvec{controller_name2}, strvec{controller_name1}, std::future_status::ready, controller_interface::return_type::ERROR); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if1->get_state().id()); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if2->get_state().id()); cm_->configure_controller(controller_name2); // Stop controller 1 RCLCPP_INFO(cm_->get_logger(), "Stopping controller #1"); switch_test_controllers(strvec{}, strvec{controller_name1}); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if1->get_state().id()); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if2->get_state().id()); // Start controller 1 again RCLCPP_INFO(cm_->get_logger(), "Starting stopped controller #1"); switch_test_controllers(strvec{controller_name1}, strvec{}); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if1->get_state().id()); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if2->get_state().id()); // Stop controller 1, start controller 2 RCLCPP_INFO(cm_->get_logger(), "Stopping controller #1, starting controller #2"); switch_test_controllers(strvec{controller_name2}, strvec{controller_name1}); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if1->get_state().id()); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE, controller_if2->get_state().id()); // Stop controller 2 RCLCPP_INFO(cm_->get_logger(), "Stopping controller #2"); switch_test_controllers(strvec{}, strvec{controller_name2}); ASSERT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if2->get_state().id()); } TEST_F(TestLoadController, can_set_and_get_non_default_update_rate) { auto controller_if = cm_->load_controller("test_controller_01", test_controller::TEST_CONTROLLER_CLASS_NAME); ASSERT_NE(controller_if, nullptr); ASSERT_EQ( lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED, controller_if->get_state().id()); controller_if->get_node()->set_parameter({"update_rate", 1337}); cm_->configure_controller("test_controller_01"); EXPECT_EQ(lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE, controller_if->get_state().id()); EXPECT_EQ(1337u, controller_if->get_update_rate()); }
#ifndef BOOST_MPL_SET_SET30_HPP_INCLUDED #define BOOST_MPL_SET_SET30_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source$ // $Date: 2004-09-02 11:41:37 -0400 (Thu, 02 Sep 2004) $ // $Revision: 24874 $ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/set/set20.hpp> #endif #include <boost/mpl/aux_/config/use_preprocessed.hpp> #if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) # define BOOST_MPL_PREPROCESSED_HEADER set30.hpp # include <boost/mpl/set/aux_/include_preprocessed.hpp> #else # include <boost/preprocessor/iterate.hpp> namespace boost { namespace mpl { # define BOOST_PP_ITERATION_PARAMS_1 \ (3,(21, 30, <boost/mpl/set/aux_/numbered.hpp>)) # include BOOST_PP_ITERATE() }} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // BOOST_MPL_SET_SET30_HPP_INCLUDED
// Ivan Carvalho // Solution to https://dmoj.ca/problem/mnyc17p3 #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll,ll> ii; const ll MOD1 = 1e9 + 9; const ll prime1 = 999983; const ll MOD2 = 1e9 + 7; const ll prime2 = 999979; const ll invprime1 = 943912055; const ll invprime2 = 672490127; const int MAXN = 1e6 + 10; ll hash1[MAXN],hash2[MAXN],pot1[MAXN],pot2[MAXN],inv1[MAXN],inv2[MAXN],shash1[MAXN],shash2[MAXN]; string s1,s2; int checa(int a,int b,int c,int d){ ll val1 = ((hash1[b] - hash1[a-1])*(inv1[a-1]))%MOD1; if(val1 < 0) val1 += MOD1; ll val2 = ((hash2[b] - hash2[a-1])*(inv2[a-1]))%MOD2; if(val2 < 0) val2 += MOD2; ll sval1 = ((shash1[d] - shash1[c-1])*(inv1[c-1]))%MOD1; if(sval1 < 0) sval1 += MOD1; ll sval2 = ((shash2[d] - shash2[c-1])*(inv2[c-1]))%MOD2; if(sval2 < 0) sval2 += MOD2; if(sval1 != val1 || sval2 != val2) return 0; return 1; } int main(){ cin >> s1 >> s2; pot1[0] = pot2[0] = inv1[0] = inv2[0] = 1; for(int i=1;i<=s1.size();i++){ pot1[i] = (pot1[i-1]*prime1) % MOD1; pot2[i] = (pot2[i-1]*prime2) % MOD2; inv1[i] = (inv1[i-1]*invprime1) % MOD1; inv2[i] = (inv2[i-1]*invprime2) % MOD2; hash1[i] = (hash1[i-1] + s1[i-1]*pot1[i]) % MOD1; hash2[i] = (hash2[i-1] + s1[i-1]*pot2[i]) % MOD2; } for(int i=1;i<=s2.size();i++){ pot1[i] = (pot1[i-1]*prime1) % MOD1; pot2[i] = (pot2[i-1]*prime2) % MOD2; inv1[i] = (inv1[i-1]*invprime1) % MOD1; inv2[i] = (inv2[i-1]*invprime2) % MOD2; shash1[i] = (shash1[i-1] + s2[i-1]*pot1[i]) % MOD1; shash2[i] = (shash2[i-1] + s2[i-1]*pot2[i]) % MOD2; } int cand1 = s1.size(),cand2 = 1,melhor1 = -1,melhor2 = -1; while(cand1 >= 1 && cand2 <= s2.size()){ if(checa(cand1,s1.size(),1,cand2)){ melhor1 = cand1; melhor2 = cand2; } cand1--; cand2++; } if(melhor1 == -1 && melhor2 == -1){ cout << s1 << s2 << endl; return 0; } melhor1--; for(int i=0;i<melhor1;i++){ cout << s1[i]; } cout << s2 << endl; return 0; }
#pragma once #include "../acl_cpp_define.hpp" namespace acl { class ACL_CPP_API noncopyable { protected: noncopyable() {} ~noncopyable() {} private: noncopyable( const noncopyable& ); const noncopyable& operator=( const noncopyable& ); }; } // namespace acl
/********************************************************************************* * OKVIS - Open Keyframe-based Visual-Inertial SLAM * Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich * * 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 Autonomous Systems Lab / ETH Zurich nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. * * Created on: Mar 7, 2013 * Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk) * Modified: Andreas Forster (an.forster@gmail.com) *********************************************************************************/ /** * @file FrameRelativeAdapter.cpp * @brief Source file for the FrameRelativeAdapter class. * @author Stefan Leutenegger * @author Andreas Forster */ #include <opengv/relative_pose/FrameRelativeAdapter.hpp> #include <okvis/FrameTypedefs.hpp> #include <okvis/MultiFrame.hpp> // cameras and distortions #include <okvis/cameras/PinholeCamera.hpp> #include <okvis/cameras/EquidistantDistortion.hpp> #include <okvis/cameras/RadialTangentialDistortion.hpp> #include <okvis/cameras/RadialTangentialDistortion8.hpp> // Constructor. opengv::relative_pose::FrameRelativeAdapter::FrameRelativeAdapter( const okvis::Estimator & estimator, const okvis::cameras::NCameraSystem & nCameraSystem, uint64_t multiFrameIdA, size_t camIdA, uint64_t multiFrameIdB, size_t camIdB) { std::shared_ptr<okvis::MultiFrame> frameAPtr = estimator.multiFrame( multiFrameIdA); std::shared_ptr<okvis::MultiFrame> frameBPtr = estimator.multiFrame( multiFrameIdB); // determine type okvis::cameras::NCameraSystem::DistortionType distortionTypeA = nCameraSystem.distortionType(camIdA); okvis::cameras::NCameraSystem::DistortionType distortionTypeB = nCameraSystem.distortionType(camIdB); double fu1 = 0; size_t numKeypointsA = frameAPtr->numKeypoints(camIdA); switch (distortionTypeA) { case okvis::cameras::NCameraSystem::RadialTangential: { fu1 = frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion> >(camIdA) ->focalLengthU(); break; } case okvis::cameras::NCameraSystem::Equidistant: { fu1 = frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::EquidistantDistortion> >(camIdA) ->focalLengthU(); break; } case okvis::cameras::NCameraSystem::RadialTangential8: { fu1 = frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion8> >(camIdA) ->focalLengthU(); break; } default: OKVIS_THROW(Exception, "Unsupported distortion type") break; } double fu2 = 0.0; size_t numKeypointsB = frameBPtr->numKeypoints(camIdB); switch (distortionTypeB) { case okvis::cameras::NCameraSystem::RadialTangential: { fu2 = frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion> >(camIdB) ->focalLengthU(); break; } case okvis::cameras::NCameraSystem::Equidistant: { fu2 = frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::EquidistantDistortion> >(camIdB) ->focalLengthU(); break; } case okvis::cameras::NCameraSystem::RadialTangential8: { fu2 = frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion8> >(camIdB) ->focalLengthU(); break; } default: OKVIS_THROW(Exception, "Unsupported distortion type") break; } // resize members bearingVectors1_.resize(numKeypointsA); bearingVectors2_.resize(numKeypointsB); sigmaAngles1_.resize(numKeypointsA); sigmaAngles2_.resize(numKeypointsB); matches_.reserve(std::min(numKeypointsA, numKeypointsB)); std::map<uint64_t, size_t> idMap; for (size_t k = 0; k < numKeypointsB; ++k) { // get landmark id, if set uint64_t lmId = frameBPtr->landmarkId(camIdB, k); if (lmId == 0) continue; // check, if existing if (!estimator.isLandmarkAdded(lmId)) continue; // remember it idMap.insert(std::pair<uint64_t, size_t>(lmId, k)); } for (size_t k = 0; k < numKeypointsA; ++k) { // get landmark id, if set uint64_t lmId = frameAPtr->landmarkId(camIdA, k); if (lmId == 0) continue; std::map<uint64_t, size_t>::const_iterator it = idMap.find(lmId); if (it != idMap.end()) { // whohoo, let's insert it. matches_.push_back(okvis::Match(k, it->second, 0.0)); } } // precompute for (size_t k = 0; k < matches_.size(); ++k) { const size_t idx1 = matches_[k].idxA; const size_t idx2 = matches_[k].idxB; Eigen::Vector2d keypoint; double keypointStdDev; frameAPtr->getKeypoint(camIdA, idx1, keypoint); frameAPtr->getKeypointSize(camIdA, idx1, keypointStdDev); keypointStdDev = 0.8 * keypointStdDev / 12.0; sigmaAngles1_[idx1] = sqrt(2) * keypointStdDev * keypointStdDev / (fu1 * fu1); switch (distortionTypeA) { case okvis::cameras::NCameraSystem::RadialTangential: { frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion> >(camIdA) ->backProject(keypoint, &bearingVectors1_[idx1]); break; } case okvis::cameras::NCameraSystem::Equidistant: { frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::EquidistantDistortion> >(camIdA)->backProject( keypoint, &bearingVectors1_[idx1]); break; } case okvis::cameras::NCameraSystem::RadialTangential8: { frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion8> >(camIdA) ->backProject(keypoint, &bearingVectors1_[idx1]); break; } default: OKVIS_THROW(Exception, "Unsupported distortion type") break; } bearingVectors1_[idx1].normalize(); frameBPtr->getKeypoint(camIdB, idx2, keypoint); frameBPtr->getKeypointSize(camIdB, idx2, keypointStdDev); keypointStdDev = 0.8 * keypointStdDev / 12.0; sigmaAngles2_[idx2] = sqrt(2) * keypointStdDev * keypointStdDev / (fu2 * fu2); switch (distortionTypeB) { case okvis::cameras::NCameraSystem::RadialTangential: { frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion> >(camIdB) ->backProject(keypoint, &bearingVectors2_[idx2]); break; } case okvis::cameras::NCameraSystem::Equidistant: { frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::EquidistantDistortion> >(camIdB) ->backProject(keypoint, &bearingVectors2_[idx2]); break; } case okvis::cameras::NCameraSystem::RadialTangential8: { frameAPtr ->geometryAs< okvis::cameras::PinholeCamera< okvis::cameras::RadialTangentialDistortion8> >(camIdB) ->backProject(keypoint, &bearingVectors2_[idx2]); break; } default: OKVIS_THROW(Exception, "Unsupported distortion type") break; } bearingVectors2_[idx2].normalize(); } } // Retrieve the bearing vector of a correspondence in viewpoint 1. opengv::bearingVector_t opengv::relative_pose::FrameRelativeAdapter::getBearingVector1( size_t index) const { return bearingVectors1_[matches_[index].idxA]; } // Retrieve the bearing vector of a correspondence in viewpoint 2. opengv::bearingVector_t opengv::relative_pose::FrameRelativeAdapter::getBearingVector2( size_t index) const { return bearingVectors2_[matches_[index].idxB]; } // Retrieve the position of a camera of a correspondence in viewpoint 1 seen from the origin of the viewpoint. opengv::translation_t opengv::relative_pose::FrameRelativeAdapter::getCamOffset1( size_t /*index*/) const { //We could also check here for camIndex being 0, because this adapter is made //for a single camera only return Eigen::Vector3d::Zero(); } // Retrieve the rotation from a camera of a correspondence in viewpoint 1 to the viewpoint origin. opengv::rotation_t opengv::relative_pose::FrameRelativeAdapter::getCamRotation1( size_t /*index*/) const { //We could also check here for camIndex being 0, because this adapter is made //for a single camera only return Eigen::Matrix3d::Identity(); } // Retrieve the position of a camera of a correspondence in viewpoint 2 seen from the origin of the viewpoint. opengv::translation_t opengv::relative_pose::FrameRelativeAdapter::getCamOffset2( size_t /*index*/) const { //We could also check here for camIndex being 0, because this adapter is made //for a single camera only return Eigen::Vector3d::Zero(); } // Retrieve the rotation from a camera of a correspondence in viewpoint 2 to the viewpoint origin. opengv::rotation_t opengv::relative_pose::FrameRelativeAdapter::getCamRotation2( size_t /*index*/) const { //We could also check here for camIndex being 0, because this adapter is made //for a single camera only return Eigen::Matrix3d::Identity(); } // Retrieve the number of correspondences. size_t opengv::relative_pose::FrameRelativeAdapter::getNumberCorrespondences() const { return matches_.size(); } // Obtain the angular standard deviation of the correspondence in frame 1 in [rad]. double opengv::relative_pose::FrameRelativeAdapter::getSigmaAngle1( size_t index) { return sigmaAngles1_[matches_[index].idxA]; } // Obtain the angular standard deviation of the correspondence in frame 2 in [rad]. double opengv::relative_pose::FrameRelativeAdapter::getSigmaAngle2( size_t index) { return sigmaAngles2_[matches_[index].idxB]; }
#include "scene_model.hpp" #include <memory> namespace rtc { struct collada_format : public rtc::scene_model { public: explicit collada_format(const std::string&); ~collada_format(); private: struct collada_format_impl; std::unique_ptr<collada_format_impl> collada_formatimpl; }; }
#include <fstream> using namespace std; class FileObject1 { public: FileObject1(); ~FileObject1(); int num; private: }; FileObject1::FileObject1() { } FileObject1::~FileObject1() { } int main() { ifstream readFile; readFile.open("123.txt", ios::in || ios::binary); if (readFile.is_open() == false) { return 0; } FileObject1* p = new FileObject1; readFile.read((char*)p, sizeof(*p)); readFile.close(); return 0; }
/* * Sketchy HTTP client * (C) 2013,2016 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/http_util.h> #include <botan/parsing.h> #include <botan/hex.h> #include <botan/internal/stl_util.h> #include <sstream> #if defined(BOTAN_HAS_BOOST_ASIO) /* * We don't need serial port support anyway, and asking for it * causes macro conflicts with Darwin's termios.h when this * file is included in the amalgamation. GH #350 */ #define BOOST_ASIO_DISABLE_SERIAL_PORT #include <boost/asio.hpp> #elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <netinet/in.h> #else //#warning "No network support enabled in http_util" #endif namespace Botan { namespace HTTP { namespace { /* * Connect to a host, write some bytes, then read until the server * closes the socket. */ std::string http_transact(const std::string& hostname, const std::string& message) { #if defined(BOTAN_HAS_BOOST_ASIO) using namespace boost::asio::ip; boost::asio::ip::tcp::iostream tcp; tcp.connect(hostname, "http"); if(!tcp) throw HTTP_Error("HTTP connection to " + hostname + " failed"); tcp << message; tcp.flush(); std::ostringstream oss; oss << tcp.rdbuf(); return oss.str(); #elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) hostent* host_addr = ::gethostbyname(hostname.c_str()); uint16_t port = 80; if(!host_addr) throw HTTP_Error("Name resolution failed for " + hostname); if(host_addr->h_addrtype != AF_INET) // FIXME throw HTTP_Error("Hostname " + hostname + " resolved to non-IPv4 address"); struct socket_raii { socket_raii(int fd) : m_fd(fd) {} ~socket_raii() { ::close(m_fd); } int m_fd; }; int fd = ::socket(PF_INET, SOCK_STREAM, 0); if(fd == -1) throw HTTP_Error("Unable to create TCP socket"); socket_raii raii(fd); sockaddr_in socket_info; ::memset(&socket_info, 0, sizeof(socket_info)); socket_info.sin_family = AF_INET; socket_info.sin_port = htons(port); ::memcpy(&socket_info.sin_addr, host_addr->h_addr, host_addr->h_length); socket_info.sin_addr = *reinterpret_cast<struct in_addr*>(host_addr->h_addr); // FIXME if(::connect(fd, reinterpret_cast<sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0) throw HTTP_Error("HTTP connection to " + hostname + " failed"); size_t sent_so_far = 0; while(sent_so_far != message.size()) { size_t left = message.size() - sent_so_far; ssize_t sent = ::write(fd, &message[sent_so_far], left); if(sent < 0) throw HTTP_Error("write to HTTP server failed, error '" + std::string(::strerror(errno)) + "'"); else sent_so_far += static_cast<size_t>(sent); } std::ostringstream oss; std::vector<char> buf(1024); // arbitrary size while(true) { ssize_t got = ::read(fd, buf.data(), buf.size()); if(got < 0) throw HTTP_Error("read from HTTP server failed, error '" + std::string(::strerror(errno)) + "'"); else if(got > 0) oss.write(buf.data(), static_cast<std::streamsize>(got)); else break; // EOF } return oss.str(); #else throw HTTP_Error("Cannot connect to " + hostname + ": network code disabled in build"); #endif } } std::string url_encode(const std::string& in) { std::ostringstream out; for(auto c : in) { if(c >= 'A' && c <= 'Z') out << c; else if(c >= 'a' && c <= 'z') out << c; else if(c >= '0' && c <= '9') out << c; else if(c == '-' || c == '_' || c == '.' || c == '~') out << c; else out << '%' << hex_encode(reinterpret_cast<uint8_t*>(&c), 1); } return out.str(); } std::ostream& operator<<(std::ostream& o, const Response& resp) { o << "HTTP " << resp.status_code() << " " << resp.status_message() << "\n"; for(auto h : resp.headers()) o << "Header '" << h.first << "' = '" << h.second << "'\n"; o << "Body " << std::to_string(resp.body().size()) << " bytes:\n"; o.write(reinterpret_cast<const char*>(&resp.body()[0]), resp.body().size()); return o; } Response http_sync(http_exch_fn http_transact, const std::string& verb, const std::string& url, const std::string& content_type, const std::vector<uint8_t>& body, size_t allowable_redirects) { if(url.empty()) throw HTTP_Error("URL empty"); const auto protocol_host_sep = url.find("://"); if(protocol_host_sep == std::string::npos) throw HTTP_Error("Invalid URL '" + url + "'"); const auto host_loc_sep = url.find('/', protocol_host_sep + 3); std::string hostname, loc; if(host_loc_sep == std::string::npos) { hostname = url.substr(protocol_host_sep + 3, std::string::npos); loc = "/"; } else { hostname = url.substr(protocol_host_sep + 3, host_loc_sep-protocol_host_sep-3); loc = url.substr(host_loc_sep, std::string::npos); } std::ostringstream outbuf; outbuf << verb << " " << loc << " HTTP/1.0\r\n"; outbuf << "Host: " << hostname << "\r\n"; if(verb == "GET") { outbuf << "Accept: */*\r\n"; outbuf << "Cache-Control: no-cache\r\n"; } else if(verb == "POST") outbuf << "Content-Length: " << body.size() << "\r\n"; if(!content_type.empty()) outbuf << "Content-Type: " << content_type << "\r\n"; outbuf << "Connection: close\r\n\r\n"; outbuf.write(reinterpret_cast<const char*>(body.data()), body.size()); std::istringstream io(http_transact(hostname, outbuf.str())); std::string line1; std::getline(io, line1); if(!io || line1.empty()) throw HTTP_Error("No response"); std::stringstream response_stream(line1); std::string http_version; unsigned int status_code; std::string status_message; response_stream >> http_version >> status_code; std::getline(response_stream, status_message); if(!response_stream || http_version.substr(0,5) != "HTTP/") throw HTTP_Error("Not an HTTP response"); std::map<std::string, std::string> headers; std::string header_line; while (std::getline(io, header_line) && header_line != "\r") { auto sep = header_line.find(": "); if(sep == std::string::npos || sep > header_line.size() - 2) throw HTTP_Error("Invalid HTTP header " + header_line); const std::string key = header_line.substr(0, sep); if(sep + 2 < header_line.size() - 1) { const std::string val = header_line.substr(sep + 2, (header_line.size() - 1) - (sep + 2)); headers[key] = val; } } if(status_code == 301 && headers.count("Location")) { if(allowable_redirects == 0) throw HTTP_Error("HTTP redirection count exceeded"); return GET_sync(headers["Location"], allowable_redirects - 1); } std::vector<uint8_t> resp_body; std::vector<uint8_t> buf(4096); while(io.good()) { io.read(reinterpret_cast<char*>(buf.data()), buf.size()); resp_body.insert(resp_body.end(), buf.data(), &buf[io.gcount()]); } const std::string header_size = search_map(headers, std::string("Content-Length")); if(!header_size.empty()) { if(resp_body.size() != to_u32bit(header_size)) throw HTTP_Error("Content-Length disagreement, header says " + header_size + " got " + std::to_string(resp_body.size())); } return Response(status_code, status_message, resp_body, headers); } Response http_sync(const std::string& verb, const std::string& url, const std::string& content_type, const std::vector<uint8_t>& body, size_t allowable_redirects) { return http_sync( http_transact, verb, url, content_type, body, allowable_redirects); } Response GET_sync(const std::string& url, size_t allowable_redirects) { return http_sync("GET", url, "", std::vector<uint8_t>(), allowable_redirects); } Response POST_sync(const std::string& url, const std::string& content_type, const std::vector<uint8_t>& body, size_t allowable_redirects) { return http_sync("POST", url, content_type, body, allowable_redirects); } } }
#include <iostream> #ifndef _BOTZONE_ONLINE #include "core.h" #include "parser.h" #include "faan.h" #include "bot.h" #endif void init(const Game &game) { using namespace faan::probability; // 0.05 ~ 0.3 results in human understandable behavior // however, larger decay may bring suprising performance decay_per_tile = 0.1 + 0.3 * game.wall_count / (NUM_TILE - 13 * NUM_PLAYER); // 1 & 9 for (tile t = CARD("W1"); t <= CARD("T1"); t += 9) { mapping[t] = [](int remain) -> float { return remain == 1 ? 2 : remain; }; mapping[t+8] = [](int remain) -> float { return remain == 1 ? 2 : remain; }; } // winds & dragons for (tile t = CARD("F1"); t <= CARD("J3"); t++) mapping[t] = [](int remain) -> float { return remain == 1 ? 4 : remain; }; } int main(int argc, char* argv[]) { vector<Message> inputs; Game game; inputs = ParseInput(); game.replay(inputs); init(game); MaxProbabilityBot bot(5); Output(bot.play(game)); }
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metrics/power/power_metrics_reporter.h" #include <memory> #include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/lifetime/browser_shutdown.h" #include "chrome/browser/metrics/usage_scenario/usage_scenario_data_store.h" #include "chrome/browser/performance_monitor/process_monitor.h" #include "components/ukm/test_ukm_recorder.h" #include "services/metrics/public/cpp/metrics_utils.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "testing/gtest/include/gtest/gtest.h" namespace { constexpr const char* kBatteryDischargeRateHistogramName = "Power.BatteryDischargeRate2"; constexpr const char* kBatteryDischargeModeHistogramName = "Power.BatteryDischargeMode"; constexpr base::TimeDelta kExpectedMetricsCollectionInterval = base::TimeDelta::FromSeconds(120); constexpr double kTolerableTimeElapsedRatio = 0.10; constexpr double kTolerablePositiveDrift = 1 + kTolerableTimeElapsedRatio; constexpr double kTolerableNegativeDrift = 1 - kTolerableTimeElapsedRatio; using UkmEntry = ukm::builders::PowerUsageScenariosIntervalData; class PowerMetricsReporterAccess : public PowerMetricsReporter { public: using PowerMetricsReporter::BatteryDischargeMode; static void ReportBatteryHistograms( base::TimeDelta sampling_interval, base::TimeDelta interval_duration, BatteryDischargeMode discharge_mode, base::Optional<int64_t> discharge_rate_during_interval) { PowerMetricsReporter::ReportBatteryHistograms( sampling_interval, interval_duration, discharge_mode, std::move(discharge_rate_during_interval)); } }; // TODO(sebmarchand|etiennep): Move this to a test util file. class FakeBatteryLevelProvider : public BatteryLevelProvider { public: explicit FakeBatteryLevelProvider( std::queue<BatteryLevelProvider::BatteryState>* battery_states) : battery_states_(battery_states) {} void GetBatteryState( base::OnceCallback<void(const BatteryState&)> callback) override { DCHECK(!battery_states_->empty()); BatteryLevelProvider::BatteryState state = battery_states_->front(); battery_states_->pop(); std::move(callback).Run(state); } private: std::queue<BatteryLevelProvider::BatteryState>* battery_states_; }; class TestProcessMonitor : public performance_monitor::ProcessMonitor { public: TestProcessMonitor() = default; TestProcessMonitor(const TestProcessMonitor& rhs) = delete; TestProcessMonitor& operator=(const TestProcessMonitor& rhs) = delete; ~TestProcessMonitor() override = default; // Call OnAggregatedMetricsSampled for all the observers with |metrics| as an // argument. void NotifyObserversForOnAggregatedMetricsSampled(const Metrics& metrics) { for (auto& obs : GetObserversForTesting()) obs.OnAggregatedMetricsSampled(metrics); } base::TimeDelta GetScheduledSamplingInterval() const override { return kExpectedMetricsCollectionInterval; } }; class TestUsageScenarioDataStoreImpl : public UsageScenarioDataStoreImpl { public: TestUsageScenarioDataStoreImpl() = default; TestUsageScenarioDataStoreImpl(const TestUsageScenarioDataStoreImpl& rhs) = delete; TestUsageScenarioDataStoreImpl& operator=( const TestUsageScenarioDataStoreImpl& rhs) = delete; ~TestUsageScenarioDataStoreImpl() override = default; IntervalData ResetIntervalData() override { return fake_data_; } void SetIntervalDataToReturn(IntervalData data) { fake_data_ = data; } private: IntervalData fake_data_; }; // This doesn't use the typical {class being tested}Test name pattern because // there's already a PowerMetricsReporterTest class in the chromeos namespace // and this conflicts with it. class PowerMetricsReporterUnitTest : public testing::Test { public: PowerMetricsReporterUnitTest() = default; PowerMetricsReporterUnitTest(const PowerMetricsReporterUnitTest& rhs) = delete; PowerMetricsReporterUnitTest& operator=( const PowerMetricsReporterUnitTest& rhs) = delete; ~PowerMetricsReporterUnitTest() override = default; void SetUp() override { // Start with a full battery. battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 1.0, true, base::TimeTicks::Now()}); std::unique_ptr<BatteryLevelProvider> battery_provider = std::make_unique<FakeBatteryLevelProvider>(&battery_states_); battery_provider_ = battery_provider.get(); base::RunLoop run_loop; power_metrics_reporter_ = std::make_unique<PowerMetricsReporter>( data_store_.AsWeakPtr(), std::move(battery_provider)); power_metrics_reporter_->OnFirstSampleForTesting(run_loop.QuitClosure()); run_loop.Run(); } void WaitForNextSample( const performance_monitor::ProcessMonitor::Metrics& metrics) { base::RunLoop run_loop; power_metrics_reporter_->OnNextSampleForTesting(run_loop.QuitClosure()); process_monitor_.NotifyObserversForOnAggregatedMetricsSampled(metrics); run_loop.Run(); } protected: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; TestProcessMonitor process_monitor_; TestUsageScenarioDataStoreImpl data_store_; std::queue<BatteryLevelProvider::BatteryState> battery_states_; std::unique_ptr<PowerMetricsReporter> power_metrics_reporter_; BatteryLevelProvider* battery_provider_; base::HistogramTester histogram_tester_; ukm::TestAutoSetUkmRecorder test_ukm_recorder_; }; } // namespace TEST_F(PowerMetricsReporterUnitTest, UKMs) { UsageScenarioDataStore::IntervalData fake_interval_data; int fake_value = 42; fake_interval_data.uptime_at_interval_end = base::TimeDelta::FromHours(++fake_value); fake_interval_data.max_tab_count = ++fake_value; fake_interval_data.max_visible_window_count = ++fake_value; fake_interval_data.top_level_navigation_count = ++fake_value; fake_interval_data.tabs_closed_during_interval = ++fake_value; fake_interval_data.user_interaction_count = ++fake_value; fake_interval_data.time_playing_video_full_screen_single_monitor = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.time_with_open_webrtc_connection = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.source_id_for_longest_visible_origin = ++fake_value; fake_interval_data.source_id_for_longest_visible_origin_duration = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.time_playing_video_in_visible_tab = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.time_since_last_user_interaction_with_browser = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.time_capturing_video = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.time_playing_audio = base::TimeDelta::FromSeconds(++fake_value); fake_interval_data.longest_visible_origin_duration = base::TimeDelta::FromSeconds(++fake_value); task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); // Pretend that the battery has dropped by 50% in 2 minutes, for a rate of // 25% per minute. battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 0.50, true, base::TimeTicks::Now()}); data_store_.SetIntervalDataToReturn(fake_interval_data); performance_monitor::ProcessMonitor::Metrics fake_metrics = {}; fake_metrics.cpu_usage = ++fake_value * 0.01; #if defined(OS_MAC) fake_metrics.idle_wakeups = ++fake_value; fake_metrics.package_idle_wakeups = ++fake_value; fake_metrics.energy_impact = ++fake_value; #endif WaitForNextSample(fake_metrics); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_EQ(entries[0]->source_id, fake_interval_data.source_id_for_longest_visible_origin); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kUptimeSecondsName, ukm::GetExponentialBucketMinForUserTiming( fake_interval_data.uptime_at_interval_end.InSeconds())); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeRateName, 2500); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeModeName, static_cast<int64_t>( PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kCPUTimeMsName, kExpectedMetricsCollectionInterval.InSeconds() * 1000 * fake_metrics.cpu_usage); #if defined(OS_MAC) test_ukm_recorder_.ExpectEntryMetric(entries[0], UkmEntry::kIdleWakeUpsName, fake_metrics.idle_wakeups); test_ukm_recorder_.ExpectEntryMetric(entries[0], UkmEntry::kPackageExitsName, fake_metrics.package_idle_wakeups); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kEnergyImpactScoreName, fake_metrics.energy_impact); #endif test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kMaxTabCountName, ukm::GetExponentialBucketMinForCounts1000( fake_interval_data.max_tab_count)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kMaxVisibleWindowCountName, ukm::GetExponentialBucketMin(fake_interval_data.max_visible_window_count, 1.05)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kTabClosedName, ukm::GetExponentialBucketMinForCounts1000( fake_interval_data.tabs_closed_during_interval)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kTopLevelNavigationEventsName, ukm::GetExponentialBucketMinForCounts1000( fake_interval_data.top_level_navigation_count)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kUserInteractionCountName, ukm::GetExponentialBucketMinForCounts1000( fake_interval_data.user_interaction_count)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kFullscreenVideoSingleMonitorSecondsName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.time_playing_video_full_screen_single_monitor)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kTimeWithOpenWebRTCConnectionSecondsName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.time_with_open_webrtc_connection)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kTimePlayingVideoInVisibleTabName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.time_playing_video_in_visible_tab)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kIntervalDurationSecondsName, kExpectedMetricsCollectionInterval.InSeconds()); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kTimeSinceInteractionWithBrowserSecondsName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.time_since_last_user_interaction_with_browser)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kVideoCaptureSecondsName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.time_capturing_video)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBrowserShuttingDownName, false); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kPlayingAudioSecondsName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.time_playing_audio)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kOriginVisibilityTimeSecondsName, PowerMetricsReporter::GetBucketForSampleForTesting( fake_interval_data.longest_visible_origin_duration)); histogram_tester_.ExpectUniqueSample(kBatteryDischargeRateHistogramName, 2500, 1); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 1); } TEST_F(PowerMetricsReporterUnitTest, UKMsBrowserShuttingDown) { UsageScenarioDataStore::IntervalData fake_interval_data = {}; fake_interval_data.source_id_for_longest_visible_origin = 42; task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 0.50, true, base::TimeTicks::Now()}); data_store_.SetIntervalDataToReturn(fake_interval_data); performance_monitor::ProcessMonitor::Metrics fake_metrics = {}; fake_metrics.cpu_usage = 0.5; #if defined(OS_MAC) fake_metrics.idle_wakeups = 42; fake_metrics.package_idle_wakeups = 43; fake_metrics.energy_impact = 44; #endif { auto fake_shutdown = browser_shutdown::SetShutdownTypeForTesting( browser_shutdown::ShutdownType::kBrowserExit); EXPECT_TRUE(browser_shutdown::HasShutdownStarted()); WaitForNextSample(fake_metrics); } auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_EQ(entries[0]->source_id, 42); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBrowserShuttingDownName, true); } TEST_F(PowerMetricsReporterUnitTest, UKMsPluggedIn) { // Update the latest reported battery state to pretend that the system isn't // running on battery. power_metrics_reporter_->battery_state_for_testing().on_battery = false; task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); // Push a battery state that indicates that the system is still not running // on battery. battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 1.0, /* on_battery - */ false, base::TimeTicks::Now()}); UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.source_id_for_longest_visible_origin = 42; data_store_.SetIntervalDataToReturn(fake_interval_data); WaitForNextSample({}); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_FALSE(test_ukm_recorder_.EntryHasMetric( entries[0], UkmEntry::kBatteryDischargeRateName)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeModeName, static_cast<int64_t>( PowerMetricsReporterAccess::BatteryDischargeMode::kPluggedIn)); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kPluggedIn, 1); } TEST_F(PowerMetricsReporterUnitTest, UKMsBatteryStateChanges) { task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); // The initial battery state indicates that the system is running on battery, // pretends that this has changed. battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 1.0, /* on_battery - */ false, base::TimeTicks::Now()}); UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.source_id_for_longest_visible_origin = 42; data_store_.SetIntervalDataToReturn(fake_interval_data); WaitForNextSample({}); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_FALSE(test_ukm_recorder_.EntryHasMetric( entries[0], UkmEntry::kBatteryDischargeRateName)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeModeName, static_cast<int64_t>( PowerMetricsReporterAccess::BatteryDischargeMode::kStateChanged)); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kStateChanged, 1); } TEST_F(PowerMetricsReporterUnitTest, UKMsBatteryStateUnavailable) { task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); // A nullopt battery value indicates that the battery level is unavailable. battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, base::nullopt, true, base::TimeTicks::Now()}); UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.source_id_for_longest_visible_origin = 42; data_store_.SetIntervalDataToReturn(fake_interval_data); WaitForNextSample({}); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_FALSE(test_ukm_recorder_.EntryHasMetric( entries[0], UkmEntry::kBatteryDischargeRateName)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeModeName, static_cast<int64_t>(PowerMetricsReporterAccess::BatteryDischargeMode:: kChargeLevelUnavailable)); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kChargeLevelUnavailable, 1); } TEST_F(PowerMetricsReporterUnitTest, UKMsNoBattery) { task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); // Indicates that the system has no battery interface. battery_states_.push(BatteryLevelProvider::BatteryState{ 0, 0, 1.0, false, base::TimeTicks::Now()}); UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.source_id_for_longest_visible_origin = 42; data_store_.SetIntervalDataToReturn(fake_interval_data); WaitForNextSample({}); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_FALSE(test_ukm_recorder_.EntryHasMetric( entries[0], UkmEntry::kBatteryDischargeRateName)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeModeName, static_cast<int64_t>( PowerMetricsReporterAccess::BatteryDischargeMode::kNoBattery)); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kNoBattery, 1); } TEST_F(PowerMetricsReporterUnitTest, UKMsBatteryStateIncrease) { // Set the initial battery level at 50%. power_metrics_reporter_->battery_state_for_testing().charge_level = 0.5; task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); // Set the new battery state at 100%. battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 1.0, true, base::TimeTicks::Now()}); UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.source_id_for_longest_visible_origin = 42; data_store_.SetIntervalDataToReturn(fake_interval_data); WaitForNextSample({}); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); // An increase in charge level is reported as an invalid discharge rate. EXPECT_FALSE(test_ukm_recorder_.EntryHasMetric( entries[0], UkmEntry::kBatteryDischargeRateName)); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kBatteryDischargeModeName, static_cast<int64_t>(PowerMetricsReporterAccess::BatteryDischargeMode:: kInvalidDischargeRate)); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kInvalidDischargeRate, 1); } TEST_F(PowerMetricsReporterUnitTest, BatteryDischargeCaptureIsTooEarly) { PowerMetricsReporterAccess::ReportBatteryHistograms( kExpectedMetricsCollectionInterval, (kExpectedMetricsCollectionInterval * kTolerableNegativeDrift) - base::TimeDelta::FromSeconds(1), PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 2500); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kInvalidInterval, 1); } TEST_F(PowerMetricsReporterUnitTest, BatteryDischargeCaptureIsEarly) { PowerMetricsReporterAccess::ReportBatteryHistograms( kExpectedMetricsCollectionInterval, (kExpectedMetricsCollectionInterval * kTolerableNegativeDrift) + base::TimeDelta::FromSeconds(1), PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 2500); histogram_tester_.ExpectUniqueSample(kBatteryDischargeRateHistogramName, 2500, 1); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 1); } TEST_F(PowerMetricsReporterUnitTest, BatteryDischargeCaptureIsTooLate) { PowerMetricsReporterAccess::ReportBatteryHistograms( kExpectedMetricsCollectionInterval, (kExpectedMetricsCollectionInterval * kTolerablePositiveDrift) + base::TimeDelta::FromSeconds(1), PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 2500); histogram_tester_.ExpectTotalCount(kBatteryDischargeRateHistogramName, 0); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kInvalidInterval, 1); } TEST_F(PowerMetricsReporterUnitTest, BatteryDischargeCaptureIsLate) { PowerMetricsReporterAccess::ReportBatteryHistograms( kExpectedMetricsCollectionInterval, (kExpectedMetricsCollectionInterval * kTolerablePositiveDrift) - base::TimeDelta::FromSeconds(1), PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 2500); histogram_tester_.ExpectUniqueSample(kBatteryDischargeRateHistogramName, 2500, 1); histogram_tester_.ExpectUniqueSample( kBatteryDischargeModeHistogramName, PowerMetricsReporterAccess::BatteryDischargeMode::kDischarging, 1); } TEST_F(PowerMetricsReporterUnitTest, UKMsNoTab) { UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.max_tab_count = 0; fake_interval_data.max_visible_window_count = 0; fake_interval_data.source_id_for_longest_visible_origin = ukm::kInvalidSourceId; task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 0.50, true, base::TimeTicks::Now()}); data_store_.SetIntervalDataToReturn(fake_interval_data); performance_monitor::ProcessMonitor::Metrics fake_metrics = {}; fake_metrics.cpu_usage = 0.5; WaitForNextSample(fake_metrics); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_EQ(entries[0]->source_id, ukm::kInvalidSourceId); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kUptimeSecondsName, ukm::GetExponentialBucketMinForUserTiming( fake_interval_data.uptime_at_interval_end.InSeconds())); } TEST_F(PowerMetricsReporterUnitTest, DurationsLongerThanIntervalAreCapped) { UsageScenarioDataStore::IntervalData fake_interval_data; fake_interval_data.time_playing_video_full_screen_single_monitor = kExpectedMetricsCollectionInterval * 100; task_environment_.FastForwardBy(kExpectedMetricsCollectionInterval); battery_states_.push(BatteryLevelProvider::BatteryState{ 1, 1, 0.50, true, base::TimeTicks::Now()}); data_store_.SetIntervalDataToReturn(fake_interval_data); performance_monitor::ProcessMonitor::Metrics fake_metrics = {}; fake_metrics.cpu_usage = 0.5; WaitForNextSample(fake_metrics); auto entries = test_ukm_recorder_.GetEntriesByName( ukm::builders::PowerUsageScenariosIntervalData::kEntryName); EXPECT_EQ(1u, entries.size()); EXPECT_EQ(entries[0]->source_id, ukm::kInvalidSourceId); test_ukm_recorder_.ExpectEntryMetric( entries[0], UkmEntry::kFullscreenVideoSingleMonitorSecondsName, // Every value greater than |kExpectedMetricsCollectionInterval| should // fall in the same overflow bucket. PowerMetricsReporter::GetBucketForSampleForTesting( kExpectedMetricsCollectionInterval * 2)); }
/****************************************************************************** * Code generated with sympy 1.9 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'Jo_dot_W0project' * ******************************************************************************/ #include "../include/baxter.hpp" void baxter::Baxter::Jo_dot_W0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0) = 0; out(1) = 0; out(2) = 0; out(3) = 0; out(4) = 0; out(5) = 0; out(6) = 0; out(7) = 0; out(8) = 0; out(9) = 0; out(10) = 0; out(11) = 0; out(12) = 0; out(13) = 0; out(14) = 0; out(15) = 0; out(16) = 0; out(17) = 0; out(18) = 0; out(19) = 0; out(20) = 0; } void baxter::Baxter::Jo_dot_BR(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0) = 0; out(1) = 0; out(2) = 0; out(3) = 0; out(4) = 0; out(5) = 0; out(6) = 0; out(7) = 0; out(8) = 0; out(9) = 0; out(10) = 0; out(11) = 0; out(12) = 0; out(13) = 0; out(14) = 0; out(15) = 0; out(16) = 0; out(17) = 0; out(18) = 0; out(19) = 0; out(20) = 0; } void baxter::Baxter::Jo_dot_0(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0) = 0; out(1) = 0; out(2) = 0; out(3) = 0; out(4) = 0; out(5) = 0; out(6) = 0; out(7) = 0; out(8) = 0; out(9) = 0; out(10) = 0; out(11) = 0; out(12) = 0; out(13) = 0; out(14) = 0; out(15) = 0; out(16) = 0; out(17) = 0; out(18) = 0; out(19) = 0; out(20) = 0; } void baxter::Baxter::Jo_dot_1(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)); out(0,1)= 0; out(0,2)= 0; out(0,3)= 0; out(0,4)= 0; out(0,5)= 0; out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)); out(1,1)= 0; out(1,2)= 0; out(1,3) = 0; out(1,4) = 0; out(1,5) = 0; out(1,6) = 0; out(2,0) = 0; out(2,1) = 0; out(2,2) = 0; out(2,3) = 0; out(2,4) = 0; out(2,5) = 0; out(2,6) = 0; } void baxter::Baxter::Jo_dot_2(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)); out(0,1)= -L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)); out(0,2)= 0; out(0,3)= 0; out(0,4)= 0; out(0,5)= 0; out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)); out(1,1)= -L2*(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)); out(1,2)= 0; out(1,3) = 0; out(1,4) = 0; out(1,5) = 0; out(1,6) = 0; out(2,0) = 0; out(2,1) = L2*sin(q(1))*dq(1); out(2,2) = 0; out(2,3) = 0; out(2,4) = 0; out(2,5) = 0; out(2,6) = 0; } void baxter::Baxter::Jo_dot_3(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2))); out(0,1)= -L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)); out(0,2)= L3*(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2))); out(0,3)= 0; out(0,4)= 0; out(0,5)= 0; out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))); out(1,1)= -L2*(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)); out(1,2)= L3*((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2))); out(1,3) = 0; out(1,4) = 0; out(1,5) = 0; out(1,6) = 0; out(2,0) = 0; out(2,1) = L2*sin(q(1))*dq(1) - L3*sin(q(1))*sin(q(2))*dq(2) + L3*cos(q(1))*cos(q(2))*dq(1); out(2,2) = -L3*sin(q(1))*sin(q(2))*dq(1) + L3*cos(q(1))*cos(q(2))*dq(2); out(2,3) = 0; out(2,4) = 0; out(2,5) = 0; out(2,6) = 0; } void baxter::Baxter::Jo_dot_4(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3))); out(0,1)= -L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))); out(0,2)= L3*(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2))) - L4*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*sin(q(3)); out(0,3)= -L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))); out(0,4)= 0; out(0,5)= 0; out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(3))); out(1,1)= -L2*(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))); out(1,2)= L3*((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2))) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(3)); out(1,3) = -L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))); out(1,4) = 0; out(1,5) = 0; out(1,6) = 0; out(2,0) = 0; out(2,1) = L2*sin(q(1))*dq(1) - L3*sin(q(1))*sin(q(2))*dq(2) + L3*cos(q(1))*cos(q(2))*dq(1) - L4*(sin(q(1))*sin(q(2))*sin(q(3))*dq(2) - sin(q(1))*cos(q(2))*cos(q(3))*dq(3) - sin(q(1))*cos(q(3))*dq(1) - sin(q(3))*cos(q(1))*cos(q(2))*dq(1) - sin(q(3))*cos(q(1))*dq(3)); out(2,2) = -L3*sin(q(1))*sin(q(2))*dq(1) + L3*cos(q(1))*cos(q(2))*dq(2) - L4*sin(q(1))*sin(q(2))*sin(q(3))*dq(1) + L4*sin(q(2))*cos(q(1))*cos(q(3))*dq(3) + L4*sin(q(3))*cos(q(1))*cos(q(2))*dq(2); out(2,3) = -L4*(-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1)); out(2,4) = 0; out(2,5) = 0; out(2,6) = 0; } void baxter::Baxter::Jo_dot_5(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3))) + L5*(((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(4))*dq(4) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3)))*cos(q(4))); out(0,1)= -L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))) + L5*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4))); out(0,2)= L3*(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2))) - L4*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*sin(q(3)) + L5*(-(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*cos(q(3))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(3))*cos(q(4))); out(0,3)= -L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))) - L5*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*dq(4) + L5*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(4)); out(0,4)= L5*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(4))); out(0,5)= 0; out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(3))) + L5*(-((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4))); out(1,1)= -L2*(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))) + L5*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4))); out(1,2)= L3*((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2))) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(3)) + L5*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(4))*cos(q(3))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(3))*cos(q(4))); out(1,3) = -L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))) - L5*(((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*dq(4) + L5*(-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(4)); out(1,4) = L5*(-((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4))); out(1,5) = 0; out(1,6) = 0; out(2,0) = 0; out(2,1) = L2*sin(q(1))*dq(1) - L3*sin(q(1))*sin(q(2))*dq(2) + L3*cos(q(1))*cos(q(2))*dq(1) - L4*(sin(q(1))*sin(q(2))*sin(q(3))*dq(2) - sin(q(1))*cos(q(2))*cos(q(3))*dq(3) - sin(q(1))*cos(q(3))*dq(1) - sin(q(3))*cos(q(1))*cos(q(2))*dq(1) - sin(q(3))*cos(q(1))*dq(3)) + L5*(-(sin(q(1))*cos(q(2))*cos(q(3)) + sin(q(3))*cos(q(1)))*sin(q(4))*dq(4) + (-sin(q(1))*sin(q(2))*cos(q(3))*dq(2) - sin(q(1))*sin(q(3))*cos(q(2))*dq(3) - sin(q(1))*sin(q(3))*dq(1) + cos(q(1))*cos(q(2))*cos(q(3))*dq(1) + cos(q(1))*cos(q(3))*dq(3))*cos(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(4) - sin(q(1))*sin(q(4))*cos(q(2))*dq(2) - sin(q(2))*sin(q(4))*cos(q(1))*dq(1)); out(2,2) = -L3*sin(q(1))*sin(q(2))*dq(1) + L3*cos(q(1))*cos(q(2))*dq(2) - L4*sin(q(1))*sin(q(2))*sin(q(3))*dq(1) + L4*sin(q(2))*cos(q(1))*cos(q(3))*dq(3) + L4*sin(q(3))*cos(q(1))*cos(q(2))*dq(2) + L5*(-sin(q(1))*sin(q(2))*cos(q(3))*cos(q(4))*dq(1) - sin(q(1))*sin(q(4))*cos(q(2))*dq(1) - sin(q(2))*sin(q(3))*cos(q(1))*cos(q(4))*dq(3) - sin(q(2))*sin(q(4))*cos(q(1))*cos(q(3))*dq(4) - sin(q(2))*sin(q(4))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*cos(q(4))*dq(2) + cos(q(1))*cos(q(2))*cos(q(4))*dq(4)); out(2,3) = -L4*(-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1)) - L5*(sin(q(1))*cos(q(3)) + sin(q(3))*cos(q(1))*cos(q(2)))*sin(q(4))*dq(4) + L5*(-sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - sin(q(1))*sin(q(3))*dq(3) - sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + cos(q(1))*cos(q(3))*dq(1))*cos(q(4)); out(2,4) = L5*((-sin(q(1))*sin(q(3)) + cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4))*dq(4) + (-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1))*sin(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(1) - sin(q(2))*sin(q(4))*cos(q(1))*dq(4) + cos(q(1))*cos(q(2))*cos(q(4))*dq(2)); out(2,5) = 0; out(2,6) = 0; } void baxter::Baxter::Jo_dot_6(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3))) + L5*(((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(4))*dq(4) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3)))*cos(q(4))); out(0,1)= -L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))) + L5*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4))); out(0,2)= L3*(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2))) - L4*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*sin(q(3)) + L5*(-(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*cos(q(3))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(3))*cos(q(4))); out(0,3)= -L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))) - L5*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*dq(4) + L5*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(4)); out(0,4)= L5*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(4))); out(0,5)= 0; out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(3))) + L5*(-((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4))); out(1,1)= -L2*(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))) + L5*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4))); out(1,2)= L3*((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2))) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(3)) + L5*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(4))*cos(q(3))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(3))*cos(q(4))); out(1,3) = -L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))) - L5*(((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*dq(4) + L5*(-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(4)); out(1,4) = L5*(-((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4))); out(1,5) = 0; out(1,6) = 0; out(2,0) = 0; out(2,1) = L2*sin(q(1))*dq(1) - L3*sin(q(1))*sin(q(2))*dq(2) + L3*cos(q(1))*cos(q(2))*dq(1) - L4*(sin(q(1))*sin(q(2))*sin(q(3))*dq(2) - sin(q(1))*cos(q(2))*cos(q(3))*dq(3) - sin(q(1))*cos(q(3))*dq(1) - sin(q(3))*cos(q(1))*cos(q(2))*dq(1) - sin(q(3))*cos(q(1))*dq(3)) + L5*(-(sin(q(1))*cos(q(2))*cos(q(3)) + sin(q(3))*cos(q(1)))*sin(q(4))*dq(4) + (-sin(q(1))*sin(q(2))*cos(q(3))*dq(2) - sin(q(1))*sin(q(3))*cos(q(2))*dq(3) - sin(q(1))*sin(q(3))*dq(1) + cos(q(1))*cos(q(2))*cos(q(3))*dq(1) + cos(q(1))*cos(q(3))*dq(3))*cos(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(4) - sin(q(1))*sin(q(4))*cos(q(2))*dq(2) - sin(q(2))*sin(q(4))*cos(q(1))*dq(1)); out(2,2) = -L3*sin(q(1))*sin(q(2))*dq(1) + L3*cos(q(1))*cos(q(2))*dq(2) - L4*sin(q(1))*sin(q(2))*sin(q(3))*dq(1) + L4*sin(q(2))*cos(q(1))*cos(q(3))*dq(3) + L4*sin(q(3))*cos(q(1))*cos(q(2))*dq(2) + L5*(-sin(q(1))*sin(q(2))*cos(q(3))*cos(q(4))*dq(1) - sin(q(1))*sin(q(4))*cos(q(2))*dq(1) - sin(q(2))*sin(q(3))*cos(q(1))*cos(q(4))*dq(3) - sin(q(2))*sin(q(4))*cos(q(1))*cos(q(3))*dq(4) - sin(q(2))*sin(q(4))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*cos(q(4))*dq(2) + cos(q(1))*cos(q(2))*cos(q(4))*dq(4)); out(2,3) = -L4*(-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1)) - L5*(sin(q(1))*cos(q(3)) + sin(q(3))*cos(q(1))*cos(q(2)))*sin(q(4))*dq(4) + L5*(-sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - sin(q(1))*sin(q(3))*dq(3) - sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + cos(q(1))*cos(q(3))*dq(1))*cos(q(4)); out(2,4) = L5*((-sin(q(1))*sin(q(3)) + cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4))*dq(4) + (-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1))*sin(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(1) - sin(q(2))*sin(q(4))*cos(q(1))*dq(4) + cos(q(1))*cos(q(2))*cos(q(4))*dq(2)); out(2,5) = 0; out(2,6) = 0; } void baxter::Baxter::Jo_dot_ee(const Vector7d& dq, const Vector7d& q, Matrix_3_7_d& out) { out(0,0)= L1*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3))) + L5*(((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(4))*dq(4) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3)))*cos(q(4))) + L6*((((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(4)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4)))*cos(q(5))*dq(5) - (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(5))*dq(5) + (((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(4))*dq(4) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3)))*cos(q(4)))*sin(q(5)) + (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(3)))*cos(q(5))); out(0,1)= -L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))) + L5*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4))) + L6*(-((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3)))*sin(q(5))*dq(5) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(4))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4)))*cos(q(5))*dq(5) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4)))*sin(q(5)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2)))*cos(q(5))); out(0,2)= L3*(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2))) - L4*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*sin(q(3)) + L5*(-(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*cos(q(3))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(3))*cos(q(4))) + L6*(-(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(3))*sin(q(5))*dq(5) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(3))*cos(q(5))*dq(3) + ((-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(3))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(4)))*cos(q(5))*dq(5) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(3))*cos(q(5)) + (-(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*cos(q(3))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(3))*cos(q(4)))*sin(q(5))); out(0,3)= -L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))) - L5*((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*dq(4) + L5*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(4)) + L6*(-((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*sin(q(5))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*cos(q(4))*cos(q(5))*dq(5) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(5))*dq(5) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(5)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*sin(q(5))*cos(q(4))); out(0,4)= L5*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(4))) + L6*((((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4)))*cos(q(5))*dq(5) + L6*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*cos(q(4)))*sin(q(5)); out(0,5)= L6*(-((((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4)))*sin(q(5))*dq(5) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*cos(q(5))*dq(5) + ((((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4))*dq(4) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4)))*cos(q(5)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) - ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) - (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) - (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*sin(q(5))); out(0,6)= 0; out(1,0)= L1*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0)) - L2*((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*dq(1) + L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1)) + L3*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(3))) + L5*(-((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4))) + L6*((((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4)))*cos(q(5))*dq(5) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(5))*dq(5) + (-((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(4)))*sin(q(5)) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(5))); out(1,1)= -L2*(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*dq(1) - L2*((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1)) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(1) - L3*((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(2) + L3*(-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2)) - L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2))) + L5*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4))) + L6*(-(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2)))*sin(q(5))*dq(5) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(4))*cos(q(1)) + (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4)))*cos(q(5))*dq(5) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(4))*cos(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2))*sin(q(4))*cos(q(1)) - (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(2))*cos(q(3)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(3)))*cos(q(4)))*sin(q(5)) + (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(3) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(3)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1))*cos(q(2)))*cos(q(5))); out(1,2)= L3*((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2))) - L4*(-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(3))*dq(3) - L4*(-(-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)))*sin(q(3)) + L5*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(4))*cos(q(3))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(3))*cos(q(4))) + L6*(-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(3))*sin(q(5))*dq(5) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(3))*cos(q(5))*dq(3) + ((((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*cos(q(3))*cos(q(4)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(4)))*cos(q(5))*dq(5) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*sin(q(3))*cos(q(5)) + (-(((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(3))*cos(q(4))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)))*sin(q(4))*cos(q(3))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(4))*dq(4) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*sin(q(4)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(3))*cos(q(4)))*sin(q(5))); out(1,3) = -L4*(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)))*cos(q(3))) - L5*(((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*dq(4) + L5*(-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*cos(q(4)) + L6*(-(-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(5))*dq(5) - (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*sin(q(4))*sin(q(5))*dq(4) + (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*cos(q(4))*cos(q(5))*dq(5) + (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(5)) + (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) + (-((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) - ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*sin(q(5))*cos(q(4))); out(1,4) = L5*(-((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4))) + L6*(((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4)))*cos(q(5))*dq(5) + L6*(-((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*cos(q(4)) + (((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) - (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*sin(q(4)))*sin(q(5)); out(1,5) = L6*(-(((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*sin(q(4)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*cos(q(4)))*sin(q(5))*dq(5) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3)))*cos(q(5))*dq(5) + (((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2)))*cos(q(4))*dq(4) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1)) + (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3)))*sin(q(4))*dq(4) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2))*dq(2) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*cos(q(1))*dq(1) - ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*sin(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*cos(q(2)))*sin(q(4)) + (-((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(3))*dq(1) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(3))*dq(3) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(3))*cos(q(1)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*sin(q(3))*dq(3) + (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*cos(q(3)))*cos(q(4)))*cos(q(5)) + ((-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(3))*dq(1) + (-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(3))*cos(q(1))*dq(3) - ((0.5)*M_SQRT2*sin(q(0))*dq(0) - 0.5*M_SQRT2*cos(q(0))*dq(0))*cos(q(1))*cos(q(3)) - (-(-0.5*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*sin(q(2)))*cos(q(3))*dq(3) - (((0.5)*M_SQRT2*sin(q(0)) - 0.5*M_SQRT2*cos(q(0)))*cos(q(2))*dq(2) - ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*sin(q(1))*sin(q(2))*dq(2) + ((0.5)*M_SQRT2*sin(q(0)) + (0.5)*M_SQRT2*cos(q(0)))*cos(q(1))*cos(q(2))*dq(1) + (-0.5*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(1))*cos(q(2)) + ((0.5)*M_SQRT2*sin(q(0))*dq(0) + (0.5)*M_SQRT2*cos(q(0))*dq(0))*sin(q(2)))*sin(q(3)))*sin(q(5))); out(1,6) = 0; out(2,0) = 0; out(2,1) = L2*sin(q(1))*dq(1) - L3*sin(q(1))*sin(q(2))*dq(2) + L3*cos(q(1))*cos(q(2))*dq(1) - L4*(sin(q(1))*sin(q(2))*sin(q(3))*dq(2) - sin(q(1))*cos(q(2))*cos(q(3))*dq(3) - sin(q(1))*cos(q(3))*dq(1) - sin(q(3))*cos(q(1))*cos(q(2))*dq(1) - sin(q(3))*cos(q(1))*dq(3)) + L5*(-(sin(q(1))*cos(q(2))*cos(q(3)) + sin(q(3))*cos(q(1)))*sin(q(4))*dq(4) + (-sin(q(1))*sin(q(2))*cos(q(3))*dq(2) - sin(q(1))*sin(q(3))*cos(q(2))*dq(3) - sin(q(1))*sin(q(3))*dq(1) + cos(q(1))*cos(q(2))*cos(q(3))*dq(1) + cos(q(1))*cos(q(3))*dq(3))*cos(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(4) - sin(q(1))*sin(q(4))*cos(q(2))*dq(2) - sin(q(2))*sin(q(4))*cos(q(1))*dq(1)) + L6*(((sin(q(1))*cos(q(2))*cos(q(3)) + sin(q(3))*cos(q(1)))*cos(q(4)) - sin(q(1))*sin(q(2))*sin(q(4)))*cos(q(5))*dq(5) - (sin(q(1))*sin(q(3))*cos(q(2)) - cos(q(1))*cos(q(3)))*sin(q(5))*dq(5) + (-(sin(q(1))*cos(q(2))*cos(q(3)) + sin(q(3))*cos(q(1)))*sin(q(4))*dq(4) + (-sin(q(1))*sin(q(2))*cos(q(3))*dq(2) - sin(q(1))*sin(q(3))*cos(q(2))*dq(3) - sin(q(1))*sin(q(3))*dq(1) + cos(q(1))*cos(q(2))*cos(q(3))*dq(1) + cos(q(1))*cos(q(3))*dq(3))*cos(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(4) - sin(q(1))*sin(q(4))*cos(q(2))*dq(2) - sin(q(2))*sin(q(4))*cos(q(1))*dq(1))*sin(q(5)) + (-sin(q(1))*sin(q(2))*sin(q(3))*dq(2) + sin(q(1))*cos(q(2))*cos(q(3))*dq(3) + sin(q(1))*cos(q(3))*dq(1) + sin(q(3))*cos(q(1))*cos(q(2))*dq(1) + sin(q(3))*cos(q(1))*dq(3))*cos(q(5))); out(2,2) = -L3*sin(q(1))*sin(q(2))*dq(1) + L3*cos(q(1))*cos(q(2))*dq(2) - L4*sin(q(1))*sin(q(2))*sin(q(3))*dq(1) + L4*sin(q(2))*cos(q(1))*cos(q(3))*dq(3) + L4*sin(q(3))*cos(q(1))*cos(q(2))*dq(2) + L5*(-sin(q(1))*sin(q(2))*cos(q(3))*cos(q(4))*dq(1) - sin(q(1))*sin(q(4))*cos(q(2))*dq(1) - sin(q(2))*sin(q(3))*cos(q(1))*cos(q(4))*dq(3) - sin(q(2))*sin(q(4))*cos(q(1))*cos(q(3))*dq(4) - sin(q(2))*sin(q(4))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*cos(q(4))*dq(2) + cos(q(1))*cos(q(2))*cos(q(4))*dq(4)) + L6*((sin(q(2))*cos(q(1))*cos(q(3))*cos(q(4)) + sin(q(4))*cos(q(1))*cos(q(2)))*cos(q(5))*dq(5) + (-sin(q(1))*sin(q(2))*cos(q(3))*cos(q(4))*dq(1) - sin(q(1))*sin(q(4))*cos(q(2))*dq(1) - sin(q(2))*sin(q(3))*cos(q(1))*cos(q(4))*dq(3) - sin(q(2))*sin(q(4))*cos(q(1))*cos(q(3))*dq(4) - sin(q(2))*sin(q(4))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*cos(q(4))*dq(2) + cos(q(1))*cos(q(2))*cos(q(4))*dq(4))*sin(q(5)) - sin(q(1))*sin(q(2))*sin(q(3))*cos(q(5))*dq(1) - sin(q(2))*sin(q(3))*sin(q(5))*cos(q(1))*dq(5) + sin(q(2))*cos(q(1))*cos(q(3))*cos(q(5))*dq(3) + sin(q(3))*cos(q(1))*cos(q(2))*cos(q(5))*dq(2)); out(2,3) = -L4*(-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1)) - L5*(sin(q(1))*cos(q(3)) + sin(q(3))*cos(q(1))*cos(q(2)))*sin(q(4))*dq(4) + L5*(-sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - sin(q(1))*sin(q(3))*dq(3) - sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + cos(q(1))*cos(q(3))*dq(1))*cos(q(4)) + L6*(-(sin(q(1))*sin(q(3)) - cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(5))*dq(5) - (sin(q(1))*cos(q(3)) + sin(q(3))*cos(q(1))*cos(q(2)))*sin(q(4))*sin(q(5))*dq(4) + (sin(q(1))*cos(q(3)) + sin(q(3))*cos(q(1))*cos(q(2)))*cos(q(4))*cos(q(5))*dq(5) + (-sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - sin(q(1))*sin(q(3))*dq(3) - sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + cos(q(1))*cos(q(3))*dq(1))*sin(q(5))*cos(q(4)) + (sin(q(1))*cos(q(2))*cos(q(3))*dq(1) + sin(q(1))*cos(q(3))*dq(3) + sin(q(2))*cos(q(1))*cos(q(3))*dq(2) + sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + sin(q(3))*cos(q(1))*dq(1))*cos(q(5))); out(2,4) = L5*((-sin(q(1))*sin(q(3)) + cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4))*dq(4) + (-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1))*sin(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(1) - sin(q(2))*sin(q(4))*cos(q(1))*dq(4) + cos(q(1))*cos(q(2))*cos(q(4))*dq(2)) + L6*(-(sin(q(1))*sin(q(3)) - cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4)) + sin(q(2))*cos(q(1))*cos(q(4)))*cos(q(5))*dq(5) + L6*((-sin(q(1))*sin(q(3)) + cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4))*dq(4) + (-sin(q(1))*cos(q(2))*cos(q(3))*dq(1) - sin(q(1))*cos(q(3))*dq(3) - sin(q(2))*cos(q(1))*cos(q(3))*dq(2) - sin(q(3))*cos(q(1))*cos(q(2))*dq(3) - sin(q(3))*cos(q(1))*dq(1))*sin(q(4)) - sin(q(1))*sin(q(2))*cos(q(4))*dq(1) - sin(q(2))*sin(q(4))*cos(q(1))*dq(4) + cos(q(1))*cos(q(2))*cos(q(4))*dq(2))*sin(q(5)); out(2,5) = L6*(-((sin(q(1))*sin(q(3)) - cos(q(1))*cos(q(2))*cos(q(3)))*cos(q(4)) + sin(q(2))*sin(q(4))*cos(q(1)))*sin(q(5))*dq(5) + (sin(q(1))*cos(q(3)) + sin(q(3))*cos(q(1))*cos(q(2)))*cos(q(5))*dq(5) + (-(sin(q(1))*sin(q(3)) - cos(q(1))*cos(q(2))*cos(q(3)))*sin(q(4))*dq(4) + (sin(q(1))*cos(q(2))*cos(q(3))*dq(1) + sin(q(1))*cos(q(3))*dq(3) + sin(q(2))*cos(q(1))*cos(q(3))*dq(2) + sin(q(3))*cos(q(1))*cos(q(2))*dq(3) + sin(q(3))*cos(q(1))*dq(1))*cos(q(4)) - sin(q(1))*sin(q(2))*sin(q(4))*dq(1) + sin(q(2))*cos(q(1))*cos(q(4))*dq(4) + sin(q(4))*cos(q(1))*cos(q(2))*dq(2))*cos(q(5)) + (-sin(q(1))*sin(q(3))*cos(q(2))*dq(1) - sin(q(1))*sin(q(3))*dq(3) - sin(q(2))*sin(q(3))*cos(q(1))*dq(2) + cos(q(1))*cos(q(2))*cos(q(3))*dq(3) + cos(q(1))*cos(q(3))*dq(1))*sin(q(5))); out(2,6) = 0; }
#include "caffe2/operators/onnxifi_op.h" namespace caffe2 { namespace { void SetInputTensorDescriptorTypeAndBuffer( const Tensor& cpu_tensor, onnxTensorDescriptorV1* desc) { if (cpu_tensor.template IsType<float>()) { desc->dataType = ONNXIFI_DATATYPE_FLOAT32; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<float>()); } else if (cpu_tensor.template IsType<int32_t>()) { desc->dataType = ONNXIFI_DATATYPE_INT32; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<int32_t>()); } else if (cpu_tensor.template IsType<int8_t>()) { desc->dataType = ONNXIFI_DATATYPE_INT8; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<int8_t>()); } else if (cpu_tensor.template IsType<uint8_t>()) { desc->dataType = ONNXIFI_DATATYPE_UINT8; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<uint8_t>()); } else if (cpu_tensor.template IsType<int64_t>()) { desc->dataType = ONNXIFI_DATATYPE_INT64; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<int64_t>()); } else if (cpu_tensor.template IsType<int16_t>()) { desc->dataType = ONNXIFI_DATATYPE_INT16; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<int16_t>()); } else if (cpu_tensor.template IsType<uint16_t>()) { desc->dataType = ONNXIFI_DATATYPE_UINT16; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<uint16_t>()); } else { CAFFE_THROW( "Unsupported tensor type in ONNXIFI: ", cpu_tensor.dtype().name()); } } void SetInputTensorDescriptorTypeAndBuffer( const int8::Int8TensorCPU& cpu_int8tensor, onnxTensorDescriptorV1* desc) { const Tensor& cpu_tensor = cpu_int8tensor.t; if (cpu_tensor.template IsType<uint8_t>()) { desc->dataType = ONNXIFI_DATATYPE_UINT8; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<uint8_t>()); } else if (cpu_tensor.template IsType<int32_t>()) { desc->dataType = ONNXIFI_DATATYPE_INT32; desc->buffer = reinterpret_cast<onnxPointer>(cpu_tensor.data<int32_t>()); } else { CAFFE_THROW( "Unsupported Int8Tensor type in ONNXIFI: ", cpu_tensor.dtype().name()); } desc->quantizationParams = 1; desc->quantizationAxis = 1; desc->scales = &cpu_int8tensor.scale; desc->biases = &cpu_int8tensor.zero_point; } TypeMeta OnnxifiTypeToDataType(uint64_t onnxifi_type) { static std::map<uint64_t, TypeMeta> data_type_map { {ONNXIFI_DATATYPE_FLOAT32, TypeMeta::Make<float>()}, {ONNXIFI_DATATYPE_INT32, TypeMeta::Make<int>()}, {ONNXIFI_DATATYPE_INT8, TypeMeta::Make<int8_t>()}, {ONNXIFI_DATATYPE_UINT8, TypeMeta::Make<uint8_t>()}, {ONNXIFI_DATATYPE_INT64, TypeMeta::Make<int64_t>()}, {ONNXIFI_DATATYPE_INT16, TypeMeta::Make<int16_t>()}, {ONNXIFI_DATATYPE_UINT16, TypeMeta::Make<uint16_t>()}, }; const auto it = data_type_map.find(onnxifi_type); CAFFE_ENFORCE( it != data_type_map.end(), "Unsupported ONNXIFI data type: ", onnxifi_type); return it->second; } void SetOutputTensorDescriptorTypeAndBuffer( uint64_t onnxifi_type, Tensor* cpu_tensor, onnxTensorDescriptorV1* desc) { desc->dataType = onnxifi_type; desc->buffer = reinterpret_cast<onnxPointer>( cpu_tensor->raw_mutable_data(OnnxifiTypeToDataType(onnxifi_type))); } void SetOutputTensorDescriptorTypeAndBuffer( uint64_t onnxifi_type, int8::Int8TensorCPU* cpu_int8tensor, onnxTensorDescriptorV1* desc) { desc->dataType = onnxifi_type; Tensor* cpu_tensor = &(cpu_int8tensor->t); desc->buffer = reinterpret_cast<onnxPointer>( cpu_tensor->raw_mutable_data(OnnxifiTypeToDataType(onnxifi_type))); desc->quantizationParams = 1; desc->quantizationAxis = 1; desc->scales = &cpu_int8tensor->scale; desc->biases = &cpu_int8tensor->zero_point; } void BlobToTensorDescriptor( const std::string& name, Workspace* ws, onnxTensorDescriptorV1* desc, std::vector<std::vector<uint64_t>>* shapes) { const Blob* blob = ws->GetBlob(name); CAFFE_ENFORCE(blob, "Blob ", name, " doesn't exist"); const bool is_int8tensor = blob->meta().id() == TypeMeta::Id<int8::Int8TensorCPU>(); // Memory type // We only allow weights to be CPU tensor or int8tensor for now CAFFE_ENFORCE( (BlobIsTensorType(*blob, CPU) || BlobIsInt8TensorCPUType(*blob)), "Initialization blob ", name, " needs to be TensorCPU or Int8TensorCPU"); desc->tag = ONNXIFI_TAG_TENSOR_DESCRIPTOR_V1; desc->memoryType = ONNXIFI_MEMORY_TYPE_CPU; if (is_int8tensor) { // Data type const auto& cpu_int8tensor = blob->template Get<int8::Int8TensorCPU>(); const auto& cpu_tensor = cpu_int8tensor.t; SetInputTensorDescriptorTypeAndBuffer(cpu_int8tensor, desc); // Set dims const auto shape = cpu_tensor.sizes(); desc->dimensions = shape.size(); shapes->emplace_back(shape.cbegin(), shape.cend()); desc->shape = shapes->back().data(); } else { // Data type const auto& cpu_tensor = blob->template Get<TensorCPU>(); SetInputTensorDescriptorTypeAndBuffer(cpu_tensor, desc); // Set dims const auto shape = cpu_tensor.sizes(); desc->dimensions = shape.size(); shapes->emplace_back(shape.cbegin(), shape.cend()); desc->shape = shapes->back().data(); desc->quantizationParams = 0; } } } // namespace template <> std::vector<onnxTensorDescriptorV1> OnnxifiOp<CPUContext>::buildInitializationList( Workspace* ws, const std::vector<std::string>& initializers, std::vector<std::string>* weight_names, std::vector<std::vector<uint64_t>>* weight_shapes) { std::unordered_set<std::string> initialization_list( initializers.begin(), initializers.end()); const std::vector<string>& ws_blobs = ws->Blobs(); // Since onnxTensorDescriptorV1.name will point into the memory in // weight_names, we need to prevent weight_names from reallocating by // reserving enough memory ahead of time weight_names->reserve(ws_blobs.size()); std::vector<onnxTensorDescriptorV1> descs; for (const auto& s : ws_blobs) { auto it = initialization_list.find(s); if (it != initialization_list.end()) { weight_names->emplace_back(s); onnxTensorDescriptorV1 tensor_desc; tensor_desc.name = weight_names->back().c_str(); BlobToTensorDescriptor(s, ws, &tensor_desc, weight_shapes); descs.push_back(tensor_desc); initialization_list.erase(it); } } CAFFE_ENFORCE(initialization_list.empty(), "Unfulfilled initialization list"); return descs; } template <> std::vector<int> OnnxifiOp<CPUContext>::extractOutputBatchSizes() const { if (!adjust_output_batch_) { return std::vector<int>(); } CAFFE_ENFORCE_EQ( input_shapes_.size(), InputSize(), "Input shapes and input size don't match. ", input_shapes_.size(), " vs ", InputSize()); CAFFE_ENFORCE_EQ( output_shapes_.size(), OutputSize(), "Output shapes and output size don't match. ", output_shapes_.size(), " vs ", OutputSize()); std::vector<int> adjusted_output_batch; for (const auto& shape : output_shapes_) { if (shape.empty()) { adjusted_output_batch.push_back(0); } else { const auto max_output_batch_size = shape.front(); const auto it = batch_pos_map_.find(max_output_batch_size); if (it == batch_pos_map_.end()) { if (use_onnx_) { // For ONNX path, it's possible that we have output batch size that is // unknown, because we handle the second outout of Concat and Split in // ONNX. But for C2 path, we should not meet with this condition. adjusted_output_batch.push_back(0); continue; } else { CAFFE_THROW("Unknow output max batch size: ", max_output_batch_size); } } auto idx = it->second; CAFFE_ENFORCE_LT(idx, input_shapes_.size(), "index out of bound"); const auto& input_shape = input_shapes_[idx]; // If input real batch size and output max size is the same, we don't need // to adjust max batch size of the output if (input_shape.empty() || input_shape.front() == max_output_batch_size) { adjusted_output_batch.push_back(0); } else { adjusted_output_batch.push_back(input_shape.front()); } } } return adjusted_output_batch; } template <> void OnnxifiOp<CPUContext>::maybeAdjustOutputBatchSizes( const std::vector<int>& real_output_batch_sizes) { CAFFE_ENFORCE_EQ(real_output_batch_sizes.size(), output_shapes_.size()); for (int i = 0; i < real_output_batch_sizes.size(); ++i) { if (!real_output_batch_sizes[i]) { continue; } auto* output_tensor = Output(i); output_tensor->ShrinkTo(real_output_batch_sizes[i]); } } template <> bool OnnxifiOp<CPUContext>::RunOnDevice() { CAFFE_ENFORCE_EQ(input_desc_.size(), InputSize()); input_shapes_.clear(); for (unsigned i = 0U; i < InputSize(); ++i) { const auto& input_tensor = Input(i); const auto tensor_dims = input_tensor.sizes(); auto& tensor_descriptor = input_desc_[i]; tensor_descriptor.tag = ONNXIFI_TAG_TENSOR_DESCRIPTOR_V1; tensor_descriptor.memoryType = ONNXIFI_MEMORY_TYPE_CPU; tensor_descriptor.dimensions = tensor_dims.size(); input_shapes_.emplace_back(tensor_dims.cbegin(), tensor_dims.cend()); tensor_descriptor.shape = input_shapes_.back().data(); SetInputTensorDescriptorTypeAndBuffer(input_tensor, &tensor_descriptor); } CAFFE_ENFORCE_EQ(output_desc_.size(), OutputSize()); output_shapes_.clear(); for (unsigned i = 0U; i < OutputSize(); ++i) { std::vector<size_t> tensor_dims; uint64_t type = SetOutputShapeAndType(i, &tensor_dims); auto& tensor_descriptor = output_desc_[i]; tensor_descriptor.tag = ONNXIFI_TAG_TENSOR_DESCRIPTOR_V1; tensor_descriptor.memoryType = ONNXIFI_MEMORY_TYPE_CPU; tensor_descriptor.dimensions = tensor_dims.size(); CAFFE_ENFORCE( tensor_descriptor.dimensions != 0, tensor_descriptor.name, " has 0 dim"); output_shapes_.emplace_back(tensor_dims.cbegin(), tensor_dims.cend()); tensor_descriptor.shape = output_shapes_.back().data(); std::vector<int64_t> tensor_dims_int64; std::copy(tensor_dims.cbegin(), tensor_dims.cend(), std::back_inserter(tensor_dims_int64)); auto* output_tensor = Output( i, tensor_dims_int64, at::dtype(OnnxifiTypeToDataType(type)).device(CPU)); SetOutputTensorDescriptorTypeAndBuffer( type, output_tensor, &tensor_descriptor); } bool ext_supported = false; onnxMemoryFenceV1 input_fence; onnxMemoryFenceV1 output_fence; std::vector<int> output_batch_sizes; #ifdef ONNXIFI_ENABLE_EXT /** * If onnxifi extension mode is enabled, * and onnxSetIOAndRunGraph is supported in backend, * then we run throw this workflow; * Else we fallback to non-onnxifi-extension workflow. **/ if (onnxSetIOAndRunGraphPointer_ != nullptr) { ext_supported = true; output_fence.tag = ONNXIFI_TAG_MEMORY_FENCE_V1; output_fence.type = ONNXIFI_SYNCHRONIZATION_EVENT; if (enable_tracing_) { traces_.reset(); traces_ = std::shared_ptr<onnxTraceEventList>( new onnxTraceEventList(), [this](onnxTraceEventList* p) { if (p && onnxReleaseTraceEventsPointer_) { CAFFE_ENFORCE_EQ( (*onnxReleaseTraceEventsPointer_)(p), ONNXIFI_STATUS_SUCCESS); } delete p; }); traces_->numEvents = 0; } CAFFE_ENFORCE_EQ( (*onnxSetIOAndRunGraphPointer_)( graph_, input_desc_.size(), input_desc_.data(), output_desc_.size(), output_desc_.data(), &output_fence, traces_.get()), ONNXIFI_STATUS_SUCCESS); output_batch_sizes = extractOutputBatchSizes(); CAFFE_ENFORCE_EQ( lib_->onnxWaitEvent(output_fence.event), ONNXIFI_STATUS_SUCCESS); CAFFE_ENFORCE_EQ( lib_->onnxReleaseEvent(output_fence.event), ONNXIFI_STATUS_SUCCESS); } #endif if (!ext_supported) { CAFFE_ENFORCE_EQ( lib_->onnxSetGraphIO( graph_, input_desc_.size(), input_desc_.data(), output_desc_.size(), output_desc_.data()), ONNXIFI_STATUS_SUCCESS); input_fence.tag = ONNXIFI_TAG_MEMORY_FENCE_V1; input_fence.type = ONNXIFI_SYNCHRONIZATION_EVENT; CAFFE_ENFORCE_EQ( lib_->onnxInitEvent(backend_, &input_fence.event), ONNXIFI_STATUS_SUCCESS); output_fence.tag = ONNXIFI_TAG_MEMORY_FENCE_V1; output_fence.type = ONNXIFI_SYNCHRONIZATION_EVENT; // Call the async run on backend, signal event on input fence and wait for // the event on output fence CAFFE_ENFORCE_EQ( lib_->onnxRunGraph(graph_, &input_fence, &output_fence), ONNXIFI_STATUS_SUCCESS); CAFFE_ENFORCE_EQ( lib_->onnxSignalEvent(input_fence.event), ONNXIFI_STATUS_SUCCESS); output_batch_sizes = extractOutputBatchSizes(); CAFFE_ENFORCE_EQ( lib_->onnxWaitEvent(output_fence.event), ONNXIFI_STATUS_SUCCESS); // Destroy the event objects CAFFE_ENFORCE_EQ( lib_->onnxReleaseEvent(input_fence.event), ONNXIFI_STATUS_SUCCESS); CAFFE_ENFORCE_EQ( lib_->onnxReleaseEvent(output_fence.event), ONNXIFI_STATUS_SUCCESS); } if (adjust_output_batch_) { maybeAdjustOutputBatchSizes(output_batch_sizes); } enable_tracing_ = false; return true; } REGISTER_CPU_OPERATOR(Onnxifi, OnnxifiOp<CPUContext>); OPERATOR_SCHEMA(Onnxifi) .NumInputs(0, INT_MAX) .NumOutputs(0, INT_MAX) .SetDoc(R"DOC( The Onnxifi operator is a black-box operator to lower the computation to Onnxifi backend )DOC") .Arg( "onnx_model", "(string default=\"\") Serialized ONNX model to be converted to backend representation") .Arg( "initializers", "Initialization pair indicating the mapping of the name between NetDef and ONNX model") .Arg( "output_resize_hints", "A list of key/value pairs indicating which input index to look up for real batch size for the given max output batch size"); } // namespace caffe2
// Copyright (c) 2016 Zahra Khatami, Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <hpx/config.hpp> #include <hpx/concurrency/cache_line_data.hpp> #include <hpx/datastructures/tuple.hpp> #include <hpx/iterator_support/traits/is_iterator.hpp> #include <hpx/iterator_support/traits/is_range.hpp> #include <hpx/parallel/util/loop.hpp> #include <hpx/type_support/pack.hpp> #include <algorithm> #include <cstddef> #include <functional> #include <iterator> #include <utility> #include <vector> #if defined(HPX_HAVE_MM_PREFETCH) #if defined(HPX_MSVC) #include <intrin.h> #endif #if defined(HPX_GCC_VERSION) #include <emmintrin.h> #endif #endif namespace hpx { namespace parallel { namespace util { namespace detail { template <typename Itr, typename... Ts> class prefetching_iterator : public std::iterator<std::random_access_iterator_tag, typename std::iterator_traits<Itr>::value_type> { public: typedef Itr base_iterator; typedef std::random_access_iterator_tag iterator_category; typedef typename std::iterator_traits<Itr>::value_type value_type; typedef std::ptrdiff_t difference_type; typedef value_type* pointer; typedef value_type& reference; private: typedef hpx::tuple<std::reference_wrapper<Ts>...> ranges_type; ranges_type rngs_; base_iterator base_; std::size_t chunk_size_; std::size_t range_size_; std::size_t idx_; public: explicit prefetching_iterator(std::size_t idx, base_iterator base, std::size_t chunk_size, std::size_t range_size, ranges_type const& rngs) : rngs_(rngs) , base_(base) , chunk_size_(chunk_size) , range_size_(range_size) , idx_((std::min)(idx, range_size)) { } ranges_type const& ranges() const { return rngs_; } Itr base() const { return base_; } std::size_t chunk_size() const { return chunk_size_; } std::size_t range_size() const { return range_size_; } std::size_t index() const { return idx_; } inline prefetching_iterator& operator+=(difference_type rhs) { std::size_t last = (std::min)(idx_ + rhs * chunk_size_, range_size_); std::advance(base_, last - idx_); idx_ = last; return *this; } inline prefetching_iterator& operator-=(difference_type rhs) { std::size_t first = 0; if (idx_ > rhs * chunk_size_) first = idx_ - rhs * chunk_size_; std::advance(base_, idx_ - first); idx_ = first; return *this; } inline prefetching_iterator& operator++() { *this += 1; return *this; } inline prefetching_iterator& operator--() { *this -= 1; return *this; } inline prefetching_iterator operator++(int) { prefetching_iterator tmp(*this); operator++(); return tmp; } inline prefetching_iterator operator--(int) { prefetching_iterator tmp(*this); operator--(); return tmp; } inline difference_type operator-( const prefetching_iterator& rhs) const { // round up distance to cover all of underlying range return (idx_ - rhs.idx_ + chunk_size_ - 1) / chunk_size_; } inline prefetching_iterator operator+(difference_type rhs) const { prefetching_iterator tmp(*this); tmp += rhs; return tmp; } // FIXME: What happens if the distance is not divisible by the // chunk_size? Should enforce this? inline prefetching_iterator operator-(difference_type rhs) const { prefetching_iterator tmp(*this); tmp -= rhs; return tmp; } friend inline prefetching_iterator operator+( const prefetching_iterator& lhs, difference_type rhs) { return rhs + lhs; } friend inline prefetching_iterator operator-( const prefetching_iterator& lhs, difference_type rhs) { return lhs - rhs; } // FIXME: should other members be compared too? inline bool operator==(const prefetching_iterator& rhs) const { return idx_ == rhs.idx_ && base_ == rhs.base_; } // FIXME: should the base iterators be compared too? inline bool operator!=(const prefetching_iterator& rhs) const { return idx_ != rhs.idx_; } inline bool operator>(const prefetching_iterator& rhs) const { return idx_ > rhs.idx_; } inline bool operator<(const prefetching_iterator& rhs) const { return idx_ < rhs.idx_; } inline bool operator>=(const prefetching_iterator& rhs) const { return idx_ >= rhs.idx_; } inline bool operator<=(const prefetching_iterator& rhs) const { return idx_ <= rhs.idx_; } // FIXME: This looks wrong, it should dispatch to the base iterator // instead. inline std::size_t& operator[](std::size_t) { return idx_; } // FIXME: This looks wrong, it should dispatch to the base iterator // instead. inline std::size_t operator*() const { return idx_; } }; /////////////////////////////////////////////////////////////////////// // Helper class to initialize prefetching_iterator template <typename Itr, typename... Ts> struct prefetcher_context { private: typedef hpx::tuple<std::reference_wrapper<Ts>...> ranges_type; Itr it_begin_; Itr it_end_; ranges_type rngs_; std::size_t chunk_size_; std::size_t range_size_; static constexpr std::size_t sizeof_first_value_type = sizeof(typename hpx::tuple_element<0, ranges_type>::type::type); public: prefetcher_context(Itr begin, Itr end, ranges_type const& rngs, std::size_t p_factor = 1) : it_begin_(begin) , it_end_(end) , rngs_(rngs) , chunk_size_((p_factor * threads::get_cache_line_size()) / sizeof_first_value_type) , range_size_(std::distance(begin, end)) { } prefetching_iterator<Itr, Ts...> begin() { return prefetching_iterator<Itr, Ts...>( 0ull, it_begin_, chunk_size_, range_size_, rngs_); } prefetching_iterator<Itr, Ts...> end() { return prefetching_iterator<Itr, Ts...>( range_size_, it_end_, chunk_size_, range_size_, rngs_); } }; /////////////////////////////////////////////////////////////////////// #if defined(HPX_HAVE_MM_PREFETCH) template <typename... T> HPX_FORCEINLINE void prefetch_addresses(T const&... ts) { int const sequencer[] = { (_mm_prefetch( const_cast<char*>((char const*) &ts), _MM_HINT_T0), 0)..., 0}; (void) sequencer; } template <typename... Ts, std::size_t... Is> HPX_FORCEINLINE void prefetch_containers(hpx::tuple<Ts...> const& t, hpx::util::index_pack<Is...>, std::size_t idx) { prefetch_addresses((hpx::get<Is>(t).get())[idx]...); } #else template <typename... Ts, std::size_t... Is> HPX_FORCEINLINE void prefetch_containers(hpx::tuple<Ts...> const& t, hpx::util::index_pack<Is...>, std::size_t idx) { int const sequencer[] = {(hpx::get<Is>(t).get()[idx], 0)..., 0}; (void) sequencer; } #endif /////////////////////////////////////////////////////////////////////// template <typename Itr, typename... Ts> struct loop<detail::prefetching_iterator<Itr, Ts...>> { typedef detail::prefetching_iterator<Itr, Ts...> iterator_type; typedef typename iterator_type::base_iterator type; typedef typename hpx::util::make_index_pack<sizeof...(Ts)>::type index_pack_type; template <typename End, typename F> static iterator_type call(iterator_type it, End end, F&& f) { for (/**/; it != end; ++it) { Itr base = it.base(); std::size_t j = it.index(); std::size_t last = (std::min)( it.index() + it.chunk_size(), it.range_size()); for (/**/; j != last; (void) ++j, ++base) f(base); if (j != it.range_size()) prefetch_containers(it.ranges(), index_pack_type(), j); } return it; } template <typename End, typename CancelToken, typename F> static iterator_type call( iterator_type it, End end, CancelToken& tok, F&& f) { for (/**/; it != end; ++it) { if (tok.was_cancelled()) break; Itr base = it.base(); std::size_t j = it.index(); std::size_t last = (std::min)( it.index() + it.chunk_size(), it.range_size()); for (/**/; j != last; (void) ++j, ++base) f(base); if (j != it.range_size()) prefetch_containers(it.ranges(), index_pack_type(), j); } return it; } }; /////////////////////////////////////////////////////////////////////// template <typename Itr, typename... Ts> struct loop_n<detail::prefetching_iterator<Itr, Ts...>> { typedef detail::prefetching_iterator<Itr, Ts...> iterator_type; typedef typename iterator_type::base_iterator type; typedef typename hpx::util::make_index_pack<sizeof...(Ts)>::type index_pack_type; template <typename F, typename Pred> static iterator_type call( iterator_type it, std::size_t count, F&& f, Pred) { for (/**/; count != 0; (void) --count, ++it) { Itr base = it.base(); std::size_t j = it.index(); std::size_t last = (std::min)( it.index() + it.chunk_size(), it.range_size()); for (/**/; j != last; (void) ++j, ++base) f(base); if (j != it.range_size()) prefetch_containers(it.ranges(), index_pack_type(), j); } return it; } template <typename CancelToken, typename F, typename Pred> static iterator_type call(iterator_type it, std::size_t count, CancelToken& tok, F&& f, Pred) { for (/**/; count != 0; (void) --count, ++it) { if (tok.was_cancelled()) break; Itr base = it.base(); std::size_t j = it.index(); std::size_t last = (std::min)( it.index() + it.chunk_size(), it.range_size()); for (/**/; j != last; (void) ++j, ++base) f(base); if (j != it.range_size()) prefetch_containers(it.ranges(), index_pack_type(), j); } return it; } }; } // namespace detail /////////////////////////////////////////////////////////////////////////// // function to create a prefetcher_context template <typename Itr, typename... Ts> detail::prefetcher_context<Itr, Ts const...> make_prefetcher_context( Itr base_begin, Itr base_end, std::size_t p_factor, Ts const&... rngs) { static_assert(hpx::traits::is_random_access_iterator<Itr>::value, "Iterators have to be of random access iterator category"); static_assert(hpx::util::all_of<hpx::traits::is_range<Ts>...>::value, "All variadic parameters have to represent ranges"); typedef hpx::tuple<std::reference_wrapper<Ts const>...> ranges_type; auto&& ranges = ranges_type(std::cref(rngs)...); return detail::prefetcher_context<Itr, Ts const...>( base_begin, base_end, std::move(ranges), p_factor); } }}} // namespace hpx::parallel::util
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2017; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 The BitcoinIndia developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); }
#include "stdafx.h" #include "control_path_builder.h" #include "control_manager.h" #include "BaseMonster/base_monster.h" #include "../../game_location_selector.h" #include "../../level_location_selector.h" #include "../../detail_path_manager.h" #include "../../ai_object_location.h" #include "../../ai_space.h" #include "../../movement_manager_space.h" #include "../../level_path_manager.h" #include "../../actor.h" #include "../../Actor_Memory.h" #include "../../visual_memory_manager.h" #ifdef DEBUG extern bool show_restrictions(CRestrictedObject *object); #endif CControlPathBuilder::CControlPathBuilder(CCustomMonster *monster) : CMovementManager(monster) { } CControlPathBuilder::~CControlPathBuilder() { } void CControlPathBuilder::load(LPCSTR section) { } void CControlPathBuilder::reinit() { // todo: remove call twice [CustomMonster reinit && control_manager reinit] inherited::reinit (); inherited_com::reinit (); m_data.use_dest_orientation = false; m_data.dest_orientation.set (0.f,0.f,0.f); m_data.try_min_time = true; m_data.target_position.set (0.f,0.f,0.f); m_data.target_node = u32(-1); m_data.enable = false; m_data.extrapolate = false; m_data.velocity_mask = u32(-1); m_data.desirable_mask = u32(-1); m_data.path_type = MovementManager::ePathTypeLevelPath; m_data.game_graph_target_vertex = u32(-1); } void CControlPathBuilder::update_schedule() { START_PROFILE("Base Monster/Path Builder/Schedule Update"); // the one and only reason is because of the restriction-change, so wait until // position and node will be in valid state if (m_data.path_type != MovementManager::ePathTypePatrolPath) { if (!accessible(m_data.target_position) || ( (m_data.target_node != u32(-1)) && (!accessible(m_data.target_node)) )) { return; } } if (m_data.reset_actuality) make_inactual(); // set enabled enable_movement (m_data.enable); // set params only if enable params if (m_data.enable) { detail().set_path_type (eDetailPathTypeSmooth); // установить direction detail().set_use_dest_orientation (m_data.use_dest_orientation); if (m_data.use_dest_orientation) detail().set_dest_direction (m_data.dest_orientation); detail().set_try_min_time (m_data.try_min_time); extrapolate_path (m_data.extrapolate); detail().set_velocity_mask (m_data.velocity_mask); detail().set_desirable_mask (m_data.desirable_mask); set_path_type (m_data.path_type); if (m_data.path_type == MovementManager::ePathTypeGamePath) { // check if we have alife task if (m_data.game_graph_target_vertex != u32(-1)) { set_game_dest_vertex (GameGraph::_GRAPH_ID(m_data.game_graph_target_vertex)); game_selector().set_selection_type (eSelectionTypeMask); } else // else just wandering through the game graph game_selector().set_selection_type (eSelectionTypeRandomBranching); } else if (m_data.path_type != MovementManager::ePathTypePatrolPath) { // set target // TODO: make it VERIFY // VERIFY3(m_data.target_node != u32(-1), "Error: Object set wrong path params! Object name:",*inherited_com::m_object->cName()); if (m_data.target_node == u32(-1)) return; detail().set_dest_position (m_data.target_position); set_level_dest_vertex (m_data.target_node); } } update_path (); m_man->notify (ControlCom::eventPathUpdated, 0); STOP_PROFILE; } void CControlPathBuilder::on_travel_point_change(const u32 &previous_travel_point_index) { inherited::on_travel_point_change (previous_travel_point_index); m_man->notify (ControlCom::eventTravelPointChange, 0); } void CControlPathBuilder::on_build_path() { m_man->notify (ControlCom::eventPathBuilt, 0); } ////////////////////////////////////////////////////////////////////////// // Special Build Path ////////////////////////////////////////////////////////////////////////// bool CControlPathBuilder::build_special(const Fvector &target, u32 node, u32 vel_mask) { if (!accessible(target)) return false; if (node == u32(-1)) { // нода в прямой видимости? restrictions().add_border(object().Position(), target); node = ai().level_graph().check_position_in_direction(object().ai_location().level_vertex_id(),object().Position(),target); restrictions().remove_border(); if (!ai().level_graph().valid_vertex_id(node) || !accessible(node)) return false; } enable_movement (true); detail().set_velocity_mask (vel_mask); detail().set_desirable_mask (vel_mask); detail().set_try_min_time (false); detail().set_use_dest_orientation (false); detail().set_path_type (eDetailPathTypeSmooth); set_path_type (MovementManager::ePathTypeLevelPath); detail().set_dest_position (target); set_level_dest_vertex (node); set_build_path_at_once (); update_path (); // check if path built successfully if (!path_completed() && (detail().time_path_built() >= Device.dwTimeGlobal)) return true; return false; } ////////////////////////////////////////////////////////////////////////// // Services ////////////////////////////////////////////////////////////////////////// bool CControlPathBuilder::is_path_end(float dist_to_end) { if (!is_path_built()) return false; if (path_completed()) return true; if (!is_moving_on_path()) return true; u32 cur_point_idx = detail().curr_travel_point_index(); u32 path_size = detail().path().size(); if (path_size < 2) return true; if (cur_point_idx + 1 >= path_size) return true; // count distance from current object position to the path end float cur_dist_to_end = object().Position().distance_to(detail().path()[detail().curr_travel_point_index()+1].position); for (u32 i=detail().curr_travel_point_index()+1; i<detail().path().size()-1; i++) { cur_dist_to_end += detail().path()[i].position.distance_to(detail().path()[i+1].position); if (cur_dist_to_end > dist_to_end) break; } if ((cur_dist_to_end < dist_to_end)) return true; return false; } bool CControlPathBuilder::valid_destination(const Fvector &pos, u32 node) { return ( ai().level_graph().valid_vertex_id(node) && ai().level_graph().valid_vertex_position(pos) && ai().level_graph().inside(node, pos) ); } bool CControlPathBuilder::valid_and_accessible(Fvector &pos, u32 node) { if (!valid_destination(pos, node) || !accessible(node)) return false; fix_position(Fvector().set(pos),node,pos); return true; } void CControlPathBuilder::fix_position(const Fvector &pos, u32 node, Fvector &res_pos) { VERIFY(accessible(node)); VERIFY(ai().level_graph().inside(node, pos)); res_pos.set (pos); res_pos.y = ai().level_graph().vertex_plane_y(node,res_pos.x,res_pos.z); #ifdef DEBUG if (!accessible(res_pos)) { u32 level_vertex_id = restrictions().accessible_nearest(Fvector().set(res_pos),res_pos); if (level_vertex_id != node) { Msg ("! src_node[%d] res_node[%d] src_pos[%f,%f,%f] res_pos[%f,%f,%f]",node,level_vertex_id,VPUSH(pos),VPUSH(res_pos)); } VERIFY3((level_vertex_id == node) || show_restrictions(m_restricted_object),"Invalid restrictions (see log for details) for object ",*(CControl_Com::m_object->cName())); } #endif } bool CControlPathBuilder::is_moving_on_path() { return (!detail().completed(inherited_com::m_object->Position()) && enabled()); } bool CControlPathBuilder::get_node_in_radius(u32 src_node, float min_radius, float max_radius, u32 attempts, u32 &dest_node) { Fvector vertex_position = ai().level_graph().vertex_position(src_node); for (u32 i=0; i<attempts; i++) { Fvector dir; dir.random_dir (); dir.normalize (); Fvector new_pos; new_pos.mad (vertex_position, dir, Random.randF(min_radius, max_radius)); restrictions().add_border (vertex_position,new_pos); dest_node = ai().level_graph().check_position_in_direction(src_node, vertex_position, new_pos); restrictions().remove_border (); if (dest_node != u32(-1) && accessible(dest_node)) return true; } return false; } void CControlPathBuilder::make_inactual() { // switch once enable_movement(!enabled()); // switch twice enable_movement(!enabled()); } bool CControlPathBuilder::can_use_distributed_compuations (u32 option) const { if (Actor()->memory().visual().visible_right_now(inherited_com::m_object)) return false; return inherited::can_use_distributed_compuations(option); } u32 CControlPathBuilder::find_nearest_vertex (const u32 &level_vertex_id, const Fvector &target_position, const float &range) { xr_vector<u32> temp; ai().graph_engine().search ( ai().level_graph(), level_vertex_id, level_vertex_id, &temp, GraphEngineSpace::CNearestVertexParameters( target_position, range ) ); VERIFY (!temp.empty()); VERIFY (temp.size() == 1); return (temp.front()); } bool CControlPathBuilder::is_path_built() { return actual_all(); }
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "frc/spline/QuinticHermiteSpline.h" using namespace frc; QuinticHermiteSpline::QuinticHermiteSpline( std::array<double, 3> xInitialControlVector, std::array<double, 3> xFinalControlVector, std::array<double, 3> yInitialControlVector, std::array<double, 3> yFinalControlVector) { const auto hermite = MakeHermiteBasis(); const auto x = ControlVectorFromArrays(xInitialControlVector, xFinalControlVector); const auto y = ControlVectorFromArrays(yInitialControlVector, yFinalControlVector); // Populate first two rows with coefficients. m_coefficients.template block<1, 6>(0, 0) = (hermite * x).transpose(); m_coefficients.template block<1, 6>(1, 0) = (hermite * y).transpose(); // Populate Row 2 and Row 3 with the derivatives of the equations above. // Then populate row 4 and 5 with the second derivatives. for (int i = 0; i < 6; i++) { m_coefficients.template block<2, 1>(2, i) = m_coefficients.template block<2, 1>(0, i) * (5 - i); m_coefficients.template block<2, 1>(4, i) = m_coefficients.template block<2, 1>(2, i) * (5 - i); } }
// Copyright (C) 1997-2018 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <gtest/gtest.h> #include <standards/square.hpp> void test(standards::square const& lat) { EXPECT_EQ(lat.get_length_x() * lat.get_length_y(), lat.num_sites()); EXPECT_EQ(2 * lat.get_length_x() * lat.get_length_y(), lat.num_bonds()); EXPECT_EQ(4, lat.num_neighbors()); std::cout << "[test for sites]\n"; for (unsigned int s = 0; s < lat.num_sites(); ++s) { for (unsigned int k = 0; k < lat.num_neighbors(); ++k) { std::cout << s << ' ' << lat.neighbor(s, k) << ' ' << lat.neighbor_bond(s, k) << std::endl; EXPECT_FALSE(lat.sublattice(s) == lat.sublattice(lat.neighbor(s, k))); EXPECT_TRUE(lat.source(lat.neighbor_bond(s, k)) == s || lat.target(lat.neighbor_bond(s, k)) == s); EXPECT_TRUE(lat.bond_site(lat.neighbor_bond(s, k), 0) == s || lat.bond_site(lat.neighbor_bond(s, k), 1) == s); } } std::cout << "[test for bonds]\n"; for (unsigned int b = 0; b < lat.num_bonds(); ++b) { unsigned int s = lat.source(b); unsigned int t = lat.target(b); std::cout << b << ' ' << s << ' ' << t << std::endl; EXPECT_FALSE(s == t); EXPECT_FALSE(lat.sublattice(s) == lat.sublattice(t)); EXPECT_TRUE(lat.neighbor_bond(s, 0) == b || lat.neighbor_bond(s, 1) == b || lat.neighbor_bond(s, 2) == b || lat.neighbor_bond(s, 3) == b); EXPECT_TRUE(lat.neighbor_bond(t, 0) == b || lat.neighbor_bond(t, 1) == b || lat.neighbor_bond(t, 2) == b || lat.neighbor_bond(t, 3) == b); } std::vector<unsigned int> count(lat.num_sites(), 0); for (unsigned int b = 0; b < lat.num_bonds(); ++b) { ++count[lat.source(b)]; ++count[lat.target(b)]; } for (unsigned int s = 0; s < lat.num_sites(); ++s) { EXPECT_EQ(4, count[s]); } } TEST(SquareTest, Square44) { unsigned int L = 4; unsigned int M = 4; standards::square lat(L, M); EXPECT_EQ(L, lat.get_length_x()); EXPECT_EQ(M, lat.get_length_y()); test(lat); } TEST(SquareTest, Square68) { unsigned int L = 6; unsigned int M = 8; standards::square lat(L, M); EXPECT_EQ(L, lat.get_length_x()); EXPECT_EQ(M, lat.get_length_y()); test(lat); }
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/webgpu/gpu_command_encoder.h" #include "third_party/blink/renderer/bindings/modules/v8/double_sequence_or_gpu_color_dict.h" #include "third_party/blink/renderer/bindings/modules/v8/unsigned_long_enforce_range_sequence_or_gpu_extent_3d_dict.h" #include "third_party/blink/renderer/bindings/modules/v8/unsigned_long_enforce_range_sequence_or_gpu_origin_3d_dict.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_command_buffer_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_command_encoder_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_compute_pass_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_image_copy_buffer.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_image_copy_texture.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_render_pass_color_attachment_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_render_pass_depth_stencil_attachment_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_render_pass_descriptor.h" #include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h" #include "third_party/blink/renderer/modules/webgpu/gpu_buffer.h" #include "third_party/blink/renderer/modules/webgpu/gpu_command_buffer.h" #include "third_party/blink/renderer/modules/webgpu/gpu_compute_pass_encoder.h" #include "third_party/blink/renderer/modules/webgpu/gpu_device.h" #include "third_party/blink/renderer/modules/webgpu/gpu_query_set.h" #include "third_party/blink/renderer/modules/webgpu/gpu_render_pass_encoder.h" #include "third_party/blink/renderer/modules/webgpu/gpu_texture.h" #include "third_party/blink/renderer/modules/webgpu/gpu_texture_view.h" #include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { WGPURenderPassColorAttachmentDescriptor AsDawnType( const GPURenderPassColorAttachmentDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPURenderPassColorAttachmentDescriptor dawn_desc = {}; dawn_desc.attachment = webgpu_desc->attachment()->GetHandle(); dawn_desc.resolveTarget = webgpu_desc->resolveTarget() ? webgpu_desc->resolveTarget()->GetHandle() : nullptr; if (webgpu_desc->loadValue().IsGPULoadOp()) { const WTF::String& gpuLoadOp = webgpu_desc->loadValue().GetAsGPULoadOp(); dawn_desc.loadOp = AsDawnEnum<WGPULoadOp>(gpuLoadOp); } else if (webgpu_desc->loadValue().IsDoubleSequence()) { const Vector<double>& gpuColor = webgpu_desc->loadValue().GetAsDoubleSequence(); dawn_desc.loadOp = WGPULoadOp_Clear; dawn_desc.clearColor = AsDawnColor(gpuColor); } else if (webgpu_desc->loadValue().IsGPUColorDict()) { const GPUColorDict* gpuColor = webgpu_desc->loadValue().GetAsGPUColorDict(); dawn_desc.loadOp = WGPULoadOp_Clear; dawn_desc.clearColor = AsDawnType(gpuColor); } else { NOTREACHED(); } dawn_desc.storeOp = AsDawnEnum<WGPUStoreOp>(webgpu_desc->storeOp()); return dawn_desc; } namespace { WGPURenderPassDepthStencilAttachmentDescriptor AsDawnType( const GPURenderPassDepthStencilAttachmentDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPURenderPassDepthStencilAttachmentDescriptor dawn_desc = {}; dawn_desc.attachment = webgpu_desc->attachment()->GetHandle(); if (webgpu_desc->depthLoadValue().IsGPULoadOp()) { const WTF::String& gpuLoadOp = webgpu_desc->depthLoadValue().GetAsGPULoadOp(); dawn_desc.depthLoadOp = AsDawnEnum<WGPULoadOp>(gpuLoadOp); dawn_desc.clearDepth = 1.0f; } else if (webgpu_desc->depthLoadValue().IsFloat()) { dawn_desc.depthLoadOp = WGPULoadOp_Clear; dawn_desc.clearDepth = webgpu_desc->depthLoadValue().GetAsFloat(); } else { NOTREACHED(); } dawn_desc.depthStoreOp = AsDawnEnum<WGPUStoreOp>(webgpu_desc->depthStoreOp()); if (webgpu_desc->stencilLoadValue().IsGPULoadOp()) { const WTF::String& gpuLoadOp = webgpu_desc->stencilLoadValue().GetAsGPULoadOp(); dawn_desc.stencilLoadOp = AsDawnEnum<WGPULoadOp>(gpuLoadOp); dawn_desc.clearStencil = 0; } else if (webgpu_desc->stencilLoadValue().IsUnsignedLong()) { dawn_desc.stencilLoadOp = WGPULoadOp_Clear; dawn_desc.clearStencil = webgpu_desc->stencilLoadValue().GetAsUnsignedLong(); } else { NOTREACHED(); } dawn_desc.stencilStoreOp = AsDawnEnum<WGPUStoreOp>(webgpu_desc->stencilStoreOp()); return dawn_desc; } WGPUBufferCopyView ValidateAndConvertBufferCopyView( const GPUImageCopyBuffer* webgpu_view, const char** error) { DCHECK(webgpu_view); DCHECK(webgpu_view->buffer()); WGPUBufferCopyView dawn_view = {}; dawn_view.nextInChain = nullptr; dawn_view.buffer = webgpu_view->buffer()->GetHandle(); *error = ValidateTextureDataLayout(webgpu_view, &dawn_view.layout); return dawn_view; } WGPUCommandEncoderDescriptor AsDawnType( const GPUCommandEncoderDescriptor* webgpu_desc, std::string* label) { DCHECK(webgpu_desc); DCHECK(label); WGPUCommandEncoderDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; if (webgpu_desc->hasLabel()) { *label = webgpu_desc->label().Utf8(); dawn_desc.label = label->c_str(); } return dawn_desc; } } // anonymous namespace // static GPUCommandEncoder* GPUCommandEncoder::Create( GPUDevice* device, const GPUCommandEncoderDescriptor* webgpu_desc) { DCHECK(device); DCHECK(webgpu_desc); ALLOW_UNUSED_LOCAL(webgpu_desc); std::string label; WGPUCommandEncoderDescriptor dawn_desc = {}; const WGPUCommandEncoderDescriptor* dawn_desc_ptr = nullptr; if (webgpu_desc) { dawn_desc = AsDawnType(webgpu_desc, &label); dawn_desc_ptr = &dawn_desc; } GPUCommandEncoder* encoder = MakeGarbageCollected<GPUCommandEncoder>( device, device->GetProcs().deviceCreateCommandEncoder(device->GetHandle(), dawn_desc_ptr)); encoder->setLabel(webgpu_desc->label()); return encoder; } GPUCommandEncoder::GPUCommandEncoder(GPUDevice* device, WGPUCommandEncoder command_encoder) : DawnObject<WGPUCommandEncoder>(device, command_encoder) {} GPURenderPassEncoder* GPUCommandEncoder::beginRenderPass( const GPURenderPassDescriptor* descriptor, ExceptionState& exception_state) { DCHECK(descriptor); uint32_t color_attachment_count = static_cast<uint32_t>(descriptor->colorAttachments().size()); // Check loadValue color is correctly formatted before further processing. for (wtf_size_t i = 0; i < color_attachment_count; ++i) { const GPURenderPassColorAttachmentDescriptor* color_attachment = descriptor->colorAttachments()[i]; const GPULoadOpOrDoubleSequenceOrGPUColorDict load_value = color_attachment->loadValue(); if (load_value.IsDoubleSequence() && load_value.GetAsDoubleSequence().size() != 4) { exception_state.ThrowRangeError("loadValue color size must be 4"); return nullptr; } } std::string label; WGPURenderPassDescriptor dawn_desc = {}; dawn_desc.colorAttachmentCount = color_attachment_count; dawn_desc.colorAttachments = nullptr; if (descriptor->hasLabel()) { label = descriptor->label().Utf8(); dawn_desc.label = label.c_str(); } std::unique_ptr<WGPURenderPassColorAttachmentDescriptor[]> color_attachments; if (color_attachment_count > 0) { color_attachments = AsDawnType(descriptor->colorAttachments()); dawn_desc.colorAttachments = color_attachments.get(); } WGPURenderPassDepthStencilAttachmentDescriptor depthStencilAttachment = {}; if (descriptor->hasDepthStencilAttachment()) { depthStencilAttachment = AsDawnType(descriptor->depthStencilAttachment()); dawn_desc.depthStencilAttachment = &depthStencilAttachment; } else { dawn_desc.depthStencilAttachment = nullptr; } if (descriptor->hasOcclusionQuerySet()) { dawn_desc.occlusionQuerySet = AsDawnType(descriptor->occlusionQuerySet()); } else { dawn_desc.occlusionQuerySet = nullptr; } GPURenderPassEncoder* encoder = MakeGarbageCollected<GPURenderPassEncoder>( device_, GetProcs().commandEncoderBeginRenderPass(GetHandle(), &dawn_desc)); encoder->setLabel(descriptor->label()); return encoder; } GPUComputePassEncoder* GPUCommandEncoder::beginComputePass( const GPUComputePassDescriptor* descriptor) { std::string label; WGPUComputePassDescriptor dawn_desc = {}; if (descriptor->hasLabel()) { label = descriptor->label().Utf8(); dawn_desc.label = label.c_str(); } GPUComputePassEncoder* encoder = MakeGarbageCollected<GPUComputePassEncoder>( device_, GetProcs().commandEncoderBeginComputePass(GetHandle(), &dawn_desc)); encoder->setLabel(descriptor->label()); return encoder; } void GPUCommandEncoder::copyBufferToTexture( GPUImageCopyBuffer* source, GPUImageCopyTexture* destination, UnsignedLongEnforceRangeSequenceOrGPUExtent3DDict& copy_size) { WGPUExtent3D dawn_copy_size = AsDawnType(&copy_size, device_); WGPUTextureCopyView dawn_destination = AsDawnType(destination, device_); const char* error = nullptr; WGPUBufferCopyView dawn_source = ValidateAndConvertBufferCopyView(source, &error); if (error) { GetProcs().commandEncoderInjectValidationError(GetHandle(), error); return; } GetProcs().commandEncoderCopyBufferToTexture( GetHandle(), &dawn_source, &dawn_destination, &dawn_copy_size); } void GPUCommandEncoder::copyTextureToBuffer( GPUImageCopyTexture* source, GPUImageCopyBuffer* destination, UnsignedLongEnforceRangeSequenceOrGPUExtent3DDict& copy_size) { WGPUExtent3D dawn_copy_size = AsDawnType(&copy_size, device_); WGPUTextureCopyView dawn_source = AsDawnType(source, device_); const char* error = nullptr; WGPUBufferCopyView dawn_destination = ValidateAndConvertBufferCopyView(destination, &error); if (error) { GetProcs().commandEncoderInjectValidationError(GetHandle(), error); return; } GetProcs().commandEncoderCopyTextureToBuffer( GetHandle(), &dawn_source, &dawn_destination, &dawn_copy_size); } void GPUCommandEncoder::copyTextureToTexture( GPUImageCopyTexture* source, GPUImageCopyTexture* destination, UnsignedLongEnforceRangeSequenceOrGPUExtent3DDict& copy_size) { WGPUTextureCopyView dawn_source = AsDawnType(source, device_); WGPUTextureCopyView dawn_destination = AsDawnType(destination, device_); WGPUExtent3D dawn_copy_size = AsDawnType(&copy_size, device_); GetProcs().commandEncoderCopyTextureToTexture( GetHandle(), &dawn_source, &dawn_destination, &dawn_copy_size); } GPUCommandBuffer* GPUCommandEncoder::finish( const GPUCommandBufferDescriptor* descriptor) { std::string label; WGPUCommandBufferDescriptor dawn_desc = {}; if (descriptor->hasLabel()) { label = descriptor->label().Utf8(); dawn_desc.label = label.c_str(); } return MakeGarbageCollected<GPUCommandBuffer>( device_, GetProcs().commandEncoderFinish(GetHandle(), &dawn_desc)); } } // namespace blink
/** * * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> #include <algorithm> #include <iterator> #include <string> using google::protobuf::Descriptor; using google::protobuf::EnumDescriptor; using google::protobuf::FieldDescriptor; using google::protobuf::FileDescriptor; using google::protobuf::MethodDescriptor; using google::protobuf::ServiceDescriptor; using google::protobuf::FieldOptions; using google::protobuf::OneofDescriptor; using google::protobuf::compiler::CodeGenerator; using google::protobuf::compiler::GeneratorContext; using google::protobuf::compiler::ParseGeneratorParameter; using google::protobuf::compiler::PluginMain; using google::protobuf::io::Printer; using google::protobuf::io::ZeroCopyOutputStream; namespace grpc { namespace web { namespace { using std::string; enum Mode { OP = 0, // first party google3 one platform services GATEWAY = 1, // open-source gRPC Gateway OPJSPB = 2, // first party google3 one platform services with JSPB GRPCWEB = 3, // client using the application/grpc-web wire format }; enum ImportStyle { CLOSURE = 0, // goog.require("grpc.web.*") COMMONJS = 1, // const grpcWeb = require("grpc-web") TYPESCRIPT = 2, // import * as grpcWeb from 'grpc-web' }; const char* kKeyword[] = { "abstract", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "typeof", "var", "void", "volatile", "while", "with", }; bool IsReserved(const string& ident) { for (size_t i = 0; i < sizeof(kKeyword) / sizeof(kKeyword[0]); i++) { if (ident == kKeyword[i]) { return true; } } return false; } string GetModeVar(const Mode mode) { switch (mode) { case OP: return "OP"; case GATEWAY: return "Gateway"; case OPJSPB: return "OPJspb"; case GRPCWEB: return "GrpcWeb"; } return ""; } string GetDeserializeMethodName(const string& mode_var) { if (mode_var == GetModeVar(Mode::OPJSPB)) { return "deserialize"; } return "deserializeBinary"; } string GetSerializeMethodName(const string& mode_var) { if (mode_var == GetModeVar(Mode::OPJSPB)) { return "serialize"; } return "serializeBinary"; } std::string GetSerializeMethodReturnType(const string& mode_var) { if (mode_var == GetModeVar(Mode::OPJSPB)) { return "string"; } return "!Uint8Array"; } string LowercaseFirstLetter(string s) { if (s.empty()) { return s; } s[0] = ::tolower(s[0]); return s; } string Lowercase(string s) { if (s.empty()) { return s; } for (size_t i = 0; i < s.size(); i++) { s[i] = ::tolower(s[i]); } return s; } string UppercaseFirstLetter(string s) { if (s.empty()) { return s; } s[0] = ::toupper(s[0]); return s; } string Uppercase(string s) { if (s.empty()) { return s; } for (size_t i = 0; i < s.size(); i++) { s[i] = ::toupper(s[i]); } return s; } // The following 5 functions were copied from // google/protobuf/src/google/protobuf/stubs/strutil.h inline bool HasPrefixString(const string& str, const string& prefix) { return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0; } inline string StripPrefixString(const string& str, const string& prefix) { if (HasPrefixString(str, prefix)) { return str.substr(prefix.size()); } else { return str; } } inline bool HasSuffixString(const string& str, const string& suffix) { return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; } inline string StripSuffixString(const string& str, const string& suffix) { if (HasSuffixString(str, suffix)) { return str.substr(0, str.size() - suffix.size()); } else { return str; } } void ReplaceCharacters(string *s, const char *remove, char replacewith) { const char *str_start = s->c_str(); const char *str = str_start; for (str = strpbrk(str, remove); str != nullptr; str = strpbrk(str + 1, remove)) { (*s)[str - str_start] = replacewith; } } // The following function was copied from // google/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc string StripProto(const string& filename) { if (HasSuffixString(filename, ".protodevel")) { return StripSuffixString(filename, ".protodevel"); } else { return StripSuffixString(filename, ".proto"); } } // The following 6 functions were copied from // google/protobuf/src/google/protobuf/compiler/js/js_generator.cc char ToLowerASCII(char c) { if (c >= 'A' && c <= 'Z') { return (c - 'A') + 'a'; } else { return c; } } std::vector<string> ParseLowerUnderscore(const string& input) { std::vector<string> words; string running = ""; for (size_t i = 0; i < input.size(); i++) { if (input[i] == '_') { if (!running.empty()) { words.push_back(running); running.clear(); } } else { running += ToLowerASCII(input[i]); } } if (!running.empty()) { words.push_back(running); } return words; } string ToUpperCamel(const std::vector<string>& words) { string result; for (size_t i = 0; i < words.size(); i++) { string word = words[i]; if (word[0] >= 'a' && word[0] <= 'z') { word[0] = (word[0] - 'a') + 'A'; } result += word; } return result; } // Returns the alias we assign to the module of the given .proto filename // when importing. string ModuleAlias(const string& filename) { // This scheme could technically cause problems if a file includes any 2 of: // foo/bar_baz.proto // foo_bar_baz.proto // foo_bar/baz.proto // // We'll worry about this problem if/when we actually see it. This name isn't // exposed to users so we can change it later if we need to. string basename = StripProto(filename); ReplaceCharacters(&basename, "-", '$'); ReplaceCharacters(&basename, "/", '_'); ReplaceCharacters(&basename, ".", '_'); return basename + "_pb"; } string JSMessageType(const Descriptor *desc, const FileDescriptor *file) { string result; if (desc->file() != file) { result = ModuleAlias(desc->file()->name()); } result += StripPrefixString(desc->full_name(), desc->file()->package()); if (!result.empty() && result[0] == '.') { result = result.substr(1); } return result; } string JSElementType(const FieldDescriptor *desc, const FileDescriptor *file) { string js_field_type; switch (desc->type()) { case FieldDescriptor::TYPE_DOUBLE: case FieldDescriptor::TYPE_FLOAT: case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SFIXED32: js_field_type = "number"; break; case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_UINT64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SFIXED64: if (desc->options().jstype() == FieldOptions::JS_STRING) { js_field_type = "string"; } else { js_field_type = "number"; } break; case FieldDescriptor::TYPE_BOOL: js_field_type = "boolean"; break; case FieldDescriptor::TYPE_STRING: js_field_type = "string"; break; case FieldDescriptor::TYPE_BYTES: js_field_type = "Uint8Array | string"; break; case FieldDescriptor::TYPE_ENUM: if (desc->enum_type()->file() != file) { js_field_type = ModuleAlias(desc->enum_type()->file()->name()); } js_field_type += StripPrefixString(desc->enum_type()->full_name(), desc->enum_type()->file()->package()); if (!js_field_type.empty() && js_field_type[0] == '.') { js_field_type = js_field_type.substr(1); } break; case FieldDescriptor::TYPE_MESSAGE: js_field_type = JSMessageType(desc->message_type(), file); break; default: js_field_type = "{}"; break; } return js_field_type; } string JSFieldType(const FieldDescriptor *desc, const FileDescriptor *file) { string js_field_type = JSElementType(desc, file); if (desc->is_map()) { string key_type = JSFieldType(desc->message_type()->field(0), file); string value_type = JSFieldType(desc->message_type()->field(1), file); return "jspb.Map<" + key_type + ", " + value_type + ">"; } if (desc->is_repeated()) { return "Array<" + js_field_type + ">"; } return js_field_type; } string AsObjectFieldType(const FieldDescriptor *desc, const FileDescriptor *file) { if (desc->type() != FieldDescriptor::TYPE_MESSAGE) { return JSFieldType(desc, file); } if (desc->is_map()) { const Descriptor* message = desc->message_type(); string key_type = AsObjectFieldType(message->field(0), file); string value_type = AsObjectFieldType(message->field(1), file); return "Array<[" + key_type + ", " + value_type + "]>"; } string field_type = JSMessageType(desc->message_type(), file) + ".AsObject"; if (desc->is_repeated()) { return "Array<" + field_type + ">"; } return field_type; } string JSElementName(const FieldDescriptor *desc) { return ToUpperCamel(ParseLowerUnderscore(desc->name())); } string JSFieldName(const FieldDescriptor *desc) { string js_field_name = JSElementName(desc); if (desc->is_map()) { js_field_name += "Map"; } else if (desc->is_repeated()) { js_field_name += "List"; } return js_field_name; } // Like ToUpperCamel except the first letter is not converted. string ToCamelCase(const std::vector<string>& words) { if (words.empty()) { return ""; } string result = words[0]; return result + ToUpperCamel(std::vector<string>( words.begin()+1, words.begin()+words.size())); } // Like JSFieldName, but with first letter not uppercased string CamelCaseJSFieldName(const FieldDescriptor *desc) { string js_field_name = ToCamelCase(ParseLowerUnderscore(desc->name())); if (desc->is_map()) { js_field_name += "Map"; } else if (desc->is_repeated()) { js_field_name += "List"; } return js_field_name; } // Returns the name of the message with a leading dot and taking into account // nesting, for example ".OuterMessage.InnerMessage", or returns empty if // descriptor is null. This function does not handle namespacing, only message // nesting. string GetNestedMessageName(const Descriptor* descriptor) { if (descriptor == nullptr) { return ""; } string result = StripPrefixString(descriptor->full_name(), descriptor->file()->package()); // Add a leading dot if one is not already present. if (!result.empty() && result[0] != '.') { result = "." + result; } return result; } // Given a filename like foo/bar/baz.proto, returns the root directory // path ../../ string GetRootPath(const string& from_filename, const string& to_filename) { if (HasPrefixString(to_filename, "google/protobuf")) { // Well-known types (.proto files in the google/protobuf directory) are // assumed to come from the 'google-protobuf' npm package. We may want to // generalize this exception later by letting others put generated code in // their own npm packages. return "google-protobuf/"; } size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/'); if (slashes == 0) { return "./"; } string result = ""; for (size_t i = 0; i < slashes; i++) { result += "../"; } return result; } // Splits path immediately following the final slash, separating it into a // directory and file name component. Directory will contain the last // slash, if it's not empty. // If there is no slash in path, Split returns an empty directory and // basename set to path. // Output values have the property that path = directory + basename. void PathSplit(const string& path, string* directory, string* basename) { string::size_type last_slash = path.rfind('/'); if (last_slash == string::npos) { if (directory) { *directory = ""; } if (basename) { *basename = path; } } else { if (directory) { *directory = path.substr(0, last_slash + 1); } if (basename) { *basename = path.substr(last_slash + 1); } } } // Returns the basename of a file. string GetBasename(string filename) { string basename; PathSplit(filename, nullptr, &basename); return basename; } /* Finds all message types used in all services in the file, and returns them * as a map of fully qualified message type name to message descriptor */ std::map<string, const Descriptor*> GetAllMessages(const FileDescriptor* file) { std::map<string, const Descriptor*> message_types; for (int service_index = 0; service_index < file->service_count(); ++service_index) { const ServiceDescriptor* service = file->service(service_index); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor *method = service->method(method_index); message_types[method->input_type()->full_name()] = method->input_type(); message_types[method->output_type()->full_name()] = method->output_type(); } } return message_types; } void PrintMessagesDeps(Printer* printer, const FileDescriptor* file) { std::map<string, const Descriptor*> messages = GetAllMessages(file); std::map<string, string> vars; for (std::map<string, const Descriptor*>::iterator it = messages.begin(); it != messages.end(); it++) { vars["full_name"] = it->first; printer->Print( vars, "goog.require('proto.$full_name$');\n"); } printer->Print("\n\n\n"); } void PrintCommonJsMessagesDeps(Printer* printer, const FileDescriptor* file) { std::map<string, string> vars; for (int i = 0; i < file->dependency_count(); i++) { const string& name = file->dependency(i)->name(); vars["alias"] = ModuleAlias(name); vars["dep_filename"] = GetRootPath(file->name(), name) + StripProto(name); // we need to give each cross-file import an alias printer->Print( vars, "\nvar $alias$ = require('$dep_filename$_pb.js')\n"); } string package = file->package(); vars["package_name"] = package; if (!package.empty()) { size_t offset = 0; size_t dotIndex = package.find('.'); printer->Print(vars, "const proto = {};\n"); while (dotIndex != string::npos) { vars["current_package_ns"] = package.substr(0, dotIndex); printer->Print(vars, "proto.$current_package_ns$ = {};\n"); offset = dotIndex + 1; dotIndex = package.find(".", offset); } } // need to import the messages from our own file vars["filename"] = GetBasename(StripProto(file->name())); if (!package.empty()) { printer->Print( vars, "proto.$package_name$ = require('./$filename$_pb.js');\n\n"); } else { printer->Print( vars, "const proto = require('./$filename$_pb.js');\n\n"); } } void PrintES6Dependencies(Printer* printer, const FileDescriptor *file) { std::map<string, string> vars; for (int i = 0; i < file->dependency_count(); i++) { const string& name = file->dependency(i)->name(); vars["alias"] = ModuleAlias(name); vars["dep_filename"] = GetRootPath(file->name(), name) + StripProto(name); // we need to give each cross-file import an alias printer->Print( vars, "import * as $alias$ from '$dep_filename$_pb';\n"); } if (file->dependency_count() != 0) { printer->Print("\n"); } } void PrintES6Imports(Printer* printer, const FileDescriptor* file) { std::map<string, string> vars; printer->Print("import * as grpcWeb from 'grpc-web';\n\n"); PrintES6Dependencies(printer, file); std::map<string, const Descriptor*> messages = GetAllMessages(file); for (std::map<string, const Descriptor*>::iterator it = messages.begin(); it != messages.end();) { if (it->second->file() != file) { it = messages.erase(it); } else { it++; } } if (messages.empty()) { return; } std::map<string, const Descriptor*>::iterator it = messages.begin(); vars["base_name"] = GetBasename(StripProto(file->name())); vars["class_name"] = it->second->name(); if (messages.size() == 1) { printer->Print(vars, "import {$class_name$} from './$base_name$_pb';\n\n"); return; } printer->Print("import {\n"); printer->Indent(); printer->Print(vars, "$class_name$"); for (it++; it != messages.end(); it++) { vars["class_name"] = it->second->name(); printer->Print(vars, ",\n$class_name$"); } printer->Outdent(); printer->Print(vars, "} from './$base_name$_pb';\n\n"); } void PrintTypescriptFile(Printer* printer, const FileDescriptor* file, std::map<string, string> vars) { PrintES6Imports(printer, file); for (int service_index = 0; service_index < file->service_count(); ++service_index) { printer->Print("export class "); const ServiceDescriptor* service = file->service(service_index); vars["service_name"] = service->name(); printer->Print(vars, "$service_name$Client {\n"); printer->Indent(); printer->Print( "client_: grpcWeb.AbstractClientBase;\n" "hostname_: string;\n" "credentials_: null | { [index: string]: string; };\n" "options_: null | { [index: string]: string; };\n\n" "constructor (hostname: string,\n" " credentials?: null | { [index: string]: string; },\n" " options?: null | { [index: string]: string; }) {\n"); printer->Indent(); printer->Print("if (!options) options = {};\n"); printer->Print("if (!credentials) credentials = {};\n"); if (vars["mode"] == GetModeVar(Mode::GRPCWEB)) { printer->Print(vars, "options['format'] = '$format$';\n\n"); } printer->Print(vars, "this.client_ = new grpcWeb.$mode$ClientBase(options);\n" "this.hostname_ = hostname;\n" "this.credentials_ = credentials;\n" "this.options_ = options;\n"); printer->Outdent(); printer->Print("}\n\n"); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor* method = service->method(method_index); vars["js_method_name"] = LowercaseFirstLetter(method->name()); vars["method_name"] = method->name(); vars["input_type"] = JSMessageType(method->input_type(), file); vars["output_type"] = JSMessageType(method->output_type(), file); vars["serialize_func_name"] = GetSerializeMethodName(vars["mode"]); vars["deserialize_func_name"] = GetDeserializeMethodName(vars["mode"]); if (!method->client_streaming()) { // TODO(jennyjiang): use methodDescriptor? printer->Print(vars, "methodInfo$method_name$ = " "new grpcWeb.AbstractClientBase.MethodInfo(\n"); printer->Indent(); printer->Print(vars, "$output_type$,\n" "(request: $input_type$) => {\n" " return request.$serialize_func_name$();\n" "},\n" "$output_type$.$deserialize_func_name$\n"); printer->Outdent(); printer->Print(");\n\n"); if (method->server_streaming()) { printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata?: grpcWeb.Metadata) {\n"); printer->Print(vars, "return this.client_.serverStreaming(\n"); printer->Indent(); printer->Print(vars, "this.hostname_ +\n" " '/$package_dot$$service_name$/$method_name$',\n" "request,\n" "metadata || {},\n" "this.methodInfo$method_name$);\n"); printer->Outdent(); printer->Outdent(); printer->Print("}\n\n"); } else { printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata: grpcWeb.Metadata | null): Promise<$output_type$>;\n\n"); printer->Outdent(); printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata: grpcWeb.Metadata | null,\n" "callback: (err: grpcWeb.Error,\n" " response: $output_type$) => void): grpcWeb.ClientReadableStream<$output_type$>;\n\n"); printer->Outdent(); printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata: grpcWeb.Metadata | null,\n" "callback?: (err: grpcWeb.Error,\n" " response: $output_type$) => void) {\n"); printer->Print(vars, "if (callback !== undefined) {\n"); printer->Indent(); printer->Print(vars, "return this.client_.rpcCall(\n"); printer->Indent(); printer->Print(vars, "this.hostname_ +\n" " '/$package_dot$$service_name$/$method_name$',\n" "request,\n" "metadata || {},\n" "this.methodInfo$method_name$,\n" "callback);\n"); printer->Outdent(); printer->Outdent(); printer->Print(vars, "}\n" "return this.client_.unaryCall(\n"); printer->Print(vars, "this.hostname_ +\n" " '/$package_dot$$service_name$/$method_name$',\n" "request,\n" "metadata || {},\n" "this.methodInfo$method_name$);\n"); printer->Outdent(); printer->Print("}\n\n"); } } } printer->Outdent(); printer->Print("}\n\n"); } } void PrintGrpcWebDtsClientClass(Printer* printer, const FileDescriptor* file, const string &client_type) { std::map<string, string> vars; vars["client_type"] = client_type; for (int service_index = 0; service_index < file->service_count(); ++service_index) { printer->Print("export class "); const ServiceDescriptor* service = file->service(service_index); vars["service_name"] = service->name(); printer->Print(vars, "$service_name$$client_type$ {\n"); printer->Indent(); printer->Print( "constructor (hostname: string,\n" " credentials?: null | { [index: string]: string; },\n" " options?: null | { [index: string]: string; });\n\n"); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor* method = service->method(method_index); vars["js_method_name"] = LowercaseFirstLetter(method->name()); vars["input_type"] = JSMessageType(method->input_type(), file); vars["output_type"] = JSMessageType(method->output_type(), file); if (!method->client_streaming()) { if (method->server_streaming()) { printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata?: grpcWeb.Metadata\n"); printer->Outdent(); printer->Print(vars, "): grpcWeb.ClientReadableStream<$output_type$>;\n\n"); } else { if (vars["client_type"] == "PromiseClient") { printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata?: grpcWeb.Metadata\n"); printer->Outdent(); printer->Print(vars, "): Promise<$output_type$>;\n\n"); } else { printer->Print(vars, "$js_method_name$(\n"); printer->Indent(); printer->Print(vars, "request: $input_type$,\n" "metadata: grpcWeb.Metadata | undefined,\n" "callback: (err: grpcWeb.Error,\n" " response: $output_type$) => void\n"); printer->Outdent(); printer->Print(vars, "): grpcWeb.ClientReadableStream<$output_type$>;"); printer->Print("\n\n"); } } } } printer->Outdent(); printer->Print("}\n\n"); } } void PrintGrpcWebDtsFile(Printer* printer, const FileDescriptor* file) { PrintES6Imports(printer, file); PrintGrpcWebDtsClientClass(printer, file, "Client"); PrintGrpcWebDtsClientClass(printer, file, "PromiseClient"); } void PrintProtoDtsEnum(Printer *printer, const EnumDescriptor *desc) { std::map<string, string> vars; vars["enum_name"] = desc->name(); printer->Print(vars, "export enum $enum_name$ { \n"); printer->Indent(); for (int i = 0; i < desc->value_count(); i++) { vars["value_name"] = Uppercase(desc->value(i)->name()); vars["value_number"] = std::to_string(desc->value(i)->number()); printer->Print(vars, "$value_name$ = $value_number$,\n"); } printer->Outdent(); printer->Print("}\n"); } void PrintProtoDtsOneofCase(Printer *printer, const OneofDescriptor *desc) { std::map<string, string> vars; vars["oneof_name"] = ToUpperCamel(ParseLowerUnderscore(desc->name())); vars["oneof_name_upper"] = Uppercase(desc->name()); printer->Print(vars, "export enum $oneof_name$Case { \n"); printer->Indent(); printer->Print(vars, "$oneof_name_upper$_NOT_SET = 0,\n"); for (int i = 0; i < desc->field_count(); i++) { const FieldDescriptor *field = desc->field(i); vars["field_name"] = Uppercase(field->name()); vars["field_number"] = std::to_string(field->number()); printer->Print(vars, "$field_name$ = $field_number$,\n"); } printer->Outdent(); printer->Print("}\n"); } void PrintProtoDtsMessage(Printer *printer, const Descriptor *desc, const FileDescriptor *file) { string class_name = desc->name(); std::map<string, string> vars; vars["class_name"] = class_name; printer->Print(vars, "export class $class_name$ extends jspb.Message {\n"); printer->Indent(); for (int i = 0; i < desc->field_count(); i++) { const FieldDescriptor* field = desc->field(i); vars["js_field_name"] = JSFieldName(field); vars["js_field_type"] = JSFieldType(field, file); if (field->type() != FieldDescriptor::TYPE_MESSAGE || field->is_repeated()) { printer->Print(vars, "get$js_field_name$(): $js_field_type$;\n"); } else { printer->Print(vars, "get$js_field_name$(): $js_field_type$ | undefined;\n"); } if (field->type() == FieldDescriptor::TYPE_BYTES && !field->is_repeated()) { printer->Print(vars, "get$js_field_name$_asU8(): Uint8Array;\n" "get$js_field_name$_asB64(): string;\n"); } if (!field->is_map() && (field->type() != FieldDescriptor::TYPE_MESSAGE || field->is_repeated())) { printer->Print(vars, "set$js_field_name$(value: $js_field_type$): $class_name$;\n"); } else if (!field->is_map()) { printer->Print(vars, "set$js_field_name$(value?: $js_field_type$): $class_name$;\n"); } if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_repeated() && !field->is_map()) { printer->Print(vars, "has$js_field_name$(): boolean;\n"); } if (field->type() == FieldDescriptor::TYPE_MESSAGE || field->is_repeated() || field->is_map()) { printer->Print(vars, "clear$js_field_name$(): $class_name$;\n"); } if (field->is_repeated() && !field->is_map()) { vars["js_field_name"] = JSElementName(field); vars["js_field_type"] = JSElementType(field, file); if (field->type() != FieldDescriptor::TYPE_MESSAGE) { printer->Print(vars, "add$js_field_name$(value: $js_field_type$, " "index?: number): $class_name$;\n"); } else { printer->Print(vars, "add$js_field_name$(value?: $js_field_type$, " "index?: number): $js_field_type$;\n"); } } printer->Print("\n"); } for (int i = 0; i < desc->oneof_decl_count(); i++) { const OneofDescriptor* oneof = desc->oneof_decl(i); vars["js_oneof_name"] = ToUpperCamel(ParseLowerUnderscore(oneof->name())); printer->Print( vars, "get$js_oneof_name$Case(): $class_name$.$js_oneof_name$Case;\n"); printer->Print("\n"); } printer->Print( vars, "serializeBinary(): Uint8Array;\n" "toObject(includeInstance?: boolean): " "$class_name$.AsObject;\n" "static toObject(includeInstance: boolean, msg: $class_name$): " "$class_name$.AsObject;\n" "static serializeBinaryToWriter(message: $class_name$, writer: " "jspb.BinaryWriter): void;\n" "static deserializeBinary(bytes: Uint8Array): $class_name$;\n" "static deserializeBinaryFromReader(message: $class_name$, reader: " "jspb.BinaryReader): $class_name$;\n"); printer->Outdent(); printer->Print("}\n\n"); printer->Print(vars, "export namespace $class_name$ {\n"); printer->Indent(); printer->Print("export type AsObject = {\n"); printer->Indent(); for (int i = 0; i < desc->field_count(); i++) { const FieldDescriptor* field = desc->field(i); string js_field_name = CamelCaseJSFieldName(field); if (IsReserved(js_field_name)) { js_field_name = "pb_" + js_field_name; } vars["js_field_name"] = js_field_name; vars["js_field_type"] = AsObjectFieldType(field, file); if (field->type() != FieldDescriptor::TYPE_MESSAGE || field->is_repeated()) { printer->Print(vars, "$js_field_name$: $js_field_type$,\n"); } else { printer->Print(vars, "$js_field_name$?: $js_field_type$,\n"); } } printer->Outdent(); printer->Print("}\n"); for (int i = 0; i < desc->nested_type_count(); i++) { if (desc->nested_type(i)->options().map_entry()) { continue; } printer->Print("\n"); PrintProtoDtsMessage(printer, desc->nested_type(i), file); } for (int i = 0; i < desc->enum_type_count(); i++) { printer->Print("\n"); PrintProtoDtsEnum(printer, desc->enum_type(i)); } for (int i = 0; i < desc->oneof_decl_count(); i++) { printer->Print("\n"); PrintProtoDtsOneofCase(printer, desc->oneof_decl(i)); } printer->Outdent(); printer->Print("}\n\n"); } void PrintProtoDtsFile(Printer *printer, const FileDescriptor *file) { printer->Print("import * as jspb from \"google-protobuf\"\n\n"); PrintES6Dependencies(printer, file); for (int i = 0; i < file->message_type_count(); i++) { PrintProtoDtsMessage(printer, file->message_type(i), file); } for (int i = 0; i < file->enum_type_count(); i++) { PrintProtoDtsEnum(printer, file->enum_type(i)); } } void PrintFileHeader(Printer* printer, const std::map<string, string>& vars) { printer->Print( vars, "/**\n" " * @fileoverview gRPC-Web generated client stub for $package$\n" " * @enhanceable\n" " * @public\n" " */\n\n" "// GENERATED CODE -- DO NOT EDIT!\n\n\n" "/* eslint-disable */" "//@ts-nocheck\n\n\n"); } void PrintMethodDescriptorFile(Printer* printer, std::map<string, string> vars) { printer->Print( vars, "/**\n" " * @fileoverview gRPC-Web generated MethodDescriptors for $package$\n" " * @enhanceable\n" " * @public\n" " */\n\n" "// GENERATED CODE -- DO NOT EDIT!\n\n\n" "/* eslint-disable */" "//@ts-nocheck\n\n\n"); printer->Print(vars, "goog.provide('proto.$package_dot$$class_name$.$" "method_name$MethodDescriptor');\n\n"); printer->Print(vars, "goog.require('grpc.web.MethodDescriptor');\n"); printer->Print(vars, "goog.require('grpc.web.MethodType');\n"); printer->Print(vars, "goog.require('$in_type$');\n"); printer->Print(vars, "goog.require('$out_type$');\n"); printer->Print(vars, "\n\ngoog.scope(function() {\n\n"); printer->Print( vars, "/**\n" " * @const\n" " * @type {!grpc.web.MethodDescriptor<\n" " * !proto.$in$,\n" " * !proto.$out$>}\n" " */\n" "proto.$package_dot$$class_name$.$method_name$MethodDescriptor = \n"); printer->Indent(); printer->Indent(); printer->Print(vars, "new grpc.web.MethodDescriptor(\n"); printer->Indent(); printer->Indent(); printer->Print(vars, "'/$package_dot$$service_name$/$method_name$',\n" "$method_type$,\n" "$in_type$,\n"); printer->Print(vars, "$out_type$,\n" "/**\n" " * @param {!proto.$in$} request\n"); printer->Print( (" * @return {" + GetSerializeMethodReturnType(vars["mode"]) + "}\n") .c_str()); printer->Print(" */\n" "function(request) {\n"); printer->Print( (" return request." + GetSerializeMethodName(vars["mode"]) + "();\n") .c_str()); printer->Print("},\n"); printer->Print( vars, ("$out_type$." + GetDeserializeMethodName(vars["mode"])).c_str()); printer->Print(vars, ");\n\n\n"); printer->Outdent(); printer->Outdent(); printer->Outdent(); printer->Outdent(); printer->Print("}); // goog.scope\n\n"); } void PrintServiceConstructor(Printer* printer, std::map<string, string> vars) { printer->Print( vars, "/**\n" " * @param {string} hostname\n" " * @param {?Object} credentials\n" " * @param {?Object} options\n" " * @constructor\n" " * @struct\n" " * @final\n" " */\n" "proto.$package_dot$$service_name$Client =\n" " function(hostname, credentials, options) {\n" " if (!options) options = {};\n"); if (vars["mode"] == GetModeVar(Mode::GRPCWEB)) { printer->Print( vars, " options['format'] = '$format$';\n\n"); } printer->Print( vars, " /**\n" " * @private @const {!grpc.web.$mode$ClientBase} The client\n" " */\n" " this.client_ = new grpc.web.$mode$ClientBase(options);\n\n" " /**\n" " * @private @const {string} The hostname\n" " */\n" " this.hostname_ = hostname;\n\n" "};\n\n\n"); } void PrintPromiseServiceConstructor(Printer* printer, std::map<string, string> vars) { printer->Print(vars, "/**\n" " * @param {string} hostname\n" " * @param {?Object} credentials\n" " * @param {?Object} options\n" " * @constructor\n" " * @struct\n" " * @final\n" " */\n" "proto.$package_dot$$service_name$PromiseClient =\n" " function(hostname, credentials, options) {\n" " if (!options) options = {};\n"); if (vars["mode"] == GetModeVar(Mode::GRPCWEB)) { printer->Print(vars, " options['format'] = '$format$';\n\n"); } printer->Print( vars, " /**\n" " * @private @const {!grpc.web.$mode$ClientBase} The client\n" " */\n" " this.client_ = new grpc.web.$mode$ClientBase(options);\n\n" " /**\n" " * @private @const {string} The hostname\n" " */\n" " this.hostname_ = hostname;\n\n" "};\n\n\n"); } void PrintMethodInfo(Printer* printer, std::map<string, string> vars) { // Print MethodDescriptor. if (vars["gen_multiple_files"] == "false") { printer->Print(vars, "/**\n" " * @const\n" " * @type {!grpc.web.MethodDescriptor<\n" " * !proto.$in$,\n" " * !proto.$out$>}\n" " */\n" "const methodDescriptor_$service_name$_$method_name$ = " "new grpc.web.MethodDescriptor(\n"); printer->Indent(); printer->Print(vars, "'/$package_dot$$service_name$/$method_name$',\n" "$method_type$,\n" "$in_type$,\n"); printer->Print(vars, "$out_type$,\n" "/**\n" " * @param {!proto.$in$} request\n"); printer->Print( (" * @return {" + GetSerializeMethodReturnType(vars["mode"]) + "}\n") .c_str()); printer->Print(" */\n" "function(request) {\n"); printer->Print( (" return request." + GetSerializeMethodName(vars["mode"]) + "();\n") .c_str()); printer->Print("},\n"); printer->Print( vars, ("$out_type$." + GetDeserializeMethodName(vars["mode"]) + "\n") .c_str()); printer->Outdent(); printer->Print(vars, ");\n\n\n"); } // Print AbstractClientBase.MethodInfo, which will be deprecated. printer->Print(vars, "/**\n" " * @const\n" " * @type {!grpc.web.AbstractClientBase.MethodInfo<\n" " * !proto.$in$,\n" " * !proto.$out$>}\n" " */\n" "const methodInfo_$service_name$_$method_name$ = " "new grpc.web.AbstractClientBase.MethodInfo(\n"); printer->Indent(); printer->Print(vars, "$out_type$,\n" "/**\n" " * @param {!proto.$in$} request\n"); printer->Print( (" * @return {" + GetSerializeMethodReturnType(vars["mode"]) + "}\n") .c_str()); printer->Print(" */\n" "function(request) {\n"); printer->Print( (" return request." + GetSerializeMethodName(vars["mode"]) + "();\n") .c_str()); printer->Print("},\n"); printer->Print( vars, ("$out_type$." + GetDeserializeMethodName(vars["mode"]) + "\n").c_str()); printer->Outdent(); printer->Print(vars, ");\n\n\n"); } void PrintUnaryCall(Printer* printer, std::map<string, string> vars) { printer->Print( vars, "/**\n" " * @param {!proto.$in$} request The\n" " * request proto\n" " * @param {?Object<string, string>} metadata User defined\n" " * call metadata\n" " * @param {function(?grpc.web.Error," " ?proto.$out$)}\n" " * callback The callback function(error, response)\n" " * @return {!grpc.web.ClientReadableStream<!proto.$out$>|undefined}\n" " * The XHR Node Readable Stream\n" " */\n" "proto.$package_dot$$service_name$Client.prototype.$js_method_name$ =\n"); printer->Indent(); printer->Print(vars, " function(request, metadata, callback) {\n" "return this.client_.rpcCall(this.hostname_ +\n"); printer->Indent(); printer->Indent(); if (vars["mode"] == GetModeVar(Mode::OP) || vars["mode"] == GetModeVar(Mode::OPJSPB)) { printer->Print(vars, "'/$$rpc/$package_dot$$service_name$/$method_name$',\n"); } else { printer->Print(vars, "'/$package_dot$$service_name$/$method_name$',\n"); } printer->Print(vars, "request,\n" "metadata || {},\n" "$method_descriptor$,\n" "callback);\n"); printer->Outdent(); printer->Outdent(); printer->Outdent(); printer->Print("};\n\n\n"); } void PrintPromiseUnaryCall(Printer* printer, std::map<string, string> vars) { printer->Print(vars, "/**\n" " * @param {!proto.$in$} request The\n" " * request proto\n" " * @param {?Object<string, string>} metadata User defined\n" " * call metadata\n" " * @return {!Promise<!proto.$out$>}\n" " * A native promise that resolves to the response\n" " */\n" "proto.$package_dot$$service_name$PromiseClient.prototype" ".$js_method_name$ =\n"); printer->Indent(); printer->Print(vars, " function(request, metadata) {\n" "return this.client_.unaryCall(this.hostname_ +\n"); printer->Indent(); printer->Indent(); if (vars["mode"] == GetModeVar(Mode::OP) || vars["mode"] == GetModeVar(Mode::OPJSPB)) { printer->Print(vars, "'/$$rpc/$package_dot$$service_name$/$method_name$',\n"); } else { printer->Print(vars, "'/$package_dot$$service_name$/$method_name$',\n"); } printer->Print(vars, "request,\n" "metadata || {},\n" "$method_descriptor$);\n"); printer->Outdent(); printer->Outdent(); printer->Outdent(); printer->Print("};\n\n\n"); } void PrintServerStreamingCall(Printer* printer, std::map<string, string> vars) { printer->Print( vars, "/**\n" " * @param {!proto.$in$} request The request proto\n" " * @param {?Object<string, string>} metadata User defined\n" " * call metadata\n" " * @return {!grpc.web.ClientReadableStream<!proto.$out$>}\n" " * The XHR Node Readable Stream\n" " */\n" "proto.$package_dot$$service_name$$client_type$.prototype." "$js_method_name$ =\n"); printer->Indent(); printer->Print( " function(request, metadata) {\n" "return this.client_.serverStreaming(this.hostname_ +\n"); printer->Indent(); printer->Indent(); if (vars["mode"] == GetModeVar(Mode::OP) || vars["mode"] == GetModeVar(Mode::OPJSPB)) { printer->Print(vars, "'/$$rpc/$package_dot$$service_name$/$method_name$',\n"); } else { printer->Print(vars, "'/$package_dot$$service_name$/$method_name$',\n"); } printer->Print(vars, "request,\n" "metadata || {},\n" "$method_descriptor$);\n"); printer->Outdent(); printer->Outdent(); printer->Outdent(); printer->Print("};\n\n\n"); } class GrpcCodeGenerator : public CodeGenerator { public: GrpcCodeGenerator() {} ~GrpcCodeGenerator() override {} bool Generate(const FileDescriptor* file, const string& parameter, GeneratorContext* context, string* error) const override { std::vector<std::pair<string, string> > options; ParseGeneratorParameter(parameter, &options); string file_name; string mode; string import_style_str; ImportStyle import_style; bool generate_dts = false; bool gen_multiple_files = false; for (size_t i = 0; i < options.size(); ++i) { if (options[i].first == "out") { file_name = options[i].second; } else if (options[i].first == "mode") { mode = options[i].second; } else if (options[i].first == "import_style") { import_style_str = options[i].second; } else if (options[i].first == "multiple_files") { gen_multiple_files = options[i].second == "true"; } else { *error = "unsupported options: " + options[i].first; return false; } } if (file_name.empty()) { file_name = StripProto(file->name()) + "_grpc_web_pb.js"; } if (mode.empty()) { *error = "options: mode is required"; return false; } std::map<string, string> vars; std::map<string, string> method_descriptors; string package = file->package(); vars["package"] = package; vars["package_dot"] = package.empty() ? "" : package + '.'; if (mode == "binary") { vars["mode"] = GetModeVar(Mode::OP); } else if (mode == "base64") { vars["mode"] = GetModeVar(Mode::GATEWAY); } else if (mode == "grpcweb" || mode == "grpcwebtext") { vars["mode"] = GetModeVar(Mode::GRPCWEB); vars["format"] = (mode == "grpcweb") ? "binary" : "text"; } else if (mode == "jspb") { vars["mode"] = GetModeVar(Mode::OPJSPB); } else { *error = "options: invalid mode - " + mode; return false; } if (import_style_str == "closure" || import_style_str.empty()) { import_style = ImportStyle::CLOSURE; } else if (import_style_str == "commonjs") { import_style = ImportStyle::COMMONJS; } else if (import_style_str == "commonjs+dts") { import_style = ImportStyle::COMMONJS; generate_dts = true; } else if (import_style_str == "typescript") { import_style = ImportStyle::TYPESCRIPT; string directory; string basename; PathSplit(file->name(), &directory, &basename); file_name = directory + UppercaseFirstLetter(StripProto(basename)) + "ServiceClientPb.ts"; } else { *error = "options: invalid import_style - " + import_style_str; return false; } if (generate_dts || import_style == ImportStyle::TYPESCRIPT) { string proto_dts_file_name = StripProto(file->name()) + "_pb.d.ts"; std::unique_ptr<ZeroCopyOutputStream> proto_dts_output( context->Open(proto_dts_file_name)); Printer proto_dts_printer(proto_dts_output.get(), '$'); PrintProtoDtsFile(&proto_dts_printer, file); } if (!file->service_count()) { // No services, nothing to do. return true; } // Only supports closure for now. if (gen_multiple_files && import_style == ImportStyle::CLOSURE) { for (int i = 0; i < file->service_count(); ++i) { const ServiceDescriptor* service = file->service(i); vars["service_name"] = service->name(); vars["class_name"] = LowercaseFirstLetter(service->name()); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor* method = service->method(method_index); string method_file_name = Lowercase(service->name()) + "_" + Lowercase(method->name()) + "_methoddescriptor.js"; std::unique_ptr<ZeroCopyOutputStream> output( context->Open(method_file_name)); Printer printer(output.get(), '$'); vars["method_name"] = method->name(); vars["in"] = method->input_type()->full_name(); vars["in_type"] = "proto." + method->input_type()->full_name(); vars["out"] = method->output_type()->full_name(); vars["out_type"] = "proto." + method->output_type()->full_name(); vars["method_type"] = method->server_streaming() ? "grpc.web.MethodType.SERVER_STREAMING" : "grpc.web.MethodType.UNARY"; PrintMethodDescriptorFile(&printer, vars); method_descriptors[service->name() + "." + method->name()] = "proto." + vars["package_dot"] + vars["class_name"] + "." + vars["method_name"] + "MethodDescriptor"; } } } std::unique_ptr<ZeroCopyOutputStream> output(context->Open(file_name)); Printer printer(output.get(), '$'); PrintFileHeader(&printer, vars); if (import_style == ImportStyle::TYPESCRIPT) { PrintTypescriptFile(&printer, file, vars); return true; } for (int i = 0; i < file->service_count(); ++i) { const ServiceDescriptor* service = file->service(i); vars["service_name"] = service->name(); switch (import_style) { case ImportStyle::CLOSURE: printer.Print( vars, "goog.provide('proto.$package_dot$$service_name$Client');\n"); printer.Print(vars, "goog.provide('proto.$package_dot$$service_name$" "PromiseClient');\n"); break; case ImportStyle::COMMONJS: break; case ImportStyle::TYPESCRIPT: break; } } printer.Print("\n"); switch (import_style) { case ImportStyle::CLOSURE: if (gen_multiple_files) { std::map<string, string>::iterator it; for (it = method_descriptors.begin(); it != method_descriptors.end(); it++) { vars["import_mtd"] = it->second; printer.Print(vars, "goog.require('$import_mtd$');\n"); } } else { printer.Print(vars, "goog.require('grpc.web.MethodDescriptor');\n"); printer.Print(vars, "goog.require('grpc.web.MethodType');\n"); } printer.Print(vars, "goog.require('grpc.web.$mode$ClientBase');\n"); printer.Print(vars, "goog.require('grpc.web.AbstractClientBase');\n"); printer.Print(vars, "goog.require('grpc.web.ClientReadableStream');\n"); printer.Print(vars, "goog.require('grpc.web.Error');\n"); PrintMessagesDeps(&printer, file); printer.Print("goog.scope(function() {\n\n"); break; case ImportStyle::COMMONJS: printer.Print(vars, "const grpc = {};\n"); printer.Print(vars, "grpc.web = require('grpc-web');\n\n"); PrintCommonJsMessagesDeps(&printer, file); break; case ImportStyle::TYPESCRIPT: break; } for (int service_index = 0; service_index < file->service_count(); ++service_index) { const ServiceDescriptor* service = file->service(service_index); vars["service_name"] = service->name(); PrintServiceConstructor(&printer, vars); PrintPromiseServiceConstructor(&printer, vars); for (int method_index = 0; method_index < service->method_count(); ++method_index) { const MethodDescriptor* method = service->method(method_index); const Descriptor* input_type = method->input_type(); const Descriptor* output_type = method->output_type(); vars["js_method_name"] = LowercaseFirstLetter(method->name()); vars["method_name"] = method->name(); vars["in"] = input_type->full_name(); vars["out"] = output_type->full_name(); vars["gen_multiple_files"] = gen_multiple_files ? "true" : "false"; vars["method_descriptor"] = gen_multiple_files ? method_descriptors[service->name() + "." + method->name()] : "methodDescriptor_" + service->name() + "_" + method->name(); // Cross-file ref in CommonJS needs to use the module alias instead // of the global name. if (import_style == ImportStyle::COMMONJS && input_type->file() != file) { vars["in_type"] = ModuleAlias(input_type->file()->name()) + GetNestedMessageName(input_type); } else { vars["in_type"] = "proto." + input_type->full_name(); } if (import_style == ImportStyle::COMMONJS && output_type->file() != file) { vars["out_type"] = ModuleAlias(output_type->file()->name()) + GetNestedMessageName(output_type); } else { vars["out_type"] = "proto." + output_type->full_name(); } // Client streaming is not supported yet if (!method->client_streaming()) { if (method->server_streaming()) { vars["method_type"] = "grpc.web.MethodType.SERVER_STREAMING"; PrintMethodInfo(&printer, vars); vars["client_type"] = "Client"; PrintServerStreamingCall(&printer, vars); vars["client_type"] = "PromiseClient"; PrintServerStreamingCall(&printer, vars); } else { vars["method_type"] = "grpc.web.MethodType.UNARY"; PrintMethodInfo(&printer, vars); PrintUnaryCall(&printer, vars); PrintPromiseUnaryCall(&printer, vars); } } } } switch (import_style) { case ImportStyle::CLOSURE: printer.Print("}); // goog.scope\n\n"); break; case ImportStyle::COMMONJS: if (!vars["package"].empty()) { printer.Print(vars, "module.exports = proto.$package$;\n\n"); } else { printer.Print(vars, "module.exports = proto;\n\n"); } break; case ImportStyle::TYPESCRIPT: break; } if (generate_dts) { string grpcweb_dts_file_name = StripProto(file->name()) + "_grpc_web_pb.d.ts"; string proto_dts_file_name = StripProto(file->name()) + "_pb.d.ts"; std::unique_ptr<ZeroCopyOutputStream> grpcweb_dts_output( context->Open(grpcweb_dts_file_name)); Printer grpcweb_dts_printer(grpcweb_dts_output.get(), '$'); PrintGrpcWebDtsFile(&grpcweb_dts_printer, file); } return true; } }; } // namespace } // namespace web } // namespace grpc int main(int argc, char* argv[]) { grpc::web::GrpcCodeGenerator generator; PluginMain(argc, argv, &generator); return 0; }
//--------------------------------------------------------------------------- #include "logger.h" #include <cstring> //--------------------------------------------------------------------------- namespace lsm { namespace tools { //--------------------------------------------------------------------------- Logger g_logger; //--------------------------------------------------------------------------- __thread char t_error_buf[512]; //--------------------------------------------------------------------------- Logger::Logger() { logger_ = base::Logger::stdout_logger_mt(); } //--------------------------------------------------------------------------- const char* Logger::OsError(int e) { return strerror_r(e, t_error_buf, sizeof(t_error_buf)); } //--------------------------------------------------------------------------- }//namespace tools }//namespace lsm //---------------------------------------------------------------------------
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). #include "table/block_based/block_based_table_reader.h" #include "db/table_properties_collector.h" #include "file/file_util.h" #include "options/options_helper.h" #include "port/port.h" #include "port/stack_trace.h" #include "rocksdb/file_system.h" #include "table/block_based/block_based_table_builder.h" #include "table/block_based/block_based_table_factory.h" #include "table/block_based/partitioned_index_iterator.h" #include "table/format.h" #include "test_util/testharness.h" #include "test_util/testutil.h" #include "util/random.h" namespace ROCKSDB_NAMESPACE { class BlockBasedTableReaderTest : public testing::Test, public testing::WithParamInterface<std::tuple< CompressionType, bool, BlockBasedTableOptions::IndexType, bool>> { protected: CompressionType compression_type_; bool use_direct_reads_; void SetUp() override { BlockBasedTableOptions::IndexType index_type; bool no_block_cache; std::tie(compression_type_, use_direct_reads_, index_type, no_block_cache) = GetParam(); SetupSyncPointsToMockDirectIO(); test_dir_ = test::PerThreadDBPath("block_based_table_reader_test"); env_ = Env::Default(); fs_ = FileSystem::Default(); ASSERT_OK(fs_->CreateDir(test_dir_, IOOptions(), nullptr)); BlockBasedTableOptions opts; opts.index_type = index_type; opts.no_block_cache = no_block_cache; table_factory_.reset( static_cast<BlockBasedTableFactory*>(NewBlockBasedTableFactory(opts))); } void TearDown() override { EXPECT_OK(DestroyDir(env_, test_dir_)); } // Creates a table with the specificied key value pairs (kv). void CreateTable(const std::string& table_name, const CompressionType& compression_type, const std::map<std::string, std::string>& kv) { std::unique_ptr<WritableFileWriter> writer; NewFileWriter(table_name, &writer); // Create table builder. Options options; ImmutableCFOptions ioptions(options); InternalKeyComparator comparator(options.comparator); ColumnFamilyOptions cf_options; MutableCFOptions moptions(cf_options); std::vector<std::unique_ptr<IntTblPropCollectorFactory>> factories; std::unique_ptr<TableBuilder> table_builder(table_factory_->NewTableBuilder( TableBuilderOptions(ioptions, moptions, comparator, &factories, compression_type, 0 /* sample_for_compression */, CompressionOptions(), false /* skip_filters */, kDefaultColumnFamilyName, -1 /* level */), 0 /* column_family_id */, writer.get())); // Build table. for (auto it = kv.begin(); it != kv.end(); it++) { std::string k = ToInternalKey(it->first); std::string v = it->second; table_builder->Add(k, v); } ASSERT_OK(table_builder->Finish()); } void NewBlockBasedTableReader(const FileOptions& foptions, const ImmutableCFOptions& ioptions, const InternalKeyComparator& comparator, const std::string& table_name, std::unique_ptr<BlockBasedTable>* table) { std::unique_ptr<RandomAccessFileReader> file; NewFileReader(table_name, foptions, &file); uint64_t file_size = 0; ASSERT_OK(env_->GetFileSize(Path(table_name), &file_size)); std::unique_ptr<TableReader> table_reader; ReadOptions ro; const auto* table_options = table_factory_->GetOptions<BlockBasedTableOptions>(); ASSERT_NE(table_options, nullptr); ASSERT_OK(BlockBasedTable::Open(ro, ioptions, EnvOptions(), *table_options, comparator, std::move(file), file_size, &table_reader)); table->reset(reinterpret_cast<BlockBasedTable*>(table_reader.release())); } std::string Path(const std::string& fname) { return test_dir_ + "/" + fname; } const std::shared_ptr<FileSystem>& fs() const { return fs_; } private: std::string test_dir_; Env* env_; std::shared_ptr<FileSystem> fs_; std::unique_ptr<BlockBasedTableFactory> table_factory_; void WriteToFile(const std::string& content, const std::string& filename) { std::unique_ptr<FSWritableFile> f; ASSERT_OK(fs_->NewWritableFile(Path(filename), FileOptions(), &f, nullptr)); ASSERT_OK(f->Append(content, IOOptions(), nullptr)); ASSERT_OK(f->Close(IOOptions(), nullptr)); } void NewFileWriter(const std::string& filename, std::unique_ptr<WritableFileWriter>* writer) { std::string path = Path(filename); EnvOptions env_options; FileOptions foptions; std::unique_ptr<FSWritableFile> file; ASSERT_OK(fs_->NewWritableFile(path, foptions, &file, nullptr)); writer->reset(new WritableFileWriter(std::move(file), path, env_options)); } void NewFileReader(const std::string& filename, const FileOptions& opt, std::unique_ptr<RandomAccessFileReader>* reader) { std::string path = Path(filename); std::unique_ptr<FSRandomAccessFile> f; ASSERT_OK(fs_->NewRandomAccessFile(path, opt, &f, nullptr)); reader->reset(new RandomAccessFileReader(std::move(f), path, env_)); } std::string ToInternalKey(const std::string& key) { InternalKey internal_key(key, 0, ValueType::kTypeValue); return internal_key.Encode().ToString(); } }; // Tests MultiGet in both direct IO and non-direct IO mode. // The keys should be in cache after MultiGet. TEST_P(BlockBasedTableReaderTest, MultiGet) { // Prepare key-value pairs to occupy multiple blocks. // Each value is 256B, every 16 pairs constitute 1 block. // Adjacent blocks contain values with different compression complexity: // human readable strings are easier to compress than random strings. std::map<std::string, std::string> kv; { Random rnd(101); uint32_t key = 0; for (int block = 0; block < 100; block++) { for (int i = 0; i < 16; i++) { char k[9] = {0}; // Internal key is constructed directly from this key, // and internal key size is required to be >= 8 bytes, // so use %08u as the format string. sprintf(k, "%08u", key); std::string v; if (block % 2) { v = rnd.HumanReadableString(256); } else { v = rnd.RandomString(256); } kv[std::string(k)] = v; key++; } } } // Prepare keys, values, and statuses for MultiGet. autovector<Slice, MultiGetContext::MAX_BATCH_SIZE> keys; autovector<PinnableSlice, MultiGetContext::MAX_BATCH_SIZE> values; autovector<Status, MultiGetContext::MAX_BATCH_SIZE> statuses; { const int step = static_cast<int>(kv.size()) / MultiGetContext::MAX_BATCH_SIZE; auto it = kv.begin(); for (int i = 0; i < MultiGetContext::MAX_BATCH_SIZE; i++) { keys.emplace_back(it->first); values.emplace_back(); statuses.emplace_back(); std::advance(it, step); } } std::string table_name = "BlockBasedTableReaderTest" + CompressionTypeToString(compression_type_); CreateTable(table_name, compression_type_, kv); std::unique_ptr<BlockBasedTable> table; Options options; ImmutableCFOptions ioptions(options); FileOptions foptions; foptions.use_direct_reads = use_direct_reads_; InternalKeyComparator comparator(options.comparator); NewBlockBasedTableReader(foptions, ioptions, comparator, table_name, &table); // Ensure that keys are not in cache before MultiGet. for (auto& key : keys) { ASSERT_FALSE(table->TEST_KeyInCache(ReadOptions(), key)); } // Prepare MultiGetContext. autovector<GetContext, MultiGetContext::MAX_BATCH_SIZE> get_context; autovector<KeyContext, MultiGetContext::MAX_BATCH_SIZE> key_context; autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE> sorted_keys; for (size_t i = 0; i < keys.size(); ++i) { get_context.emplace_back( BytewiseComparator(), nullptr, nullptr, nullptr, GetContext::kNotFound, keys[i], &values[i], nullptr, nullptr, nullptr, true /* do_merge */, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); key_context.emplace_back(nullptr, keys[i], &values[i], nullptr, &statuses.back()); key_context.back().get_context = &get_context.back(); } for (auto& key_ctx : key_context) { sorted_keys.emplace_back(&key_ctx); } MultiGetContext ctx(&sorted_keys, 0, sorted_keys.size(), 0, ReadOptions()); // Execute MultiGet. MultiGetContext::Range range = ctx.GetMultiGetRange(); table->MultiGet(ReadOptions(), &range, nullptr); for (const Status& status : statuses) { ASSERT_OK(status); } // Check that keys are in cache after MultiGet. for (size_t i = 0; i < keys.size(); i++) { ASSERT_TRUE(table->TEST_KeyInCache(ReadOptions(), keys[i])); ASSERT_EQ(values[i].ToString(), kv[keys[i].ToString()]); } } class BlockBasedTableReaderTestVerifyChecksum : public BlockBasedTableReaderTest { public: BlockBasedTableReaderTestVerifyChecksum() : BlockBasedTableReaderTest() {} }; TEST_P(BlockBasedTableReaderTestVerifyChecksum, ChecksumMismatch) { // Prepare key-value pairs to occupy multiple blocks. // Each value is 256B, every 16 pairs constitute 1 block. // Adjacent blocks contain values with different compression complexity: // human readable strings are easier to compress than random strings. Random rnd(101); std::map<std::string, std::string> kv; { uint32_t key = 0; for (int block = 0; block < 800; block++) { for (int i = 0; i < 16; i++) { char k[9] = {0}; // Internal key is constructed directly from this key, // and internal key size is required to be >= 8 bytes, // so use %08u as the format string. sprintf(k, "%08u", key); std::string v = rnd.RandomString(256); kv[std::string(k)] = v; key++; } } } std::string table_name = "BlockBasedTableReaderTest" + CompressionTypeToString(compression_type_); CreateTable(table_name, compression_type_, kv); std::unique_ptr<BlockBasedTable> table; Options options; ImmutableCFOptions ioptions(options); FileOptions foptions; foptions.use_direct_reads = use_direct_reads_; InternalKeyComparator comparator(options.comparator); NewBlockBasedTableReader(foptions, ioptions, comparator, table_name, &table); // Use the top level iterator to find the offset/size of the first // 2nd level index block and corrupt the block IndexBlockIter iiter_on_stack; BlockCacheLookupContext context{TableReaderCaller::kUserVerifyChecksum}; InternalIteratorBase<IndexValue>* iiter = table->NewIndexIterator( ReadOptions(), /*disable_prefix_seek=*/false, &iiter_on_stack, /*get_context=*/nullptr, &context); std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr; if (iiter != &iiter_on_stack) { iiter_unique_ptr = std::unique_ptr<InternalIteratorBase<IndexValue>>(iiter); } ASSERT_OK(iiter->status()); iiter->SeekToFirst(); BlockHandle handle = static_cast<PartitionedIndexIterator*>(iiter) ->index_iter_->value() .handle; table.reset(); // Corrupt the block pointed to by handle ASSERT_OK(test::CorruptFile(options.env, Path(table_name), static_cast<int>(handle.offset()), 128)); NewBlockBasedTableReader(foptions, ioptions, comparator, table_name, &table); Status s = table->VerifyChecksum(ReadOptions(), TableReaderCaller::kUserVerifyChecksum); ASSERT_EQ(s.code(), Status::kCorruption); } // Param 1: compression type // Param 2: whether to use direct reads // Param 3: Block Based Table Index type // Param 4: BBTO no_block_cache option #ifdef ROCKSDB_LITE // Skip direct I/O tests in lite mode since direct I/O is unsupported. INSTANTIATE_TEST_CASE_P( MultiGet, BlockBasedTableReaderTest, ::testing::Combine( ::testing::ValuesIn(GetSupportedCompressions()), ::testing::Values(false), ::testing::Values(BlockBasedTableOptions::IndexType::kBinarySearch), ::testing::Values(false))); #else // ROCKSDB_LITE INSTANTIATE_TEST_CASE_P( MultiGet, BlockBasedTableReaderTest, ::testing::Combine( ::testing::ValuesIn(GetSupportedCompressions()), ::testing::Bool(), ::testing::Values(BlockBasedTableOptions::IndexType::kBinarySearch), ::testing::Values(false))); #endif // ROCKSDB_LITE INSTANTIATE_TEST_CASE_P( VerifyChecksum, BlockBasedTableReaderTestVerifyChecksum, ::testing::Combine( ::testing::ValuesIn(GetSupportedCompressions()), ::testing::Values(false), ::testing::Values( BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch), ::testing::Values(true))); } // namespace ROCKSDB_NAMESPACE int main(int argc, char** argv) { ROCKSDB_NAMESPACE::port::InstallStackTraceHandler(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "libadt/vectset.hpp" #include "memory/allocation.inline.hpp" #include "opto/block.hpp" #include "opto/c2compiler.hpp" #include "opto/callnode.hpp" #include "opto/cfgnode.hpp" #include "opto/machnode.hpp" #include "opto/opcodes.hpp" #include "opto/phaseX.hpp" #include "opto/rootnode.hpp" #include "opto/runtime.hpp" #include "runtime/deoptimization.hpp" #ifdef TARGET_ARCH_MODEL_x86_32 # include "adfiles/ad_x86_32.hpp" #endif #ifdef TARGET_ARCH_MODEL_x86_64 # include "adfiles/ad_x86_64.hpp" #endif #ifdef TARGET_ARCH_MODEL_sparc # include "adfiles/ad_sparc.hpp" #endif #ifdef TARGET_ARCH_MODEL_zero # include "adfiles/ad_zero.hpp" #endif #ifdef TARGET_ARCH_MODEL_arm # include "adfiles/ad_arm.hpp" #endif #ifdef TARGET_ARCH_MODEL_ppc # include "adfiles/ad_ppc.hpp" #endif // Portions of code courtesy of Clifford Click // Optimization - Graph Style // To avoid float value underflow #define MIN_BLOCK_FREQUENCY 1.e-35f //----------------------------schedule_node_into_block------------------------- // Insert node n into block b. Look for projections of n and make sure they // are in b also. void PhaseCFG::schedule_node_into_block( Node *n, Block *b ) { // Set basic block of n, Add n to b, _bbs.map(n->_idx, b); b->add_inst(n); // After Matching, nearly any old Node may have projections trailing it. // These are usually machine-dependent flags. In any case, they might // float to another block below this one. Move them up. for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { Node* use = n->fast_out(i); if (use->is_Proj()) { Block* buse = _bbs[use->_idx]; if (buse != b) { // In wrong block? if (buse != NULL) buse->find_remove(use); // Remove from wrong block _bbs.map(use->_idx, b); // Re-insert in this block b->add_inst(use); } } } } //----------------------------replace_block_proj_ctrl------------------------- // Nodes that have is_block_proj() nodes as their control need to use // the appropriate Region for their actual block as their control since // the projection will be in a predecessor block. void PhaseCFG::replace_block_proj_ctrl( Node *n ) { const Node *in0 = n->in(0); assert(in0 != NULL, "Only control-dependent"); const Node *p = in0->is_block_proj(); if (p != NULL && p != n) { // Control from a block projection? assert(!n->pinned() || n->is_MachConstantBase() || n->is_SafePointScalarObject(), "only pinned MachConstantBase or SafePointScalarObject node is expected here"); // Find trailing Region Block *pb = _bbs[in0->_idx]; // Block-projection already has basic block uint j = 0; if (pb->_num_succs != 1) { // More then 1 successor? // Search for successor uint max = pb->_nodes.size(); assert( max > 1, "" ); uint start = max - pb->_num_succs; // Find which output path belongs to projection for (j = start; j < max; j++) { if( pb->_nodes[j] == in0 ) break; } assert( j < max, "must find" ); // Change control to match head of successor basic block j -= start; } n->set_req(0, pb->_succs[j]->head()); } } //------------------------------schedule_pinned_nodes-------------------------- // Set the basic block for Nodes pinned into blocks void PhaseCFG::schedule_pinned_nodes( VectorSet &visited ) { // Allocate node stack of size C->unique()+8 to avoid frequent realloc GrowableArray <Node *> spstack(C->unique()+8); spstack.push(_root); while ( spstack.is_nonempty() ) { Node *n = spstack.pop(); if( !visited.test_set(n->_idx) ) { // Test node and flag it as visited if( n->pinned() && !_bbs.lookup(n->_idx) ) { // Pinned? Nail it down! assert( n->in(0), "pinned Node must have Control" ); // Before setting block replace block_proj control edge replace_block_proj_ctrl(n); Node *input = n->in(0); while( !input->is_block_start() ) input = input->in(0); Block *b = _bbs[input->_idx]; // Basic block of controlling input schedule_node_into_block(n, b); } for( int i = n->req() - 1; i >= 0; --i ) { // For all inputs if( n->in(i) != NULL ) spstack.push(n->in(i)); } } } } #ifdef ASSERT // Assert that new input b2 is dominated by all previous inputs. // Check this by by seeing that it is dominated by b1, the deepest // input observed until b2. static void assert_dom(Block* b1, Block* b2, Node* n, Block_Array &bbs) { if (b1 == NULL) return; assert(b1->_dom_depth < b2->_dom_depth, "sanity"); Block* tmp = b2; while (tmp != b1 && tmp != NULL) { tmp = tmp->_idom; } if (tmp != b1) { // Detected an unschedulable graph. Print some nice stuff and die. tty->print_cr("!!! Unschedulable graph !!!"); for (uint j=0; j<n->len(); j++) { // For all inputs Node* inn = n->in(j); // Get input if (inn == NULL) continue; // Ignore NULL, missing inputs Block* inb = bbs[inn->_idx]; tty->print("B%d idom=B%d depth=%2d ",inb->_pre_order, inb->_idom ? inb->_idom->_pre_order : 0, inb->_dom_depth); inn->dump(); } tty->print("Failing node: "); n->dump(); assert(false, "unscheduable graph"); } } #endif static Block* find_deepest_input(Node* n, Block_Array &bbs) { // Find the last input dominated by all other inputs. Block* deepb = NULL; // Deepest block so far int deepb_dom_depth = 0; for (uint k = 0; k < n->len(); k++) { // For all inputs Node* inn = n->in(k); // Get input if (inn == NULL) continue; // Ignore NULL, missing inputs Block* inb = bbs[inn->_idx]; assert(inb != NULL, "must already have scheduled this input"); if (deepb_dom_depth < (int) inb->_dom_depth) { // The new inb must be dominated by the previous deepb. // The various inputs must be linearly ordered in the dom // tree, or else there will not be a unique deepest block. DEBUG_ONLY(assert_dom(deepb, inb, n, bbs)); deepb = inb; // Save deepest block deepb_dom_depth = deepb->_dom_depth; } } assert(deepb != NULL, "must be at least one input to n"); return deepb; } //------------------------------schedule_early--------------------------------- // Find the earliest Block any instruction can be placed in. Some instructions // are pinned into Blocks. Unpinned instructions can appear in last block in // which all their inputs occur. bool PhaseCFG::schedule_early(VectorSet &visited, Node_List &roots) { // Allocate stack with enough space to avoid frequent realloc Node_Stack nstack(roots.Size() + 8); // (unique >> 1) + 24 from Java2D stats // roots.push(_root); _root will be processed among C->top() inputs roots.push(C->top()); visited.set(C->top()->_idx); while (roots.size() != 0) { // Use local variables nstack_top_n & nstack_top_i to cache values // on stack's top. Node *nstack_top_n = roots.pop(); uint nstack_top_i = 0; //while_nstack_nonempty: while (true) { // Get parent node and next input's index from stack's top. Node *n = nstack_top_n; uint i = nstack_top_i; if (i == 0) { // Fixup some control. Constants without control get attached // to root and nodes that use is_block_proj() nodes should be attached // to the region that starts their block. const Node *in0 = n->in(0); if (in0 != NULL) { // Control-dependent? replace_block_proj_ctrl(n); } else { // n->in(0) == NULL if (n->req() == 1) { // This guy is a constant with NO inputs? n->set_req(0, _root); } } } // First, visit all inputs and force them to get a block. If an // input is already in a block we quit following inputs (to avoid // cycles). Instead we put that Node on a worklist to be handled // later (since IT'S inputs may not have a block yet). bool done = true; // Assume all n's inputs will be processed while (i < n->len()) { // For all inputs Node *in = n->in(i); // Get input ++i; if (in == NULL) continue; // Ignore NULL, missing inputs int is_visited = visited.test_set(in->_idx); if (!_bbs.lookup(in->_idx)) { // Missing block selection? if (is_visited) { // assert( !visited.test(in->_idx), "did not schedule early" ); return false; } nstack.push(n, i); // Save parent node and next input's index. nstack_top_n = in; // Process current input now. nstack_top_i = 0; done = false; // Not all n's inputs processed. break; // continue while_nstack_nonempty; } else if (!is_visited) { // Input not yet visited? roots.push(in); // Visit this guy later, using worklist } } if (done) { // All of n's inputs have been processed, complete post-processing. // Some instructions are pinned into a block. These include Region, // Phi, Start, Return, and other control-dependent instructions and // any projections which depend on them. if (!n->pinned()) { // Set earliest legal block. _bbs.map(n->_idx, find_deepest_input(n, _bbs)); } else { assert(_bbs[n->_idx] == _bbs[n->in(0)->_idx], "Pinned Node should be at the same block as its control edge"); } if (nstack.is_empty()) { // Finished all nodes on stack. // Process next node on the worklist 'roots'. break; } // Get saved parent node and next input's index. nstack_top_n = nstack.node(); nstack_top_i = nstack.index(); nstack.pop(); } // if (done) } // while (true) } // while (roots.size() != 0) return true; } //------------------------------dom_lca---------------------------------------- // Find least common ancestor in dominator tree // LCA is a current notion of LCA, to be raised above 'this'. // As a convenient boundary condition, return 'this' if LCA is NULL. // Find the LCA of those two nodes. Block* Block::dom_lca(Block* LCA) { if (LCA == NULL || LCA == this) return this; Block* anc = this; while (anc->_dom_depth > LCA->_dom_depth) anc = anc->_idom; // Walk up till anc is as high as LCA while (LCA->_dom_depth > anc->_dom_depth) LCA = LCA->_idom; // Walk up till LCA is as high as anc while (LCA != anc) { // Walk both up till they are the same LCA = LCA->_idom; anc = anc->_idom; } return LCA; } //--------------------------raise_LCA_above_use-------------------------------- // We are placing a definition, and have been given a def->use edge. // The definition must dominate the use, so move the LCA upward in the // dominator tree to dominate the use. If the use is a phi, adjust // the LCA only with the phi input paths which actually use this def. static Block* raise_LCA_above_use(Block* LCA, Node* use, Node* def, Block_Array &bbs) { Block* buse = bbs[use->_idx]; if (buse == NULL) return LCA; // Unused killing Projs have no use block if (!use->is_Phi()) return buse->dom_lca(LCA); uint pmax = use->req(); // Number of Phi inputs // Why does not this loop just break after finding the matching input to // the Phi? Well...it's like this. I do not have true def-use/use-def // chains. Means I cannot distinguish, from the def-use direction, which // of many use-defs lead from the same use to the same def. That is, this // Phi might have several uses of the same def. Each use appears in a // different predecessor block. But when I enter here, I cannot distinguish // which use-def edge I should find the predecessor block for. So I find // them all. Means I do a little extra work if a Phi uses the same value // more than once. for (uint j=1; j<pmax; j++) { // For all inputs if (use->in(j) == def) { // Found matching input? Block* pred = bbs[buse->pred(j)->_idx]; LCA = pred->dom_lca(LCA); } } return LCA; } //----------------------------raise_LCA_above_marks---------------------------- // Return a new LCA that dominates LCA and any of its marked predecessors. // Search all my parents up to 'early' (exclusive), looking for predecessors // which are marked with the given index. Return the LCA (in the dom tree) // of all marked blocks. If there are none marked, return the original // LCA. static Block* raise_LCA_above_marks(Block* LCA, node_idx_t mark, Block* early, Block_Array &bbs) { Block_List worklist; worklist.push(LCA); while (worklist.size() > 0) { Block* mid = worklist.pop(); if (mid == early) continue; // stop searching here // Test and set the visited bit. if (mid->raise_LCA_visited() == mark) continue; // already visited // Don't process the current LCA, otherwise the search may terminate early if (mid != LCA && mid->raise_LCA_mark() == mark) { // Raise the LCA. LCA = mid->dom_lca(LCA); if (LCA == early) break; // stop searching everywhere assert(early->dominates(LCA), "early is high enough"); // Resume searching at that point, skipping intermediate levels. worklist.push(LCA); if (LCA == mid) continue; // Don't mark as visited to avoid early termination. } else { // Keep searching through this block's predecessors. for (uint j = 1, jmax = mid->num_preds(); j < jmax; j++) { Block* mid_parent = bbs[ mid->pred(j)->_idx ]; worklist.push(mid_parent); } } mid->set_raise_LCA_visited(mark); } return LCA; } //--------------------------memory_early_block-------------------------------- // This is a variation of find_deepest_input, the heart of schedule_early. // Find the "early" block for a load, if we considered only memory and // address inputs, that is, if other data inputs were ignored. // // Because a subset of edges are considered, the resulting block will // be earlier (at a shallower dom_depth) than the true schedule_early // point of the node. We compute this earlier block as a more permissive // site for anti-dependency insertion, but only if subsume_loads is enabled. static Block* memory_early_block(Node* load, Block* early, Block_Array &bbs) { Node* base; Node* index; Node* store = load->in(MemNode::Memory); load->as_Mach()->memory_inputs(base, index); assert(base != NodeSentinel && index != NodeSentinel, "unexpected base/index inputs"); Node* mem_inputs[4]; int mem_inputs_length = 0; if (base != NULL) mem_inputs[mem_inputs_length++] = base; if (index != NULL) mem_inputs[mem_inputs_length++] = index; if (store != NULL) mem_inputs[mem_inputs_length++] = store; // In the comparision below, add one to account for the control input, // which may be null, but always takes up a spot in the in array. if (mem_inputs_length + 1 < (int) load->req()) { // This "load" has more inputs than just the memory, base and index inputs. // For purposes of checking anti-dependences, we need to start // from the early block of only the address portion of the instruction, // and ignore other blocks that may have factored into the wider // schedule_early calculation. if (load->in(0) != NULL) mem_inputs[mem_inputs_length++] = load->in(0); Block* deepb = NULL; // Deepest block so far int deepb_dom_depth = 0; for (int i = 0; i < mem_inputs_length; i++) { Block* inb = bbs[mem_inputs[i]->_idx]; if (deepb_dom_depth < (int) inb->_dom_depth) { // The new inb must be dominated by the previous deepb. // The various inputs must be linearly ordered in the dom // tree, or else there will not be a unique deepest block. DEBUG_ONLY(assert_dom(deepb, inb, load, bbs)); deepb = inb; // Save deepest block deepb_dom_depth = deepb->_dom_depth; } } early = deepb; } return early; } //--------------------------insert_anti_dependences--------------------------- // A load may need to witness memory that nearby stores can overwrite. // For each nearby store, either insert an "anti-dependence" edge // from the load to the store, or else move LCA upward to force the // load to (eventually) be scheduled in a block above the store. // // Do not add edges to stores on distinct control-flow paths; // only add edges to stores which might interfere. // // Return the (updated) LCA. There will not be any possibly interfering // store between the load's "early block" and the updated LCA. // Any stores in the updated LCA will have new precedence edges // back to the load. The caller is expected to schedule the load // in the LCA, in which case the precedence edges will make LCM // preserve anti-dependences. The caller may also hoist the load // above the LCA, if it is not the early block. Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) { assert(load->needs_anti_dependence_check(), "must be a load of some sort"); assert(LCA != NULL, ""); DEBUG_ONLY(Block* LCA_orig = LCA); // Compute the alias index. Loads and stores with different alias indices // do not need anti-dependence edges. uint load_alias_idx = C->get_alias_index(load->adr_type()); #ifdef ASSERT if (load_alias_idx == Compile::AliasIdxBot && C->AliasLevel() > 0 && (PrintOpto || VerifyAliases || PrintMiscellaneous && (WizardMode || Verbose))) { // Load nodes should not consume all of memory. // Reporting a bottom type indicates a bug in adlc. // If some particular type of node validly consumes all of memory, // sharpen the preceding "if" to exclude it, so we can catch bugs here. tty->print_cr("*** Possible Anti-Dependence Bug: Load consumes all of memory."); load->dump(2); if (VerifyAliases) assert(load_alias_idx != Compile::AliasIdxBot, ""); } #endif assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrComp), "String compare is only known 'load' that does not conflict with any stores"); assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrEquals), "String equals is a 'load' that does not conflict with any stores"); assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrIndexOf), "String indexOf is a 'load' that does not conflict with any stores"); assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_AryEq), "Arrays equals is a 'load' that do not conflict with any stores"); if (!C->alias_type(load_alias_idx)->is_rewritable()) { // It is impossible to spoil this load by putting stores before it, // because we know that the stores will never update the value // which 'load' must witness. return LCA; } node_idx_t load_index = load->_idx; // Note the earliest legal placement of 'load', as determined by // by the unique point in the dom tree where all memory effects // and other inputs are first available. (Computed by schedule_early.) // For normal loads, 'early' is the shallowest place (dom graph wise) // to look for anti-deps between this load and any store. Block* early = _bbs[load_index]; // If we are subsuming loads, compute an "early" block that only considers // memory or address inputs. This block may be different than the // schedule_early block in that it could be at an even shallower depth in the // dominator tree, and allow for a broader discovery of anti-dependences. if (C->subsume_loads()) { early = memory_early_block(load, early, _bbs); } ResourceArea *area = Thread::current()->resource_area(); Node_List worklist_mem(area); // prior memory state to store Node_List worklist_store(area); // possible-def to explore Node_List worklist_visited(area); // visited mergemem nodes Node_List non_early_stores(area); // all relevant stores outside of early bool must_raise_LCA = false; #ifdef TRACK_PHI_INPUTS // %%% This extra checking fails because MergeMem nodes are not GVNed. // Provide "phi_inputs" to check if every input to a PhiNode is from the // original memory state. This indicates a PhiNode for which should not // prevent the load from sinking. For such a block, set_raise_LCA_mark // may be overly conservative. // Mechanism: count inputs seen for each Phi encountered in worklist_store. DEBUG_ONLY(GrowableArray<uint> phi_inputs(area, C->unique(),0,0)); #endif // 'load' uses some memory state; look for users of the same state. // Recurse through MergeMem nodes to the stores that use them. // Each of these stores is a possible definition of memory // that 'load' needs to use. We need to force 'load' // to occur before each such store. When the store is in // the same block as 'load', we insert an anti-dependence // edge load->store. // The relevant stores "nearby" the load consist of a tree rooted // at initial_mem, with internal nodes of type MergeMem. // Therefore, the branches visited by the worklist are of this form: // initial_mem -> (MergeMem ->)* store // The anti-dependence constraints apply only to the fringe of this tree. Node* initial_mem = load->in(MemNode::Memory); worklist_store.push(initial_mem); worklist_visited.push(initial_mem); worklist_mem.push(NULL); while (worklist_store.size() > 0) { // Examine a nearby store to see if it might interfere with our load. Node* mem = worklist_mem.pop(); Node* store = worklist_store.pop(); uint op = store->Opcode(); // MergeMems do not directly have anti-deps. // Treat them as internal nodes in a forward tree of memory states, // the leaves of which are each a 'possible-def'. if (store == initial_mem // root (exclusive) of tree we are searching || op == Op_MergeMem // internal node of tree we are searching ) { mem = store; // It's not a possibly interfering store. if (store == initial_mem) initial_mem = NULL; // only process initial memory once for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { store = mem->fast_out(i); if (store->is_MergeMem()) { // Be sure we don't get into combinatorial problems. // (Allow phis to be repeated; they can merge two relevant states.) uint j = worklist_visited.size(); for (; j > 0; j--) { if (worklist_visited.at(j-1) == store) break; } if (j > 0) continue; // already on work list; do not repeat worklist_visited.push(store); } worklist_mem.push(mem); worklist_store.push(store); } continue; } if (op == Op_MachProj || op == Op_Catch) continue; if (store->needs_anti_dependence_check()) continue; // not really a store // Compute the alias index. Loads and stores with different alias // indices do not need anti-dependence edges. Wide MemBar's are // anti-dependent on everything (except immutable memories). const TypePtr* adr_type = store->adr_type(); if (!C->can_alias(adr_type, load_alias_idx)) continue; // Most slow-path runtime calls do NOT modify Java memory, but // they can block and so write Raw memory. if (store->is_Mach()) { MachNode* mstore = store->as_Mach(); if (load_alias_idx != Compile::AliasIdxRaw) { // Check for call into the runtime using the Java calling // convention (and from there into a wrapper); it has no // _method. Can't do this optimization for Native calls because // they CAN write to Java memory. if (mstore->ideal_Opcode() == Op_CallStaticJava) { assert(mstore->is_MachSafePoint(), ""); MachSafePointNode* ms = (MachSafePointNode*) mstore; assert(ms->is_MachCallJava(), ""); MachCallJavaNode* mcj = (MachCallJavaNode*) ms; if (mcj->_method == NULL) { // These runtime calls do not write to Java visible memory // (other than Raw) and so do not require anti-dependence edges. continue; } } // Same for SafePoints: they read/write Raw but only read otherwise. // This is basically a workaround for SafePoints only defining control // instead of control + memory. if (mstore->ideal_Opcode() == Op_SafePoint) continue; } else { // Some raw memory, such as the load of "top" at an allocation, // can be control dependent on the previous safepoint. See // comments in GraphKit::allocate_heap() about control input. // Inserting an anti-dep between such a safepoint and a use // creates a cycle, and will cause a subsequent failure in // local scheduling. (BugId 4919904) // (%%% How can a control input be a safepoint and not a projection??) if (mstore->ideal_Opcode() == Op_SafePoint && load->in(0) == mstore) continue; } } // Identify a block that the current load must be above, // or else observe that 'store' is all the way up in the // earliest legal block for 'load'. In the latter case, // immediately insert an anti-dependence edge. Block* store_block = _bbs[store->_idx]; assert(store_block != NULL, "unused killing projections skipped above"); if (store->is_Phi()) { // 'load' uses memory which is one (or more) of the Phi's inputs. // It must be scheduled not before the Phi, but rather before // each of the relevant Phi inputs. // // Instead of finding the LCA of all inputs to a Phi that match 'mem', // we mark each corresponding predecessor block and do a combined // hoisting operation later (raise_LCA_above_marks). // // Do not assert(store_block != early, "Phi merging memory after access") // PhiNode may be at start of block 'early' with backedge to 'early' DEBUG_ONLY(bool found_match = false); for (uint j = PhiNode::Input, jmax = store->req(); j < jmax; j++) { if (store->in(j) == mem) { // Found matching input? DEBUG_ONLY(found_match = true); Block* pred_block = _bbs[store_block->pred(j)->_idx]; if (pred_block != early) { // If any predecessor of the Phi matches the load's "early block", // we do not need a precedence edge between the Phi and 'load' // since the load will be forced into a block preceding the Phi. pred_block->set_raise_LCA_mark(load_index); assert(!LCA_orig->dominates(pred_block) || early->dominates(pred_block), "early is high enough"); must_raise_LCA = true; } else { // anti-dependent upon PHI pinned below 'early', no edge needed LCA = early; // but can not schedule below 'early' } } } assert(found_match, "no worklist bug"); #ifdef TRACK_PHI_INPUTS #ifdef ASSERT // This assert asks about correct handling of PhiNodes, which may not // have all input edges directly from 'mem'. See BugId 4621264 int num_mem_inputs = phi_inputs.at_grow(store->_idx,0) + 1; // Increment by exactly one even if there are multiple copies of 'mem' // coming into the phi, because we will run this block several times // if there are several copies of 'mem'. (That's how DU iterators work.) phi_inputs.at_put(store->_idx, num_mem_inputs); assert(PhiNode::Input + num_mem_inputs < store->req(), "Expect at least one phi input will not be from original memory state"); #endif //ASSERT #endif //TRACK_PHI_INPUTS } else if (store_block != early) { // 'store' is between the current LCA and earliest possible block. // Label its block, and decide later on how to raise the LCA // to include the effect on LCA of this store. // If this store's block gets chosen as the raised LCA, we // will find him on the non_early_stores list and stick him // with a precedence edge. // (But, don't bother if LCA is already raised all the way.) if (LCA != early) { store_block->set_raise_LCA_mark(load_index); must_raise_LCA = true; non_early_stores.push(store); } } else { // Found a possibly-interfering store in the load's 'early' block. // This means 'load' cannot sink at all in the dominator tree. // Add an anti-dep edge, and squeeze 'load' into the highest block. assert(store != load->in(0), "dependence cycle found"); if (verify) { assert(store->find_edge(load) != -1, "missing precedence edge"); } else { store->add_prec(load); } LCA = early; // This turns off the process of gathering non_early_stores. } } // (Worklist is now empty; all nearby stores have been visited.) // Finished if 'load' must be scheduled in its 'early' block. // If we found any stores there, they have already been given // precedence edges. if (LCA == early) return LCA; // We get here only if there are no possibly-interfering stores // in the load's 'early' block. Move LCA up above all predecessors // which contain stores we have noted. // // The raised LCA block can be a home to such interfering stores, // but its predecessors must not contain any such stores. // // The raised LCA will be a lower bound for placing the load, // preventing the load from sinking past any block containing // a store that may invalidate the memory state required by 'load'. if (must_raise_LCA) LCA = raise_LCA_above_marks(LCA, load->_idx, early, _bbs); if (LCA == early) return LCA; // Insert anti-dependence edges from 'load' to each store // in the non-early LCA block. // Mine the non_early_stores list for such stores. if (LCA->raise_LCA_mark() == load_index) { while (non_early_stores.size() > 0) { Node* store = non_early_stores.pop(); Block* store_block = _bbs[store->_idx]; if (store_block == LCA) { // add anti_dependence from store to load in its own block assert(store != load->in(0), "dependence cycle found"); if (verify) { assert(store->find_edge(load) != -1, "missing precedence edge"); } else { store->add_prec(load); } } else { assert(store_block->raise_LCA_mark() == load_index, "block was marked"); // Any other stores we found must be either inside the new LCA // or else outside the original LCA. In the latter case, they // did not interfere with any use of 'load'. assert(LCA->dominates(store_block) || !LCA_orig->dominates(store_block), "no stray stores"); } } } // Return the highest block containing stores; any stores // within that block have been given anti-dependence edges. return LCA; } // This class is used to iterate backwards over the nodes in the graph. class Node_Backward_Iterator { private: Node_Backward_Iterator(); public: // Constructor for the iterator Node_Backward_Iterator(Node *root, VectorSet &visited, Node_List &stack, Block_Array &bbs); // Postincrement operator to iterate over the nodes Node *next(); private: VectorSet &_visited; Node_List &_stack; Block_Array &_bbs; }; // Constructor for the Node_Backward_Iterator Node_Backward_Iterator::Node_Backward_Iterator( Node *root, VectorSet &visited, Node_List &stack, Block_Array &bbs ) : _visited(visited), _stack(stack), _bbs(bbs) { // The stack should contain exactly the root stack.clear(); stack.push(root); // Clear the visited bits visited.Clear(); } // Iterator for the Node_Backward_Iterator Node *Node_Backward_Iterator::next() { // If the _stack is empty, then just return NULL: finished. if ( !_stack.size() ) return NULL; // '_stack' is emulating a real _stack. The 'visit-all-users' loop has been // made stateless, so I do not need to record the index 'i' on my _stack. // Instead I visit all users each time, scanning for unvisited users. // I visit unvisited not-anti-dependence users first, then anti-dependent // children next. Node *self = _stack.pop(); // I cycle here when I am entering a deeper level of recursion. // The key variable 'self' was set prior to jumping here. while( 1 ) { _visited.set(self->_idx); // Now schedule all uses as late as possible. uint src = self->is_Proj() ? self->in(0)->_idx : self->_idx; uint src_rpo = _bbs[src]->_rpo; // Schedule all nodes in a post-order visit Node *unvisited = NULL; // Unvisited anti-dependent Node, if any // Scan for unvisited nodes for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) { // For all uses, schedule late Node* n = self->fast_out(i); // Use // Skip already visited children if ( _visited.test(n->_idx) ) continue; // do not traverse backward control edges Node *use = n->is_Proj() ? n->in(0) : n; uint use_rpo = _bbs[use->_idx]->_rpo; if ( use_rpo < src_rpo ) continue; // Phi nodes always precede uses in a basic block if ( use_rpo == src_rpo && use->is_Phi() ) continue; unvisited = n; // Found unvisited // Check for possible-anti-dependent if( !n->needs_anti_dependence_check() ) break; // Not visited, not anti-dep; schedule it NOW } // Did I find an unvisited not-anti-dependent Node? if ( !unvisited ) break; // All done with children; post-visit 'self' // Visit the unvisited Node. Contains the obvious push to // indicate I'm entering a deeper level of recursion. I push the // old state onto the _stack and set a new state and loop (recurse). _stack.push(self); self = unvisited; } // End recursion loop return self; } //------------------------------ComputeLatenciesBackwards---------------------- // Compute the latency of all the instructions. void PhaseCFG::ComputeLatenciesBackwards(VectorSet &visited, Node_List &stack) { #ifndef PRODUCT if (trace_opto_pipelining()) tty->print("\n#---- ComputeLatenciesBackwards ----\n"); #endif Node_Backward_Iterator iter((Node *)_root, visited, stack, _bbs); Node *n; // Walk over all the nodes from last to first while (n = iter.next()) { // Set the latency for the definitions of this instruction partial_latency_of_defs(n); } } // end ComputeLatenciesBackwards //------------------------------partial_latency_of_defs------------------------ // Compute the latency impact of this node on all defs. This computes // a number that increases as we approach the beginning of the routine. void PhaseCFG::partial_latency_of_defs(Node *n) { // Set the latency for this instruction #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# latency_to_inputs: node_latency[%d] = %d for node", n->_idx, _node_latency->at_grow(n->_idx)); dump(); } #endif if (n->is_Proj()) n = n->in(0); if (n->is_Root()) return; uint nlen = n->len(); uint use_latency = _node_latency->at_grow(n->_idx); uint use_pre_order = _bbs[n->_idx]->_pre_order; for ( uint j=0; j<nlen; j++ ) { Node *def = n->in(j); if (!def || def == n) continue; // Walk backwards thru projections if (def->is_Proj()) def = def->in(0); #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# in(%2d): ", j); def->dump(); } #endif // If the defining block is not known, assume it is ok Block *def_block = _bbs[def->_idx]; uint def_pre_order = def_block ? def_block->_pre_order : 0; if ( (use_pre_order < def_pre_order) || (use_pre_order == def_pre_order && n->is_Phi()) ) continue; uint delta_latency = n->latency(j); uint current_latency = delta_latency + use_latency; if (_node_latency->at_grow(def->_idx) < current_latency) { _node_latency->at_put_grow(def->_idx, current_latency); } #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print_cr("# %d + edge_latency(%d) == %d -> %d, node_latency[%d] = %d", use_latency, j, delta_latency, current_latency, def->_idx, _node_latency->at_grow(def->_idx)); } #endif } } //------------------------------latency_from_use------------------------------- // Compute the latency of a specific use int PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) { // If self-reference, return no latency if (use == n || use->is_Root()) return 0; uint def_pre_order = _bbs[def->_idx]->_pre_order; uint latency = 0; // If the use is not a projection, then it is simple... if (!use->is_Proj()) { #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# out(): "); use->dump(); } #endif uint use_pre_order = _bbs[use->_idx]->_pre_order; if (use_pre_order < def_pre_order) return 0; if (use_pre_order == def_pre_order && use->is_Phi()) return 0; uint nlen = use->len(); uint nl = _node_latency->at_grow(use->_idx); for ( uint j=0; j<nlen; j++ ) { if (use->in(j) == n) { // Change this if we want local latencies uint ul = use->latency(j); uint l = ul + nl; if (latency < l) latency = l; #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print_cr("# %d + edge_latency(%d) == %d -> %d, latency = %d", nl, j, ul, l, latency); } #endif } } } else { // This is a projection, just grab the latency of the use(s) for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) { uint l = latency_from_use(use, def, use->fast_out(j)); if (latency < l) latency = l; } } return latency; } //------------------------------latency_from_uses------------------------------ // Compute the latency of this instruction relative to all of it's uses. // This computes a number that increases as we approach the beginning of the // routine. void PhaseCFG::latency_from_uses(Node *n) { // Set the latency for this instruction #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# latency_from_outputs: node_latency[%d] = %d for node", n->_idx, _node_latency->at_grow(n->_idx)); dump(); } #endif uint latency=0; const Node *def = n->is_Proj() ? n->in(0): n; for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { uint l = latency_from_use(n, def, n->fast_out(i)); if (latency < l) latency = l; } _node_latency->at_put_grow(n->_idx, latency); } //------------------------------hoist_to_cheaper_block------------------------- // Pick a block for node self, between early and LCA, that is a cheaper // alternative to LCA. Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) { const double delta = 1+PROB_UNLIKELY_MAG(4); Block* least = LCA; double least_freq = least->_freq; uint target = _node_latency->at_grow(self->_idx); uint start_latency = _node_latency->at_grow(LCA->_nodes[0]->_idx); uint end_latency = _node_latency->at_grow(LCA->_nodes[LCA->end_idx()]->_idx); bool in_latency = (target <= start_latency); const Block* root_block = _bbs[_root->_idx]; // Turn off latency scheduling if scheduling is just plain off if (!C->do_scheduling()) in_latency = true; // Do not hoist (to cover latency) instructions which target a // single register. Hoisting stretches the live range of the // single register and may force spilling. MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL; if (mach && mach->out_RegMask().is_bound1() && mach->out_RegMask().is_NotEmpty()) in_latency = true; #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# Find cheaper block for latency %d: ", _node_latency->at_grow(self->_idx)); self->dump(); tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g", LCA->_pre_order, LCA->_nodes[0]->_idx, start_latency, LCA->_nodes[LCA->end_idx()]->_idx, end_latency, least_freq); } #endif // Walk up the dominator tree from LCA (Lowest common ancestor) to // the earliest legal location. Capture the least execution frequency. while (LCA != early) { LCA = LCA->_idom; // Follow up the dominator tree if (LCA == NULL) { // Bailout without retry C->record_method_not_compilable("late schedule failed: LCA == NULL"); return least; } // Don't hoist machine instructions to the root basic block if (mach && LCA == root_block) break; uint start_lat = _node_latency->at_grow(LCA->_nodes[0]->_idx); uint end_idx = LCA->end_idx(); uint end_lat = _node_latency->at_grow(LCA->_nodes[end_idx]->_idx); double LCA_freq = LCA->_freq; #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g", LCA->_pre_order, LCA->_nodes[0]->_idx, start_lat, end_idx, end_lat, LCA_freq); } #endif if (LCA_freq < least_freq || // Better Frequency ( !in_latency && // No block containing latency LCA_freq < least_freq * delta && // No worse frequency target >= end_lat && // within latency range !self->is_iteratively_computed() ) // But don't hoist IV increments // because they may end up above other uses of their phi forcing // their result register to be different from their input. ) { least = LCA; // Found cheaper block least_freq = LCA_freq; start_latency = start_lat; end_latency = end_lat; if (target <= start_lat) in_latency = true; } } #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print_cr("# Choose block B%d with start latency=%d and freq=%g", least->_pre_order, start_latency, least_freq); } #endif // See if the latency needs to be updated if (target < end_latency) { #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print_cr("# Change latency for [%4d] from %d to %d", self->_idx, target, end_latency); } #endif _node_latency->at_put_grow(self->_idx, end_latency); partial_latency_of_defs(self); } return least; } //------------------------------schedule_late----------------------------------- // Now schedule all codes as LATE as possible. This is the LCA in the // dominator tree of all USES of a value. Pick the block with the least // loop nesting depth that is lowest in the dominator tree. extern const char must_clone[]; void PhaseCFG::schedule_late(VectorSet &visited, Node_List &stack) { #ifndef PRODUCT if (trace_opto_pipelining()) tty->print("\n#---- schedule_late ----\n"); #endif Node_Backward_Iterator iter((Node *)_root, visited, stack, _bbs); Node *self; // Walk over all the nodes from last to first while (self = iter.next()) { Block* early = _bbs[self->_idx]; // Earliest legal placement if (self->is_top()) { // Top node goes in bb #2 with other constants. // It must be special-cased, because it has no out edges. early->add_inst(self); continue; } // No uses, just terminate if (self->outcnt() == 0) { assert(self->Opcode() == Op_MachProj, "sanity"); continue; // Must be a dead machine projection } // If node is pinned in the block, then no scheduling can be done. if( self->pinned() ) // Pinned in block? continue; MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL; if (mach) { switch (mach->ideal_Opcode()) { case Op_CreateEx: // Don't move exception creation early->add_inst(self); continue; break; case Op_CheckCastPP: // Don't move CheckCastPP nodes away from their input, if the input // is a rawptr (5071820). Node *def = self->in(1); if (def != NULL && def->bottom_type()->base() == Type::RawPtr) { early->add_inst(self); #ifdef ASSERT _raw_oops.push(def); #endif continue; } break; } } // Gather LCA of all uses Block *LCA = NULL; { for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) { // For all uses, find LCA Node* use = self->fast_out(i); LCA = raise_LCA_above_use(LCA, use, self, _bbs); } } // (Hide defs of imax, i from rest of block.) // Place temps in the block of their use. This isn't a // requirement for correctness but it reduces useless // interference between temps and other nodes. if (mach != NULL && mach->is_MachTemp()) { _bbs.map(self->_idx, LCA); LCA->add_inst(self); continue; } // Check if 'self' could be anti-dependent on memory if (self->needs_anti_dependence_check()) { // Hoist LCA above possible-defs and insert anti-dependences to // defs in new LCA block. LCA = insert_anti_dependences(LCA, self); } if (early->_dom_depth > LCA->_dom_depth) { // Somehow the LCA has moved above the earliest legal point. // (One way this can happen is via memory_early_block.) if (C->subsume_loads() == true && !C->failing()) { // Retry with subsume_loads == false // If this is the first failure, the sentinel string will "stick" // to the Compile object, and the C2Compiler will see it and retry. C->record_failure(C2Compiler::retry_no_subsuming_loads()); } else { // Bailout without retry when (early->_dom_depth > LCA->_dom_depth) C->record_method_not_compilable("late schedule failed: incorrect graph"); } return; } // If there is no opportunity to hoist, then we're done. bool try_to_hoist = (LCA != early); // Must clone guys stay next to use; no hoisting allowed. // Also cannot hoist guys that alter memory or are otherwise not // allocatable (hoisting can make a value live longer, leading to // anti and output dependency problems which are normally resolved // by the register allocator giving everyone a different register). if (mach != NULL && must_clone[mach->ideal_Opcode()]) try_to_hoist = false; Block* late = NULL; if (try_to_hoist) { // Now find the block with the least execution frequency. // Start at the latest schedule and work up to the earliest schedule // in the dominator tree. Thus the Node will dominate all its uses. late = hoist_to_cheaper_block(LCA, early, self); } else { // Just use the LCA of the uses. late = LCA; } // Put the node into target block schedule_node_into_block(self, late); #ifdef ASSERT if (self->needs_anti_dependence_check()) { // since precedence edges are only inserted when we're sure they // are needed make sure that after placement in a block we don't // need any new precedence edges. verify_anti_dependences(late, self); } #endif } // Loop until all nodes have been visited } // end ScheduleLate //------------------------------GlobalCodeMotion------------------------------- void PhaseCFG::GlobalCodeMotion( Matcher &matcher, uint unique, Node_List &proj_list ) { ResourceMark rm; #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("\n---- Start GlobalCodeMotion ----\n"); } #endif // Initialize the bbs.map for things on the proj_list uint i; for( i=0; i < proj_list.size(); i++ ) _bbs.map(proj_list[i]->_idx, NULL); // Set the basic block for Nodes pinned into blocks Arena *a = Thread::current()->resource_area(); VectorSet visited(a); schedule_pinned_nodes( visited ); // Find the earliest Block any instruction can be placed in. Some // instructions are pinned into Blocks. Unpinned instructions can // appear in last block in which all their inputs occur. visited.Clear(); Node_List stack(a); stack.map( (unique >> 1) + 16, NULL); // Pre-grow the list if (!schedule_early(visited, stack)) { // Bailout without retry C->record_method_not_compilable("early schedule failed"); return; } // Build Def-Use edges. proj_list.push(_root); // Add real root as another root proj_list.pop(); // Compute the latency information (via backwards walk) for all the // instructions in the graph _node_latency = new GrowableArray<uint>(); // resource_area allocation if( C->do_scheduling() ) ComputeLatenciesBackwards(visited, stack); // Now schedule all codes as LATE as possible. This is the LCA in the // dominator tree of all USES of a value. Pick the block with the least // loop nesting depth that is lowest in the dominator tree. // ( visited.Clear() called in schedule_late()->Node_Backward_Iterator() ) schedule_late(visited, stack); if( C->failing() ) { // schedule_late fails only when graph is incorrect. assert(!VerifyGraphEdges, "verification should have failed"); return; } unique = C->unique(); #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("\n---- Detect implicit null checks ----\n"); } #endif // Detect implicit-null-check opportunities. Basically, find NULL checks // with suitable memory ops nearby. Use the memory op to do the NULL check. // I can generate a memory op if there is not one nearby. if (C->is_method_compilation()) { // Don't do it for natives, adapters, or runtime stubs int allowed_reasons = 0; // ...and don't do it when there have been too many traps, globally. for (int reason = (int)Deoptimization::Reason_none+1; reason < Compile::trapHistLength; reason++) { assert(reason < BitsPerInt, "recode bit map"); if (!C->too_many_traps((Deoptimization::DeoptReason) reason)) allowed_reasons |= nth_bit(reason); } // By reversing the loop direction we get a very minor gain on mpegaudio. // Feel free to revert to a forward loop for clarity. // for( int i=0; i < (int)matcher._null_check_tests.size(); i+=2 ) { for( int i= matcher._null_check_tests.size()-2; i>=0; i-=2 ) { Node *proj = matcher._null_check_tests[i ]; Node *val = matcher._null_check_tests[i+1]; _bbs[proj->_idx]->implicit_null_check(this, proj, val, allowed_reasons); // The implicit_null_check will only perform the transformation // if the null branch is truly uncommon, *and* it leads to an // uncommon trap. Combined with the too_many_traps guards // above, this prevents SEGV storms reported in 6366351, // by recompiling offending methods without this optimization. } } #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("\n---- Start Local Scheduling ----\n"); } #endif // Schedule locally. Right now a simple topological sort. // Later, do a real latency aware scheduler. int *ready_cnt = NEW_RESOURCE_ARRAY(int,C->unique()); memset( ready_cnt, -1, C->unique() * sizeof(int) ); visited.Clear(); for (i = 0; i < _num_blocks; i++) { if (!_blocks[i]->schedule_local(this, matcher, ready_cnt, visited)) { if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) { C->record_method_not_compilable("local schedule failed"); } return; } } // If we inserted any instructions between a Call and his CatchNode, // clone the instructions on all paths below the Catch. for( i=0; i < _num_blocks; i++ ) _blocks[i]->call_catch_cleanup(_bbs); #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("\n---- After GlobalCodeMotion ----\n"); for (uint i = 0; i < _num_blocks; i++) { _blocks[i]->dump(); } } #endif // Dead. _node_latency = (GrowableArray<uint> *)0xdeadbeef; } //------------------------------Estimate_Block_Frequency----------------------- // Estimate block frequencies based on IfNode probabilities. void PhaseCFG::Estimate_Block_Frequency() { // Force conditional branches leading to uncommon traps to be unlikely, // not because we get to the uncommon_trap with less relative frequency, // but because an uncommon_trap typically causes a deopt, so we only get // there once. if (C->do_freq_based_layout()) { Block_List worklist; Block* root_blk = _blocks[0]; for (uint i = 1; i < root_blk->num_preds(); i++) { Block *pb = _bbs[root_blk->pred(i)->_idx]; if (pb->has_uncommon_code()) { worklist.push(pb); } } while (worklist.size() > 0) { Block* uct = worklist.pop(); if (uct == _broot) continue; for (uint i = 1; i < uct->num_preds(); i++) { Block *pb = _bbs[uct->pred(i)->_idx]; if (pb->_num_succs == 1) { worklist.push(pb); } else if (pb->num_fall_throughs() == 2) { pb->update_uncommon_branch(uct); } } } } // Create the loop tree and calculate loop depth. _root_loop = create_loop_tree(); _root_loop->compute_loop_depth(0); // Compute block frequency of each block, relative to a single loop entry. _root_loop->compute_freq(); // Adjust all frequencies to be relative to a single method entry _root_loop->_freq = 1.0; _root_loop->scale_freq(); // Save outmost loop frequency for LRG frequency threshold _outer_loop_freq = _root_loop->outer_loop_freq(); // force paths ending at uncommon traps to be infrequent if (!C->do_freq_based_layout()) { Block_List worklist; Block* root_blk = _blocks[0]; for (uint i = 1; i < root_blk->num_preds(); i++) { Block *pb = _bbs[root_blk->pred(i)->_idx]; if (pb->has_uncommon_code()) { worklist.push(pb); } } while (worklist.size() > 0) { Block* uct = worklist.pop(); uct->_freq = PROB_MIN; for (uint i = 1; i < uct->num_preds(); i++) { Block *pb = _bbs[uct->pred(i)->_idx]; if (pb->_num_succs == 1 && pb->_freq > PROB_MIN) { worklist.push(pb); } } } } #ifdef ASSERT for (uint i = 0; i < _num_blocks; i++ ) { Block *b = _blocks[i]; assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency"); } #endif #ifndef PRODUCT if (PrintCFGBlockFreq) { tty->print_cr("CFG Block Frequencies"); _root_loop->dump_tree(); if (Verbose) { tty->print_cr("PhaseCFG dump"); dump(); tty->print_cr("Node dump"); _root->dump(99999); } } #endif } //----------------------------create_loop_tree-------------------------------- // Create a loop tree from the CFG CFGLoop* PhaseCFG::create_loop_tree() { #ifdef ASSERT assert( _blocks[0] == _broot, "" ); for (uint i = 0; i < _num_blocks; i++ ) { Block *b = _blocks[i]; // Check that _loop field are clear...we could clear them if not. assert(b->_loop == NULL, "clear _loop expected"); // Sanity check that the RPO numbering is reflected in the _blocks array. // It doesn't have to be for the loop tree to be built, but if it is not, // then the blocks have been reordered since dom graph building...which // may question the RPO numbering assert(b->_rpo == i, "unexpected reverse post order number"); } #endif int idct = 0; CFGLoop* root_loop = new CFGLoop(idct++); Block_List worklist; // Assign blocks to loops for(uint i = _num_blocks - 1; i > 0; i-- ) { // skip Root block Block *b = _blocks[i]; if (b->head()->is_Loop()) { Block* loop_head = b; assert(loop_head->num_preds() - 1 == 2, "loop must have 2 predecessors"); Node* tail_n = loop_head->pred(LoopNode::LoopBackControl); Block* tail = _bbs[tail_n->_idx]; // Defensively filter out Loop nodes for non-single-entry loops. // For all reasonable loops, the head occurs before the tail in RPO. if (i <= tail->_rpo) { // The tail and (recursive) predecessors of the tail // are made members of a new loop. assert(worklist.size() == 0, "nonempty worklist"); CFGLoop* nloop = new CFGLoop(idct++); assert(loop_head->_loop == NULL, "just checking"); loop_head->_loop = nloop; // Add to nloop so push_pred() will skip over inner loops nloop->add_member(loop_head); nloop->push_pred(loop_head, LoopNode::LoopBackControl, worklist, _bbs); while (worklist.size() > 0) { Block* member = worklist.pop(); if (member != loop_head) { for (uint j = 1; j < member->num_preds(); j++) { nloop->push_pred(member, j, worklist, _bbs); } } } } } } // Create a member list for each loop consisting // of both blocks and (immediate child) loops. for (uint i = 0; i < _num_blocks; i++) { Block *b = _blocks[i]; CFGLoop* lp = b->_loop; if (lp == NULL) { // Not assigned to a loop. Add it to the method's pseudo loop. b->_loop = root_loop; lp = root_loop; } if (lp == root_loop || b != lp->head()) { // loop heads are already members lp->add_member(b); } if (lp != root_loop) { if (lp->parent() == NULL) { // Not a nested loop. Make it a child of the method's pseudo loop. root_loop->add_nested_loop(lp); } if (b == lp->head()) { // Add nested loop to member list of parent loop. lp->parent()->add_member(lp); } } } return root_loop; } //------------------------------push_pred-------------------------------------- void CFGLoop::push_pred(Block* blk, int i, Block_List& worklist, Block_Array& node_to_blk) { Node* pred_n = blk->pred(i); Block* pred = node_to_blk[pred_n->_idx]; CFGLoop *pred_loop = pred->_loop; if (pred_loop == NULL) { // Filter out blocks for non-single-entry loops. // For all reasonable loops, the head occurs before the tail in RPO. if (pred->_rpo > head()->_rpo) { pred->_loop = this; worklist.push(pred); } } else if (pred_loop != this) { // Nested loop. while (pred_loop->_parent != NULL && pred_loop->_parent != this) { pred_loop = pred_loop->_parent; } // Make pred's loop be a child if (pred_loop->_parent == NULL) { add_nested_loop(pred_loop); // Continue with loop entry predecessor. Block* pred_head = pred_loop->head(); assert(pred_head->num_preds() - 1 == 2, "loop must have 2 predecessors"); assert(pred_head != head(), "loop head in only one loop"); push_pred(pred_head, LoopNode::EntryControl, worklist, node_to_blk); } else { assert(pred_loop->_parent == this && _parent == NULL, "just checking"); } } } //------------------------------add_nested_loop-------------------------------- // Make cl a child of the current loop in the loop tree. void CFGLoop::add_nested_loop(CFGLoop* cl) { assert(_parent == NULL, "no parent yet"); assert(cl != this, "not my own parent"); cl->_parent = this; CFGLoop* ch = _child; if (ch == NULL) { _child = cl; } else { while (ch->_sibling != NULL) { ch = ch->_sibling; } ch->_sibling = cl; } } //------------------------------compute_loop_depth----------------------------- // Store the loop depth in each CFGLoop object. // Recursively walk the children to do the same for them. void CFGLoop::compute_loop_depth(int depth) { _depth = depth; CFGLoop* ch = _child; while (ch != NULL) { ch->compute_loop_depth(depth + 1); ch = ch->_sibling; } } //------------------------------compute_freq----------------------------------- // Compute the frequency of each block and loop, relative to a single entry // into the dominating loop head. void CFGLoop::compute_freq() { // Bottom up traversal of loop tree (visit inner loops first.) // Set loop head frequency to 1.0, then transitively // compute frequency for all successors in the loop, // as well as for each exit edge. Inner loops are // treated as single blocks with loop exit targets // as the successor blocks. // Nested loops first CFGLoop* ch = _child; while (ch != NULL) { ch->compute_freq(); ch = ch->_sibling; } assert (_members.length() > 0, "no empty loops"); Block* hd = head(); hd->_freq = 1.0f; for (int i = 0; i < _members.length(); i++) { CFGElement* s = _members.at(i); float freq = s->_freq; if (s->is_block()) { Block* b = s->as_Block(); for (uint j = 0; j < b->_num_succs; j++) { Block* sb = b->_succs[j]; update_succ_freq(sb, freq * b->succ_prob(j)); } } else { CFGLoop* lp = s->as_CFGLoop(); assert(lp->_parent == this, "immediate child"); for (int k = 0; k < lp->_exits.length(); k++) { Block* eb = lp->_exits.at(k).get_target(); float prob = lp->_exits.at(k).get_prob(); update_succ_freq(eb, freq * prob); } } } // For all loops other than the outer, "method" loop, // sum and normalize the exit probability. The "method" loop // should keep the initial exit probability of 1, so that // inner blocks do not get erroneously scaled. if (_depth != 0) { // Total the exit probabilities for this loop. float exits_sum = 0.0f; for (int i = 0; i < _exits.length(); i++) { exits_sum += _exits.at(i).get_prob(); } // Normalize the exit probabilities. Until now, the // probabilities estimate the possibility of exit per // a single loop iteration; afterward, they estimate // the probability of exit per loop entry. for (int i = 0; i < _exits.length(); i++) { Block* et = _exits.at(i).get_target(); float new_prob = 0.0f; if (_exits.at(i).get_prob() > 0.0f) { new_prob = _exits.at(i).get_prob() / exits_sum; } BlockProbPair bpp(et, new_prob); _exits.at_put(i, bpp); } // Save the total, but guard against unreasonable probability, // as the value is used to estimate the loop trip count. // An infinite trip count would blur relative block // frequencies. if (exits_sum > 1.0f) exits_sum = 1.0; if (exits_sum < PROB_MIN) exits_sum = PROB_MIN; _exit_prob = exits_sum; } } //------------------------------succ_prob------------------------------------- // Determine the probability of reaching successor 'i' from the receiver block. float Block::succ_prob(uint i) { int eidx = end_idx(); Node *n = _nodes[eidx]; // Get ending Node int op = n->Opcode(); if (n->is_Mach()) { if (n->is_MachNullCheck()) { // Can only reach here if called after lcm. The original Op_If is gone, // so we attempt to infer the probability from one or both of the // successor blocks. assert(_num_succs == 2, "expecting 2 successors of a null check"); // If either successor has only one predecessor, then the // probability estimate can be derived using the // relative frequency of the successor and this block. if (_succs[i]->num_preds() == 2) { return _succs[i]->_freq / _freq; } else if (_succs[1-i]->num_preds() == 2) { return 1 - (_succs[1-i]->_freq / _freq); } else { // Estimate using both successor frequencies float freq = _succs[i]->_freq; return freq / (freq + _succs[1-i]->_freq); } } op = n->as_Mach()->ideal_Opcode(); } // Switch on branch type switch( op ) { case Op_CountedLoopEnd: case Op_If: { assert (i < 2, "just checking"); // Conditionals pass on only part of their frequency float prob = n->as_MachIf()->_prob; assert(prob >= 0.0 && prob <= 1.0, "out of range probability"); // If succ[i] is the FALSE branch, invert path info if( _nodes[i + eidx + 1]->Opcode() == Op_IfFalse ) { return 1.0f - prob; // not taken } else { return prob; // taken } } case Op_Jump: // Divide the frequency between all successors evenly return 1.0f/_num_succs; case Op_Catch: { const CatchProjNode *ci = _nodes[i + eidx + 1]->as_CatchProj(); if (ci->_con == CatchProjNode::fall_through_index) { // Fall-thru path gets the lion's share. return 1.0f - PROB_UNLIKELY_MAG(5)*_num_succs; } else { // Presume exceptional paths are equally unlikely return PROB_UNLIKELY_MAG(5); } } case Op_Root: case Op_Goto: // Pass frequency straight thru to target return 1.0f; case Op_NeverBranch: return 0.0f; case Op_TailCall: case Op_TailJump: case Op_Return: case Op_Halt: case Op_Rethrow: // Do not push out freq to root block return 0.0f; default: ShouldNotReachHere(); } return 0.0f; } //------------------------------num_fall_throughs----------------------------- // Return the number of fall-through candidates for a block int Block::num_fall_throughs() { int eidx = end_idx(); Node *n = _nodes[eidx]; // Get ending Node int op = n->Opcode(); if (n->is_Mach()) { if (n->is_MachNullCheck()) { // In theory, either side can fall-thru, for simplicity sake, // let's say only the false branch can now. return 1; } op = n->as_Mach()->ideal_Opcode(); } // Switch on branch type switch( op ) { case Op_CountedLoopEnd: case Op_If: return 2; case Op_Root: case Op_Goto: return 1; case Op_Catch: { for (uint i = 0; i < _num_succs; i++) { const CatchProjNode *ci = _nodes[i + eidx + 1]->as_CatchProj(); if (ci->_con == CatchProjNode::fall_through_index) { return 1; } } return 0; } case Op_Jump: case Op_NeverBranch: case Op_TailCall: case Op_TailJump: case Op_Return: case Op_Halt: case Op_Rethrow: return 0; default: ShouldNotReachHere(); } return 0; } //------------------------------succ_fall_through----------------------------- // Return true if a specific successor could be fall-through target. bool Block::succ_fall_through(uint i) { int eidx = end_idx(); Node *n = _nodes[eidx]; // Get ending Node int op = n->Opcode(); if (n->is_Mach()) { if (n->is_MachNullCheck()) { // In theory, either side can fall-thru, for simplicity sake, // let's say only the false branch can now. return _nodes[i + eidx + 1]->Opcode() == Op_IfFalse; } op = n->as_Mach()->ideal_Opcode(); } // Switch on branch type switch( op ) { case Op_CountedLoopEnd: case Op_If: case Op_Root: case Op_Goto: return true; case Op_Catch: { const CatchProjNode *ci = _nodes[i + eidx + 1]->as_CatchProj(); return ci->_con == CatchProjNode::fall_through_index; } case Op_Jump: case Op_NeverBranch: case Op_TailCall: case Op_TailJump: case Op_Return: case Op_Halt: case Op_Rethrow: return false; default: ShouldNotReachHere(); } return false; } //------------------------------update_uncommon_branch------------------------ // Update the probability of a two-branch to be uncommon void Block::update_uncommon_branch(Block* ub) { int eidx = end_idx(); Node *n = _nodes[eidx]; // Get ending Node int op = n->as_Mach()->ideal_Opcode(); assert(op == Op_CountedLoopEnd || op == Op_If, "must be a If"); assert(num_fall_throughs() == 2, "must be a two way branch block"); // Which successor is ub? uint s; for (s = 0; s <_num_succs; s++) { if (_succs[s] == ub) break; } assert(s < 2, "uncommon successor must be found"); // If ub is the true path, make the proability small, else // ub is the false path, and make the probability large bool invert = (_nodes[s + eidx + 1]->Opcode() == Op_IfFalse); // Get existing probability float p = n->as_MachIf()->_prob; if (invert) p = 1.0 - p; if (p > PROB_MIN) { p = PROB_MIN; } if (invert) p = 1.0 - p; n->as_MachIf()->_prob = p; } //------------------------------update_succ_freq------------------------------- // Update the appropriate frequency associated with block 'b', a successor of // a block in this loop. void CFGLoop::update_succ_freq(Block* b, float freq) { if (b->_loop == this) { if (b == head()) { // back branch within the loop // Do nothing now, the loop carried frequency will be // adjust later in scale_freq(). } else { // simple branch within the loop b->_freq += freq; } } else if (!in_loop_nest(b)) { // branch is exit from this loop BlockProbPair bpp(b, freq); _exits.append(bpp); } else { // branch into nested loop CFGLoop* ch = b->_loop; ch->_freq += freq; } } //------------------------------in_loop_nest----------------------------------- // Determine if block b is in the receiver's loop nest. bool CFGLoop::in_loop_nest(Block* b) { int depth = _depth; CFGLoop* b_loop = b->_loop; int b_depth = b_loop->_depth; if (depth == b_depth) { return true; } while (b_depth > depth) { b_loop = b_loop->_parent; b_depth = b_loop->_depth; } return b_loop == this; } //------------------------------scale_freq------------------------------------- // Scale frequency of loops and blocks by trip counts from outer loops // Do a top down traversal of loop tree (visit outer loops first.) void CFGLoop::scale_freq() { float loop_freq = _freq * trip_count(); _freq = loop_freq; for (int i = 0; i < _members.length(); i++) { CFGElement* s = _members.at(i); float block_freq = s->_freq * loop_freq; if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY) block_freq = MIN_BLOCK_FREQUENCY; s->_freq = block_freq; } CFGLoop* ch = _child; while (ch != NULL) { ch->scale_freq(); ch = ch->_sibling; } } // Frequency of outer loop float CFGLoop::outer_loop_freq() const { if (_child != NULL) { return _child->_freq; } return _freq; } #ifndef PRODUCT //------------------------------dump_tree-------------------------------------- void CFGLoop::dump_tree() const { dump(); if (_child != NULL) _child->dump_tree(); if (_sibling != NULL) _sibling->dump_tree(); } //------------------------------dump------------------------------------------- void CFGLoop::dump() const { for (int i = 0; i < _depth; i++) tty->print(" "); tty->print("%s: %d trip_count: %6.0f freq: %6.0f\n", _depth == 0 ? "Method" : "Loop", _id, trip_count(), _freq); for (int i = 0; i < _depth; i++) tty->print(" "); tty->print(" members:", _id); int k = 0; for (int i = 0; i < _members.length(); i++) { if (k++ >= 6) { tty->print("\n "); for (int j = 0; j < _depth+1; j++) tty->print(" "); k = 0; } CFGElement *s = _members.at(i); if (s->is_block()) { Block *b = s->as_Block(); tty->print(" B%d(%6.3f)", b->_pre_order, b->_freq); } else { CFGLoop* lp = s->as_CFGLoop(); tty->print(" L%d(%6.3f)", lp->_id, lp->_freq); } } tty->print("\n"); for (int i = 0; i < _depth; i++) tty->print(" "); tty->print(" exits: "); k = 0; for (int i = 0; i < _exits.length(); i++) { if (k++ >= 7) { tty->print("\n "); for (int j = 0; j < _depth+1; j++) tty->print(" "); k = 0; } Block *blk = _exits.at(i).get_target(); float prob = _exits.at(i).get_prob(); tty->print(" ->%d@%d%%", blk->_pre_order, (int)(prob*100)); } tty->print("\n"); } #endif
#ifndef Magnum_SceneGraph_Animable_hpp #define Magnum_SceneGraph_Animable_hpp /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file * @brief @ref compilation-speedup-hpp "Template implementation" for @ref Animable.h and @ref AnimableGroup.h */ #include "Magnum/Timeline.h" #include "Magnum/Math/Constants.h" #include "Magnum/SceneGraph/AnimableGroup.h" #include "Magnum/SceneGraph/Animable.h" namespace Magnum { namespace SceneGraph { template<UnsignedInt dimensions, class T> Animable<dimensions, T>::Animable(AbstractObject<dimensions, T>& object, AnimableGroup<dimensions, T>* group): AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>(object, group), _duration(0.0f), startTime(Constants::inf()), pauseTime(-Constants::inf()), previousState(AnimationState::Stopped), currentState(AnimationState::Stopped), _repeated(false), _repeatCount(0), repeats(0) {} template<UnsignedInt dimensions, class T> Animable<dimensions, T>::~Animable() {} template<UnsignedInt dimensions, class T> Animable<dimensions, T>& Animable<dimensions, T>::setState(AnimationState state) { if(currentState == state) return *this; /* Not allowed (for sanity) */ if(previousState == AnimationState::Stopped && state == AnimationState::Paused) return *this; /* Wake up the group in case no animations are running */ animables()->wakeUp = true; currentState = state; return *this; } template<UnsignedInt dimensions, class T> AnimableGroup<dimensions, T>* Animable<dimensions, T>::animables() { return static_cast<AnimableGroup<dimensions, T>*>(AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>::group()); } template<UnsignedInt dimensions, class T> const AnimableGroup<dimensions, T>* Animable<dimensions, T>::animables() const { return static_cast<const AnimableGroup<dimensions, T>*>(AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>::group()); } template<UnsignedInt dimensions, class T> void AnimableGroup<dimensions, T>::step(const Float time, const Float delta) { if(!_runningCount && !wakeUp) return; wakeUp = false; for(std::size_t i = 0; i != AnimableGroup<dimensions, T>::size(); ++i) { Animable<dimensions, T>& animable = (*this)[i]; /* The animation was stopped recently, just decrease count of running animations if the animation was running before */ if(animable.previousState != AnimationState::Stopped && animable.currentState == AnimationState::Stopped) { if(animable.previousState == AnimationState::Running) --_runningCount; animable.previousState = AnimationState::Stopped; animable.animationStopped(); continue; /* The animation was paused recently, set pause time to previous frame time */ } else if(animable.previousState == AnimationState::Running && animable.currentState == AnimationState::Paused) { animable.previousState = AnimationState::Paused; animable.pauseTime = time; --_runningCount; animable.animationPaused(); continue; /* Skip the rest for not running animations */ } else if(animable.currentState != AnimationState::Running) { CORRADE_INTERNAL_ASSERT(animable.previousState == animable.currentState); continue; /* The animation was started recently, set start time to previous frame time, reset repeat count */ } else if(animable.previousState == AnimationState::Stopped) { animable.previousState = AnimationState::Running; animable.startTime = time; animable.repeats = 0; ++_runningCount; animable.animationStarted(); /* The animation was resumed recently, add pause duration to start time */ } else if(animable.previousState == AnimationState::Paused) { animable.previousState = AnimationState::Running; animable.startTime += time - animable.pauseTime; ++_runningCount; animable.animationResumed(); } CORRADE_INTERNAL_ASSERT(animable.previousState == AnimationState::Running); /* Animation time exceeded duration */ if(animable._duration != 0.0f && time-animable.startTime > animable._duration) { /* Not repeated or repeat count exceeded, stop */ if(!animable._repeated || animable.repeats+1 == animable._repeatCount) { animable.previousState = AnimationState::Stopped; animable.currentState = AnimationState::Stopped; --_runningCount; animable.animationStopped(); continue; } /* Increase repeat count and add duration to startTime */ ++animable.repeats; animable.startTime += animable._duration; } /* Animation is still running, perform animation step */ CORRADE_ASSERT(time-animable.startTime >= 0.0f, "SceneGraph::AnimableGroup::step(): animation was started in future - probably wrong time passed", ); CORRADE_ASSERT(delta >= 0.0f, "SceneGraph::AnimableGroup::step(): negative delta passed", ); animable.animationStep(time - animable.startTime, delta); } CORRADE_INTERNAL_ASSERT((_runningCount <= AnimableGroup<dimensions, T>::size())); } }} #endif
#include "animatorOperations.h" #include "GUI/qtUtils.h" #include "GUI/asyncAnimatorPanel.h" #include "animation/asyncAnimator.h" #include "common/importFiles.h" #include "common/exportFiles.h" #include "drawables/drawableCage.h" #include "drawables/drawableSkeleton.h" #include "drawables/drawableCharacter.h" #include "skinning/cageSkinning.h" #include "skinning/skeletonSkinning.h" #include "operators/cageUpdater.h" #include "operators/skeletonUpdater.h" #include "GUI/glCanvas.h" #include "GUI/mainWindow.h" #include "controller.h" #include <QInputDialog> #include <vector> #include <stack> void initializeAnimator() { Controller * c = Controller::get(); if(c->isCageLoaded || c->isSkeletonLoaded) { c->asyncAnimator->create(c->cage, c->skeleton); c->isAnimatorInitialized = true; } } void clearAnimator() { Controller * c = Controller::get(); c->isAnimatorActivated = false; c->isAnimatorInitialized = false; c->asyncAnimator->clear(); c->asyncAnimatorPanel->updateKeyframeList(); updateGUI(); } void loadSkelAnimationFromFile() { std::string filename; Controller * c = Controller::get(); if (openFileSelectionDialog(filename, "Load Skel Animation", "Skeleton Animation (*.ska *.txt)")) { if(c->isAnimatorInitialized) { std::cout << "Loading animation: " << filename << std::endl; double charRadius = 0.0; c->character->sceneRadius(charRadius); std::vector<double> t; std::vector<std::vector<cg3::Transform>> skelKeyframes; int animationFileVersionNumber; loadSkelAnimation( filename.c_str(), t, skelKeyframes, animationFileVersionNumber); convertSkelKeyframes(animationFileVersionNumber, skelKeyframes); c->asyncAnimator->loadSkelAnimation(t,skelKeyframes); } } } void convertSkelKeyframes(int keyframesVersion, std::vector<std::vector<cg3::Transform>> & skelKeyframes) { Controller * c = Controller::get(); std::vector<SkeletonNode> nodes = c->skeleton->getNodesVector(); if(keyframesVersion==2) { //Compute the local transform for the current pose keyframes for(ulong i=0; i<skelKeyframes.size(); i++) { for(ulong j=0; j<skelKeyframes[i].size(); j++){ if(nodes[j].getFather()==-1) { skelKeyframes[i][j].setTranslation(skelKeyframes[i][j].getTranslation() - nodes[j].getLocalTRest().getTranslation()); } skelKeyframes[i][j] = nodes[j].getLocalTRest().cumulateWith(skelKeyframes[i][j]); } } } if(keyframesVersion==3) { //compute the local transform from the global current pose keyframes for(ulong i=0; i<skelKeyframes.size(); i++) { std::vector<cg3::Transform> v3GlobalTransforms(skelKeyframes[i]); for(ulong n=0; n<skelKeyframes[i].size(); n++) { SkeletonNode & node = nodes[n]; const int fatherIndex = node.getFather(); if(fatherIndex != -1) { cg3::Transform fatherTransformation = v3GlobalTransforms[fatherIndex]; skelKeyframes[i][n] = fatherTransformation.inverse().cumulateWith(v3GlobalTransforms[n]); } } } } } void saveSkelAnimationToFile() { std::string filename; Controller * c = Controller::get(); if (openFileSaveDialog(filename, "Save Skel Animation", "Skeleton Animation (*.ska *.txt)")) { if(c->isAnimatorInitialized) { std::vector<std::vector<cg3::Transform>> skelKeyframes(c->asyncAnimator->getSkelKeyframeVector()); //SAVE V3 KEYFRAMES std::stack<int> stack; std::vector<SkeletonNode> nodes = c->skeleton->getNodesVector(); for(int n:c->skeleton->getRootsIndexes()) { stack.push(n); } while (!stack.empty()) { const int n = stack.top(); stack.pop(); SkeletonNode & node = nodes[n]; const int fatherIndex = node.getFather(); for(ulong i=0; i<skelKeyframes.size(); i++) { if(fatherIndex != -1) { const cg3::Transform & restFatherTransformation = skelKeyframes[i][fatherIndex]; skelKeyframes[i][n] = restFatherTransformation.cumulateWith (skelKeyframes[i][n]); } } const std::vector<ulong> & childs = node.getNext(); for(ulong child:childs) { stack.push(child); } } saveSkelAnimation(filename.c_str(), c->asyncAnimator->getSkelKeyframeTimeVector(), skelKeyframes); } } } void loadCageAnimationFromFile() { std::string filename; Controller * c = Controller::get(); if (openFileSelectionDialog(filename, "Load Cage Animation", "Text File (*.txt)")) { if(c->isAnimatorInitialized) { std::cout << "Loading animation: " << filename << std::endl; std::vector<double> t; std::vector<std::vector<double>> cageKeyframes; loadCageAnimation( filename.c_str(), t, cageKeyframes); c->asyncAnimator->loadCageAnimation(t,cageKeyframes); } } } void saveCageAnimationToFile() { std::string filename; Controller * c = Controller::get(); if (openFileSaveDialog(filename, "Save CageAnimation", "Text File (*.txt)")) { if(c->isAnimatorInitialized) { saveCageAnimation(filename.c_str(), c->asyncAnimator->getCageKeyframeTimeVector(), c->asyncAnimator->getCageKeyframeVector()); } } } void addSkelKeyframe() { Controller * c = Controller::get(); if(c->isSkeletonSkinningInitialized) { bool ok; double t = QInputDialog::getDouble(c->mainWindow, "Keyframe time (in seconds)", "Second: ", 0, 0, 2147483647, 6, &ok); if (ok && t>=0) { //skel keyframe std::vector<cg3::Transform> skelKeyframes(c->skeleton->getNumNodes()); for(unsigned long i=0; i<c->skeleton->getNumNodes(); ++i) { const SkeletonNode & n = c->skeleton->getNode(i); cg3::Transform Tdeformed(n.getLocalTCurrent()); skelKeyframes[i] = Tdeformed;//.cumulateWith(Trest.inverse()); } c->asyncAnimator->addSkelKeyframe(t, skelKeyframes); } } } void addCageKeyframe() { Controller * c = Controller::get(); if(c->isCageSkinningInitialized) { bool ok; double t = QInputDialog::getDouble(c->mainWindow, "Keyframe time (in seconds)", "Second: ", 0, 0, 2147483647, 6, &ok); if (ok && t>=0) { //cage keyframe const std::vector<double> & originalRestCage = c->cage->getOriginalRestPoseVertices(); const std::vector<double> & restCage = c->cage->getRestPoseVertices(); std::vector<double> cageOffsets(restCage.size()); for(int i=0; i<restCage.size(); ++i) { cageOffsets[i] = restCage[i] - originalRestCage[i]; } c->asyncAnimator->addCageKeyframe(t, cageOffsets); } } } void setSkelKeyframe(unsigned long frameIndex) { Controller * c = Controller::get(); c->asyncAnimator->setSkeletonKeyframeIndex(frameIndex); //Skeleton Skinning if(c->isSkeletonSkinningInitialized) { c->skeletonSkinning->deform(); if(c->isCageUpdaterInitialized && c->isCageUpdaterActive) { c->cageUpdater->updatePosition(); } } c->character->updateNormals(); c->glCanvas->refreshScene(); } void setCageKeyframe(unsigned long frameIndex) { Controller * c = Controller::get(); c->asyncAnimator->setCageKeyframeIndex(frameIndex); //Cage Skinning if(c->isCageSkinningInitialized) { c->cageSkinning->deform(); if(c->isSkeletonUpdaterActive) { c->skeletonUpdater->updatePosition(); } c->skeletonSkinning->deform(); c->cageUpdater->updatePosition(); } c->character->updateNormals(); c->glCanvas->refreshScene(); } void setNextSkelKeyframe() { Controller * c = Controller::get(); //Skeleton Skinning if((c->isSkeletonSkinningInitialized) && (c->isAnimatorInitialized)) { int frameIndex = c->asyncAnimator->getSkelKeyframeIndex(); c->asyncAnimator->setSkeletonKeyframeIndex(frameIndex+1); c->glCanvas->runSkinningPipeline(); } } void setNextCageKeyframe() { Controller * c = Controller::get(); if((c->isCageSkinningInitialized) && (c->isAnimatorInitialized)) { int frameIndex = c->asyncAnimator->getCageKeyframeIndex(); c->asyncAnimator->setCageKeyframeIndex(frameIndex+1); c->glCanvas->runSkinningPipeline(); } } void deleteSkelKeyframe(int index) { Controller * c = Controller::get(); if(c->isAnimatorInitialized) { c->asyncAnimator->deleteSkelKeyframe(index); /*if(c->isCageSkinningInitialized) { c->asyncAnimator->set; c->cageSkinning->deform(); c->cage->updateNormals(); } c->glCanvas->refreshScene();*/ } } void deleteCageKeyframe(int index) { Controller * c = Controller::get(); if(c->isAnimatorInitialized) { c->asyncAnimator->deleteCageKeyframe(index); } } void editSkelKeyframeTime(int index) { Controller * c = Controller::get(); if(c->isAnimatorInitialized) { bool ok; double actualTime = c->asyncAnimator->getSkelKeyframeTimeVector()[index]; double t = QInputDialog::getDouble(c->mainWindow, "Keyframe time (in seconds)", "Second: ", actualTime, 0, 2147483647, 6, &ok); if (ok && t>0) { c->asyncAnimator->editSkelKeyframeTime(index, t); } } } void editCageKeyframeTime(int index) { Controller * c = Controller::get(); if(c->isAnimatorInitialized) { bool ok; double actualTime = c->asyncAnimator->getCageKeyframeTimeVector()[index]; double t = QInputDialog::getDouble(c->mainWindow, "Keyframe time (in seconds)", "Second: ", actualTime, 0, 2147483647, 6, &ok); if (ok && t>0) { c->asyncAnimator->editCageKeyframeTime(index, t); } } }
// Copyright (c) 2011-2014 The Phtevencoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "utilitydialog.h" #include "ui_helpmessagedialog.h" #include "phtevencoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "clientversion.h" #include "init.h" #include "util.h" #include <stdio.h> #include <QCloseEvent> #include <QLabel> #include <QRegExp> #include <QTextTable> #include <QTextCursor> #include <QVBoxLayout> /** "Help message" or "About" dialog box */ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : QDialog(parent), ui(new Ui::HelpMessageDialog) { ui->setupUi(this); QString version = tr("Phtevencoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()); /* On x86 add a bit specifier to the version so that users can distinguish between * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious. */ #if defined(__x86_64__) version += " " + tr("(%1-bit)").arg(64); #elif defined(__i386__ ) version += " " + tr("(%1-bit)").arg(32); #endif if (about) { setWindowTitle(tr("About Phtevencoin Core")); /// HTML-format the license message from the core QString licenseInfo = QString::fromStdString(LicenseInfo()); QString licenseInfoHTML = licenseInfo; // Make URLs clickable QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2); uri.setMinimal(true); // use non-greedy matching licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>"); // Replace newlines with HTML breaks licenseInfoHTML.replace("\n\n", "<br><br>"); ui->aboutMessage->setTextFormat(Qt::RichText); ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); text = version + "\n" + licenseInfo; ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML); ui->aboutMessage->setWordWrap(true); ui->helpMessage->setVisible(false); } else { setWindowTitle(tr("Command-line options")); QString header = tr("Usage:") + "\n" + " phtevencoin-qt [" + tr("command-line options") + "] " + "\n"; QTextCursor cursor(ui->helpMessage->document()); cursor.insertText(version); cursor.insertBlock(); cursor.insertText(header); cursor.insertBlock(); QString coreOptions = QString::fromStdString(HelpMessage(HMM_PHTEVENCOIN_QT)); text = version + "\n" + header + "\n" + coreOptions; QTextTableFormat tf; tf.setBorderStyle(QTextFrameFormat::BorderStyle_None); tf.setCellPadding(2); QVector<QTextLength> widths; widths << QTextLength(QTextLength::PercentageLength, 35); widths << QTextLength(QTextLength::PercentageLength, 65); tf.setColumnWidthConstraints(widths); QTextCharFormat bold; bold.setFontWeight(QFont::Bold); Q_FOREACH (const QString &line, coreOptions.split("\n")) { if (line.startsWith(" -")) { cursor.currentTable()->appendRows(1); cursor.movePosition(QTextCursor::PreviousCell); cursor.movePosition(QTextCursor::NextRow); cursor.insertText(line.trimmed()); cursor.movePosition(QTextCursor::NextCell); } else if (line.startsWith(" ")) { cursor.insertText(line.trimmed()+' '); } else if (line.size() > 0) { //Title of a group if (cursor.currentTable()) cursor.currentTable()->appendRows(1); cursor.movePosition(QTextCursor::Down); cursor.insertText(line.trimmed(), bold); cursor.insertTable(1, 2, tf); } } ui->helpMessage->moveCursor(QTextCursor::Start); ui->scrollArea->setVisible(false); ui->aboutLogo->setVisible(false); } } HelpMessageDialog::~HelpMessageDialog() { delete ui; } void HelpMessageDialog::printToConsole() { // On other operating systems, the expected action is to print the message to the console. fprintf(stdout, "%s\n", qPrintable(text)); } void HelpMessageDialog::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } void HelpMessageDialog::on_okButton_accepted() { close(); } /** "Shutdown" window */ ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f): QWidget(parent, f) { QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(new QLabel( tr("Phtevencoin Core is shutting down...") + "<br /><br />" + tr("Do not shut down the computer until this window disappears."))); setLayout(layout); } void ShutdownWindow::showShutdownWindow(PhtevencoinGUI *window) { if (!window) return; // Show a simple window indicating shutdown status QWidget *shutdownWindow = new ShutdownWindow(); // We don't hold a direct pointer to the shutdown window after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. shutdownWindow->setAttribute(Qt::WA_DeleteOnClose); shutdownWindow->setWindowTitle(window->windowTitle()); // Center shutdown window at where main window was const QPoint global = window->mapToGlobal(window->rect().center()); shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2); shutdownWindow->show(); } void ShutdownWindow::closeEvent(QCloseEvent *event) { event->ignore(); }
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include "AndroidRoutingServiceProxy.h" #include "AndroidRoutingServiceExampleView.h" JNIEXPORT void JNICALL Java_com_eegeo_examples_routingservice_RoutingServiceJniMethods_MoveUp( JNIEnv* jenv, jobject obj, jlong nativeObjectPtr) { Examples::AndroidRoutingServiceExampleView* pExample = (Examples::AndroidRoutingServiceExampleView*)(nativeObjectPtr); pExample->MoveUp(); } JNIEXPORT void JNICALL Java_com_eegeo_examples_routingservice_RoutingServiceJniMethods_MoveDown( JNIEnv* jenv, jobject obj, jlong nativeObjectPtr) { Examples::AndroidRoutingServiceExampleView* pExample = (Examples::AndroidRoutingServiceExampleView*)(nativeObjectPtr); pExample->MoveDown(); } JNIEXPORT void JNICALL Java_com_eegeo_examples_routingservice_RoutingServiceJniMethods_GetRoute( JNIEnv* jenv, jobject obj, jlong nativeObjectPtr) { Examples::AndroidRoutingServiceExampleView* pExample = (Examples::AndroidRoutingServiceExampleView*)(nativeObjectPtr); pExample->GetRoute(); } JNIEXPORT void JNICALL Java_com_eegeo_examples_routingservice_RoutingServiceJniMethods_ToggleExpanded( JNIEnv* jenv, jobject obj, jlong nativeObjectPtr) { Examples::AndroidRoutingServiceExampleView* pExample = (Examples::AndroidRoutingServiceExampleView*)(nativeObjectPtr); pExample->ToggleExpanded(); }
#include<iostream> using namespace std; class Node { public : int data; Node* right,*left; }node; Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } int level(Node* root,Node* a,int lev) { if(!root) return 0; if(root == a) return lev; int l = level(root->left,a,lev+1); if(l!=0) return l; return level(root->right,a,lev+1); } int isSibling(Node* root,Node* a,Node* b) { if(!root) return 0; if(root->left && root->right) return ((root->left==a && root->right==b) || (root->right==a && root->left==b) || isSibling(root->left,a,b) || isSibling(root->right,a,b)); } int isCousin(Node* root,Node* a,Node* b) { if(level(root,a,1) == level(root,b,1) && !(isSibling(root,a,b))) return 1; else return 0; } int main() { Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); Node *Node1,*Node2; Node1 = root->left->left; Node2 = root->right->right; isCousin(root,Node1,Node2)? puts("Yes"): puts("No"); return 0; }
/*! @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause */ #pragma once #include <vector> #include <pyclustering/container/adjacency.hpp> #include <pyclustering/container/adjacency_connector.hpp> #include <pyclustering/container/dynamic_data.hpp> #include <pyclustering/container/ensemble_data.hpp> #include <pyclustering/nnet/network.hpp> using namespace pyclustering::container; namespace pyclustering { namespace nnet { #define OUTPUT_ACTIVE_STATE (double) 1.0 #define OUTPUT_INACTIVE_STATE (double) 0.0 struct pcnn_oscillator { double output; double feeding; double linking; double threshold; pcnn_oscillator() : output(0.0), feeding(0.0), linking(0.0), threshold(0.0) { } }; struct pcnn_parameters { double VF = 1.0; double VL = 1.0; double VT = 10.0; double AF = 0.1; double AL = 0.1; double AT = 0.5; double W = 1.0; double M = 1.0; double B = 0.1; bool FAST_LINKING = false; }; using pcnn_ensemble = std::vector<std::size_t>; using pcnn_stimulus = std::vector<double>; using pcnn_time_signal = std::vector<std::size_t>; struct pcnn_network_state { public: std::vector<double> m_output; double m_time; public: std::size_t size() const; }; class pcnn_dynamic : public dynamic_data<pcnn_network_state> { public: pcnn_dynamic(); ~pcnn_dynamic(); public: void allocate_sync_ensembles(ensemble_data<pcnn_ensemble> & sync_ensembles) const; void allocate_spike_ensembles(ensemble_data<pcnn_ensemble> & spike_ensembles) const; void allocate_time_signal(pcnn_time_signal & time_signal) const; public: /** * * @brief Returns dynamic state of oscillator of the pulse-coupled neural network at the * specified iteration step. * * @param[in] iteration: number of iteration at which oscillator state is required. * @param[in] index_oscillator: index of oscillator whose state is required. * * @return dynamic state of the oscillator at the specified iteration. * */ inline double dynamic_oscillator_at(const size_t iteration, const size_t index_oscillator) const { return at(iteration).m_output[index_oscillator]; } }; class pcnn { protected: std::vector<pcnn_oscillator> m_oscillators; std::shared_ptr<adjacency_collection> m_connection; pcnn_parameters m_params; private: const static size_t MAXIMUM_MATRIX_REPRESENTATION_SIZE; public: pcnn(); pcnn(const size_t p_size, const connection_t p_structure, const pcnn_parameters & p_parameters); pcnn(const size_t p_size, const connection_t p_structure, const size_t p_height, const size_t p_width, const pcnn_parameters & p_parameters); virtual ~pcnn() = default; public: void simulate(const std::size_t steps, const pcnn_stimulus & stimulus, pcnn_dynamic & output_dynamic); inline size_t size() const { return m_oscillators.size(); } private: void initilize(const size_t p_size, const connection_t p_structure, const size_t p_height, const size_t p_width, const pcnn_parameters & p_parameters); void calculate_states(const pcnn_stimulus & stimulus); void store_dynamic(const std::size_t step, pcnn_dynamic & dynamic) const; void fast_linking(const std::vector<double> & feeding, std::vector<double> & linking, std::vector<double> & output); }; } }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h" #include <map> #include <memory> #include <tuple> #include <utility> #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" #include "base/test/test_simple_task_runner.h" #include "components/subresource_filter/content/browser/async_document_subresource_filter.h" #include "components/subresource_filter/content/browser/subresource_filter_observer_manager.h" #include "components/subresource_filter/content/common/subresource_filter_messages.h" #include "components/subresource_filter/core/common/activation_level.h" #include "components/subresource_filter/core/common/activation_state.h" #include "components/subresource_filter/core/common/test_ruleset_creator.h" #include "components/subresource_filter/core/common/test_ruleset_utils.h" #include "components/url_pattern_index/proto/rules.pb.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/navigation_throttle.h" #include "content/public/browser/web_contents.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/navigation_simulator.h" #include "content/public/test/test_renderer_host.h" #include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/url_constants.h" namespace subresource_filter { namespace proto = url_pattern_index::proto; const char kTestURLWithActivation[] = "https://www.page-with-activation.com/"; const char kTestURLWithActivation2[] = "https://www.page-with-activation-2.com/"; const char kTestURLWithDryRun[] = "https://www.page-with-dryrun.com/"; const char kTestURLWithNoActivation[] = "https://www.page-without-activation.com/"; // Enum determining when the mock page state throttle notifies the throttle // manager of page level activation state. enum PageActivationNotificationTiming { WILL_START_REQUEST, WILL_PROCESS_RESPONSE, }; // Simple throttle that sends page-level activation to the manager for a // specific set of URLs. class MockPageStateActivationThrottle : public content::NavigationThrottle { public: MockPageStateActivationThrottle( content::NavigationHandle* navigation_handle, PageActivationNotificationTiming activation_throttle_state) : content::NavigationThrottle(navigation_handle), activation_throttle_state_(activation_throttle_state) { // Add some default activations. mock_page_activations_[GURL(kTestURLWithActivation)] = ActivationState(ActivationLevel::ENABLED); mock_page_activations_[GURL(kTestURLWithActivation2)] = ActivationState(ActivationLevel::ENABLED); mock_page_activations_[GURL(kTestURLWithDryRun)] = ActivationState(ActivationLevel::DRYRUN); mock_page_activations_[GURL(kTestURLWithNoActivation)] = ActivationState(ActivationLevel::DISABLED); } ~MockPageStateActivationThrottle() override {} // content::NavigationThrottle: content::NavigationThrottle::ThrottleCheckResult WillStartRequest() override { return MaybeNotifyActivation(WILL_START_REQUEST); } content::NavigationThrottle::ThrottleCheckResult WillProcessResponse() override { return MaybeNotifyActivation(WILL_PROCESS_RESPONSE); } const char* GetNameForLogging() override { return "MockPageStateActivationThrottle"; } private: content::NavigationThrottle::ThrottleCheckResult MaybeNotifyActivation( PageActivationNotificationTiming throttle_state) { if (throttle_state == activation_throttle_state_) { auto it = mock_page_activations_.find(navigation_handle()->GetURL()); if (it != mock_page_activations_.end()) { // The throttle manager does not use the activation decision. SubresourceFilterObserverManager::FromWebContents( navigation_handle()->GetWebContents()) ->NotifyPageActivationComputed( navigation_handle(), ActivationDecision::UNKNOWN, it->second); } } return content::NavigationThrottle::PROCEED; } std::map<GURL, ActivationState> mock_page_activations_; PageActivationNotificationTiming activation_throttle_state_; DISALLOW_COPY_AND_ASSIGN(MockPageStateActivationThrottle); }; class ContentSubresourceFilterThrottleManagerTest : public content::RenderViewHostTestHarness, public content::WebContentsObserver, public ContentSubresourceFilterThrottleManager::Delegate, public ::testing::WithParamInterface<PageActivationNotificationTiming> { public: ContentSubresourceFilterThrottleManagerTest() : ContentSubresourceFilterThrottleManager::Delegate() {} ~ContentSubresourceFilterThrottleManagerTest() override {} // content::RenderViewHostTestHarness: void SetUp() override { content::RenderViewHostTestHarness::SetUp(); NavigateAndCommit(GURL("https://example.first")); // Initialize the ruleset dealer. std::vector<proto::UrlRule> rules; rules.push_back(testing::CreateWhitelistRuleForDocument( "whitelist.com", proto::ACTIVATION_TYPE_DOCUMENT, {"page-with-activation.com"})); rules.push_back(testing::CreateSuffixRule("disallowed.html")); ASSERT_NO_FATAL_FAILURE(test_ruleset_creator_.CreateRulesetWithRules( rules, &test_ruleset_pair_)); // Make the blocking task runner run on the current task runner for the // tests, to ensure that the NavigationSimulator properly runs all necessary // tasks while waiting for throttle checks to finish. dealer_handle_ = base::MakeUnique<VerifiedRulesetDealer::Handle>( base::MessageLoop::current()->task_runner()); dealer_handle_->SetRulesetFile( testing::TestRuleset::Open(test_ruleset_pair_.indexed)); throttle_manager_ = base::MakeUnique<ContentSubresourceFilterThrottleManager>( this, dealer_handle_.get(), RenderViewHostTestHarness::web_contents()); Observe(RenderViewHostTestHarness::web_contents()); } void TearDown() override { throttle_manager_.reset(); dealer_handle_.reset(); base::RunLoop().RunUntilIdle(); content::RenderViewHostTestHarness::TearDown(); } void ExpectActivationSignalForFrame(content::RenderFrameHost* rfh, bool expect_activation) { content::MockRenderProcessHost* render_process_host = static_cast<content::MockRenderProcessHost*>(rfh->GetProcess()); const IPC::Message* message = render_process_host->sink().GetFirstMessageMatching( SubresourceFilterMsg_ActivateForNextCommittedLoad::ID); ASSERT_EQ(expect_activation, !!message); if (expect_activation) { std::tuple<ActivationState> args; SubresourceFilterMsg_ActivateForNextCommittedLoad::Read(message, &args); ActivationLevel level = std::get<0>(args).activation_level; EXPECT_NE(ActivationLevel::DISABLED, level); } render_process_host->sink().ClearMessages(); } // Helper methods: void CreateTestNavigation(const GURL& url, content::RenderFrameHost* render_frame_host) { DCHECK(!navigation_simulator_); DCHECK(render_frame_host); navigation_simulator_ = content::NavigationSimulator::CreateRendererInitiated( url, render_frame_host); } void CreateSubframeWithTestNavigation(const GURL& url, content::RenderFrameHost* parent) { content::RenderFrameHost* subframe = content::RenderFrameHostTester::For(parent)->AppendChild( base::StringPrintf("subframe-%s", url.spec().c_str())); CreateTestNavigation(url, subframe); } void SimulateStartAndExpectResult( content::NavigationThrottle::ThrottleCheckResult expect_result) { navigation_simulator_->Start(); content::NavigationThrottle::ThrottleCheckResult result = navigation_simulator_->GetLastThrottleCheckResult(); EXPECT_EQ(expect_result, result); if (result != content::NavigationThrottle::PROCEED) navigation_simulator_.reset(); } void SimulateRedirectAndExpectResult( const GURL& new_url, content::NavigationThrottle::ThrottleCheckResult expect_result) { navigation_simulator_->Redirect(new_url); content::NavigationThrottle::ThrottleCheckResult result = navigation_simulator_->GetLastThrottleCheckResult(); EXPECT_EQ(expect_result, result); if (result != content::NavigationThrottle::PROCEED) navigation_simulator_.reset(); } // Returns the RenderFrameHost that the navigation commit in. content::RenderFrameHost* SimulateCommitAndExpectResult( content::NavigationThrottle::ThrottleCheckResult expect_result) { navigation_simulator_->Commit(); content::NavigationThrottle::ThrottleCheckResult result = navigation_simulator_->GetLastThrottleCheckResult(); EXPECT_EQ(expect_result, result); auto scoped_simulator = std::move(navigation_simulator_); if (result == content::NavigationThrottle::PROCEED) return scoped_simulator->GetFinalRenderFrameHost(); return nullptr; } void SimulateSameDocumentCommit() { navigation_simulator_->CommitSameDocument(); navigation_simulator_.reset(); } void SimulateFailedNavigation(net::Error error) { navigation_simulator_->Fail(error); if (error != net::ERR_ABORTED) { navigation_simulator_->CommitErrorPage(); } navigation_simulator_.reset(); } void NavigateAndCommitMainFrame(const GURL& url) { CreateTestNavigation(url, main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); } bool ManagerHasRulesetHandle() { return throttle_manager_->ruleset_handle_for_testing(); } int disallowed_notification_count() { return disallowed_notification_count_; } protected: // content::WebContentsObserver void DidStartNavigation( content::NavigationHandle* navigation_handle) override { if (navigation_handle->IsSameDocument()) return; // Inject the proper throttles at this time. std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; PageActivationNotificationTiming state = ::testing::UnitTest::GetInstance()->current_test_info()->value_param() ? GetParam() : WILL_PROCESS_RESPONSE; throttles.push_back(base::MakeUnique<MockPageStateActivationThrottle>( navigation_handle, state)); throttle_manager_->MaybeAppendNavigationThrottles(navigation_handle, &throttles); for (auto& it : throttles) { navigation_handle->RegisterThrottleForTesting(std::move(it)); } } // ContentSubresourceFilterThrottleManager::Delegate: void OnFirstSubresourceLoadDisallowed() override { ++disallowed_notification_count_; } private: testing::TestRulesetCreator test_ruleset_creator_; testing::TestRulesetPair test_ruleset_pair_; std::unique_ptr<VerifiedRulesetDealer::Handle> dealer_handle_; std::unique_ptr<ContentSubresourceFilterThrottleManager> throttle_manager_; std::unique_ptr<content::NavigationSimulator> navigation_simulator_; // Incremented on every OnFirstSubresourceLoadDisallowed call. int disallowed_notification_count_ = 0; DISALLOW_COPY_AND_ASSIGN(ContentSubresourceFilterThrottleManagerTest); }; INSTANTIATE_TEST_CASE_P(PageActivationNotificationTiming, ContentSubresourceFilterThrottleManagerTest, ::testing::Values(WILL_START_REQUEST, WILL_PROCESS_RESPONSE)); TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateMainFrameAndFilterSubframeNavigation) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // A disallowed subframe navigation should be successfully filtered. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, NoPageActivation) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithNoActivation)); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); EXPECT_FALSE(ManagerHasRulesetHandle()); // A disallowed subframe navigation should not be filtered. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); EXPECT_EQ(0, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateMainFrameAndDoNotFilterDryRun) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithDryRun)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // A disallowed subframe navigation should not be filtered in dry-run mode. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* child = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); // But it should still be activated. ExpectActivationSignalForFrame(child, true /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateMainFrameAndFilterSubframeNavigationOnRedirect) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // A disallowed subframe navigation via redirect should be successfully // filtered. CreateSubframeWithTestNavigation( GURL("https://www.example.com/before-redirect.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::NavigationThrottle::ThrottleCheckResult expected_result = content::IsBrowserSideNavigationEnabled() ? content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE : content::NavigationThrottle::CANCEL; SimulateRedirectAndExpectResult( GURL("https://www.example.com/disallowed.html"), expected_result); EXPECT_EQ(1, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateMainFrameAndDoNotFilterSubframeNavigation) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // An allowed subframe navigation should complete successfully. CreateSubframeWithTestNavigation( GURL("https://www.example.com/allowed1.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); SimulateRedirectAndExpectResult(GURL("https://www.example.com/allowed2.html"), content::NavigationThrottle::PROCEED); content::RenderFrameHost* child = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(child, true /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); } // This should fail if the throttle manager notifies the delegate twice of a // disallowed load for the same page load. TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateMainFrameAndFilterTwoSubframeNavigations) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // A disallowed subframe navigation should be successfully filtered. CreateSubframeWithTestNavigation( GURL("https://www.example.com/1/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); CreateSubframeWithTestNavigation( GURL("https://www.example.com/2/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateTwoMainFramesAndFilterTwoSubframeNavigations) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // A disallowed subframe navigation should be successfully filtered. CreateSubframeWithTestNavigation( GURL("https://www.example.com/1/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); // Commit another navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation2)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); CreateSubframeWithTestNavigation( GURL("https://www.example.com/2/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(2, disallowed_notification_count()); } // Test that the disallow load notification will not be repeated for the first // disallowed load that follows a same-document navigation. TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivateMainFrameDoNotNotifyAfterSameDocumentNav) { // Commit a navigation that triggers page level activation. NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // A disallowed subframe navigation should be successfully filtered. CreateSubframeWithTestNavigation( GURL("https://www.example.com/1/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); // Commit another navigation that triggers page level activation. GURL url2 = GURL(base::StringPrintf("%s#ref", kTestURLWithActivation)); CreateTestNavigation(url2, main_rfh()); SimulateSameDocumentCommit(); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); CreateSubframeWithTestNavigation( GURL("https://www.example.com/2/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, DoNotFilterForInactiveFrame) { NavigateAndCommitMainFrame(GURL("https://do-not-activate.html")); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); // A subframe navigation should complete successfully. CreateSubframeWithTestNavigation(GURL("https://www.example.com/allowed.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* child = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(child, false /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); } // Once there are no activated frames, the manager drops its ruleset handle. If // another frame is activated, make sure the handle is regenerated. TEST_P(ContentSubresourceFilterThrottleManagerTest, RulesetHandleRegeneration) { NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); // Simulate a renderer crash which should delete the frame. EXPECT_TRUE(ManagerHasRulesetHandle()); process()->SimulateCrash(); EXPECT_FALSE(ManagerHasRulesetHandle()); NavigateAndCommit(GURL("https://example.reset")); NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(2, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, SameSiteNavigation_RulesetGoesAway) { GURL same_site_inactive_url = GURL(base::StringPrintf("%sinactive.html", kTestURLWithActivation)); NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); EXPECT_TRUE(ManagerHasRulesetHandle()); NavigateAndCommitMainFrame(same_site_inactive_url); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); EXPECT_FALSE(ManagerHasRulesetHandle()); // A subframe navigation should complete successfully. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* child = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(child, false /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, SameSiteFailedNavigation_MaintainActivation) { NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); EXPECT_TRUE(ManagerHasRulesetHandle()); GURL same_site_inactive_url = GURL(base::StringPrintf("%sinactive.html", kTestURLWithActivation)); CreateTestNavigation(same_site_inactive_url, main_rfh()); SimulateFailedNavigation(net::ERR_ABORTED); EXPECT_TRUE(ManagerHasRulesetHandle()); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); // A subframe navigation fail. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); } TEST_P(ContentSubresourceFilterThrottleManagerTest, FailedNavigationToErrorPage_NoActivation) { NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); EXPECT_TRUE(ManagerHasRulesetHandle()); GURL same_site_inactive_url = GURL(base::StringPrintf("%sinactive.html", kTestURLWithActivation)); CreateTestNavigation(same_site_inactive_url, main_rfh()); SimulateFailedNavigation(net::ERR_FAILED); EXPECT_FALSE(ManagerHasRulesetHandle()); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* child = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(child, false /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); } // Ensure activation propagates into great-grandchild frames, including cross // process ones. TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivationPropagation) { NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // Navigate a subframe to a URL that is not itself disallowed. Subresource // filtering for this subframe document should still be activated. CreateSubframeWithTestNavigation(GURL("https://www.a.com/allowed.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* subframe1 = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(subframe1, true /* expect_activation */); // Navigate a sub-subframe to a URL that is not itself disallowed. Subresource // filtering for this subframe document should still be activated. CreateSubframeWithTestNavigation(GURL("https://www.b.com/allowed.html"), subframe1); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* subframe2 = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(subframe2, true /* expect_activation */); // A final, nested subframe navigation is filtered. CreateSubframeWithTestNavigation(GURL("https://www.c.com/disallowed.html"), subframe2); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); } // Ensure activation propagates through whitelisted documents. TEST_P(ContentSubresourceFilterThrottleManagerTest, ActivationPropagation2) { NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // Navigate a subframe that is not filtered, but should still activate. CreateSubframeWithTestNavigation(GURL("https://whitelist.com"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* subframe1 = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(subframe1, true /* expect_activation */); // Navigate a sub-subframe that is not filtered due to the whitelist. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), subframe1); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* subframe2 = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(subframe2, true /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); // An identical series of events that don't match whitelist rules cause // filtering. CreateSubframeWithTestNavigation(GURL("https://average-joe.com"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* subframe3 = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(subframe3, true /* expect_activation */); // Navigate a sub-subframe that is not filtered due to the whitelist. CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), subframe3); SimulateStartAndExpectResult( content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE); EXPECT_EQ(1, disallowed_notification_count()); } // Same-site navigations within a single RFH do not persist activation. TEST_P(ContentSubresourceFilterThrottleManagerTest, SameSiteNavigationStopsActivation) { NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */); // Mock a same-site navigation, in the same RFH, this URL does not trigger // page level activation. NavigateAndCommitMainFrame( GURL(base::StringPrintf("%s/some_path/", kTestURLWithActivation))); ExpectActivationSignalForFrame(main_rfh(), false /* expect_activation */); CreateSubframeWithTestNavigation( GURL("https://www.example.com/disallowed.html"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* child = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(child, false /* expect_activation */); EXPECT_EQ(0, disallowed_notification_count()); } TEST_F(ContentSubresourceFilterThrottleManagerTest, LogActivation) { base::HistogramTester tester; const char kActivationStateHistogram[] = "SubresourceFilter.PageLoad.ActivationState"; NavigateAndCommitMainFrame(GURL(kTestURLWithDryRun)); tester.ExpectBucketCount(kActivationStateHistogram, static_cast<int>(ActivationLevel::DRYRUN), 1); NavigateAndCommitMainFrame(GURL(kTestURLWithNoActivation)); tester.ExpectBucketCount(kActivationStateHistogram, static_cast<int>(ActivationLevel::DISABLED), 1); NavigateAndCommitMainFrame(GURL(kTestURLWithActivation)); tester.ExpectBucketCount(kActivationStateHistogram, static_cast<int>(ActivationLevel::ENABLED), 1); // Navigate a subframe that is not filtered, but should still activate. CreateSubframeWithTestNavigation(GURL("https://whitelist.com"), main_rfh()); SimulateStartAndExpectResult(content::NavigationThrottle::PROCEED); content::RenderFrameHost* subframe1 = SimulateCommitAndExpectResult(content::NavigationThrottle::PROCEED); ExpectActivationSignalForFrame(subframe1, true /* expect_activation */); tester.ExpectTotalCount(kActivationStateHistogram, 3); // Only those with page level activation do ruleset lookups. tester.ExpectTotalCount("SubresourceFilter.PageLoad.Activation.WallDuration", 2); tester.ExpectTotalCount("SubresourceFilter.PageLoad.Activation.CPUDuration", 2); } // TODO(csharrison): Make sure the following conditions are exercised in tests: // // - Synchronous navigations to about:blank. These hit issues with the // NavigationSimulator currently. } // namespace subresource_filter
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include <d3d11_4.h> #include "draw_call_tracker.hpp" struct DECLSPEC_UUID("27B0246B-2152-4D42-AD11-32489472238F") D3D11DeviceContext : ID3D11DeviceContext4 { D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext *original); D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext1 *original); D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext2 *original); D3D11DeviceContext(D3D11Device *device, ID3D11DeviceContext3 *original); D3D11DeviceContext(const D3D11DeviceContext &) = delete; D3D11DeviceContext &operator=(const D3D11DeviceContext &) = delete; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObj) override; ULONG STDMETHODCALLTYPE AddRef() override; ULONG STDMETHODCALLTYPE Release() override; #pragma region ID3D11DeviceChild void STDMETHODCALLTYPE GetDevice(ID3D11Device **ppDevice) override; HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData) override; HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT DataSize, const void *pData) override; HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown *pData) override; #pragma endregion #pragma region ID3D11DeviceContext void STDMETHODCALLTYPE VSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) override; void STDMETHODCALLTYPE PSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) override; void STDMETHODCALLTYPE PSSetShader(ID3D11PixelShader *pPixelShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) override; void STDMETHODCALLTYPE PSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) override; void STDMETHODCALLTYPE VSSetShader(ID3D11VertexShader *pVertexShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) override; void STDMETHODCALLTYPE DrawIndexed(UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation) override; void STDMETHODCALLTYPE Draw(UINT VertexCount, UINT StartVertexLocation) override; HRESULT STDMETHODCALLTYPE Map(ID3D11Resource *pResource, UINT Subresource, D3D11_MAP MapType, UINT MapFlags, D3D11_MAPPED_SUBRESOURCE *pMappedResource) override; void STDMETHODCALLTYPE Unmap(ID3D11Resource *pResource, UINT Subresource) override; void STDMETHODCALLTYPE PSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) override; void STDMETHODCALLTYPE IASetInputLayout(ID3D11InputLayout *pInputLayout) override; void STDMETHODCALLTYPE IASetVertexBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppVertexBuffers, const UINT *pStrides, const UINT *pOffsets) override; void STDMETHODCALLTYPE IASetIndexBuffer(ID3D11Buffer *pIndexBuffer, DXGI_FORMAT Format, UINT Offset) override; void STDMETHODCALLTYPE DrawIndexedInstanced(UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) override; void STDMETHODCALLTYPE DrawInstanced(UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) override; void STDMETHODCALLTYPE GSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) override; void STDMETHODCALLTYPE GSSetShader(ID3D11GeometryShader *pShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) override; void STDMETHODCALLTYPE IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY Topology) override; void STDMETHODCALLTYPE VSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) override; void STDMETHODCALLTYPE VSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) override; void STDMETHODCALLTYPE Begin(ID3D11Asynchronous *pAsync) override; void STDMETHODCALLTYPE End(ID3D11Asynchronous *pAsync) override; HRESULT STDMETHODCALLTYPE GetData(ID3D11Asynchronous *pAsync, void *pData, UINT DataSize, UINT GetDataFlags) override; void STDMETHODCALLTYPE SetPredication(ID3D11Predicate *pPredicate, BOOL PredicateValue) override; void STDMETHODCALLTYPE GSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) override; void STDMETHODCALLTYPE GSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) override; void STDMETHODCALLTYPE OMSetRenderTargets(UINT NumViews, ID3D11RenderTargetView *const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView) override; void STDMETHODCALLTYPE OMSetRenderTargetsAndUnorderedAccessViews(UINT NumRTVs, ID3D11RenderTargetView *const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView, UINT UAVStartSlot, UINT NumUAVs, ID3D11UnorderedAccessView *const *ppUnorderedAccessViews, const UINT *pUAVInitialCounts) override; void STDMETHODCALLTYPE OMSetBlendState(ID3D11BlendState *pBlendState, const FLOAT BlendFactor[4], UINT SampleMask) override; void STDMETHODCALLTYPE OMSetDepthStencilState(ID3D11DepthStencilState *pDepthStencilState, UINT StencilRef) override; void STDMETHODCALLTYPE SOSetTargets(UINT NumBuffers, ID3D11Buffer *const *ppSOTargets, const UINT *pOffsets) override; void STDMETHODCALLTYPE DrawAuto() override; void STDMETHODCALLTYPE DrawIndexedInstancedIndirect(ID3D11Buffer *pBufferForArgs, UINT AlignedByteOffsetForArgs) override; void STDMETHODCALLTYPE DrawInstancedIndirect(ID3D11Buffer *pBufferForArgs, UINT AlignedByteOffsetForArgs) override; void STDMETHODCALLTYPE Dispatch(UINT ThreadGroupCountX, UINT ThreadGroupCountY, UINT ThreadGroupCountZ) override; void STDMETHODCALLTYPE DispatchIndirect(ID3D11Buffer *pBufferForArgs, UINT AlignedByteOffsetForArgs) override; void STDMETHODCALLTYPE RSSetState(ID3D11RasterizerState *pRasterizerState) override; void STDMETHODCALLTYPE RSSetViewports(UINT NumViewports, const D3D11_VIEWPORT *pViewports) override; void STDMETHODCALLTYPE RSSetScissorRects(UINT NumRects, const D3D11_RECT *pRects) override; void STDMETHODCALLTYPE CopySubresourceRegion(ID3D11Resource *pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ, ID3D11Resource *pSrcResource, UINT SrcSubresource, const D3D11_BOX *pSrcBox) override; void STDMETHODCALLTYPE CopyResource(ID3D11Resource *pDstResource, ID3D11Resource *pSrcResource) override; void STDMETHODCALLTYPE UpdateSubresource(ID3D11Resource *pDstResource, UINT DstSubresource, const D3D11_BOX *pDstBox, const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) override; void STDMETHODCALLTYPE CopyStructureCount(ID3D11Buffer *pDstBuffer, UINT DstAlignedByteOffset, ID3D11UnorderedAccessView *pSrcView) override; void STDMETHODCALLTYPE ClearRenderTargetView(ID3D11RenderTargetView *pRenderTargetView, const FLOAT ColorRGBA[4]) override; void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(ID3D11UnorderedAccessView *pUnorderedAccessView, const UINT Values[4]) override; void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(ID3D11UnorderedAccessView *pUnorderedAccessView, const FLOAT Values[4]) override; void STDMETHODCALLTYPE ClearDepthStencilView(ID3D11DepthStencilView *pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) override; void STDMETHODCALLTYPE GenerateMips(ID3D11ShaderResourceView *pShaderResourceView) override; void STDMETHODCALLTYPE SetResourceMinLOD(ID3D11Resource *pResource, FLOAT MinLOD) override; FLOAT STDMETHODCALLTYPE GetResourceMinLOD(ID3D11Resource *pResource) override; void STDMETHODCALLTYPE ResolveSubresource(ID3D11Resource *pDstResource, UINT DstSubresource, ID3D11Resource *pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) override; void STDMETHODCALLTYPE ExecuteCommandList(ID3D11CommandList *pCommandList, BOOL RestoreContextState) override; void STDMETHODCALLTYPE HSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) override; void STDMETHODCALLTYPE HSSetShader(ID3D11HullShader *pHullShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) override; void STDMETHODCALLTYPE HSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) override; void STDMETHODCALLTYPE HSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) override; void STDMETHODCALLTYPE DSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) override; void STDMETHODCALLTYPE DSSetShader(ID3D11DomainShader *pDomainShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) override; void STDMETHODCALLTYPE DSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) override; void STDMETHODCALLTYPE DSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) override; void STDMETHODCALLTYPE CSSetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView *const *ppShaderResourceViews) override; void STDMETHODCALLTYPE CSSetUnorderedAccessViews(UINT StartSlot, UINT NumUAVs, ID3D11UnorderedAccessView *const *ppUnorderedAccessViews, const UINT *pUAVInitialCounts) override; void STDMETHODCALLTYPE CSSetShader(ID3D11ComputeShader *pComputeShader, ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) override; void STDMETHODCALLTYPE CSSetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState *const *ppSamplers) override; void STDMETHODCALLTYPE CSSetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers) override; void STDMETHODCALLTYPE VSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) override; void STDMETHODCALLTYPE PSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) override; void STDMETHODCALLTYPE PSGetShader(ID3D11PixelShader **ppPixelShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) override; void STDMETHODCALLTYPE PSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) override; void STDMETHODCALLTYPE VSGetShader(ID3D11VertexShader **ppVertexShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) override; void STDMETHODCALLTYPE PSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) override; void STDMETHODCALLTYPE IAGetInputLayout(ID3D11InputLayout **ppInputLayout) override; void STDMETHODCALLTYPE IAGetVertexBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppVertexBuffers, UINT *pStrides, UINT *pOffsets) override; void STDMETHODCALLTYPE IAGetIndexBuffer(ID3D11Buffer **pIndexBuffer, DXGI_FORMAT *Format, UINT *Offset) override; void STDMETHODCALLTYPE GSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) override; void STDMETHODCALLTYPE GSGetShader(ID3D11GeometryShader **ppGeometryShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) override; void STDMETHODCALLTYPE IAGetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY *pTopology) override; void STDMETHODCALLTYPE VSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) override; void STDMETHODCALLTYPE VSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) override; void STDMETHODCALLTYPE GetPredication(ID3D11Predicate **ppPredicate, BOOL *pPredicateValue) override; void STDMETHODCALLTYPE GSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) override; void STDMETHODCALLTYPE GSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) override; void STDMETHODCALLTYPE OMGetRenderTargets(UINT NumViews, ID3D11RenderTargetView **ppRenderTargetViews, ID3D11DepthStencilView **ppDepthStencilView) override; void STDMETHODCALLTYPE OMGetRenderTargetsAndUnorderedAccessViews(UINT NumRTVs, ID3D11RenderTargetView **ppRenderTargetViews, ID3D11DepthStencilView **ppDepthStencilView, UINT UAVStartSlot, UINT NumUAVs, ID3D11UnorderedAccessView **ppUnorderedAccessViews) override; void STDMETHODCALLTYPE OMGetBlendState(ID3D11BlendState **ppBlendState, FLOAT BlendFactor[4], UINT *pSampleMask) override; void STDMETHODCALLTYPE OMGetDepthStencilState(ID3D11DepthStencilState **ppDepthStencilState, UINT *pStencilRef) override; void STDMETHODCALLTYPE SOGetTargets(UINT NumBuffers, ID3D11Buffer **ppSOTargets) override; void STDMETHODCALLTYPE RSGetState(ID3D11RasterizerState **ppRasterizerState) override; void STDMETHODCALLTYPE RSGetViewports(UINT *pNumViewports, D3D11_VIEWPORT *pViewports) override; void STDMETHODCALLTYPE RSGetScissorRects(UINT *pNumRects, D3D11_RECT *pRects) override; void STDMETHODCALLTYPE HSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) override; void STDMETHODCALLTYPE HSGetShader(ID3D11HullShader **ppHullShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) override; void STDMETHODCALLTYPE HSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) override; void STDMETHODCALLTYPE HSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) override; void STDMETHODCALLTYPE DSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) override; void STDMETHODCALLTYPE DSGetShader(ID3D11DomainShader **ppDomainShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) override; void STDMETHODCALLTYPE DSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) override; void STDMETHODCALLTYPE DSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) override; void STDMETHODCALLTYPE CSGetShaderResources(UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView **ppShaderResourceViews) override; void STDMETHODCALLTYPE CSGetUnorderedAccessViews(UINT StartSlot, UINT NumUAVs, ID3D11UnorderedAccessView **ppUnorderedAccessViews) override; void STDMETHODCALLTYPE CSGetShader(ID3D11ComputeShader **ppComputeShader, ID3D11ClassInstance **ppClassInstances, UINT *pNumClassInstances) override; void STDMETHODCALLTYPE CSGetSamplers(UINT StartSlot, UINT NumSamplers, ID3D11SamplerState **ppSamplers) override; void STDMETHODCALLTYPE CSGetConstantBuffers(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers) override; void STDMETHODCALLTYPE ClearState() override; void STDMETHODCALLTYPE Flush() override; UINT STDMETHODCALLTYPE GetContextFlags() override; HRESULT STDMETHODCALLTYPE FinishCommandList(BOOL RestoreDeferredContextState, ID3D11CommandList **ppCommandList) override; D3D11_DEVICE_CONTEXT_TYPE STDMETHODCALLTYPE GetType() override; #pragma endregion #pragma region ID3D11DeviceContext1 void STDMETHODCALLTYPE CopySubresourceRegion1(ID3D11Resource *pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ, ID3D11Resource *pSrcResource, UINT SrcSubresource, const D3D11_BOX *pSrcBox, UINT CopyFlags) override; void STDMETHODCALLTYPE UpdateSubresource1(ID3D11Resource *pDstResource, UINT DstSubresource, const D3D11_BOX *pDstBox, const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch, UINT CopyFlags) override; void STDMETHODCALLTYPE DiscardResource(ID3D11Resource *pResource) override; void STDMETHODCALLTYPE DiscardView(ID3D11View *pResourceView) override; void STDMETHODCALLTYPE VSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) override; void STDMETHODCALLTYPE HSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) override; void STDMETHODCALLTYPE DSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) override; void STDMETHODCALLTYPE GSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) override; void STDMETHODCALLTYPE PSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) override; void STDMETHODCALLTYPE CSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer *const *ppConstantBuffers, const UINT *pFirstConstant, const UINT *pNumConstants) override; void STDMETHODCALLTYPE VSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) override; void STDMETHODCALLTYPE HSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) override; void STDMETHODCALLTYPE DSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) override; void STDMETHODCALLTYPE GSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) override; void STDMETHODCALLTYPE PSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) override; void STDMETHODCALLTYPE CSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer **ppConstantBuffers, UINT *pFirstConstant, UINT *pNumConstants) override; void STDMETHODCALLTYPE SwapDeviceContextState(ID3DDeviceContextState *pState, ID3DDeviceContextState **ppPreviousState) override; void STDMETHODCALLTYPE ClearView(ID3D11View *pView, const FLOAT Color[4], const D3D11_RECT *pRect, UINT NumRects) override; void STDMETHODCALLTYPE DiscardView1(ID3D11View *pResourceView, const D3D11_RECT *pRects, UINT NumRects) override; #pragma endregion #pragma region ID3D11DeviceContext2 HRESULT STDMETHODCALLTYPE UpdateTileMappings(ID3D11Resource *pTiledResource, UINT NumTiledResourceRegions, const D3D11_TILED_RESOURCE_COORDINATE *pTiledResourceRegionStartCoordinates, const D3D11_TILE_REGION_SIZE *pTiledResourceRegionSizes, ID3D11Buffer *pTilePool, UINT NumRanges, const UINT *pRangeFlags, const UINT *pTilePoolStartOffsets, const UINT *pRangeTileCounts, UINT Flags) override; HRESULT STDMETHODCALLTYPE CopyTileMappings(ID3D11Resource *pDestTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pDestRegionStartCoordinate, ID3D11Resource *pSourceTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pSourceRegionStartCoordinate, const D3D11_TILE_REGION_SIZE *pTileRegionSize, UINT Flags) override; void STDMETHODCALLTYPE CopyTiles(ID3D11Resource *pTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate, const D3D11_TILE_REGION_SIZE *pTileRegionSize, ID3D11Buffer *pBuffer, UINT64 BufferStartOffsetInBytes, UINT Flags) override; void STDMETHODCALLTYPE UpdateTiles(ID3D11Resource *pDestTiledResource, const D3D11_TILED_RESOURCE_COORDINATE *pDestTileRegionStartCoordinate, const D3D11_TILE_REGION_SIZE *pDestTileRegionSize, const void *pSourceTileData, UINT Flags) override; HRESULT STDMETHODCALLTYPE ResizeTilePool(ID3D11Buffer *pTilePool, UINT64 NewSizeInBytes) override; void STDMETHODCALLTYPE TiledResourceBarrier(ID3D11DeviceChild *pTiledResourceOrViewAccessBeforeBarrier, ID3D11DeviceChild *pTiledResourceOrViewAccessAfterBarrier) override; BOOL STDMETHODCALLTYPE IsAnnotationEnabled() override; void STDMETHODCALLTYPE SetMarkerInt(LPCWSTR pLabel, INT Data) override; void STDMETHODCALLTYPE BeginEventInt(LPCWSTR pLabel, INT Data) override; void STDMETHODCALLTYPE EndEvent() override; #pragma endregion #pragma region ID3D11DeviceContext3 void STDMETHODCALLTYPE Flush1(D3D11_CONTEXT_TYPE ContextType, HANDLE hEvent) override; void STDMETHODCALLTYPE SetHardwareProtectionState(BOOL HwProtectionEnable) override; void STDMETHODCALLTYPE GetHardwareProtectionState(BOOL *pHwProtectionEnable) override; #pragma endregion #pragma region ID3D11DeviceContext4 HRESULT STDMETHODCALLTYPE Signal(ID3D11Fence *pFence, UINT64 Value) override; HRESULT STDMETHODCALLTYPE Wait(ID3D11Fence *pFence, UINT64 Value) override; #pragma endregion void clear_drawcall_stats(); #if RESHADE_DX11_CAPTURE_DEPTH_BUFFERS bool save_depth_texture(ID3D11DepthStencilView *pDepthStencilView, bool cleared); void track_active_rendertargets(UINT NumViews, ID3D11RenderTargetView *const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView); void track_cleared_depthstencil(ID3D11DepthStencilView* pDepthStencilView); #endif bool check_and_upgrade_interface(REFIID riid); LONG _ref = 1; ID3D11DeviceContext *_orig; unsigned int _interface_version; D3D11Device *const _device; reshade::d3d11::draw_call_tracker _draw_call_tracker; };
#include "math.h" #include "gtest/gtest.h" #include "expressions/parameterized_array_type/ParameterizedArrayTypeExpression.h" #include "zserio/RebindAlloc.h" namespace expressions { namespace parameterized_array_type { using allocator_type = ParameterizedArrayTypeExpression::allocator_type; template <typename T> using vector_type = std::vector<T, zserio::RebindAlloc<allocator_type, T>>; TEST(ParameterizedArrayTypeTest, bitSizeOfWithOptional) { ParameterizedArrayHolder parameterizedArrayHolder; const size_t arrayLength = 2; vector_type<ParameterizedArrayElement> array; array.reserve(arrayLength); for (size_t i = 1; i <= arrayLength; ++i) { ParameterizedArrayElement element; element.setValue1(0); array.push_back(element); } parameterizedArrayHolder.setArray(array); ParameterizedArrayTypeExpression parameterizedArrayTypeExpression; parameterizedArrayTypeExpression.setHolder(parameterizedArrayHolder); parameterizedArrayTypeExpression.setIsValue1Zero(true); parameterizedArrayTypeExpression.initializeChildren(); const size_t parameterizedArrayTypeExpressionBitSizeWithOptional = 33; ASSERT_EQ(parameterizedArrayTypeExpressionBitSizeWithOptional, parameterizedArrayTypeExpression.bitSizeOf()); } TEST(ParameterizedArrayTypeTest, bitSizeOfWithoutOptional) { ParameterizedArrayHolder parameterizedArrayHolder; const size_t arrayLength = 2; vector_type<ParameterizedArrayElement> array; array.reserve(arrayLength); for (size_t i = 1; i <= arrayLength; ++i) { ParameterizedArrayElement element; element.setValue1(1); array.push_back(element); } parameterizedArrayHolder.setArray(array); ParameterizedArrayTypeExpression parameterizedArrayTypeExpression; parameterizedArrayTypeExpression.setHolder(parameterizedArrayHolder); parameterizedArrayTypeExpression.setIsValue1Zero(false); parameterizedArrayTypeExpression.initializeChildren(); const size_t parameterizedArrayTypeExpressionBitSizeWithOptional = 32; ASSERT_EQ(parameterizedArrayTypeExpressionBitSizeWithOptional, parameterizedArrayTypeExpression.bitSizeOf()); } } // namespace parameterized_array_type } // namespace expressions
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/quads/render_pass.h" #include "cc/base/math_util.h" #include "cc/base/scoped_ptr_vector.h" #include "cc/output/copy_output_request.h" #include "cc/quads/checkerboard_draw_quad.h" #include "cc/quads/render_pass_draw_quad.h" #include "cc/test/geometry_test_utils.h" #include "cc/test/render_pass_test_common.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/effects/SkBlurImageFilter.h" #include "ui/gfx/transform.h" using cc::TestRenderPass; namespace cc { namespace { struct RenderPassSize { // If you add a new field to this class, make sure to add it to the // Copy() tests. RenderPass::Id id; QuadList quad_list; SharedQuadStateList shared_quad_state_list; gfx::Transform transform_to_root_target; gfx::Rect output_rect; gfx::Rect damage_rect; bool has_transparent_background; ScopedPtrVector<CopyOutputRequest> copy_callbacks; }; static void CompareRenderPassLists(const RenderPassList& expected_list, const RenderPassList& actual_list) { EXPECT_EQ(expected_list.size(), actual_list.size()); for (size_t i = 0; i < actual_list.size(); ++i) { RenderPass* expected = expected_list[i]; RenderPass* actual = actual_list[i]; EXPECT_EQ(expected->id, actual->id); EXPECT_RECT_EQ(expected->output_rect, actual->output_rect); EXPECT_EQ(expected->transform_to_root_target, actual->transform_to_root_target); EXPECT_RECT_EQ(expected->damage_rect, actual->damage_rect); EXPECT_EQ(expected->has_transparent_background, actual->has_transparent_background); EXPECT_EQ(expected->shared_quad_state_list.size(), actual->shared_quad_state_list.size()); EXPECT_EQ(expected->quad_list.size(), actual->quad_list.size()); for (size_t i = 0; i < expected->quad_list.size(); ++i) { EXPECT_EQ(expected->quad_list[i]->rect.ToString(), actual->quad_list[i]->rect.ToString()); EXPECT_EQ( expected->quad_list[i]->shared_quad_state->content_bounds.ToString(), actual->quad_list[i]->shared_quad_state->content_bounds.ToString()); } } } TEST(RenderPassTest, CopyShouldBeIdenticalExceptIdAndQuads) { RenderPass::Id id(3, 2); gfx::Rect output_rect(45, 22, 120, 13); gfx::Transform transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); gfx::Rect damage_rect(56, 123, 19, 43); bool has_transparent_background = true; scoped_ptr<TestRenderPass> pass = TestRenderPass::Create(); pass->SetAll(id, output_rect, damage_rect, transform_to_root, has_transparent_background); pass->copy_requests.push_back(CopyOutputRequest::CreateEmptyRequest()); // Stick a quad in the pass, this should not get copied. scoped_ptr<SharedQuadState> shared_state = SharedQuadState::Create(); shared_state->SetAll(gfx::Transform(), gfx::Size(), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state.Pass()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad = CheckerboardDrawQuad::Create(); checkerboard_quad->SetNew( pass->shared_quad_state_list.back(), gfx::Rect(), gfx::Rect(), SkColor()); pass->quad_list.push_back(checkerboard_quad.PassAs<DrawQuad>()); RenderPass::Id new_id(63, 4); scoped_ptr<RenderPass> copy = pass->Copy(new_id); EXPECT_EQ(new_id, copy->id); EXPECT_RECT_EQ(pass->output_rect, copy->output_rect); EXPECT_EQ(pass->transform_to_root_target, copy->transform_to_root_target); EXPECT_RECT_EQ(pass->damage_rect, copy->damage_rect); EXPECT_EQ(pass->has_transparent_background, copy->has_transparent_background); EXPECT_EQ(0u, copy->quad_list.size()); // The copy request should not be copied/duplicated. EXPECT_EQ(1u, pass->copy_requests.size()); EXPECT_EQ(0u, copy->copy_requests.size()); EXPECT_EQ(sizeof(RenderPassSize), sizeof(RenderPass)); } TEST(RenderPassTest, CopyAllShouldBeIdentical) { RenderPassList pass_list; RenderPass::Id id(3, 2); gfx::Rect output_rect(45, 22, 120, 13); gfx::Transform transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); gfx::Rect damage_rect(56, 123, 19, 43); bool has_transparent_background = true; scoped_ptr<TestRenderPass> pass = TestRenderPass::Create(); pass->SetAll(id, output_rect, damage_rect, transform_to_root, has_transparent_background); // Two quads using one shared state. scoped_ptr<SharedQuadState> shared_state1 = SharedQuadState::Create(); shared_state1->SetAll(gfx::Transform(), gfx::Size(1, 1), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state1.Pass()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad1 = CheckerboardDrawQuad::Create(); checkerboard_quad1->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(1, 1, 1, 1), gfx::Rect(1, 1, 1, 1), SkColor()); pass->quad_list.push_back(checkerboard_quad1.PassAs<DrawQuad>()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad2 = CheckerboardDrawQuad::Create(); checkerboard_quad2->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(2, 2, 2, 2), gfx::Rect(2, 2, 2, 2), SkColor()); pass->quad_list.push_back(checkerboard_quad2.PassAs<DrawQuad>()); // And two quads using another shared state. scoped_ptr<SharedQuadState> shared_state2 = SharedQuadState::Create(); shared_state2->SetAll(gfx::Transform(), gfx::Size(2, 2), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state2.Pass()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad3 = CheckerboardDrawQuad::Create(); checkerboard_quad3->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(3, 3, 3, 3), gfx::Rect(3, 3, 3, 3), SkColor()); pass->quad_list.push_back(checkerboard_quad3.PassAs<DrawQuad>()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad4 = CheckerboardDrawQuad::Create(); checkerboard_quad4->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(4, 4, 4, 4), gfx::Rect(4, 4, 4, 4), SkColor()); pass->quad_list.push_back(checkerboard_quad4.PassAs<DrawQuad>()); // A second render pass with a quad. RenderPass::Id contrib_id(4, 1); gfx::Rect contrib_output_rect(10, 15, 12, 17); gfx::Transform contrib_transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); gfx::Rect contrib_damage_rect(11, 16, 10, 15); bool contrib_has_transparent_background = true; scoped_ptr<TestRenderPass> contrib = TestRenderPass::Create(); contrib->SetAll(contrib_id, contrib_output_rect, contrib_damage_rect, contrib_transform_to_root, contrib_has_transparent_background); scoped_ptr<SharedQuadState> contrib_shared_state = SharedQuadState::Create(); contrib_shared_state->SetAll(gfx::Transform(), gfx::Size(2, 2), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); contrib->AppendSharedQuadState(contrib_shared_state.Pass()); scoped_ptr<CheckerboardDrawQuad> contrib_quad = CheckerboardDrawQuad::Create(); contrib_quad->SetNew(contrib->shared_quad_state_list.back(), gfx::Rect(3, 3, 3, 3), gfx::Rect(3, 3, 3, 3), SkColor()); contrib->quad_list.push_back(contrib_quad.PassAs<DrawQuad>()); // And a RenderPassDrawQuad for the contributing pass. scoped_ptr<RenderPassDrawQuad> pass_quad = RenderPassDrawQuad::Create(); pass_quad->SetNew(pass->shared_quad_state_list.back(), contrib_output_rect, contrib_output_rect, contrib_id, false, // is_replica 0, // mask_resource_id contrib_damage_rect, gfx::RectF(), // mask_uv_rect FilterOperations(), FilterOperations()); pass->quad_list.push_back(pass_quad.PassAs<DrawQuad>()); pass_list.push_back(pass.PassAs<RenderPass>()); pass_list.push_back(contrib.PassAs<RenderPass>()); // Make a copy with CopyAll(). RenderPassList copy_list; RenderPass::CopyAll(pass_list, &copy_list); CompareRenderPassLists(pass_list, copy_list); } TEST(RenderPassTest, CopyAllWithCulledQuads) { RenderPassList pass_list; RenderPass::Id id(3, 2); gfx::Rect output_rect(45, 22, 120, 13); gfx::Transform transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); gfx::Rect damage_rect(56, 123, 19, 43); bool has_transparent_background = true; scoped_ptr<TestRenderPass> pass = TestRenderPass::Create(); pass->SetAll(id, output_rect, damage_rect, transform_to_root, has_transparent_background); // A shared state with a quad. scoped_ptr<SharedQuadState> shared_state1 = SharedQuadState::Create(); shared_state1->SetAll(gfx::Transform(), gfx::Size(1, 1), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state1.Pass()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad1 = CheckerboardDrawQuad::Create(); checkerboard_quad1->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(1, 1, 1, 1), gfx::Rect(1, 1, 1, 1), SkColor()); pass->quad_list.push_back(checkerboard_quad1.PassAs<DrawQuad>()); // A shared state with no quads, they were culled. scoped_ptr<SharedQuadState> shared_state2 = SharedQuadState::Create(); shared_state2->SetAll(gfx::Transform(), gfx::Size(2, 2), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state2.Pass()); // A second shared state with no quads. scoped_ptr<SharedQuadState> shared_state3 = SharedQuadState::Create(); shared_state3->SetAll(gfx::Transform(), gfx::Size(2, 2), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state3.Pass()); // A last shared state with a quad again. scoped_ptr<SharedQuadState> shared_state4 = SharedQuadState::Create(); shared_state4->SetAll(gfx::Transform(), gfx::Size(2, 2), gfx::Rect(), gfx::Rect(), false, 1, SkXfermode::kSrcOver_Mode); pass->AppendSharedQuadState(shared_state4.Pass()); scoped_ptr<CheckerboardDrawQuad> checkerboard_quad2 = CheckerboardDrawQuad::Create(); checkerboard_quad2->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(3, 3, 3, 3), gfx::Rect(3, 3, 3, 3), SkColor()); pass->quad_list.push_back(checkerboard_quad2.PassAs<DrawQuad>()); pass_list.push_back(pass.PassAs<RenderPass>()); // Make a copy with CopyAll(). RenderPassList copy_list; RenderPass::CopyAll(pass_list, &copy_list); CompareRenderPassLists(pass_list, copy_list); } } // namespace } // namespace cc
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> #include <QClipboard> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(false); ui->stealthCB->setEnabled(true); ui->stealthCB->setVisible(true); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); ui->stealthCB->setVisible(false); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(true); ui->stealthCB->setEnabled(false); ui->stealthCB->setVisible(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); ui->stealthCB->setVisible(false); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); mapper->addMapping(ui->stealthCB, AddressTableModel::Type); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: { int typeInd = ui->stealthCB->isChecked() ? AddressTableModel::AT_Stealth : AddressTableModel::AT_Normal; address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text(), typeInd); } break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Freedomcoin address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); } void EditAddressDialog::on_EditAddressPasteButton_clicked() { // Paste text from clipboard into recipient field ui->addressEdit->setText(QApplication::clipboard()->text()); }
#include <torch/extension.h> #include <torch/csrc/autograd/variable.h> #include <pybind11/pybind11.h> #include "common.h" #include "cpu.cpp" namespace py = pybind11; using namespace pybind11::literals; using namespace std::string_literals; #ifdef NOCUDA Descent descend(MCTS m) { return mctscpu::descend(m); } TT root(MCTS m) { return mctscpu::root(m); } void backup(Backup m, TT leaves) { return mctscpu::backup(m, leaves); } #else Descent descend(MCTS m) { if (m.logits.t.device().is_cuda()) { return mctscuda::descend(m); } else { return mctscpu::descend(m); } } TT root(MCTS m) { if (m.logits.t.device().is_cuda()) { return mctscuda::root(m); } else { return mctscpu::root(m); } } void backup(Backup bk, TT leaves) { if (bk.terminal.t.device().is_cuda()) { return mctscuda::backup(bk, leaves); } else { return mctscpu::backup(bk, leaves); } } #endif PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { py::class_<Descent>(m, "Descent", py::module_local()) .def_property_readonly("parents", [](Descent r) { return r.parents.t; }) .def_property_readonly("actions", [](Descent r) { return r.actions.t; }); py::class_<MCTS>(m, "MCTS", py::module_local()) .def(py::init<TT, TT, TT, TT, TT, TT, TT>(), "logits"_a, "w"_a, "n"_a, "c_puct"_a, "seats"_a, "terminal"_a, "children"_a) .def_property_readonly("logits", [](MCTS s) { return s.logits.t; }) .def_property_readonly("w", [](MCTS s) { return s.w.t; }) .def_property_readonly("n", [](MCTS s) { return s.n.t; }) .def_property_readonly("c_puct", [](MCTS s) { return s.c_puct.t; }) .def_property_readonly("seats", [](MCTS s) { return s.seats.t; }) .def_property_readonly("terminal", [](MCTS s) { return s.terminal.t; }) .def_property_readonly("children", [](MCTS s) { return s.children.t; }); py::class_<Backup>(m, "Backup", py::module_local()) .def(py::init<TT, TT, TT, TT, TT, TT>(), "v"_a, "w"_a, "n"_a, "rewards"_a, "parents"_a, "terminal"_a); m.def("descend", &descend, "m"_a, py::call_guard<py::gil_scoped_release>()); m.def("root", &root, "m"_a, py::call_guard<py::gil_scoped_release>()); m.def("backup", &backup, "bk"_a, "leaves"_a, py::call_guard<py::gil_scoped_release>()); }
/* _______ ________ \ \ / _____/ ____ ___ / | \/ \ ____/ __ \ / \ / | \ \_\ \ ___/| | \ \____|__ /\______ /\___ >___| / \/ \/ \/ \/ The MIT License (MIT) COPYRIGHT (C) 2018 FIXCOM, LLC 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, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __NGEN_DRAWING_GPUSCHEME_HPP #define __NGEN_DRAWING_GPUSCHEME_HPP #include "Ngen.Drawing.GpuElement.hpp" namespace Ngen { namespace Drawing { class ngen_drawing_api GpuScheme { public: GpuScheme(const string& name, std::initializer_list<GpuElement> init, VoidStaticDelegate<GpuScheme*>::TFunction initializer) : mName(name), mElementMap(), mInitialize(initializer), mSize(0) { uword offset = 0; uword i = 0; for(auto e : init) { e.Offset(offset); mSize += e.Size(); offset += e.Size(); mElementMap.Add(e.Id(), e); i++; } } GpuScheme(const string& name, std::initializer_list<GpuElement> init) : mName(name), mElementMap(), mInitialize(), mSize(0) { uword offset = 0; uword i = 0; for(auto e : init) { e.Offset(offset); mSize += e.Size(); offset += e.Size(); mElementMap.Add(e.Id(), e); i++; } } uword Size() const { return mSize; } const mirror Name() const { return mName; } void Initialize() { mInitialize.Call(this); } GpuElement* Element(const string& usage, uword usageIndex) { return &mElementMap[usage+string::From(usageIndex)]; } Array<GpuElement> Elements() const { return mElementMap.Values(); } protected: const mirror mName; Map<mirror, GpuElement> mElementMap; VoidStaticDelegate<GpuScheme*> mInitialize; uword mSize; }; } } #endif // __NGEN_DRAWING_GPUSCHEME_HPP
/******************************************************************** Rhapsody : 8.0.5 Login : Paul Elder Component : DefaultComponent Configuration : DefaultConfig Model Element : Publisher_comp //! Generated Date : Fri, 18, Jul 2014 File Path : DefaultComponent\DefaultConfig\Publisher_comp.cpp *********************************************************************/ //## auto_generated #include "Publisher_comp.h" //## package Examples::Publisher_comp //## package Examples::Publisher_comp //## class Publisher_comp Publisher_comp::Publisher_comp() { } Publisher_comp::~Publisher_comp() { } /********************************************************************* File Path : DefaultComponent\DefaultConfig\Publisher_comp.cpp *********************************************************************/
//----------------------------------------------------------------------------------------------- // SmoothNoise.cpp // #include "./RawNoise.hpp" #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/common.hpp> #include <glm/geometric.hpp> ///////////////////////////////////////////////////////////////////////////////////////////////// // For all fractal (and Perlin) noise functions, the following internal naming conventions // are used, primarily to help me visualize 3D and 4D constructs clearly. They need not // have any actual bearing on / relationship to actual external coordinate systems. // // 1D noise: only X (+east / -west) // 2D noise: also Y (+north / -south) // 3D noise: also Z (+above / -below) // 4D noise: also T (+after / -before) ///////////////////////////////////////////////////////////////////////////////////////////////// namespace SquirrelNoise4 { namespace Easing { static float SmoothStep( float t ) { //return 2*(t*t*t) - 3*(t*t); //return t*t * (2*t-3); // optimised //return 3*(t*t) - 2*(t*t*t); return t*t * (3-2*t); // optimised } } // Easing //----------------------------------------------------------------------------------------------- float Compute1dFractalNoise( float position, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float currentPosition = position * (1.f / scale); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine noise values at nearby integer "grid point" positions float positionFloor = ::glm::floor( currentPosition ); int32_t indexWest = (int32_t) positionFloor; int32_t indexEast = indexWest + 1; float valueWest = Get1dNoiseZeroToOne( indexWest, seed ); float valueEast = Get1dNoiseZeroToOne( indexEast, seed ); // Do a smoothed (nonlinear) weighted average of nearby grid point values float distanceFromWest = currentPosition - positionFloor; float weightEast = Easing::SmoothStep( distanceFromWest ); // Gives rounder (nonlinear) results float weightWest = 1.f - weightEast; float noiseZeroToOne = (valueWest * weightWest) + (valueEast * weightEast); float noiseThisOctave = 2.f * (noiseZeroToOne - 0.5f); // Map from [0,1] to [-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPosition *= octaveScale; currentPosition += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used! totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- float Compute2dFractalNoise( float posX, float posY, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float invScale = (1.f / scale); ::glm::vec2 currentPos( posX * invScale, posY * invScale ); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine noise values at nearby integer "grid point" positions ::glm::vec2 cellMins( ::glm::floor( currentPos.x ), ::glm::floor( currentPos.y ) ); int32_t indexWestX = (int32_t) cellMins.x; int32_t indexSouthY = (int32_t) cellMins.y; int32_t indexEastX = indexWestX + 1; int32_t indexNorthY = indexSouthY + 1; float valueSouthWest = Get2dNoiseZeroToOne( indexWestX, indexSouthY, seed ); float valueSouthEast = Get2dNoiseZeroToOne( indexEastX, indexSouthY, seed ); float valueNorthWest = Get2dNoiseZeroToOne( indexWestX, indexNorthY, seed ); float valueNorthEast = Get2dNoiseZeroToOne( indexEastX, indexNorthY, seed ); // Do a smoothed (nonlinear) weighted average of nearby grid point values ::glm::vec2 displacementFromMins = currentPos - cellMins; float weightEast = Easing::SmoothStep( displacementFromMins.x ); float weightNorth = Easing::SmoothStep( displacementFromMins.y ); float weightWest = 1.f - weightEast; float weightSouth = 1.f - weightNorth; float blendSouth = (weightEast * valueSouthEast) + (weightWest * valueSouthWest); float blendNorth = (weightEast * valueNorthEast) + (weightWest * valueNorthWest); float blendTotal = (weightSouth * blendSouth) + (weightNorth * blendNorth); float noiseThisOctave = 2.f * (blendTotal - 0.5f); // Map from [0,1] to [-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPos *= octaveScale; currentPos.x += OCTAVE_OFFSET; // Add "irrational" offsets to noise position components currentPos.y += OCTAVE_OFFSET; // at each octave to break up their grid alignment ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- float Compute3dFractalNoise( float posX, float posY, float posZ, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float invScale = (1.f / scale); ::glm::vec3 currentPos( posX * invScale, posY * invScale, posZ * invScale ); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine noise values at nearby integer "grid point" positions ::glm::vec3 cellMins( ::glm::floor( currentPos.x ), ::glm::floor( currentPos.y ), ::glm::floor( currentPos.z ) ); int32_t indexWestX = (int32_t) cellMins.x; int32_t indexSouthY = (int32_t) cellMins.y; int32_t indexBelowZ = (int32_t) cellMins.z; int32_t indexEastX = indexWestX + 1; int32_t indexNorthY = indexSouthY + 1; int32_t indexAboveZ = indexBelowZ + 1; // Noise grid cell has 8 corners in 3D float aboveSouthWest = Get3dNoiseZeroToOne( indexWestX, indexSouthY, indexAboveZ, seed ); float aboveSouthEast = Get3dNoiseZeroToOne( indexEastX, indexSouthY, indexAboveZ, seed ); float aboveNorthWest = Get3dNoiseZeroToOne( indexWestX, indexNorthY, indexAboveZ, seed ); float aboveNorthEast = Get3dNoiseZeroToOne( indexEastX, indexNorthY, indexAboveZ, seed ); float belowSouthWest = Get3dNoiseZeroToOne( indexWestX, indexSouthY, indexBelowZ, seed ); float belowSouthEast = Get3dNoiseZeroToOne( indexEastX, indexSouthY, indexBelowZ, seed ); float belowNorthWest = Get3dNoiseZeroToOne( indexWestX, indexNorthY, indexBelowZ, seed ); float belowNorthEast = Get3dNoiseZeroToOne( indexEastX, indexNorthY, indexBelowZ, seed ); // Do a smoothed (nonlinear) weighted average of nearby grid point values ::glm::vec3 displacementFromMins = currentPos - cellMins; float weightEast = Easing::SmoothStep( displacementFromMins.x ); float weightNorth = Easing::SmoothStep( displacementFromMins.y ); float weightAbove = Easing::SmoothStep( displacementFromMins.z ); float weightWest = 1.f - weightEast; float weightSouth = 1.f - weightNorth; float weightBelow = 1.f - weightAbove; // 8-way blend (8 -> 4 -> 2 -> 1) float blendBelowSouth = (weightEast * belowSouthEast) + (weightWest * belowSouthWest); float blendBelowNorth = (weightEast * belowNorthEast) + (weightWest * belowNorthWest); float blendAboveSouth = (weightEast * aboveSouthEast) + (weightWest * aboveSouthWest); float blendAboveNorth = (weightEast * aboveNorthEast) + (weightWest * aboveNorthWest); float blendBelow = (weightSouth * blendBelowSouth) + (weightNorth * blendBelowNorth); float blendAbove = (weightSouth * blendAboveSouth) + (weightNorth * blendAboveNorth); float blendTotal = (weightBelow * blendBelow) + (weightAbove * blendAbove); float noiseThisOctave = 2.f * (blendTotal - 0.5f); // Map from [0,1] to [-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPos *= octaveScale; currentPos.x += OCTAVE_OFFSET; // Add "irrational" offsets to noise position components currentPos.y += OCTAVE_OFFSET; // at each octave to break up their grid alignment currentPos.z += OCTAVE_OFFSET; ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- float Compute4dFractalNoise( float posX, float posY, float posZ, float posT, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float invScale = (1.f / scale); ::glm::vec4 currentPos( posX * invScale, posY * invScale, posZ * invScale, posT * invScale ); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine noise values at nearby integer "grid point" positions ::glm::vec4 cellMins( ::glm::floor( currentPos.x ), ::glm::floor( currentPos.y ), ::glm::floor( currentPos.z ), ::glm::floor( currentPos.w ) ); int32_t indexWestX = (int32_t) cellMins.x; int32_t indexSouthY = (int32_t) cellMins.y; int32_t indexBelowZ = (int32_t) cellMins.z; int32_t indexBeforeT = (int32_t) cellMins.w; int32_t indexEastX = indexWestX + 1; int32_t indexNorthY = indexSouthY + 1; int32_t indexAboveZ = indexBelowZ + 1; int32_t indexAfterT = indexBeforeT + 1; // Noise grid cell has 16 "corners" in 4D float beforeBelowSW = Get4dNoiseZeroToOne( indexWestX, indexSouthY, indexBelowZ, indexBeforeT, seed ); float beforeBelowSE = Get4dNoiseZeroToOne( indexEastX, indexSouthY, indexBelowZ, indexBeforeT, seed ); float beforeBelowNW = Get4dNoiseZeroToOne( indexWestX, indexNorthY, indexBelowZ, indexBeforeT, seed ); float beforeBelowNE = Get4dNoiseZeroToOne( indexEastX, indexNorthY, indexBelowZ, indexBeforeT, seed ); float beforeAboveSW = Get4dNoiseZeroToOne( indexWestX, indexSouthY, indexAboveZ, indexBeforeT, seed ); float beforeAboveSE = Get4dNoiseZeroToOne( indexEastX, indexSouthY, indexAboveZ, indexBeforeT, seed ); float beforeAboveNW = Get4dNoiseZeroToOne( indexWestX, indexNorthY, indexAboveZ, indexBeforeT, seed ); float beforeAboveNE = Get4dNoiseZeroToOne( indexEastX, indexNorthY, indexAboveZ, indexBeforeT, seed ); float afterBelowSW = Get4dNoiseZeroToOne( indexWestX, indexSouthY, indexBelowZ, indexAfterT, seed ); float afterBelowSE = Get4dNoiseZeroToOne( indexEastX, indexSouthY, indexBelowZ, indexAfterT, seed ); float afterBelowNW = Get4dNoiseZeroToOne( indexWestX, indexNorthY, indexBelowZ, indexAfterT, seed ); float afterBelowNE = Get4dNoiseZeroToOne( indexEastX, indexNorthY, indexBelowZ, indexAfterT, seed ); float afterAboveSW = Get4dNoiseZeroToOne( indexWestX, indexSouthY, indexAboveZ, indexAfterT, seed ); float afterAboveSE = Get4dNoiseZeroToOne( indexEastX, indexSouthY, indexAboveZ, indexAfterT, seed ); float afterAboveNW = Get4dNoiseZeroToOne( indexWestX, indexNorthY, indexAboveZ, indexAfterT, seed ); float afterAboveNE = Get4dNoiseZeroToOne( indexEastX, indexNorthY, indexAboveZ, indexAfterT, seed ); // Do a smoothed (nonlinear) weighted average of nearby grid point values ::glm::vec4 displacementFromMins = currentPos - cellMins; float weightEast = Easing::SmoothStep( displacementFromMins.x ); float weightNorth = Easing::SmoothStep( displacementFromMins.y ); float weightAbove = Easing::SmoothStep( displacementFromMins.z ); float weightAfter = Easing::SmoothStep( displacementFromMins.w ); float weightWest = 1.f - weightEast; float weightSouth = 1.f - weightNorth; float weightBelow = 1.f - weightAbove; float weightBefore = 1.f - weightAfter; // 16-way blend (16 -> 8 -> 4 -> 2 -> 1) float blendBeforeBelowSouth = (weightEast * beforeBelowSE) + (weightWest * beforeBelowSW); float blendBeforeBelowNorth = (weightEast * beforeBelowNE) + (weightWest * beforeBelowNW); float blendBeforeAboveSouth = (weightEast * beforeAboveSE) + (weightWest * beforeAboveSW); float blendBeforeAboveNorth = (weightEast * beforeAboveNE) + (weightWest * beforeAboveNW); float blendAfterBelowSouth = (weightEast * afterBelowSE) + (weightWest * afterBelowSW); float blendAfterBelowNorth = (weightEast * afterBelowNE) + (weightWest * afterBelowNW); float blendAfterAboveSouth = (weightEast * afterAboveSE) + (weightWest * afterAboveSW); float blendAfterAboveNorth = (weightEast * afterAboveNE) + (weightWest * afterAboveNW); float blendBeforeBelow = (weightSouth * blendBeforeBelowSouth) + (weightNorth * blendBeforeBelowNorth); float blendBeforeAbove = (weightSouth * blendBeforeAboveSouth) + (weightNorth * blendBeforeAboveNorth); float blendAfterBelow = (weightSouth * blendAfterBelowSouth) + (weightNorth * blendAfterBelowNorth); float blendAfterAbove = (weightSouth * blendAfterAboveSouth) + (weightNorth * blendAfterAboveNorth); float blendBefore = (weightBelow * blendBeforeBelow) + (weightAbove * blendBeforeAbove); float blendAfter = (weightBelow * blendAfterBelow) + (weightAbove * blendAfterAbove); float blendTotal = (weightBefore * blendBefore) + (weightAfter * blendAfter); float noiseThisOctave = 2.f * (blendTotal - 0.5f); // Map from [0,1] to [-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPos *= octaveScale; currentPos.x += OCTAVE_OFFSET; // Add "irrational" offsets to noise position components currentPos.y += OCTAVE_OFFSET; // at each octave to break up their grid alignment currentPos.z += OCTAVE_OFFSET; currentPos.w += OCTAVE_OFFSET; ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- // Perlin noise is fractal noise with "gradient vector smoothing" applied. // // In 1D, the gradients are trivial: -1.0 or 1.0, so resulting noise is boring at one octave. // float Compute1dPerlinNoise( float position, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave const float gradients[2] = { -1.f, 1.f }; // 1D unit "gradient" vectors; one back, one forward float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float currentPosition = position * (1.f / scale); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine random "gradient vectors" (just +1 or -1 for 1D Perlin) for surrounding corners float positionFloor = (float) ::glm::floor( currentPosition ); int32_t indexWest = (int32_t) positionFloor; int32_t indexEast = indexWest + 1; float gradientWest = gradients[ Get1dNoiseUint32( indexWest, seed ) & 0x00000001 ]; float gradientEast = gradients[ Get1dNoiseUint32( indexEast, seed ) & 0x00000001 ]; // Dot each point's gradient with displacement from point to position float displacementFromWest = currentPosition - positionFloor; // always positive float displacementFromEast = displacementFromWest - 1.f; // always negative float dotWest = gradientWest * displacementFromWest; // 1D "dot product" is... multiply float dotEast = gradientEast * displacementFromEast; // Do a smoothed (nonlinear) weighted average of dot results float weightEast = Easing::SmoothStep( displacementFromWest ); float weightWest = 1.f - weightEast; float blendTotal = (weightWest * dotWest) + (weightEast * dotEast); float noiseThisOctave = 2.f * blendTotal; // 1D Perlin is in [-.5,.5]; map to [-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPosition *= octaveScale; currentPosition += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- // Perlin noise is fractal noise with "gradient vector smoothing" applied. // // In 2D, gradients are unit-length vectors in various directions with even angular distribution. // float Compute2dPerlinNoise( float posX, float posY, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave const ::glm::vec2 gradients[ 8 ] = // Normalized unit vectors in 8 quarter-cardinal directions { ::glm::vec2( +0.923879533f, +0.382683432f ), // 22.5 degrees (ENE) ::glm::vec2( +0.382683432f, +0.923879533f ), // 67.5 degrees (NNE) ::glm::vec2( -0.382683432f, +0.923879533f ), // 112.5 degrees (NNW) ::glm::vec2( -0.923879533f, +0.382683432f ), // 157.5 degrees (WNW) ::glm::vec2( -0.923879533f, -0.382683432f ), // 202.5 degrees (WSW) ::glm::vec2( -0.382683432f, -0.923879533f ), // 247.5 degrees (SSW) ::glm::vec2( +0.382683432f, -0.923879533f ), // 292.5 degrees (SSE) ::glm::vec2( +0.923879533f, -0.382683432f ) // 337.5 degrees (ESE) }; float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float invScale = (1.f / scale); ::glm::vec2 currentPos( posX * invScale, posY * invScale ); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine random unit "gradient vectors" for surrounding corners ::glm::vec2 cellMins( ::glm::floor( currentPos.x ), ::glm::floor( currentPos.y ) ); ::glm::vec2 cellMaxs( cellMins.x + 1.f, cellMins.y + 1.f ); int32_t indexWestX = (int32_t) cellMins.x; int32_t indexSouthY = (int32_t) cellMins.y; int32_t indexEastX = indexWestX + 1; int32_t indexNorthY = indexSouthY + 1; uint32_t noiseSW = Get2dNoiseUint32( indexWestX, indexSouthY, seed ); uint32_t noiseSE = Get2dNoiseUint32( indexEastX, indexSouthY, seed ); uint32_t noiseNW = Get2dNoiseUint32( indexWestX, indexNorthY, seed ); uint32_t noiseNE = Get2dNoiseUint32( indexEastX, indexNorthY, seed ); const ::glm::vec2& gradientSW = gradients[ noiseSW & 0x00000007 ]; const ::glm::vec2& gradientSE = gradients[ noiseSE & 0x00000007 ]; const ::glm::vec2& gradientNW = gradients[ noiseNW & 0x00000007 ]; const ::glm::vec2& gradientNE = gradients[ noiseNE & 0x00000007 ]; // Dot each corner's gradient with displacement from corner to position ::glm::vec2 displacementFromSW( currentPos.x - cellMins.x, currentPos.y - cellMins.y ); ::glm::vec2 displacementFromSE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y ); ::glm::vec2 displacementFromNW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y ); ::glm::vec2 displacementFromNE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y ); float dotSouthWest = ::glm::dot( gradientSW, displacementFromSW ); float dotSouthEast = ::glm::dot( gradientSE, displacementFromSE ); float dotNorthWest = ::glm::dot( gradientNW, displacementFromNW ); float dotNorthEast = ::glm::dot( gradientNE, displacementFromNE ); // Do a smoothed (nonlinear) weighted average of dot results float weightEast = Easing::SmoothStep( displacementFromSW.x ); float weightNorth = Easing::SmoothStep( displacementFromSW.y ); float weightWest = 1.f - weightEast; float weightSouth = 1.f - weightNorth; float blendSouth = (weightEast * dotSouthEast) + (weightWest * dotSouthWest); float blendNorth = (weightEast * dotNorthEast) + (weightWest * dotNorthWest); float blendTotal = (weightSouth * blendSouth) + (weightNorth * blendNorth); float noiseThisOctave = blendTotal * (1.f / 0.662578106f); // 2D Perlin is in [-.662578106,.662578106]; map to ~[-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPos *= octaveScale; currentPos.x += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids currentPos.y += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- // Perlin noise is fractal noise with "gradient vector smoothing" applied. // // In 3D, gradients are unit-length vectors in random (3D) directions. // float Compute3dPerlinNoise( float posX, float posY, float posZ, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave const float fSQRT_3_OVER_3 = 0.577350269189f; const ::glm::vec3 gradients[ 8 ] = // Traditional "12 edges" requires modulus and isn't any better. { ::glm::vec3( +fSQRT_3_OVER_3, +fSQRT_3_OVER_3, +fSQRT_3_OVER_3 ), // Normalized unit 3D vectors ::glm::vec3( -fSQRT_3_OVER_3, +fSQRT_3_OVER_3, +fSQRT_3_OVER_3 ), // pointing toward cube ::glm::vec3( +fSQRT_3_OVER_3, -fSQRT_3_OVER_3, +fSQRT_3_OVER_3 ), // corners, so components ::glm::vec3( -fSQRT_3_OVER_3, -fSQRT_3_OVER_3, +fSQRT_3_OVER_3 ), // are all sqrt(3)/3, i.e. ::glm::vec3( +fSQRT_3_OVER_3, +fSQRT_3_OVER_3, -fSQRT_3_OVER_3 ), // 0.5773502691896257645091f. ::glm::vec3( -fSQRT_3_OVER_3, +fSQRT_3_OVER_3, -fSQRT_3_OVER_3 ), // These are slightly better ::glm::vec3( +fSQRT_3_OVER_3, -fSQRT_3_OVER_3, -fSQRT_3_OVER_3 ), // than axes (1,0,0) and much ::glm::vec3( -fSQRT_3_OVER_3, -fSQRT_3_OVER_3, -fSQRT_3_OVER_3 ) // faster than edges (1,1,0). }; float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float invScale = (1.f / scale); ::glm::vec3 currentPos( posX * invScale, posY * invScale, posZ * invScale ); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine random unit "gradient vectors" for surrounding corners ::glm::vec3 cellMins( ::glm::floor( currentPos.x ), ::glm::floor( currentPos.y ), ::glm::floor( currentPos.z ) ); ::glm::vec3 cellMaxs( cellMins.x + 1.f, cellMins.y + 1.f, cellMins.z + 1.f ); int32_t indexWestX = (int32_t) cellMins.x; int32_t indexSouthY = (int32_t) cellMins.y; int32_t indexBelowZ = (int32_t) cellMins.z; int32_t indexEastX = indexWestX + 1; int32_t indexNorthY = indexSouthY + 1; int32_t indexAboveZ = indexBelowZ + 1; uint32_t noiseBelowSW = Get3dNoiseUint32( indexWestX, indexSouthY, indexBelowZ, seed ); uint32_t noiseBelowSE = Get3dNoiseUint32( indexEastX, indexSouthY, indexBelowZ, seed ); uint32_t noiseBelowNW = Get3dNoiseUint32( indexWestX, indexNorthY, indexBelowZ, seed ); uint32_t noiseBelowNE = Get3dNoiseUint32( indexEastX, indexNorthY, indexBelowZ, seed ); uint32_t noiseAboveSW = Get3dNoiseUint32( indexWestX, indexSouthY, indexAboveZ, seed ); uint32_t noiseAboveSE = Get3dNoiseUint32( indexEastX, indexSouthY, indexAboveZ, seed ); uint32_t noiseAboveNW = Get3dNoiseUint32( indexWestX, indexNorthY, indexAboveZ, seed ); uint32_t noiseAboveNE = Get3dNoiseUint32( indexEastX, indexNorthY, indexAboveZ, seed ); ::glm::vec3 gradientBelowSW = gradients[ noiseBelowSW & 0x00000007 ]; ::glm::vec3 gradientBelowSE = gradients[ noiseBelowSE & 0x00000007 ]; ::glm::vec3 gradientBelowNW = gradients[ noiseBelowNW & 0x00000007 ]; ::glm::vec3 gradientBelowNE = gradients[ noiseBelowNE & 0x00000007 ]; ::glm::vec3 gradientAboveSW = gradients[ noiseAboveSW & 0x00000007 ]; ::glm::vec3 gradientAboveSE = gradients[ noiseAboveSE & 0x00000007 ]; ::glm::vec3 gradientAboveNW = gradients[ noiseAboveNW & 0x00000007 ]; ::glm::vec3 gradientAboveNE = gradients[ noiseAboveNE & 0x00000007 ]; // Dot each corner's gradient with displacement from corner to position ::glm::vec3 displacementFromBelowSW( currentPos.x - cellMins.x, currentPos.y - cellMins.y, currentPos.z - cellMins.z ); ::glm::vec3 displacementFromBelowSE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y, currentPos.z - cellMins.z ); ::glm::vec3 displacementFromBelowNW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y, currentPos.z - cellMins.z ); ::glm::vec3 displacementFromBelowNE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y, currentPos.z - cellMins.z ); ::glm::vec3 displacementFromAboveSW( currentPos.x - cellMins.x, currentPos.y - cellMins.y, currentPos.z - cellMaxs.z ); ::glm::vec3 displacementFromAboveSE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y, currentPos.z - cellMaxs.z ); ::glm::vec3 displacementFromAboveNW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y, currentPos.z - cellMaxs.z ); ::glm::vec3 displacementFromAboveNE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y, currentPos.z - cellMaxs.z ); float dotBelowSW = ::glm::dot( gradientBelowSW, displacementFromBelowSW ); float dotBelowSE = ::glm::dot( gradientBelowSE, displacementFromBelowSE ); float dotBelowNW = ::glm::dot( gradientBelowNW, displacementFromBelowNW ); float dotBelowNE = ::glm::dot( gradientBelowNE, displacementFromBelowNE ); float dotAboveSW = ::glm::dot( gradientAboveSW, displacementFromAboveSW ); float dotAboveSE = ::glm::dot( gradientAboveSE, displacementFromAboveSE ); float dotAboveNW = ::glm::dot( gradientAboveNW, displacementFromAboveNW ); float dotAboveNE = ::glm::dot( gradientAboveNE, displacementFromAboveNE ); // Do a smoothed (nonlinear) weighted average of dot results float weightEast = Easing::SmoothStep( displacementFromBelowSW.x ); float weightNorth = Easing::SmoothStep( displacementFromBelowSW.y ); float weightAbove = Easing::SmoothStep( displacementFromBelowSW.z ); float weightWest = 1.f - weightEast; float weightSouth = 1.f - weightNorth; float weightBelow = 1.f - weightAbove; // 8-way blend (8 -> 4 -> 2 -> 1) float blendBelowSouth = (weightEast * dotBelowSE) + (weightWest * dotBelowSW); float blendBelowNorth = (weightEast * dotBelowNE) + (weightWest * dotBelowNW); float blendAboveSouth = (weightEast * dotAboveSE) + (weightWest * dotAboveSW); float blendAboveNorth = (weightEast * dotAboveNE) + (weightWest * dotAboveNW); float blendBelow = (weightSouth * blendBelowSouth) + (weightNorth * blendBelowNorth); float blendAbove = (weightSouth * blendAboveSouth) + (weightNorth * blendAboveNorth); float blendTotal = (weightBelow * blendBelow) + (weightAbove * blendAbove); float noiseThisOctave = blendTotal * (1.f / 0.793856621f); // 3D Perlin is in [-.793856621,.793856621]; map to ~[-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPos *= octaveScale; currentPos.x += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids currentPos.y += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids currentPos.z += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } //----------------------------------------------------------------------------------------------- // Perlin noise is fractal noise with "gradient vector smoothing" applied. // // In 4D, gradients are unit-length hyper-vectors in random (4D) directions. // float Compute4dPerlinNoise( float posX, float posY, float posZ, float posT, float scale, uint32_t numOctaves, float octavePersistence, float octaveScale, bool renormalize, uint32_t seed ) { const float OCTAVE_OFFSET = 0.636764989593174f; // Translation/bias to add to each octave const ::glm::vec4 gradients[ 16 ] = // Hard to tell if this is any better in 4D than just having 8 { ::glm::vec4( +0.5f, +0.5f, +0.5f, +0.5f ), // Normalized unit 4D vectors pointing toward each ::glm::vec4( -0.5f, +0.5f, +0.5f, +0.5f ), // of the 16 hypercube corners, so components are ::glm::vec4( +0.5f, -0.5f, +0.5f, +0.5f ), // all sqrt(4)/4, i.e. one-half. ::glm::vec4( -0.5f, -0.5f, +0.5f, +0.5f ), // ::glm::vec4( +0.5f, +0.5f, -0.5f, +0.5f ), // It's hard to tell whether these are any better ::glm::vec4( -0.5f, +0.5f, -0.5f, +0.5f ), // or worse than vectors facing axes (1,0,0,0) or ::glm::vec4( +0.5f, -0.5f, -0.5f, +0.5f ), // 3D edges (.7,.7,0,0) or 4D edges (.57,.57,.57,0) ::glm::vec4( -0.5f, -0.5f, -0.5f, +0.5f ), // but less-axial gradients looked a little better ::glm::vec4( +0.5f, +0.5f, +0.5f, -0.5f ), // with 2D and 3D noise so I'm assuming this is as ::glm::vec4( -0.5f, +0.5f, +0.5f, -0.5f ), // good or better as any other gradient-selection ::glm::vec4( +0.5f, -0.5f, +0.5f, -0.5f ), // scheme (and is crazy-fast). *shrug* ::glm::vec4( -0.5f, -0.5f, +0.5f, -0.5f ), // ::glm::vec4( +0.5f, +0.5f, -0.5f, -0.5f ), // Plus, we want a power-of-two number of evenly- ::glm::vec4( -0.5f, +0.5f, -0.5f, -0.5f ), // distributed gradients, so we can cheaply select ::glm::vec4( +0.5f, -0.5f, -0.5f, -0.5f ), // one from bit-noise (use bit-mask, not modulus). ::glm::vec4( -0.5f, -0.5f, -0.5f, -0.5f ) // }; float totalNoise = 0.f; float totalAmplitude = 0.f; float currentAmplitude = 1.f; float invScale = (1.f / scale); ::glm::vec4 currentPos( posX * invScale, posY * invScale, posZ * invScale, posT * invScale ); for( uint32_t octaveNum = 0; octaveNum < numOctaves; ++ octaveNum ) { // Determine random unit "gradient vectors" for 16 surrounding 4D (hypercube) cell corners ::glm::vec4 cellMins( ::glm::floor( currentPos.x ), ::glm::floor( currentPos.y ), ::glm::floor( currentPos.z ), ::glm::floor( currentPos.w ) ); ::glm::vec4 cellMaxs( cellMins.x + 1.f, cellMins.y + 1.f, cellMins.z + 1.f, cellMins.w + 1.f ); int32_t indexWestX = (int32_t) cellMins.x; int32_t indexSouthY = (int32_t) cellMins.y; int32_t indexBelowZ = (int32_t) cellMins.z; int32_t indexBeforeT = (int32_t) cellMins.w; int32_t indexEastX = indexWestX + 1; int32_t indexNorthY = indexSouthY + 1; int32_t indexAboveZ = indexBelowZ + 1; int32_t indexAfterT = indexBeforeT + 1; // "BeforeBSW" stands for "BeforeBelowSouthWest" below (i.e. 4D hypercube mins), etc. uint32_t noiseBeforeBSW = Get4dNoiseUint32( indexWestX, indexSouthY, indexBelowZ, indexBeforeT, seed ); uint32_t noiseBeforeBSE = Get4dNoiseUint32( indexEastX, indexSouthY, indexBelowZ, indexBeforeT, seed ); uint32_t noiseBeforeBNW = Get4dNoiseUint32( indexWestX, indexNorthY, indexBelowZ, indexBeforeT, seed ); uint32_t noiseBeforeBNE = Get4dNoiseUint32( indexEastX, indexNorthY, indexBelowZ, indexBeforeT, seed ); uint32_t noiseBeforeASW = Get4dNoiseUint32( indexWestX, indexSouthY, indexAboveZ, indexBeforeT, seed ); uint32_t noiseBeforeASE = Get4dNoiseUint32( indexEastX, indexSouthY, indexAboveZ, indexBeforeT, seed ); uint32_t noiseBeforeANW = Get4dNoiseUint32( indexWestX, indexNorthY, indexAboveZ, indexBeforeT, seed ); uint32_t noiseBeforeANE = Get4dNoiseUint32( indexEastX, indexNorthY, indexAboveZ, indexBeforeT, seed ); uint32_t noiseAfterBSW = Get4dNoiseUint32( indexWestX, indexSouthY, indexBelowZ, indexAfterT, seed ); uint32_t noiseAfterBSE = Get4dNoiseUint32( indexEastX, indexSouthY, indexBelowZ, indexAfterT, seed ); uint32_t noiseAfterBNW = Get4dNoiseUint32( indexWestX, indexNorthY, indexBelowZ, indexAfterT, seed ); uint32_t noiseAfterBNE = Get4dNoiseUint32( indexEastX, indexNorthY, indexBelowZ, indexAfterT, seed ); uint32_t noiseAfterASW = Get4dNoiseUint32( indexWestX, indexSouthY, indexAboveZ, indexAfterT, seed ); uint32_t noiseAfterASE = Get4dNoiseUint32( indexEastX, indexSouthY, indexAboveZ, indexAfterT, seed ); uint32_t noiseAfterANW = Get4dNoiseUint32( indexWestX, indexNorthY, indexAboveZ, indexAfterT, seed ); uint32_t noiseAfterANE = Get4dNoiseUint32( indexEastX, indexNorthY, indexAboveZ, indexAfterT, seed ); // Mask with 15 (mod 16) to look up in gradients table ::glm::vec4 gradientBeforeBSW = gradients[ noiseBeforeBSW & 0x0000000F ]; ::glm::vec4 gradientBeforeBSE = gradients[ noiseBeforeBSE & 0x0000000F ]; ::glm::vec4 gradientBeforeBNW = gradients[ noiseBeforeBNW & 0x0000000F ]; ::glm::vec4 gradientBeforeBNE = gradients[ noiseBeforeBNE & 0x0000000F ]; ::glm::vec4 gradientBeforeASW = gradients[ noiseBeforeASW & 0x0000000F ]; ::glm::vec4 gradientBeforeASE = gradients[ noiseBeforeASE & 0x0000000F ]; ::glm::vec4 gradientBeforeANW = gradients[ noiseBeforeANW & 0x0000000F ]; ::glm::vec4 gradientBeforeANE = gradients[ noiseBeforeANE & 0x0000000F ]; ::glm::vec4 gradientAfterBSW = gradients[ noiseAfterBSW & 0x0000000F ]; ::glm::vec4 gradientAfterBSE = gradients[ noiseAfterBSE & 0x0000000F ]; ::glm::vec4 gradientAfterBNW = gradients[ noiseAfterBNW & 0x0000000F ]; ::glm::vec4 gradientAfterBNE = gradients[ noiseAfterBNE & 0x0000000F ]; ::glm::vec4 gradientAfterASW = gradients[ noiseAfterASW & 0x0000000F ]; ::glm::vec4 gradientAfterASE = gradients[ noiseAfterASE & 0x0000000F ]; ::glm::vec4 gradientAfterANW = gradients[ noiseAfterANW & 0x0000000F ]; ::glm::vec4 gradientAfterANE = gradients[ noiseAfterANE & 0x0000000F ]; // Dot each corner's gradient with displacement from corner to position ::glm::vec4 displacementFromBeforeBSW( currentPos.x - cellMins.x, currentPos.y - cellMins.y, currentPos.z - cellMins.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeBSE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y, currentPos.z - cellMins.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeBNW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y, currentPos.z - cellMins.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeBNE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y, currentPos.z - cellMins.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeASW( currentPos.x - cellMins.x, currentPos.y - cellMins.y, currentPos.z - cellMaxs.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeASE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y, currentPos.z - cellMaxs.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeANW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y, currentPos.z - cellMaxs.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromBeforeANE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y, currentPos.z - cellMaxs.z, currentPos.w - cellMins.w ); ::glm::vec4 displacementFromAfterBSW( currentPos.x - cellMins.x, currentPos.y - cellMins.y, currentPos.z - cellMins.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterBSE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y, currentPos.z - cellMins.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterBNW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y, currentPos.z - cellMins.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterBNE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y, currentPos.z - cellMins.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterASW( currentPos.x - cellMins.x, currentPos.y - cellMins.y, currentPos.z - cellMaxs.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterASE( currentPos.x - cellMaxs.x, currentPos.y - cellMins.y, currentPos.z - cellMaxs.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterANW( currentPos.x - cellMins.x, currentPos.y - cellMaxs.y, currentPos.z - cellMaxs.z, currentPos.w - cellMaxs.w ); ::glm::vec4 displacementFromAfterANE( currentPos.x - cellMaxs.x, currentPos.y - cellMaxs.y, currentPos.z - cellMaxs.z, currentPos.w - cellMaxs.w ); float dotBeforeBSW = ::glm::dot( gradientBeforeBSW, displacementFromBeforeBSW ); float dotBeforeBSE = ::glm::dot( gradientBeforeBSE, displacementFromBeforeBSE ); float dotBeforeBNW = ::glm::dot( gradientBeforeBNW, displacementFromBeforeBNW ); float dotBeforeBNE = ::glm::dot( gradientBeforeBNE, displacementFromBeforeBNE ); float dotBeforeASW = ::glm::dot( gradientBeforeASW, displacementFromBeforeASW ); float dotBeforeASE = ::glm::dot( gradientBeforeASE, displacementFromBeforeASE ); float dotBeforeANW = ::glm::dot( gradientBeforeANW, displacementFromBeforeANW ); float dotBeforeANE = ::glm::dot( gradientBeforeANE, displacementFromBeforeANE ); float dotAfterBSW = ::glm::dot( gradientAfterBSW, displacementFromAfterBSW ); float dotAfterBSE = ::glm::dot( gradientAfterBSE, displacementFromAfterBSE ); float dotAfterBNW = ::glm::dot( gradientAfterBNW, displacementFromAfterBNW ); float dotAfterBNE = ::glm::dot( gradientAfterBNE, displacementFromAfterBNE ); float dotAfterASW = ::glm::dot( gradientAfterASW, displacementFromAfterASW ); float dotAfterASE = ::glm::dot( gradientAfterASE, displacementFromAfterASE ); float dotAfterANW = ::glm::dot( gradientAfterANW, displacementFromAfterANW ); float dotAfterANE = ::glm::dot( gradientAfterANE, displacementFromAfterANE ); // Do a smoothed (nonlinear) weighted average of dot results float weightEast = Easing::SmoothStep( displacementFromBeforeBSW.x ); float weightNorth = Easing::SmoothStep( displacementFromBeforeBSW.y ); float weightAbove = Easing::SmoothStep( displacementFromBeforeBSW.z ); float weightAfter = Easing::SmoothStep( displacementFromBeforeBSW.w ); float weightWest = 1.f - weightEast; float weightSouth = 1.f - weightNorth; float weightBelow = 1.f - weightAbove; float weightBefore = 1.f - weightAfter; // 16-way blend (16 -> 8 -> 4 -> 2 -> 1) float blendBeforeBelowSouth = (weightEast * dotBeforeBSE) + (weightWest * dotBeforeBSW); float blendBeforeBelowNorth = (weightEast * dotBeforeBNE) + (weightWest * dotBeforeBNW); float blendBeforeAboveSouth = (weightEast * dotBeforeASE) + (weightWest * dotBeforeASW); float blendBeforeAboveNorth = (weightEast * dotBeforeANE) + (weightWest * dotBeforeANW); float blendAfterBelowSouth = (weightEast * dotAfterBSE) + (weightWest * dotAfterBSW); float blendAfterBelowNorth = (weightEast * dotAfterBNE) + (weightWest * dotAfterBNW); float blendAfterAboveSouth = (weightEast * dotAfterASE) + (weightWest * dotAfterASW); float blendAfterAboveNorth = (weightEast * dotAfterANE) + (weightWest * dotAfterANW); float blendBeforeBelow = (weightSouth * blendBeforeBelowSouth) + (weightNorth * blendBeforeBelowNorth); float blendBeforeAbove = (weightSouth * blendBeforeAboveSouth) + (weightNorth * blendBeforeAboveNorth); float blendAfterBelow = (weightSouth * blendAfterBelowSouth) + (weightNorth * blendAfterBelowNorth); float blendAfterAbove = (weightSouth * blendAfterAboveSouth) + (weightNorth * blendAfterAboveNorth); float blendBefore = (weightBelow * blendBeforeBelow) + (weightAbove * blendBeforeAbove); float blendAfter = (weightBelow * blendAfterBelow) + (weightAbove * blendAfterAbove); float blendTotal = (weightBefore * blendBefore) + (weightAfter * blendAfter); float noiseThisOctave = blendTotal * (1.f / 0.6875f); // 4D Perlin is in [-.6875,.6875]; map to ~[-1,1] // Accumulate results and prepare for next octave (if any) totalNoise += noiseThisOctave * currentAmplitude; totalAmplitude += currentAmplitude; currentAmplitude *= octavePersistence; currentPos *= octaveScale; currentPos.x += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids currentPos.y += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids currentPos.z += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids currentPos.w += OCTAVE_OFFSET; // Add "irrational" offset to de-align octave grids ++ seed; // Eliminates octaves "echoing" each other (since each octave is uniquely seeded) } // Re-normalize total noise to within [-1,1] and fix octaves pulling us far away from limits if( renormalize && totalAmplitude > 0.f ) { totalNoise /= totalAmplitude; // Amplitude exceeds 1.0 if octaves are used totalNoise = (totalNoise * 0.5f) + 0.5f; // Map to [0,1] totalNoise = Easing::SmoothStep( totalNoise ); // Push towards extents (octaves pull us away) totalNoise = (totalNoise * 2.0f) - 1.f; // Map back to [-1,1] } return totalNoise; } } // SquirrelNoise4
//-------------------------------------------------- // // File: SequenceTree_MostParsimonious.cpp // // Author: Isaac Elias // e-mail: isaac@nada.kth.se // // cvs: $Id: SequenceTree_MostParsimonious.cpp,v 1.2 2006/12/19 09:24:36 isaac Exp $ // // IMPLEMENTATION of SequenceTree::computeMostParsimoniousSequences() // //-------------------------------------------------- #include "SequenceTree.hpp" #include <string> #include "nucleotide.hpp" #include <vector> #include "log_utils.hpp" #include "std_c_utils.h" using namespace std; //The parsimony information is saved in a vector of 4 integers. Each position //has one parsimony inforamtion typedef vector<size_t> p_info; typedef vector<p_info> p_vector; std::istream & operator>>(std::istream &in,p_info p){ in >>p[DNA_A_]; in >> p[DNA_C_];in >> p[DNA_G_];in >> p[DNA_T_]; return in; } std::ostream& operator<<(std::ostream & os, p_info p){ os << p[DNA_A_]; os << p[DNA_C_]; os << p[DNA_G_]; os << p[DNA_T_]; return os; } typedef Tree<p_vector> ParsimonyTree; static void backtrack(SequenceTree::Node *sn, ParsimonyTree::Node *pn); size_t SequenceTree::computeMostParsimoniousSequences(){ SequenceTree::Node *oldRoot = getRoot(); reRootAtHighDegreeNode(); p_vector defaultVec; ParsimonyTree pTree(*this,defaultVec); ParsimonyTree::NodeVector nodes; nodes.reserve(pTree.getNumNodes()); //init the leafs p_info defaultVal(4); defaultVal[0]=10;defaultVal[1]=10;defaultVal[2]=10;defaultVal[3]=10; SequenceTree::NodeVector origLeafs; origLeafs.reserve(getNumLeafs()); addLeafs(origLeafs); pTree.addLeafs(nodes); string &seq = oldRoot->data.s.seq; for ( size_t i = 0 ;i < origLeafs.size() ; i++ ){ seq = origLeafs[i]->data.s.seq; p_vector &pos = nodes[i]->data; pos.resize(seq.length(),defaultVal); for ( size_t j = 0 ; j < seq.length() ; j++ ){ nucleotide n = char2nucleotide(seq[j]); pos[j][n] = 0; } } //constants const size_t seqlen = seq.length(); const size_t numNodes = getNumNodes(); const size_t numSymbols = 4; //BOTTOM UP nodes.clear(); pTree.addNodesInPostfixOrder(nodes); for ( size_t i = 0 ; i < numNodes ; i++ ){ if ( nodes[i]->isLeaf() ) continue; p_vector &pos = nodes[i]->data; pos.resize(seq.length(),defaultVal); //for each position in the sequence for( size_t j = 0 ; j < seqlen ; j++ ){ p_info &p = pos[j]; //For each possible symbol compute the parsimony score //by taking the minimum sum over the children for ( size_t sym = 0 ; sym < numSymbols ; sym++ ){ p[sym] = 0; ParsimonyTree::Node *child = nodes[i]->getRightMostChild(); for ( ; child != NULL ; child = child->getLeftSibling() ){ p_info &child_p = (child->data)[j]; size_t score = child_p[0] + (sym != 0 ? 1 : 0); for ( size_t symC = 1 ; symC < numSymbols ; symC++ ){ size_t symCp = child_p[symC] + (sym != symC ? 1 : 0); score = MIN(score, symCp); } //add the best cost the the parsimony at the parent p[sym] += score; }//end children loop }//end symbol loop }//end sequence position }//end node loop //BACK TRACK //first create the best sequence in the root and then backtrack down. SequenceTree::Node *sroot = getRoot(); ParsimonyTree::Node *proot = pTree.getRoot(); p_vector &pos = proot->data; seq = sroot->data.s.seq; seq.resize(seqlen,'x'); size_t totalParsimony = 0; for ( size_t i = 0 ; i < seqlen ; i++ ){ p_info &p = pos[i]; nucleotide min_n = DNA_A_; size_t score = p[DNA_A_]; if ( p[DNA_C_] < score ){ min_n = DNA_C_;score = p[DNA_C_]; } if ( p[DNA_G_] < score ){ min_n = DNA_G_;score = p[DNA_G_]; } if ( p[DNA_T_] < score ){ min_n = DNA_T_;score = p[DNA_T_]; } seq[i] = nucleotide2char(min_n); totalParsimony+= score; } SequenceTree::Node *child = sroot->getRightMostChild(); ParsimonyTree::Node *childP = proot->getRightMostChild(); for ( ; child != NULL ; child = child->getLeftSibling(), childP = childP->getLeftSibling() ) backtrack(child,childP); //reroot the tree to its old position reRootAt(oldRoot); return totalParsimony; } static void backtrack(SequenceTree::Node *sn, ParsimonyTree::Node *pn){ if ( sn->isLeaf() ) return; p_vector &pos = pn->data; const size_t seqlen = pos.size(); string &seq = sn->data.s.seq; seq.resize(seqlen,'x'); string &parentseq = sn->getParent()->data.s.seq; for ( size_t i = 0 ; i < seqlen ; i++ ){ p_info &p = pos[i]; nucleotide parent_n = char2nucleotide(parentseq[i]); nucleotide min_n = parent_n; size_t score = p[min_n]; if ( p[DNA_A_]+1 < score ){ min_n = DNA_A_; score = p[DNA_A_]+1; } if ( p[DNA_C_]+1 < score ){ min_n = DNA_C_; score = p[DNA_C_]+1; } if ( p[DNA_G_]+1 < score ){ min_n = DNA_G_; score = p[DNA_G_]+1; } if ( p[DNA_T_]+1 < score ){ min_n = DNA_T_; } seq[i] = nucleotide2char(min_n); } //continue backtracking SequenceTree::Node *child = sn->getRightMostChild(); ParsimonyTree::Node *childP = pn->getRightMostChild(); for ( ; child != NULL ; child = child->getLeftSibling(), childP = childP->getLeftSibling() ) backtrack(child,childP); }
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved. // Usage Environment // Implementation #include "UsageEnvironment.hh" void UsageEnvironment::reclaim() { // We delete ourselves only if we have no remainining state: if (liveMediaPriv == NULL && groupsockPriv == NULL) delete this; } UsageEnvironment::UsageEnvironment(TaskScheduler& scheduler) : liveMediaPriv(NULL), groupsockPriv(NULL), fScheduler(scheduler) { } UsageEnvironment::~UsageEnvironment() { } // By default, we handle 'should not occur'-type library errors by calling abort(). Subclasses can redefine this, if desired. // (If your runtime library doesn't define the "abort()" function, then define your own (e.g., that does nothing).) void UsageEnvironment::internalError() { abort(); } TaskScheduler::TaskScheduler() { } TaskScheduler::~TaskScheduler() { } void TaskScheduler::rescheduleDelayedTask(TaskToken& task, int64_t microseconds, TaskFunc* proc, void* clientData) { unscheduleDelayedTask(task); task = scheduleDelayedTask(microseconds, proc, clientData); } // By default, we handle 'should not occur'-type library errors by calling abort(). Subclasses can redefine this, if desired. void TaskScheduler::internalError() { abort(); }
//===-- SBDebugger.cpp ----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "SBReproducerPrivate.h" #include "SystemInitializerFull.h" #include "lldb/API/SBDebugger.h" #include "lldb/lldb-private.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBCommandInterpreter.h" #include "lldb/API/SBCommandInterpreterRunOptions.h" #include "lldb/API/SBCommandReturnObject.h" #include "lldb/API/SBError.h" #include "lldb/API/SBEvent.h" #include "lldb/API/SBFile.h" #include "lldb/API/SBFrame.h" #include "lldb/API/SBListener.h" #include "lldb/API/SBProcess.h" #include "lldb/API/SBSourceManager.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBStringList.h" #include "lldb/API/SBStructuredData.h" #include "lldb/API/SBTarget.h" #include "lldb/API/SBThread.h" #include "lldb/API/SBTypeCategory.h" #include "lldb/API/SBTypeFilter.h" #include "lldb/API/SBTypeFormat.h" #include "lldb/API/SBTypeNameSpecifier.h" #include "lldb/API/SBTypeSummary.h" #include "lldb/API/SBTypeSynthetic.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/StructuredDataImpl.h" #include "lldb/DataFormatters/DataVisualization.h" #include "lldb/Host/Config.h" #include "lldb/Host/XML.h" #include "lldb/Initialization/SystemLifetimeManager.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Interpreter/OptionGroupPlatform.h" #include "lldb/Target/Process.h" #include "lldb/Target/TargetList.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/State.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/ManagedStatic.h" using namespace lldb; using namespace lldb_private; static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, Status &error) { llvm::sys::DynamicLibrary dynlib = llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str()); if (dynlib.isValid()) { typedef bool (*LLDBCommandPluginInit)(lldb::SBDebugger & debugger); lldb::SBDebugger debugger_sb(debugger_sp); // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger) // function. // TODO: mangle this differently for your system - on OSX, the first // underscore needs to be removed and the second one stays LLDBCommandPluginInit init_func = (LLDBCommandPluginInit)(uintptr_t)dynlib.getAddressOfSymbol( "_ZN4lldb16PluginInitializeENS_10SBDebuggerE"); if (init_func) { if (init_func(debugger_sb)) return dynlib; else error.SetErrorString("plug-in refused to load " "(lldb::PluginInitialize(lldb::SBDebugger) " "returned false)"); } else { error.SetErrorString("plug-in is missing the required initialization: " "lldb::PluginInitialize(lldb::SBDebugger)"); } } else { if (FileSystem::Instance().Exists(spec)) error.SetErrorString("this file does not represent a loadable dylib"); else error.SetErrorString("no such file"); } return llvm::sys::DynamicLibrary(); } static llvm::ManagedStatic<SystemLifetimeManager> g_debugger_lifetime; SBError SBInputReader::Initialize( lldb::SBDebugger &sb_debugger, unsigned long (*callback)(void *, lldb::SBInputReader *, lldb::InputReaderAction, char const *, unsigned long), void *a, lldb::InputReaderGranularity b, char const *c, char const *d, bool e) { LLDB_RECORD_DUMMY( lldb::SBError, SBInputReader, Initialize, (lldb::SBDebugger &, unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction, const char *, unsigned long), void *, lldb::InputReaderGranularity, const char *, const char *, bool), sb_debugger, callback, a, b, c, d, e); return SBError(); } void SBInputReader::SetIsDone(bool b) { LLDB_RECORD_METHOD(void, SBInputReader, SetIsDone, (bool), b); } bool SBInputReader::IsActive() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBInputReader, IsActive); return false; } SBDebugger::SBDebugger() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBDebugger); } SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp) : m_opaque_sp(debugger_sp) { LLDB_RECORD_CONSTRUCTOR(SBDebugger, (const lldb::DebuggerSP &), debugger_sp); } SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) { LLDB_RECORD_CONSTRUCTOR(SBDebugger, (const lldb::SBDebugger &), rhs); } SBDebugger::~SBDebugger() = default; SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) { LLDB_RECORD_METHOD(lldb::SBDebugger &, SBDebugger, operator=,(const lldb::SBDebugger &), rhs); if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } return LLDB_RECORD_RESULT(*this); } void SBDebugger::Initialize() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(void, SBDebugger, Initialize); SBError ignored = SBDebugger::InitializeWithErrorHandling(); } lldb::SBError SBDebugger::InitializeWithErrorHandling() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBError, SBDebugger, InitializeWithErrorHandling); SBError error; if (auto e = g_debugger_lifetime->Initialize( std::make_unique<SystemInitializerFull>(), LoadPlugin)) { error.SetError(Status(std::move(e))); } return LLDB_RECORD_RESULT(error); } void SBDebugger::Terminate() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(void, SBDebugger, Terminate); g_debugger_lifetime->Terminate(); } void SBDebugger::Clear() { LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, Clear); if (m_opaque_sp) m_opaque_sp->ClearIOHandlers(); m_opaque_sp.reset(); } SBDebugger SBDebugger::Create() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBDebugger, SBDebugger, Create); return LLDB_RECORD_RESULT(SBDebugger::Create(false, nullptr, nullptr)); } SBDebugger SBDebugger::Create(bool source_init_files) { LLDB_RECORD_STATIC_METHOD(lldb::SBDebugger, SBDebugger, Create, (bool), source_init_files); return LLDB_RECORD_RESULT( SBDebugger::Create(source_init_files, nullptr, nullptr)); } SBDebugger SBDebugger::Create(bool source_init_files, lldb::LogOutputCallback callback, void *baton) { LLDB_RECORD_DUMMY(lldb::SBDebugger, SBDebugger, Create, (bool, lldb::LogOutputCallback, void *), source_init_files, callback, baton); SBDebugger debugger; // Currently we have issues if this function is called simultaneously on two // different threads. The issues mainly revolve around the fact that the // lldb_private::FormatManager uses global collections and having two threads // parsing the .lldbinit files can cause mayhem. So to get around this for // now we need to use a mutex to prevent bad things from happening. static std::recursive_mutex g_mutex; std::lock_guard<std::recursive_mutex> guard(g_mutex); debugger.reset(Debugger::CreateInstance(callback, baton)); SBCommandInterpreter interp = debugger.GetCommandInterpreter(); if (source_init_files) { interp.get()->SkipLLDBInitFiles(false); interp.get()->SkipAppInitFiles(false); SBCommandReturnObject result; interp.SourceInitFileInHomeDirectory(result, false); } else { interp.get()->SkipLLDBInitFiles(true); interp.get()->SkipAppInitFiles(true); } return debugger; } void SBDebugger::Destroy(SBDebugger &debugger) { LLDB_RECORD_STATIC_METHOD(void, SBDebugger, Destroy, (lldb::SBDebugger &), debugger); Debugger::Destroy(debugger.m_opaque_sp); if (debugger.m_opaque_sp.get() != nullptr) debugger.m_opaque_sp.reset(); } void SBDebugger::MemoryPressureDetected() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(void, SBDebugger, MemoryPressureDetected); // Since this function can be call asynchronously, we allow it to be non- // mandatory. We have seen deadlocks with this function when called so we // need to safeguard against this until we can determine what is causing the // deadlocks. const bool mandatory = false; ModuleList::RemoveOrphanSharedModules(mandatory); } bool SBDebugger::IsValid() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, IsValid); return this->operator bool(); } SBDebugger::operator bool() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, operator bool); return m_opaque_sp.get() != nullptr; } void SBDebugger::SetAsync(bool b) { LLDB_RECORD_METHOD(void, SBDebugger, SetAsync, (bool), b); if (m_opaque_sp) m_opaque_sp->SetAsyncExecution(b); } bool SBDebugger::GetAsync() { LLDB_RECORD_METHOD_NO_ARGS(bool, SBDebugger, GetAsync); return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false); } void SBDebugger::SkipLLDBInitFiles(bool b) { LLDB_RECORD_METHOD(void, SBDebugger, SkipLLDBInitFiles, (bool), b); if (m_opaque_sp) m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b); } void SBDebugger::SkipAppInitFiles(bool b) { LLDB_RECORD_METHOD(void, SBDebugger, SkipAppInitFiles, (bool), b); if (m_opaque_sp) m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b); } void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) { LLDB_RECORD_METHOD(void, SBDebugger, SetInputFileHandle, (FILE *, bool), fh, transfer_ownership); SetInputFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership)); } SBError SBDebugger::SetInputFile(FileSP file_sp) { LLDB_RECORD_METHOD(SBError, SBDebugger, SetInputFile, (FileSP), file_sp); return LLDB_RECORD_RESULT(SetInputFile(SBFile(file_sp))); } // Shouldn't really be settable after initialization as this could cause lots // of problems; don't want users trying to switch modes in the middle of a // debugging session. SBError SBDebugger::SetInputFile(SBFile file) { LLDB_RECORD_METHOD(SBError, SBDebugger, SetInputFile, (SBFile), file); SBError error; if (!m_opaque_sp) { error.ref().SetErrorString("invalid debugger"); return LLDB_RECORD_RESULT(error); } repro::DataRecorder *recorder = nullptr; if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) recorder = g->GetOrCreate<repro::CommandProvider>().GetNewRecorder(); FileSP file_sp = file.m_opaque_sp; static std::unique_ptr<repro::MultiLoader<repro::CommandProvider>> loader = repro::MultiLoader<repro::CommandProvider>::Create( repro::Reproducer::Instance().GetLoader()); if (loader) { llvm::Optional<std::string> nextfile = loader->GetNextFile(); FILE *fh = nextfile ? FileSystem::Instance().Fopen(nextfile->c_str(), "r") : nullptr; // FIXME Jonas Devlieghere: shouldn't this error be propagated out to the // reproducer somehow if fh is NULL? if (fh) { file_sp = std::make_shared<NativeFile>(fh, true); } } if (!file_sp || !file_sp->IsValid()) { error.ref().SetErrorString("invalid file"); return LLDB_RECORD_RESULT(error); } m_opaque_sp->SetInputFile(file_sp, recorder); return LLDB_RECORD_RESULT(error); } SBError SBDebugger::SetOutputFile(FileSP file_sp) { LLDB_RECORD_METHOD(SBError, SBDebugger, SetOutputFile, (FileSP), file_sp); return LLDB_RECORD_RESULT(SetOutputFile(SBFile(file_sp))); } void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) { LLDB_RECORD_METHOD(void, SBDebugger, SetOutputFileHandle, (FILE *, bool), fh, transfer_ownership); SetOutputFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership)); } SBError SBDebugger::SetOutputFile(SBFile file) { LLDB_RECORD_METHOD(SBError, SBDebugger, SetOutputFile, (SBFile file), file); SBError error; if (!m_opaque_sp) { error.ref().SetErrorString("invalid debugger"); return LLDB_RECORD_RESULT(error); } if (!file) { error.ref().SetErrorString("invalid file"); return LLDB_RECORD_RESULT(error); } m_opaque_sp->SetOutputFile(file.m_opaque_sp); return LLDB_RECORD_RESULT(error); } void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) { LLDB_RECORD_METHOD(void, SBDebugger, SetErrorFileHandle, (FILE *, bool), fh, transfer_ownership); SetErrorFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership)); } SBError SBDebugger::SetErrorFile(FileSP file_sp) { LLDB_RECORD_METHOD(SBError, SBDebugger, SetErrorFile, (FileSP), file_sp); return LLDB_RECORD_RESULT(SetErrorFile(SBFile(file_sp))); } SBError SBDebugger::SetErrorFile(SBFile file) { LLDB_RECORD_METHOD(SBError, SBDebugger, SetErrorFile, (SBFile file), file); SBError error; if (!m_opaque_sp) { error.ref().SetErrorString("invalid debugger"); return LLDB_RECORD_RESULT(error); } if (!file) { error.ref().SetErrorString("invalid file"); return LLDB_RECORD_RESULT(error); } m_opaque_sp->SetErrorFile(file.m_opaque_sp); return LLDB_RECORD_RESULT(error); } FILE *SBDebugger::GetInputFileHandle() { LLDB_RECORD_METHOD_NO_ARGS(FILE *, SBDebugger, GetInputFileHandle); if (m_opaque_sp) { File &file_sp = m_opaque_sp->GetInputFile(); return LLDB_RECORD_RESULT(file_sp.GetStream()); } return LLDB_RECORD_RESULT(nullptr); } SBFile SBDebugger::GetInputFile() { LLDB_RECORD_METHOD_NO_ARGS(SBFile, SBDebugger, GetInputFile); if (m_opaque_sp) { return LLDB_RECORD_RESULT(SBFile(m_opaque_sp->GetInputFileSP())); } return LLDB_RECORD_RESULT(SBFile()); } FILE *SBDebugger::GetOutputFileHandle() { LLDB_RECORD_METHOD_NO_ARGS(FILE *, SBDebugger, GetOutputFileHandle); if (m_opaque_sp) { StreamFile &stream_file = m_opaque_sp->GetOutputStream(); return LLDB_RECORD_RESULT(stream_file.GetFile().GetStream()); } return LLDB_RECORD_RESULT(nullptr); } SBFile SBDebugger::GetOutputFile() { LLDB_RECORD_METHOD_NO_ARGS(SBFile, SBDebugger, GetOutputFile); if (m_opaque_sp) { SBFile file(m_opaque_sp->GetOutputStream().GetFileSP()); return LLDB_RECORD_RESULT(file); } return LLDB_RECORD_RESULT(SBFile()); } FILE *SBDebugger::GetErrorFileHandle() { LLDB_RECORD_METHOD_NO_ARGS(FILE *, SBDebugger, GetErrorFileHandle); if (m_opaque_sp) { StreamFile &stream_file = m_opaque_sp->GetErrorStream(); return LLDB_RECORD_RESULT(stream_file.GetFile().GetStream()); } return LLDB_RECORD_RESULT(nullptr); } SBFile SBDebugger::GetErrorFile() { LLDB_RECORD_METHOD_NO_ARGS(SBFile, SBDebugger, GetErrorFile); SBFile file; if (m_opaque_sp) { SBFile file(m_opaque_sp->GetErrorStream().GetFileSP()); return LLDB_RECORD_RESULT(file); } return LLDB_RECORD_RESULT(SBFile()); } void SBDebugger::SaveInputTerminalState() { LLDB_RECORD_DUMMY_NO_ARGS(void, SBDebugger, SaveInputTerminalState); if (m_opaque_sp) m_opaque_sp->SaveInputTerminalState(); } void SBDebugger::RestoreInputTerminalState() { LLDB_RECORD_DUMMY_NO_ARGS(void, SBDebugger, RestoreInputTerminalState); if (m_opaque_sp) m_opaque_sp->RestoreInputTerminalState(); } SBCommandInterpreter SBDebugger::GetCommandInterpreter() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBCommandInterpreter, SBDebugger, GetCommandInterpreter); SBCommandInterpreter sb_interpreter; if (m_opaque_sp) sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter()); return LLDB_RECORD_RESULT(sb_interpreter); } void SBDebugger::HandleCommand(const char *command) { LLDB_RECORD_METHOD(void, SBDebugger, HandleCommand, (const char *), command); if (m_opaque_sp) { TargetSP target_sp(m_opaque_sp->GetSelectedTarget()); std::unique_lock<std::recursive_mutex> lock; if (target_sp) lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); SBCommandInterpreter sb_interpreter(GetCommandInterpreter()); SBCommandReturnObject result; sb_interpreter.HandleCommand(command, result, false); result.PutError(m_opaque_sp->GetErrorStream().GetFileSP()); result.PutOutput(m_opaque_sp->GetOutputStream().GetFileSP()); if (!m_opaque_sp->GetAsyncExecution()) { SBProcess process(GetCommandInterpreter().GetProcess()); ProcessSP process_sp(process.GetSP()); if (process_sp) { EventSP event_sp; ListenerSP lldb_listener_sp = m_opaque_sp->GetListener(); while (lldb_listener_sp->GetEventForBroadcaster( process_sp.get(), event_sp, std::chrono::seconds(0))) { SBEvent event(event_sp); HandleProcessEvent(process, event, GetOutputFile(), GetErrorFile()); } } } } } SBListener SBDebugger::GetListener() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBListener, SBDebugger, GetListener); SBListener sb_listener; if (m_opaque_sp) sb_listener.reset(m_opaque_sp->GetListener()); return LLDB_RECORD_RESULT(sb_listener); } void SBDebugger::HandleProcessEvent(const SBProcess &process, const SBEvent &event, SBFile out, SBFile err) { LLDB_RECORD_METHOD( void, SBDebugger, HandleProcessEvent, (const lldb::SBProcess &, const lldb::SBEvent &, SBFile, SBFile), process, event, out, err); return HandleProcessEvent(process, event, out.m_opaque_sp, err.m_opaque_sp); } void SBDebugger::HandleProcessEvent(const SBProcess &process, const SBEvent &event, FILE *out, FILE *err) { LLDB_RECORD_METHOD( void, SBDebugger, HandleProcessEvent, (const lldb::SBProcess &, const lldb::SBEvent &, FILE *, FILE *), process, event, out, err); FileSP outfile = std::make_shared<NativeFile>(out, false); FileSP errfile = std::make_shared<NativeFile>(err, false); return HandleProcessEvent(process, event, outfile, errfile); } void SBDebugger::HandleProcessEvent(const SBProcess &process, const SBEvent &event, FileSP out_sp, FileSP err_sp) { LLDB_RECORD_METHOD( void, SBDebugger, HandleProcessEvent, (const lldb::SBProcess &, const lldb::SBEvent &, FileSP, FileSP), process, event, out_sp, err_sp); if (!process.IsValid()) return; TargetSP target_sp(process.GetTarget().GetSP()); if (!target_sp) return; const uint32_t event_type = event.GetType(); char stdio_buffer[1024]; size_t len; std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); if (event_type & (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) { // Drain stdout when we stop just in case we have any bytes while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0) if (out_sp) out_sp->Write(stdio_buffer, len); } if (event_type & (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) { // Drain stderr when we stop just in case we have any bytes while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0) if (err_sp) err_sp->Write(stdio_buffer, len); } if (event_type & Process::eBroadcastBitStateChanged) { StateType event_state = SBProcess::GetStateFromEvent(event); if (event_state == eStateInvalid) return; bool is_stopped = StateIsStoppedState(event_state); if (!is_stopped) process.ReportEventState(event, out_sp); } } SBSourceManager SBDebugger::GetSourceManager() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBSourceManager, SBDebugger, GetSourceManager); SBSourceManager sb_source_manager(*this); return LLDB_RECORD_RESULT(sb_source_manager); } bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) { LLDB_RECORD_CHAR_PTR_STATIC_METHOD(bool, SBDebugger, GetDefaultArchitecture, (char *, size_t), arch_name, "", arch_name_len); if (arch_name && arch_name_len) { ArchSpec default_arch = Target::GetDefaultArchitecture(); if (default_arch.IsValid()) { const std::string &triple_str = default_arch.GetTriple().str(); if (!triple_str.empty()) ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str()); else ::snprintf(arch_name, arch_name_len, "%s", default_arch.GetArchitectureName()); return true; } } if (arch_name && arch_name_len) arch_name[0] = '\0'; return false; } bool SBDebugger::SetDefaultArchitecture(const char *arch_name) { LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, SetDefaultArchitecture, (const char *), arch_name); if (arch_name) { ArchSpec arch(arch_name); if (arch.IsValid()) { Target::SetDefaultArchitecture(arch); return true; } } return false; } ScriptLanguage SBDebugger::GetScriptingLanguage(const char *script_language_name) { LLDB_RECORD_METHOD(lldb::ScriptLanguage, SBDebugger, GetScriptingLanguage, (const char *), script_language_name); if (!script_language_name) return eScriptLanguageDefault; return OptionArgParser::ToScriptLanguage( llvm::StringRef(script_language_name), eScriptLanguageDefault, nullptr); } const char *SBDebugger::GetVersionString() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBDebugger, GetVersionString); return lldb_private::GetVersion(); } const char *SBDebugger::StateAsCString(StateType state) { LLDB_RECORD_STATIC_METHOD(const char *, SBDebugger, StateAsCString, (lldb::StateType), state); return lldb_private::StateAsCString(state); } static void AddBoolConfigEntry(StructuredData::Dictionary &dict, llvm::StringRef name, bool value, llvm::StringRef description) { auto entry_up = std::make_unique<StructuredData::Dictionary>(); entry_up->AddBooleanItem("value", value); entry_up->AddStringItem("description", description); dict.AddItem(name, std::move(entry_up)); } static void AddLLVMTargets(StructuredData::Dictionary &dict) { auto array_up = std::make_unique<StructuredData::Array>(); #define LLVM_TARGET(target) \ array_up->AddItem(std::make_unique<StructuredData::String>(#target)); #include "llvm/Config/Targets.def" auto entry_up = std::make_unique<StructuredData::Dictionary>(); entry_up->AddItem("value", std::move(array_up)); entry_up->AddStringItem("description", "A list of configured LLVM targets."); dict.AddItem("targets", std::move(entry_up)); } SBStructuredData SBDebugger::GetBuildConfiguration() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(lldb::SBStructuredData, SBDebugger, GetBuildConfiguration); auto config_up = std::make_unique<StructuredData::Dictionary>(); AddBoolConfigEntry( *config_up, "xml", XMLDocument::XMLEnabled(), "A boolean value that indicates if XML support is enabled in LLDB"); AddBoolConfigEntry( *config_up, "curses", LLDB_ENABLE_CURSES, "A boolean value that indicates if curses support is enabled in LLDB"); AddBoolConfigEntry( *config_up, "editline", LLDB_ENABLE_LIBEDIT, "A boolean value that indicates if editline support is enabled in LLDB"); AddBoolConfigEntry( *config_up, "lzma", LLDB_ENABLE_LZMA, "A boolean value that indicates if lzma support is enabled in LLDB"); AddBoolConfigEntry( *config_up, "python", LLDB_ENABLE_PYTHON, "A boolean value that indicates if python support is enabled in LLDB"); AddBoolConfigEntry( *config_up, "lua", LLDB_ENABLE_LUA, "A boolean value that indicates if lua support is enabled in LLDB"); AddLLVMTargets(*config_up); SBStructuredData data; data.m_impl_up->SetObjectSP(std::move(config_up)); return LLDB_RECORD_RESULT(data); } bool SBDebugger::StateIsRunningState(StateType state) { LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, StateIsRunningState, (lldb::StateType), state); const bool result = lldb_private::StateIsRunningState(state); return result; } bool SBDebugger::StateIsStoppedState(StateType state) { LLDB_RECORD_STATIC_METHOD(bool, SBDebugger, StateIsStoppedState, (lldb::StateType), state); const bool result = lldb_private::StateIsStoppedState(state, false); return result; } lldb::SBTarget SBDebugger::CreateTarget(const char *filename, const char *target_triple, const char *platform_name, bool add_dependent_modules, lldb::SBError &sb_error) { LLDB_RECORD_METHOD( lldb::SBTarget, SBDebugger, CreateTarget, (const char *, const char *, const char *, bool, lldb::SBError &), filename, target_triple, platform_name, add_dependent_modules, sb_error); SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { sb_error.Clear(); OptionGroupPlatform platform_options(false); platform_options.SetPlatformName(platform_name); sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget( *m_opaque_sp, filename, target_triple, add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, &platform_options, target_sp); if (sb_error.Success()) sb_target.SetSP(target_sp); } else { sb_error.SetErrorString("invalid debugger"); } Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); LLDB_LOGF(log, "SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, " "platform_name=%s, add_dependent_modules=%u, error=%s) => " "SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), filename, target_triple, platform_name, add_dependent_modules, sb_error.GetCString(), static_cast<void *>(target_sp.get())); return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename, const char *target_triple) { LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, CreateTargetWithFileAndTargetTriple, (const char *, const char *), filename, target_triple); SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { const bool add_dependent_modules = true; Status error(m_opaque_sp->GetTargetList().CreateTarget( *m_opaque_sp, filename, target_triple, add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr, target_sp)); sb_target.SetSP(target_sp); } Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); LLDB_LOGF(log, "SBDebugger(%p)::CreateTargetWithFileAndTargetTriple " "(filename=\"%s\", triple=%s) => SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), filename, target_triple, static_cast<void *>(target_sp.get())); return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename, const char *arch_cstr) { LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, CreateTargetWithFileAndArch, (const char *, const char *), filename, arch_cstr); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { Status error; const bool add_dependent_modules = true; error = m_opaque_sp->GetTargetList().CreateTarget( *m_opaque_sp, filename, arch_cstr, add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr, target_sp); if (error.Success()) { m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get()); sb_target.SetSP(target_sp); } } LLDB_LOGF(log, "SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", " "arch=%s) => SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), filename, arch_cstr, static_cast<void *>(target_sp.get())); return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::CreateTarget(const char *filename) { LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, CreateTarget, (const char *), filename); SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { Status error; const bool add_dependent_modules = true; error = m_opaque_sp->GetTargetList().CreateTarget( *m_opaque_sp, filename, "", add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr, target_sp); if (error.Success()) { m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get()); sb_target.SetSP(target_sp); } } Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); LLDB_LOGF(log, "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), filename, static_cast<void *>(target_sp.get())); return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::GetDummyTarget() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTarget, SBDebugger, GetDummyTarget); SBTarget sb_target; if (m_opaque_sp) { sb_target.SetSP(m_opaque_sp->GetDummyTarget()->shared_from_this()); } Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); LLDB_LOGF(log, "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(sb_target.GetSP().get())); return LLDB_RECORD_RESULT(sb_target); } bool SBDebugger::DeleteTarget(lldb::SBTarget &target) { LLDB_RECORD_METHOD(bool, SBDebugger, DeleteTarget, (lldb::SBTarget &), target); bool result = false; if (m_opaque_sp) { TargetSP target_sp(target.GetSP()); if (target_sp) { // No need to lock, the target list is thread safe result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp); target_sp->Destroy(); target.Clear(); } } Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); LLDB_LOGF(log, "SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(target.m_opaque_sp.get()), result); return result; } SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) { LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, GetTargetAtIndex, (uint32_t), idx); SBTarget sb_target; if (m_opaque_sp) { // No need to lock, the target list is thread safe sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx)); } return LLDB_RECORD_RESULT(sb_target); } uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) { LLDB_RECORD_METHOD(uint32_t, SBDebugger, GetIndexOfTarget, (lldb::SBTarget), target); lldb::TargetSP target_sp = target.GetSP(); if (!target_sp) return UINT32_MAX; if (!m_opaque_sp) return UINT32_MAX; return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP()); } SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) { LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithProcessID, (lldb::pid_t), pid); SBTarget sb_target; if (m_opaque_sp) { // No need to lock, the target list is thread safe sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid)); } return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename, const char *arch_name) { LLDB_RECORD_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithFileAndArch, (const char *, const char *), filename, arch_name); SBTarget sb_target; if (m_opaque_sp && filename && filename[0]) { // No need to lock, the target list is thread safe ArchSpec arch = Platform::GetAugmentedArchSpec( m_opaque_sp->GetPlatformList().GetSelectedPlatform().get(), arch_name); TargetSP target_sp( m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture( FileSpec(filename), arch_name ? &arch : nullptr)); sb_target.SetSP(target_sp); } return LLDB_RECORD_RESULT(sb_target); } SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) { SBTarget sb_target; if (m_opaque_sp) { // No need to lock, the target list is thread safe sb_target.SetSP( m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get())); } return sb_target; } uint32_t SBDebugger::GetNumTargets() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumTargets); if (m_opaque_sp) { // No need to lock, the target list is thread safe return m_opaque_sp->GetTargetList().GetNumTargets(); } return 0; } SBTarget SBDebugger::GetSelectedTarget() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTarget, SBDebugger, GetSelectedTarget); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { // No need to lock, the target list is thread safe target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget(); sb_target.SetSP(target_sp); } if (log) { SBStream sstr; sb_target.GetDescription(sstr, eDescriptionLevelBrief); LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(target_sp.get()), sstr.GetData()); } return LLDB_RECORD_RESULT(sb_target); } void SBDebugger::SetSelectedTarget(SBTarget &sb_target) { LLDB_RECORD_METHOD(void, SBDebugger, SetSelectedTarget, (lldb::SBTarget &), sb_target); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); TargetSP target_sp(sb_target.GetSP()); if (m_opaque_sp) { m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get()); } if (log) { SBStream sstr; sb_target.GetDescription(sstr, eDescriptionLevelBrief); LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(target_sp.get()), sstr.GetData()); } } SBPlatform SBDebugger::GetSelectedPlatform() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBPlatform, SBDebugger, GetSelectedPlatform); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); SBPlatform sb_platform; DebuggerSP debugger_sp(m_opaque_sp); if (debugger_sp) { sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform()); } LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(sb_platform.GetSP().get()), sb_platform.GetName()); return LLDB_RECORD_RESULT(sb_platform); } void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) { LLDB_RECORD_METHOD(void, SBDebugger, SetSelectedPlatform, (lldb::SBPlatform &), sb_platform); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); DebuggerSP debugger_sp(m_opaque_sp); if (debugger_sp) { debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP()); } LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)", static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(sb_platform.GetSP().get()), sb_platform.GetName()); } uint32_t SBDebugger::GetNumPlatforms() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumPlatforms); if (m_opaque_sp) { // No need to lock, the platform list is thread safe return m_opaque_sp->GetPlatformList().GetSize(); } return 0; } SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) { LLDB_RECORD_METHOD(lldb::SBPlatform, SBDebugger, GetPlatformAtIndex, (uint32_t), idx); SBPlatform sb_platform; if (m_opaque_sp) { // No need to lock, the platform list is thread safe sb_platform.SetSP(m_opaque_sp->GetPlatformList().GetAtIndex(idx)); } return LLDB_RECORD_RESULT(sb_platform); } uint32_t SBDebugger::GetNumAvailablePlatforms() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumAvailablePlatforms); uint32_t idx = 0; while (true) { if (!PluginManager::GetPlatformPluginNameAtIndex(idx)) { break; } ++idx; } // +1 for the host platform, which should always appear first in the list. return idx + 1; } SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) { LLDB_RECORD_METHOD(lldb::SBStructuredData, SBDebugger, GetAvailablePlatformInfoAtIndex, (uint32_t), idx); SBStructuredData data; auto platform_dict = std::make_unique<StructuredData::Dictionary>(); llvm::StringRef name_str("name"), desc_str("description"); if (idx == 0) { PlatformSP host_platform_sp(Platform::GetHostPlatform()); platform_dict->AddStringItem( name_str, host_platform_sp->GetPluginName().GetStringRef()); platform_dict->AddStringItem( desc_str, llvm::StringRef(host_platform_sp->GetDescription())); } else if (idx > 0) { const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex(idx - 1); if (!plugin_name) { return LLDB_RECORD_RESULT(data); } platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name)); const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1); if (!plugin_desc) { return LLDB_RECORD_RESULT(data); } platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc)); } data.m_impl_up->SetObjectSP( StructuredData::ObjectSP(platform_dict.release())); return LLDB_RECORD_RESULT(data); } void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) { LLDB_RECORD_DUMMY(void, SBDebugger, DispatchInput, (void *, const void *, size_t), baton, data, data_len); DispatchInput(data, data_len); } void SBDebugger::DispatchInput(const void *data, size_t data_len) { LLDB_RECORD_DUMMY(void, SBDebugger, DispatchInput, (const void *, size_t), data, data_len); // Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); // // if (log) // LLDB_LOGF(log, "SBDebugger(%p)::DispatchInput (data=\"%.*s\", // size_t=%" PRIu64 ")", // m_opaque_sp.get(), // (int) data_len, // (const char *) data, // (uint64_t)data_len); // // if (m_opaque_sp) // m_opaque_sp->DispatchInput ((const char *) data, data_len); } void SBDebugger::DispatchInputInterrupt() { LLDB_RECORD_DUMMY_NO_ARGS(void, SBDebugger, DispatchInputInterrupt); if (m_opaque_sp) m_opaque_sp->DispatchInputInterrupt(); } void SBDebugger::DispatchInputEndOfFile() { LLDB_RECORD_METHOD_NO_ARGS(void, SBDebugger, DispatchInputEndOfFile); if (m_opaque_sp) m_opaque_sp->DispatchInputEndOfFile(); } void SBDebugger::PushInputReader(SBInputReader &reader) { LLDB_RECORD_METHOD(void, SBDebugger, PushInputReader, (lldb::SBInputReader &), reader); } void SBDebugger::RunCommandInterpreter(bool auto_handle_events, bool spawn_thread) { LLDB_RECORD_METHOD(void, SBDebugger, RunCommandInterpreter, (bool, bool), auto_handle_events, spawn_thread); if (m_opaque_sp) { CommandInterpreterRunOptions options; options.SetAutoHandleEvents(auto_handle_events); options.SetSpawnThread(spawn_thread); m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(options); } } void SBDebugger::RunCommandInterpreter(bool auto_handle_events, bool spawn_thread, SBCommandInterpreterRunOptions &options, int &num_errors, bool &quit_requested, bool &stopped_for_crash) { LLDB_RECORD_METHOD(void, SBDebugger, RunCommandInterpreter, (bool, bool, lldb::SBCommandInterpreterRunOptions &, int &, bool &, bool &), auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash); if (m_opaque_sp) { options.SetAutoHandleEvents(auto_handle_events); options.SetSpawnThread(spawn_thread); CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); CommandInterpreterRunResult result = interp.RunCommandInterpreter(options.ref()); num_errors = result.GetNumErrors(); quit_requested = result.IsResult(lldb::eCommandInterpreterResultQuitRequested); stopped_for_crash = result.IsResult(lldb::eCommandInterpreterResultInferiorCrash); } } SBCommandInterpreterRunResult SBDebugger::RunCommandInterpreter( const SBCommandInterpreterRunOptions &options) { LLDB_RECORD_METHOD(lldb::SBCommandInterpreterRunResult, SBDebugger, RunCommandInterpreter, (const lldb::SBCommandInterpreterRunOptions &), options); if (!m_opaque_sp) return LLDB_RECORD_RESULT(SBCommandInterpreterRunResult()); CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); CommandInterpreterRunResult result = interp.RunCommandInterpreter(options.ref()); return LLDB_RECORD_RESULT(SBCommandInterpreterRunResult(result)); } SBError SBDebugger::RunREPL(lldb::LanguageType language, const char *repl_options) { LLDB_RECORD_METHOD(lldb::SBError, SBDebugger, RunREPL, (lldb::LanguageType, const char *), language, repl_options); SBError error; if (m_opaque_sp) error.ref() = m_opaque_sp->RunREPL(language, repl_options); else error.SetErrorString("invalid debugger"); return LLDB_RECORD_RESULT(error); } void SBDebugger::reset(const DebuggerSP &debugger_sp) { m_opaque_sp = debugger_sp; } Debugger *SBDebugger::get() const { return m_opaque_sp.get(); } Debugger &SBDebugger::ref() const { assert(m_opaque_sp.get()); return *m_opaque_sp; } const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; } SBDebugger SBDebugger::FindDebuggerWithID(int id) { LLDB_RECORD_STATIC_METHOD(lldb::SBDebugger, SBDebugger, FindDebuggerWithID, (int), id); // No need to lock, the debugger list is thread safe SBDebugger sb_debugger; DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id); if (debugger_sp) sb_debugger.reset(debugger_sp); return LLDB_RECORD_RESULT(sb_debugger); } const char *SBDebugger::GetInstanceName() { LLDB_RECORD_METHOD_NO_ARGS(const char *, SBDebugger, GetInstanceName); return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr); } SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value, const char *debugger_instance_name) { LLDB_RECORD_STATIC_METHOD(lldb::SBError, SBDebugger, SetInternalVariable, (const char *, const char *, const char *), var_name, value, debugger_instance_name); SBError sb_error; DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( ConstString(debugger_instance_name))); Status error; if (debugger_sp) { ExecutionContext exe_ctx( debugger_sp->GetCommandInterpreter().GetExecutionContext()); error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign, var_name, value); } else { error.SetErrorStringWithFormat("invalid debugger instance name '%s'", debugger_instance_name); } if (error.Fail()) sb_error.SetError(error); return LLDB_RECORD_RESULT(sb_error); } SBStringList SBDebugger::GetInternalVariableValue(const char *var_name, const char *debugger_instance_name) { LLDB_RECORD_STATIC_METHOD( lldb::SBStringList, SBDebugger, GetInternalVariableValue, (const char *, const char *), var_name, debugger_instance_name); SBStringList ret_value; DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( ConstString(debugger_instance_name))); Status error; if (debugger_sp) { ExecutionContext exe_ctx( debugger_sp->GetCommandInterpreter().GetExecutionContext()); lldb::OptionValueSP value_sp( debugger_sp->GetPropertyValue(&exe_ctx, var_name, false, error)); if (value_sp) { StreamString value_strm; value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue); const std::string &value_str = std::string(value_strm.GetString()); if (!value_str.empty()) { StringList string_list; string_list.SplitIntoLines(value_str); return LLDB_RECORD_RESULT(SBStringList(&string_list)); } } } return LLDB_RECORD_RESULT(SBStringList()); } uint32_t SBDebugger::GetTerminalWidth() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBDebugger, GetTerminalWidth); return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0); } void SBDebugger::SetTerminalWidth(uint32_t term_width) { LLDB_RECORD_DUMMY(void, SBDebugger, SetTerminalWidth, (uint32_t), term_width); if (m_opaque_sp) m_opaque_sp->SetTerminalWidth(term_width); } const char *SBDebugger::GetPrompt() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBDebugger, GetPrompt); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); LLDB_LOGF(log, "SBDebugger(%p)::GetPrompt () => \"%s\"", static_cast<void *>(m_opaque_sp.get()), (m_opaque_sp ? m_opaque_sp->GetPrompt().str().c_str() : "")); return (m_opaque_sp ? ConstString(m_opaque_sp->GetPrompt()).GetCString() : nullptr); } void SBDebugger::SetPrompt(const char *prompt) { LLDB_RECORD_METHOD(void, SBDebugger, SetPrompt, (const char *), prompt); if (m_opaque_sp) m_opaque_sp->SetPrompt(llvm::StringRef::withNullAsEmpty(prompt)); } const char *SBDebugger::GetReproducerPath() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBDebugger, GetReproducerPath); return (m_opaque_sp ? ConstString(m_opaque_sp->GetReproducerPath()).GetCString() : nullptr); } ScriptLanguage SBDebugger::GetScriptLanguage() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::ScriptLanguage, SBDebugger, GetScriptLanguage); return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone); } void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) { LLDB_RECORD_METHOD(void, SBDebugger, SetScriptLanguage, (lldb::ScriptLanguage), script_lang); if (m_opaque_sp) { m_opaque_sp->SetScriptLanguage(script_lang); } } bool SBDebugger::SetUseExternalEditor(bool value) { LLDB_RECORD_METHOD(bool, SBDebugger, SetUseExternalEditor, (bool), value); return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false); } bool SBDebugger::GetUseExternalEditor() { LLDB_RECORD_METHOD_NO_ARGS(bool, SBDebugger, GetUseExternalEditor); return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false); } bool SBDebugger::SetUseColor(bool value) { LLDB_RECORD_METHOD(bool, SBDebugger, SetUseColor, (bool), value); return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false); } bool SBDebugger::GetUseColor() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, GetUseColor); return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false); } bool SBDebugger::SetUseSourceCache(bool value) { LLDB_RECORD_METHOD(bool, SBDebugger, SetUseSourceCache, (bool), value); return (m_opaque_sp ? m_opaque_sp->SetUseSourceCache(value) : false); } bool SBDebugger::GetUseSourceCache() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, GetUseSourceCache); return (m_opaque_sp ? m_opaque_sp->GetUseSourceCache() : false); } bool SBDebugger::GetDescription(SBStream &description) { LLDB_RECORD_METHOD(bool, SBDebugger, GetDescription, (lldb::SBStream &), description); Stream &strm = description.ref(); if (m_opaque_sp) { const char *name = m_opaque_sp->GetInstanceName().AsCString(); user_id_t id = m_opaque_sp->GetID(); strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id); } else strm.PutCString("No value"); return true; } user_id_t SBDebugger::GetID() { LLDB_RECORD_METHOD_NO_ARGS(lldb::user_id_t, SBDebugger, GetID); return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID); } SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) { LLDB_RECORD_METHOD(lldb::SBError, SBDebugger, SetCurrentPlatform, (const char *), platform_name_cstr); SBError sb_error; if (m_opaque_sp) { if (platform_name_cstr && platform_name_cstr[0]) { ConstString platform_name(platform_name_cstr); PlatformSP platform_sp(Platform::Find(platform_name)); if (platform_sp) { // Already have a platform with this name, just select it m_opaque_sp->GetPlatformList().SetSelectedPlatform(platform_sp); } else { // We don't have a platform by this name yet, create one platform_sp = Platform::Create(platform_name, sb_error.ref()); if (platform_sp) { // We created the platform, now append and select it bool make_selected = true; m_opaque_sp->GetPlatformList().Append(platform_sp, make_selected); } } } else { sb_error.ref().SetErrorString("invalid platform name"); } } else { sb_error.ref().SetErrorString("invalid debugger"); } return LLDB_RECORD_RESULT(sb_error); } bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) { LLDB_RECORD_METHOD(bool, SBDebugger, SetCurrentPlatformSDKRoot, (const char *), sysroot); Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (m_opaque_sp) { PlatformSP platform_sp( m_opaque_sp->GetPlatformList().GetSelectedPlatform()); if (platform_sp) { if (log && sysroot) LLDB_LOGF(log, "SBDebugger::SetCurrentPlatformSDKRoot (\"%s\")", sysroot); platform_sp->SetSDKRootDirectory(ConstString(sysroot)); return true; } } return false; } bool SBDebugger::GetCloseInputOnEOF() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBDebugger, GetCloseInputOnEOF); return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false); } void SBDebugger::SetCloseInputOnEOF(bool b) { LLDB_RECORD_METHOD(void, SBDebugger, SetCloseInputOnEOF, (bool), b); if (m_opaque_sp) m_opaque_sp->SetCloseInputOnEOF(b); } SBTypeCategory SBDebugger::GetCategory(const char *category_name) { LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, (const char *), category_name); if (!category_name || *category_name == 0) return LLDB_RECORD_RESULT(SBTypeCategory()); TypeCategoryImplSP category_sp; if (DataVisualization::Categories::GetCategory(ConstString(category_name), category_sp, false)) { return LLDB_RECORD_RESULT(SBTypeCategory(category_sp)); } else { return LLDB_RECORD_RESULT(SBTypeCategory()); } } SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) { LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, (lldb::LanguageType), lang_type); TypeCategoryImplSP category_sp; if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) { return LLDB_RECORD_RESULT(SBTypeCategory(category_sp)); } else { return LLDB_RECORD_RESULT(SBTypeCategory()); } } SBTypeCategory SBDebugger::CreateCategory(const char *category_name) { LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, CreateCategory, (const char *), category_name); if (!category_name || *category_name == 0) return LLDB_RECORD_RESULT(SBTypeCategory()); TypeCategoryImplSP category_sp; if (DataVisualization::Categories::GetCategory(ConstString(category_name), category_sp, true)) { return LLDB_RECORD_RESULT(SBTypeCategory(category_sp)); } else { return LLDB_RECORD_RESULT(SBTypeCategory()); } } bool SBDebugger::DeleteCategory(const char *category_name) { LLDB_RECORD_METHOD(bool, SBDebugger, DeleteCategory, (const char *), category_name); if (!category_name || *category_name == 0) return false; return DataVisualization::Categories::Delete(ConstString(category_name)); } uint32_t SBDebugger::GetNumCategories() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBDebugger, GetNumCategories); return DataVisualization::Categories::GetCount(); } SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) { LLDB_RECORD_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategoryAtIndex, (uint32_t), index); return LLDB_RECORD_RESULT( SBTypeCategory(DataVisualization::Categories::GetCategoryAtIndex(index))); } SBTypeCategory SBDebugger::GetDefaultCategory() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBTypeCategory, SBDebugger, GetDefaultCategory); return LLDB_RECORD_RESULT(GetCategory("default")); } SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) { LLDB_RECORD_METHOD(lldb::SBTypeFormat, SBDebugger, GetFormatForType, (lldb::SBTypeNameSpecifier), type_name); SBTypeCategory default_category_sb = GetDefaultCategory(); if (default_category_sb.GetEnabled()) return LLDB_RECORD_RESULT(default_category_sb.GetFormatForType(type_name)); return LLDB_RECORD_RESULT(SBTypeFormat()); } SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) { LLDB_RECORD_METHOD(lldb::SBTypeSummary, SBDebugger, GetSummaryForType, (lldb::SBTypeNameSpecifier), type_name); if (!type_name.IsValid()) return LLDB_RECORD_RESULT(SBTypeSummary()); return LLDB_RECORD_RESULT( SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP()))); } SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) { LLDB_RECORD_METHOD(lldb::SBTypeFilter, SBDebugger, GetFilterForType, (lldb::SBTypeNameSpecifier), type_name); if (!type_name.IsValid()) return LLDB_RECORD_RESULT(SBTypeFilter()); return LLDB_RECORD_RESULT( SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP()))); } SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) { LLDB_RECORD_METHOD(lldb::SBTypeSynthetic, SBDebugger, GetSyntheticForType, (lldb::SBTypeNameSpecifier), type_name); if (!type_name.IsValid()) return LLDB_RECORD_RESULT(SBTypeSynthetic()); return LLDB_RECORD_RESULT(SBTypeSynthetic( DataVisualization::GetSyntheticForType(type_name.GetSP()))); } static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) { if (categories == nullptr) return {}; size_t len = 0; while (categories[len] != nullptr) ++len; return llvm::makeArrayRef(categories, len); } bool SBDebugger::EnableLog(const char *channel, const char **categories) { LLDB_RECORD_METHOD(bool, SBDebugger, EnableLog, (const char *, const char **), channel, categories); if (m_opaque_sp) { uint32_t log_options = LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; std::string error; llvm::raw_string_ostream error_stream(error); return m_opaque_sp->EnableLog(channel, GetCategoryArray(categories), "", log_options, error_stream); } else return false; } void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton) { LLDB_RECORD_DUMMY(void, SBDebugger, SetLoggingCallback, (lldb::LogOutputCallback, void *), log_callback, baton); if (m_opaque_sp) { return m_opaque_sp->SetLoggingCallback(log_callback, baton); } } namespace lldb_private { namespace repro { template <> void RegisterMethods<SBInputReader>(Registry &R) { LLDB_REGISTER_METHOD(void, SBInputReader, SetIsDone, (bool)); LLDB_REGISTER_METHOD_CONST(bool, SBInputReader, IsActive, ()); } static void SetFileHandleRedirect(SBDebugger *, FILE *, bool) { // Do nothing. } static SBError SetFileRedirect(SBDebugger *, SBFile file) { return SBError(); } static SBError SetFileRedirect(SBDebugger *, FileSP file) { return SBError(); } template <> void RegisterMethods<SBDebugger>(Registry &R) { // Custom implementation. R.Register(&invoke<void (SBDebugger::*)(FILE *, bool)>::method< &SBDebugger::SetErrorFileHandle>::record, &SetFileHandleRedirect); R.Register(&invoke<void (SBDebugger::*)(FILE *, bool)>::method< &SBDebugger::SetOutputFileHandle>::record, &SetFileHandleRedirect); R.Register(&invoke<SBError (SBDebugger::*)( SBFile)>::method<&SBDebugger::SetInputFile>::record, &SetFileRedirect); R.Register(&invoke<SBError (SBDebugger::*)( SBFile)>::method<&SBDebugger::SetOutputFile>::record, &SetFileRedirect); R.Register(&invoke<SBError (SBDebugger::*)( SBFile)>::method<&SBDebugger::SetErrorFile>::record, &SetFileRedirect); R.Register(&invoke<SBError (SBDebugger::*)( FileSP)>::method<&SBDebugger::SetInputFile>::record, &SetFileRedirect); R.Register(&invoke<SBError (SBDebugger::*)( FileSP)>::method<&SBDebugger::SetOutputFile>::record, &SetFileRedirect); R.Register(&invoke<SBError (SBDebugger::*)( FileSP)>::method<&SBDebugger::SetErrorFile>::record, &SetFileRedirect); LLDB_REGISTER_CHAR_PTR_METHOD_STATIC(bool, SBDebugger, GetDefaultArchitecture); LLDB_REGISTER_CONSTRUCTOR(SBDebugger, ()); LLDB_REGISTER_CONSTRUCTOR(SBDebugger, (const lldb::DebuggerSP &)); LLDB_REGISTER_CONSTRUCTOR(SBDebugger, (const lldb::SBDebugger &)); LLDB_REGISTER_METHOD(lldb::SBDebugger &, SBDebugger, operator=,(const lldb::SBDebugger &)); LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, Initialize, ()); LLDB_REGISTER_STATIC_METHOD(lldb::SBError, SBDebugger, InitializeWithErrorHandling, ()); LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, Terminate, ()); LLDB_REGISTER_METHOD(void, SBDebugger, Clear, ()); LLDB_REGISTER_STATIC_METHOD(lldb::SBDebugger, SBDebugger, Create, ()); LLDB_REGISTER_STATIC_METHOD(lldb::SBDebugger, SBDebugger, Create, (bool)); LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, Destroy, (lldb::SBDebugger &)); LLDB_REGISTER_STATIC_METHOD(void, SBDebugger, MemoryPressureDetected, ()); LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, IsValid, ()); LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, operator bool,()); LLDB_REGISTER_METHOD(void, SBDebugger, SetAsync, (bool)); LLDB_REGISTER_METHOD(bool, SBDebugger, GetAsync, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SkipLLDBInitFiles, (bool)); LLDB_REGISTER_METHOD(void, SBDebugger, SkipAppInitFiles, (bool)); LLDB_REGISTER_METHOD(void, SBDebugger, SetInputFileHandle, (FILE *, bool)); LLDB_REGISTER_METHOD(FILE *, SBDebugger, GetInputFileHandle, ()); LLDB_REGISTER_METHOD(FILE *, SBDebugger, GetOutputFileHandle, ()); LLDB_REGISTER_METHOD(FILE *, SBDebugger, GetErrorFileHandle, ()); LLDB_REGISTER_METHOD(SBFile, SBDebugger, GetInputFile, ()); LLDB_REGISTER_METHOD(SBFile, SBDebugger, GetOutputFile, ()); LLDB_REGISTER_METHOD(SBFile, SBDebugger, GetErrorFile, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SaveInputTerminalState, ()); LLDB_REGISTER_METHOD(void, SBDebugger, RestoreInputTerminalState, ()); LLDB_REGISTER_METHOD(lldb::SBCommandInterpreter, SBDebugger, GetCommandInterpreter, ()); LLDB_REGISTER_METHOD(void, SBDebugger, HandleCommand, (const char *)); LLDB_REGISTER_METHOD(lldb::SBListener, SBDebugger, GetListener, ()); LLDB_REGISTER_METHOD( void, SBDebugger, HandleProcessEvent, (const lldb::SBProcess &, const lldb::SBEvent &, FILE *, FILE *)); LLDB_REGISTER_METHOD( void, SBDebugger, HandleProcessEvent, (const lldb::SBProcess &, const lldb::SBEvent &, SBFile, SBFile)); LLDB_REGISTER_METHOD( void, SBDebugger, HandleProcessEvent, (const lldb::SBProcess &, const lldb::SBEvent &, FileSP, FileSP)); LLDB_REGISTER_METHOD(lldb::SBSourceManager, SBDebugger, GetSourceManager, ()); LLDB_REGISTER_STATIC_METHOD(bool, SBDebugger, SetDefaultArchitecture, (const char *)); LLDB_REGISTER_METHOD(lldb::ScriptLanguage, SBDebugger, GetScriptingLanguage, (const char *)); LLDB_REGISTER_STATIC_METHOD(const char *, SBDebugger, GetVersionString, ()); LLDB_REGISTER_STATIC_METHOD(const char *, SBDebugger, StateAsCString, (lldb::StateType)); LLDB_REGISTER_STATIC_METHOD(lldb::SBStructuredData, SBDebugger, GetBuildConfiguration, ()); LLDB_REGISTER_STATIC_METHOD(bool, SBDebugger, StateIsRunningState, (lldb::StateType)); LLDB_REGISTER_STATIC_METHOD(bool, SBDebugger, StateIsStoppedState, (lldb::StateType)); LLDB_REGISTER_METHOD( lldb::SBTarget, SBDebugger, CreateTarget, (const char *, const char *, const char *, bool, lldb::SBError &)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, CreateTargetWithFileAndTargetTriple, (const char *, const char *)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, CreateTargetWithFileAndArch, (const char *, const char *)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, CreateTarget, (const char *)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, GetDummyTarget, ()); LLDB_REGISTER_METHOD(bool, SBDebugger, DeleteTarget, (lldb::SBTarget &)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, GetTargetAtIndex, (uint32_t)); LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetIndexOfTarget, (lldb::SBTarget)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithProcessID, (lldb::pid_t)); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, FindTargetWithFileAndArch, (const char *, const char *)); LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumTargets, ()); LLDB_REGISTER_METHOD(lldb::SBTarget, SBDebugger, GetSelectedTarget, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SetSelectedTarget, (lldb::SBTarget &)); LLDB_REGISTER_METHOD(lldb::SBPlatform, SBDebugger, GetSelectedPlatform, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SetSelectedPlatform, (lldb::SBPlatform &)); LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumPlatforms, ()); LLDB_REGISTER_METHOD(lldb::SBPlatform, SBDebugger, GetPlatformAtIndex, (uint32_t)); LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumAvailablePlatforms, ()); LLDB_REGISTER_METHOD(lldb::SBStructuredData, SBDebugger, GetAvailablePlatformInfoAtIndex, (uint32_t)); LLDB_REGISTER_METHOD(void, SBDebugger, DispatchInputInterrupt, ()); LLDB_REGISTER_METHOD(void, SBDebugger, DispatchInputEndOfFile, ()); LLDB_REGISTER_METHOD(void, SBDebugger, PushInputReader, (lldb::SBInputReader &)); LLDB_REGISTER_METHOD(void, SBDebugger, RunCommandInterpreter, (bool, bool)); LLDB_REGISTER_METHOD(void, SBDebugger, RunCommandInterpreter, (bool, bool, lldb::SBCommandInterpreterRunOptions &, int &, bool &, bool &)); LLDB_REGISTER_METHOD(lldb::SBError, SBDebugger, RunREPL, (lldb::LanguageType, const char *)); LLDB_REGISTER_STATIC_METHOD(lldb::SBDebugger, SBDebugger, FindDebuggerWithID, (int)); LLDB_REGISTER_METHOD(const char *, SBDebugger, GetInstanceName, ()); LLDB_REGISTER_STATIC_METHOD(lldb::SBError, SBDebugger, SetInternalVariable, (const char *, const char *, const char *)); LLDB_REGISTER_STATIC_METHOD(lldb::SBStringList, SBDebugger, GetInternalVariableValue, (const char *, const char *)); LLDB_REGISTER_METHOD_CONST(uint32_t, SBDebugger, GetTerminalWidth, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SetTerminalWidth, (uint32_t)); LLDB_REGISTER_METHOD_CONST(const char *, SBDebugger, GetPrompt, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SetPrompt, (const char *)); LLDB_REGISTER_METHOD_CONST(const char *, SBDebugger, GetReproducerPath, ()); LLDB_REGISTER_METHOD_CONST(lldb::ScriptLanguage, SBDebugger, GetScriptLanguage, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SetScriptLanguage, (lldb::ScriptLanguage)); LLDB_REGISTER_METHOD(bool, SBDebugger, SetUseExternalEditor, (bool)); LLDB_REGISTER_METHOD(bool, SBDebugger, GetUseExternalEditor, ()); LLDB_REGISTER_METHOD(bool, SBDebugger, SetUseColor, (bool)); LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, GetUseColor, ()); LLDB_REGISTER_METHOD(bool, SBDebugger, GetDescription, (lldb::SBStream &)); LLDB_REGISTER_METHOD(lldb::user_id_t, SBDebugger, GetID, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBDebugger, SetCurrentPlatform, (const char *)); LLDB_REGISTER_METHOD(bool, SBDebugger, SetCurrentPlatformSDKRoot, (const char *)); LLDB_REGISTER_METHOD_CONST(bool, SBDebugger, GetCloseInputOnEOF, ()); LLDB_REGISTER_METHOD(void, SBDebugger, SetCloseInputOnEOF, (bool)); LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, (const char *)); LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategory, (lldb::LanguageType)); LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, CreateCategory, (const char *)); LLDB_REGISTER_METHOD(bool, SBDebugger, DeleteCategory, (const char *)); LLDB_REGISTER_METHOD(uint32_t, SBDebugger, GetNumCategories, ()); LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetCategoryAtIndex, (uint32_t)); LLDB_REGISTER_METHOD(lldb::SBTypeCategory, SBDebugger, GetDefaultCategory, ()); LLDB_REGISTER_METHOD(lldb::SBTypeFormat, SBDebugger, GetFormatForType, (lldb::SBTypeNameSpecifier)); LLDB_REGISTER_METHOD(lldb::SBTypeSummary, SBDebugger, GetSummaryForType, (lldb::SBTypeNameSpecifier)); LLDB_REGISTER_METHOD(lldb::SBTypeSynthetic, SBDebugger, GetSyntheticForType, (lldb::SBTypeNameSpecifier)); LLDB_REGISTER_METHOD(lldb::SBTypeFilter, SBDebugger, GetFilterForType, (lldb::SBTypeNameSpecifier)); LLDB_REGISTER_METHOD(bool, SBDebugger, EnableLog, (const char *, const char **)); LLDB_REGISTER_METHOD(lldb::SBCommandInterpreterRunResult, SBDebugger, RunCommandInterpreter, (const lldb::SBCommandInterpreterRunOptions &)); } } // namespace repro } // namespace lldb_private
// bslstp_hashtable.cpp -*-C++-*- #ifndef BDE_OPENSOURCE_PUBLICATION // STP #include <bslstp_hashtable.h> namespace bsl { // Force instantiation. template class _Stl_prime<bool>; } // close namespace bsl #endif // BDE_OPENSOURCE_PUBLICATION -- STP
// Copyright (c) 2012-2017, The CryptoNote developers, The Marcoin developers // // This file is part of Marcoin. // // Bytecoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>. #include "TransactionUtils.h" #include <unordered_set> #include "crypto/crypto.h" #include "CryptoNoteCore/Account.h" #include "CryptoNoteFormatUtils.h" #include "Common/TransactionExtra.h" using namespace Crypto; namespace CryptoNote { bool checkInputsKeyimagesDiff(const CryptoNote::TransactionPrefix& tx) { std::unordered_set<Crypto::KeyImage> ki; for (const auto& in : tx.inputs) { if (in.type() == typeid(KeyInput)) { if (!ki.insert(boost::get<KeyInput>(in).keyImage).second) return false; } } return true; } // TransactionInput helper functions size_t getRequiredSignaturesCount(const TransactionInput& in) { if (in.type() == typeid(KeyInput)) { return boost::get<KeyInput>(in).outputIndexes.size(); } return 0; } uint64_t getTransactionInputAmount(const TransactionInput& in) { if (in.type() == typeid(KeyInput)) { return boost::get<KeyInput>(in).amount; } return 0; } TransactionTypes::InputType getTransactionInputType(const TransactionInput& in) { if (in.type() == typeid(KeyInput)) { return TransactionTypes::InputType::Key; } if (in.type() == typeid(BaseInput)) { return TransactionTypes::InputType::Generating; } return TransactionTypes::InputType::Invalid; } const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) { if (transaction.inputs.size() <= index) { throw std::runtime_error("Transaction input index out of range"); } return transaction.inputs[index]; } const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index, TransactionTypes::InputType type) { const auto& input = getInputChecked(transaction, index); if (getTransactionInputType(input) != type) { throw std::runtime_error("Unexpected transaction input type"); } return input; } // TransactionOutput helper functions TransactionTypes::OutputType getTransactionOutputType(const TransactionOutputTarget& out) { if (out.type() == typeid(KeyOutput)) { return TransactionTypes::OutputType::Key; } return TransactionTypes::OutputType::Invalid; } const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) { if (transaction.outputs.size() <= index) { throw std::runtime_error("Transaction output index out of range"); } return transaction.outputs[index]; } const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index, TransactionTypes::OutputType type) { const auto& output = getOutputChecked(transaction, index); if (getTransactionOutputType(output.target) != type) { throw std::runtime_error("Unexpected transaction output target type"); } return output; } bool findOutputsToAccount(const CryptoNote::TransactionPrefix& transaction, const AccountPublicAddress& addr, const SecretKey& viewSecretKey, std::vector<uint32_t>& out, uint64_t& amount) { AccountKeys keys; keys.address = addr; // only view secret key is used, spend key is not needed keys.viewSecretKey = viewSecretKey; Crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(transaction.extra); amount = 0; size_t keyIndex = 0; uint32_t outputIndex = 0; Crypto::KeyDerivation derivation; generate_key_derivation(txPubKey, keys.viewSecretKey, derivation); for (const TransactionOutput& o : transaction.outputs) { assert(o.target.type() == typeid(KeyOutput)); if (o.target.type() == typeid(KeyOutput)) { if (is_out_to_acc(keys, boost::get<KeyOutput>(o.target), derivation, keyIndex)) { out.push_back(outputIndex); amount += o.amount; } ++keyIndex; } ++outputIndex; } return true; } }
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2010 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-04-19 // Updated : 2009-02-19 // Licence : This source is under MIT License // File : glm/gtx/matrix_major_storage.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace gtx{ namespace matrix_major_storage { template <typename T> inline detail::tmat2x2<T> rowMajor2( const detail::tvec2<T>& v1, const detail::tvec2<T>& v2) { detail::tmat2x2<T> Result; Result[0][0] = v1.x; Result[1][0] = v1.y; Result[0][1] = v2.x; Result[1][1] = v2.y; return Result; } template <typename T> inline detail::tmat2x2<T> rowMajor2( const detail::tmat2x2<T>& m) { detail::tmat2x2<T> Result; Result[0][0] = m[0][0]; Result[0][1] = m[1][0]; Result[1][0] = m[0][1]; Result[1][1] = m[1][1]; return Result; } template <typename T> inline detail::tmat3x3<T> rowMajor3( const detail::tvec3<T>& v1, const detail::tvec3<T>& v2, const detail::tvec3<T>& v3) { detail::tmat3x3<T> Result; Result[0][0] = v1.x; Result[1][0] = v1.y; Result[2][0] = v1.z; Result[0][1] = v2.x; Result[1][1] = v2.y; Result[2][1] = v2.z; Result[0][2] = v3.x; Result[1][2] = v3.y; Result[2][2] = v3.z; return Result; } template <typename T> inline detail::tmat3x3<T> rowMajor3( const detail::tmat3x3<T>& m) { detail::tmat3x3<T> Result; Result[0][0] = m[0][0]; Result[0][1] = m[1][0]; Result[0][2] = m[2][0]; Result[1][0] = m[0][1]; Result[1][1] = m[1][1]; Result[1][2] = m[2][1]; Result[2][0] = m[0][2]; Result[2][1] = m[1][2]; Result[2][2] = m[2][2]; return Result; } template <typename T> inline detail::tmat4x4<T> rowMajor4( const detail::tvec4<T>& v1, const detail::tvec4<T>& v2, const detail::tvec4<T>& v3, const detail::tvec4<T>& v4) { detail::tmat4x4<T> Result; Result[0][0] = v1.x; Result[1][0] = v1.y; Result[2][0] = v1.z; Result[3][0] = v1.w; Result[0][1] = v2.x; Result[1][1] = v2.y; Result[2][1] = v2.z; Result[3][1] = v2.w; Result[0][2] = v3.x; Result[1][2] = v3.y; Result[2][2] = v3.z; Result[3][2] = v3.w; Result[0][3] = v4.x; Result[1][3] = v4.y; Result[2][3] = v4.z; Result[3][3] = v4.w; return Result; } template <typename T> inline detail::tmat4x4<T> rowMajor4( const detail::tmat4x4<T>& m) { detail::tmat4x4<T> Result; Result[0][0] = m[0][0]; Result[0][1] = m[1][0]; Result[0][2] = m[2][0]; Result[0][3] = m[3][0]; Result[1][0] = m[0][1]; Result[1][1] = m[1][1]; Result[1][2] = m[2][1]; Result[1][3] = m[3][1]; Result[2][0] = m[0][2]; Result[2][1] = m[1][2]; Result[2][2] = m[2][2]; Result[2][3] = m[3][2]; Result[3][0] = m[0][3]; Result[3][1] = m[1][3]; Result[3][2] = m[2][3]; Result[3][3] = m[3][3]; return Result; } template <typename T> inline detail::tmat2x2<T> colMajor2( const detail::tvec2<T>& v1, const detail::tvec2<T>& v2) { return detail::tmat2x2<T>(v1, v2); } template <typename T> inline detail::tmat2x2<T> colMajor2( const detail::tmat2x2<T>& m) { return detail::tmat2x2<T>(m); } template <typename T> inline detail::tmat3x3<T> colMajor3( const detail::tvec3<T>& v1, const detail::tvec3<T>& v2, const detail::tvec3<T>& v3) { return detail::tmat3x3<T>(v1, v2, v3); } template <typename T> inline detail::tmat3x3<T> colMajor3( const detail::tmat3x3<T>& m) { return detail::tmat3x3<T>(m); } template <typename T> inline detail::tmat4x4<T> colMajor4( const detail::tvec4<T>& v1, const detail::tvec4<T>& v2, const detail::tvec4<T>& v3, const detail::tvec4<T>& v4) { return detail::tmat4x4<T>(v1, v2, v3, v4); } template <typename T> inline detail::tmat4x4<T> colMajor4( const detail::tmat4x4<T>& m) { return detail::tmat4x4<T>(m); } }//namespace matrix_major_storage }//namespace gtx }//namespace glm
/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 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. */ /** * @file * This file implements OTNS utilities. * */ #include "otns.hpp" #if (OPENTHREAD_MTD || OPENTHREAD_FTD) && OPENTHREAD_CONFIG_OTNS_ENABLE #include "common/debug.hpp" #include "common/locator-getters.hpp" namespace ot { namespace Utils { const int kMaxStatusStringLength = 128; void Otns::EmitShortAddress(uint16_t aShortAddress) { EmitStatus("rloc16=%d", aShortAddress); } void Otns::EmitExtendedAddress(const Mac::ExtAddress &aExtAddress) { Mac::ExtAddress revExtAddress; revExtAddress.Set(aExtAddress.m8, Mac::ExtAddress::kReverseByteOrder); EmitStatus("extaddr=%s", revExtAddress.ToString().AsCString()); } void Otns::EmitPingRequest(const Ip6::Address &aPeerAddress, uint16_t aPingLength, uint32_t aTimestamp, uint8_t aHopLimit) { OT_UNUSED_VARIABLE(aHopLimit); EmitStatus("ping_request=%s,%d,%lu", aPeerAddress.ToString().AsCString(), aPingLength, aTimestamp); } void Otns::EmitPingReply(const Ip6::Address &aPeerAddress, uint16_t aPingLength, uint32_t aTimestamp, uint8_t aHopLimit) { EmitStatus("ping_reply=%s,%u,%lu,%d", aPeerAddress.ToString().AsCString(), aPingLength, aTimestamp, aHopLimit); } void Otns::EmitStatus(const char *aFmt, ...) { char statusStr[kMaxStatusStringLength + 1]; int n; va_list ap; va_start(ap, aFmt); n = vsnprintf(statusStr, sizeof(statusStr), aFmt, ap); OT_UNUSED_VARIABLE(n); OT_ASSERT(n >= 0); va_end(ap); otPlatOtnsStatus(statusStr); } void Otns::HandleNotifierEvents(Events aEvents) { if (aEvents.Contains(kEventThreadRoleChanged)) { EmitStatus("role=%d", Get<Mle::Mle>().GetRole()); } if (aEvents.Contains(kEventThreadPartitionIdChanged)) { EmitStatus("parid=%x", Get<Mle::Mle>().GetLeaderData().GetPartitionId()); } #if OPENTHREAD_CONFIG_JOINER_ENABLE if (aEvents.Contains(kEventJoinerStateChanged)) { EmitStatus("joiner_state=%d", Get<MeshCoP::Joiner>().GetState()); } #endif } void Otns::EmitNeighborChange(NeighborTable::Event aEvent, const Neighbor &aNeighbor) { switch (aEvent) { case OT_NEIGHBOR_TABLE_EVENT_ROUTER_ADDED: EmitStatus("router_added=%s", aNeighbor.GetExtAddress().ToString().AsCString()); break; case OT_NEIGHBOR_TABLE_EVENT_ROUTER_REMOVED: EmitStatus("router_removed=%s", aNeighbor.GetExtAddress().ToString().AsCString()); break; case OT_NEIGHBOR_TABLE_EVENT_CHILD_ADDED: EmitStatus("child_added=%s", aNeighbor.GetExtAddress().ToString().AsCString()); break; case OT_NEIGHBOR_TABLE_EVENT_CHILD_REMOVED: EmitStatus("child_removed=%s", aNeighbor.GetExtAddress().ToString().AsCString()); break; } } void Otns::EmitTransmit(const Mac::TxFrame &aFrame) { Mac::Address dst; uint16_t frameControlField = aFrame.GetFrameControlField(); uint8_t channel = aFrame.GetChannel(); uint8_t sequence = aFrame.GetSequence(); IgnoreError(aFrame.GetDstAddr(dst)); if (dst.IsShort()) { EmitStatus("transmit=%d,%04x,%d,%04x", channel, frameControlField, sequence, dst.GetShort()); } else if (dst.IsExtended()) { EmitStatus("transmit=%d,%04x,%d,%s", channel, frameControlField, sequence, dst.ToString().AsCString()); } else { EmitStatus("transmit=%d,%04x,%d", channel, frameControlField, sequence); } } void Otns::EmitDeviceMode(Mle::DeviceMode aMode) { EmitStatus("mode=%s%s%s%s", aMode.IsRxOnWhenIdle() ? "r" : "", aMode.IsSecureDataRequest() ? "s" : "", aMode.IsFullThreadDevice() ? "d" : "", aMode.IsFullNetworkData() ? "n" : ""); } } // namespace Utils } // namespace ot #endif // (OPENTHREAD_MTD || OPENTHREAD_FTD) && OPENTHREAD_CONFIG_OTNS_ENABLE