text
stringlengths
1
1.05M
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2019 The digiquian Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coincontroldialog.h" #include "ui_coincontroldialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "txmempool.h" #include "walletmodel.h" #include "wallet/coincontrol.h" #include "init.h" #include "policy/policy.h" #include "validation.h" // For mempool #include "wallet/wallet.h" #include "instantx.h" #include "privatesend-client.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QApplication> #include <QCheckBox> #include <QCursor> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QSettings> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> QList<CAmount> CoinControlDialog::payAmounts; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); bool CoinControlDialog::fSubtractFeeFromAmount = false; bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const { int column = treeWidget()->sortColumn(); if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS || column == CoinControlDialog::COLUMN_PRIVATESEND_ROUNDS) return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong(); return QTreeWidgetItem::operator<(other); } CoinControlDialog::CoinControlDialog(const PlatformStyle *_platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0), platformStyle(_platformStyle) { ui->setupUi(this); /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // Toggle lock state connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190); ui->treeWidget->setColumnWidth(COLUMN_PRIVATESEND_ROUNDS, 88); ui->treeWidget->setColumnWidth(COLUMN_DATE, 80); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transaction hash in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) ui->radioTreeMode->click(); if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt())); } CoinControlDialog::~CoinControlDialog() { QSettings settings; settings.setValue("nCoinControlMode", ui->radioListMode->isChecked()); settings.setValue("nCoinControlSortColumn", sortColumn); settings.setValue("nCoinControlSortOrder", (int)sortOrder); delete ui; } void CoinControlDialog::setModel(WalletModel *_model) { this->model = _model; if(_model && _model->getOptionsModel() && _model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(_model, this); } } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure CoinControlDialog::updateLabels(model, this); } // Toggle lock state void CoinControlDialog::buttonToggleLockClicked() { QTreeWidgetItem *item; QString theme = GUIUtil::getThemeName(); // Works in list-mode only if(ui->radioListMode->isChecked()){ ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++){ item = ui->treeWidget->topLevelItem(i); COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())){ model->unlockCoin(outpt); item->setDisabled(false); item->setIcon(COLUMN_CHECKBOX, QIcon()); } else{ model->lockCoin(outpt); item->setDisabled(true); item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed")); } updateLabelLocked(); } ui->treeWidget->setEnabled(true); CoinControlDialog::updateLabels(model, this); } else{ QMessageBox msgBox; msgBox.setObjectName("lockMessageBox"); msgBox.setStyleSheet(GUIUtil::loadStyleSheet()); msgBox.setText(tr("Please switch to \"List mode\" to use this function.")); msgBox.exec(); } } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else // this means click on parent node in tree mode -> disable all { copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin void CoinControlDialog::lockCoin() { QString theme = GUIUtil::getThemeName(); if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, "")); } // copy label "Dust" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } else { if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else { coinControl->Select(outpt); int nRounds = pwalletMain->GetOutpointPrivateSendRounds(outpt); if (coinControl->fUsePrivateSend && nRounds < privateSendClient.nPrivateSendRounds) { QMessageBox::warning(this, windowTitle(), tr("Non-anonymized input selected. <b>PrivateSend will be disabled.</b><br><br>If you still want to use PrivateSend, please deselect all non-nonymized inputs first and then check PrivateSend checkbox again."), QMessageBox::Ok, QMessageBox::Ok); coinControl->fUsePrivateSend = false; } } // selection changed -> update labels if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); } // TODO: Remove this temporary qt5 fix after Qt5.3 and Qt5.4 are no longer used. // Fixed in Qt5.5 and above: https://bugreports.qt.io/browse/QTBUG-43473 #if QT_VERSION >= 0x050000 else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } #endif } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { std::vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); } void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { if (!model) return; // nPayAmount CAmount nPayAmount = 0; bool fDust = false; CMutableTransaction txDummy; Q_FOREACH(const CAmount &amount, CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > 0) { CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); if (txout.IsDust(dustRelayFee)) fDust = true; } } CAmount nAmount = 0; CAmount nPayFee = 0; CAmount nAfterFee = 0; CAmount nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; int nQuantityUncompressed = 0; bool fAllowFree = false; std::vector<COutPoint> vCoinControl; std::vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH(const COutput& out, vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); if (model->isSpent(outpt)) { coinControl->UnSelect(outpt); continue; } // Quantity nQuantity++; // Amount nAmount += out.tx->tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->tx->vout[out.i].nValue * (out.nDepth+1); // Bytes CTxDestination address; if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&address); if (keyid && model->getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if (!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; // in all error cases, simply assume 148 here } else nBytesInputs += 148; // Add inputs to calculate InstantSend Fee later if(coinControl->fUseInstantSend) txDummy.vin.push_back(CTxIn()); } // calculation if (nQuantity > 0) { // Bytes nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here // in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate if (CoinControlDialog::fSubtractFeeFromAmount) if (nAmount - nPayAmount == 0) nBytes -= 34; // Fee nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); if (nPayFee > 0 && coinControl->nMinimumTotalFee > nPayFee) nPayFee = coinControl->nMinimumTotalFee; // InstantSend Fee if (coinControl->fUseInstantSend) nPayFee = std::max(nPayFee, CTxLockRequest(txDummy).GetMinFee()); // Allow free? (require at least hard-coded threshold and default to that if no estimate) double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority) double dPriorityNeeded = std::max(mempoolEstimatePriority, AllowFreeThreshold()); fAllowFree = (dPriority >= dPriorityNeeded); if (fSendFreeTransactions) if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) nPayFee = 0; if (nPayAmount > 0) { nChange = nAmount - nPayAmount; if (!CoinControlDialog::fSubtractFeeFromAmount) nChange -= nPayFee; // PrivateSend Fee = overpay if(coinControl->fUsePrivateSend && nChange > 0) { nPayFee += nChange; nChange = 0; } // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < MIN_CHANGE) { CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0)); if (txout.IsDust(dustRelayFee)) { if (CoinControlDialog::fSubtractFeeFromAmount) // dust-change will be raised until no dust nChange = txout.GetDustThreshold(dustRelayFee); else { nPayFee += nChange; nChange = 0; } } } if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount) nBytes -= 34; } // after fee nAfterFee = std::max<CAmount>(nAmount - nPayFee, 0); } // actually update labels int nDisplayUnit = BitcoinUnits::QUIAN; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee"); QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes"); QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange"); // enable/disable "dust" and "change" dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes l7->setText(fDust ? tr("yes") : tr("no")); // Dust l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change if (nPayFee > 0 && (coinControl->nMinimumTotalFee < nPayFee)) { l3->setText(ASYMP_UTF8 + l3->text()); l4->setText(ASYMP_UTF8 + l4->text()); if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount) l8->setText(ASYMP_UTF8 + l8->text()); } // turn label red when dust l7->setStyleSheet((fDust) ? "color:red;" : ""); // tool tips QString toolTipDust = tr("This label turns red if any recipient receives an amount smaller than the current dust threshold."); // how many satoshis the estimated fee can vary per byte we guess wrong double dFeeVary; if (payTxFee.GetFeePerK() > 0) dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), payTxFee.GetFeePerK()) / 1000; else { dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), mempool.estimateSmartFee(nTxConfirmTarget).GetFeePerK()) / 1000; } QString toolTip4 = tr("Can vary +/- %1 duff(s) per input.").arg(dFeeVary); l3->setToolTip(toolTip4); l4->setToolTip(toolTip4); l7->setToolTip(toolTipDust); l8->setToolTip(toolTip4); dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip()); dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip()); dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds"); if (label) label->setVisible(nChange < 0); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) return; bool treeMode = ui->radioTreeMode->isChecked(); QString theme = GUIUtil::getThemeName(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); itemWalletAddress->setToolTip(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); itemWalletAddress->setToolTip(COLUMN_ADDRESS, sWalletAddress); } CAmount nSum = 0; int nChildren = 0; BOOST_FOREACH(const COutput& out, coins.second) { nSum += out.tx->tx->vout[out.i].nValue; nChildren++; CCoinControlWidgetItem *itemOutput; if (treeMode) itemOutput = new CCoinControlWidgetItem(itemWalletAddress); else itemOutput = new CCoinControlWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); // if listMode or change => show digiquian address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); itemOutput->setToolTip(COLUMN_ADDRESS, sAddress); } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue)); itemOutput->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue)); itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->tx->vout[out.i].nValue)); // padding so that sorting works correctly // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setToolTip(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime())); // PrivateSend rounds COutPoint outpoint = COutPoint(out.tx->tx->GetHash(), out.i); int nRounds = pwalletMain->GetOutpointPrivateSendRounds(outpoint); if (nRounds >= 0 || fDebug) itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, QString::number(nRounds)); else itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, tr("n/a")); itemOutput->setData(COLUMN_PRIVATESEND_ROUNDS, Qt::UserRole, QVariant((qlonglong)nRounds)); // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth)); itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth)); // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed")); } // set checkbox if (coinControl->IsSelected(COutPoint(txhash, out.i))) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } // amount if (treeMode) { itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)nSum)); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); }
; ; Word: DROP ; Dictionary: (a - ) ; Date: 1st February 2018 ; Macro: Yes ; Notes: ; pop hl pop de jp (hl)
.686 .model flat,stdcall option casemap:none include .\bnlib.inc include .\bignum.inc .code ;; esi=bnX ;; edi=Prod ;; School boy _bn_muldw_basecase proc c pushad mov ebp,[esp+pushad_ebx] xor ebx,ebx .repeat xor edx,edx mov eax,[esi].BN.dwArray[ebx*4-4+4] xor ecx,ecx inc ebx mul edi add eax,ecx adc edx,0 add [ebp].BN.dwArray[0*4-4+4],eax adc edx,0 add ebp,4 mov [ebp].BN.dwArray[1*4-4],edx .until ebx >= [esi].BN.dwSize popad ret _bn_muldw_basecase endp end
#include "ogm/ast/parse.h" #include <iostream> #include <cstring> payload_type_t ogm_ast_tree_get_payload_type( const ogm_ast_t* tree ) { switch (tree->m_subtype) { case ogm_ast_st_imp_assignment: case ogm_ast_st_exp_arithmetic: case ogm_ast_st_exp_accessor: case ogm_ast_st_imp_body: case ogm_ast_st_imp_loop: case ogm_ast_st_imp_control: return ogm_ast_payload_t_spec; case ogm_ast_st_exp_literal_primitive: return ogm_ast_payload_t_literal_primitive; case ogm_ast_st_imp_var: return ogm_ast_payload_t_declaration; case ogm_ast_st_imp_enum: case ogm_ast_st_exp_literal_struct: return ogm_ast_payload_t_declaration_enum; case ogm_ast_st_exp_literal_function: return ogm_ast_payload_t_literal_function; case ogm_ast_st_exp_identifier: return ogm_ast_payload_t_string; case ogm_ast_st_imp_body_list: return ogm_ast_payload_t_string_list; default: return ogm_ast_payload_t_none; } } const char* ogm_ast_tree_get_payload_string( const ogm_ast_t* tree ) { if (ogm_ast_tree_get_payload_type(tree) == ogm_ast_payload_t_string) { return (const char*) tree->m_payload; } else { return nullptr; } } const char* ogm_ast_tree_get_payload_string_list( const ogm_ast_t* tree, size_t i ) { if (ogm_ast_tree_get_payload_type(tree) == ogm_ast_payload_t_string_list) { if (i >= tree->m_sub_count) return nullptr; return ((const char**) tree->m_payload)[i]; } else { return nullptr; } } bool ogm_ast_tree_get_spec( const ogm_ast_t* tree, ogm_ast_spec_t* out_spec ) { if (ogm_ast_tree_get_payload_type(tree) == ogm_ast_payload_t_spec) { *out_spec = tree->m_spec; return true; } else { *out_spec = ogm_ast_spec_none; return false; } } bool ogm_ast_tree_get_payload_literal_primitive( const ogm_ast_t* tree, ogm_ast_literal_primitive_t** out_payload ) { if (tree->m_subtype == ogm_ast_st_exp_literal_primitive) { *out_payload = (ogm_ast_literal_primitive_t*)tree->m_payload; return true; } return false; } bool ogm_ast_tree_get_payload_declaration( const ogm_ast_t* tree, ogm_ast_declaration_t** out_payload ) { if (tree->m_subtype == ogm_ast_st_imp_var || tree->m_subtype == ogm_ast_st_imp_enum || tree->m_subtype == ogm_ast_st_exp_literal_struct) { *out_payload = (ogm_ast_declaration_t*)tree->m_payload; return true; } return false; } bool ogm_ast_tree_get_payload_function_literal( const ogm_ast_t* tree, ogm_ast_literal_function_t** out_payload ) { if (tree->m_subtype == ogm_ast_st_exp_literal_function) { *out_payload = (ogm_ast_literal_function_t*)tree->m_payload; return true; } return false; } void print_indent( int32_t indent ) { for (int32_t i = 0; i < indent; i++) { std::cout << " "; } } void ogm_ast_tree_print_helper( const ogm_ast_t* tree, int32_t indent ) { print_indent(indent); if (tree->m_type == ogm_ast_t_exp) { std::cout << "& "; } else { std::cout << "> "; } std::cout << ogm_ast_subtype_string[tree->m_subtype]; ogm_ast_spec_t spec; if (ogm_ast_tree_get_spec(tree, &spec)) { std::cout << " " << ogm_ast_spec_string[tree->m_spec]; } // extra payload: switch(tree->m_subtype) { case ogm_ast_st_exp_literal_primitive: { ogm_ast_literal_primitive_t* payload; ogm_ast_tree_get_payload_literal_primitive(tree, &payload); std::cout << ": " << payload->m_value; } break; case ogm_ast_st_exp_identifier: std::cout << ": " << (char*) tree->m_payload; break; default: break; } std::cout << " [" << tree->m_start.m_line + 1<< ":" << tree->m_start.m_column + 1 << " - " << tree->m_end.m_line + 1<< ":" << tree->m_end.m_column + 1 << "]"; std::cout << std::endl; // subtrees for (int32_t i = 0; i < tree->m_sub_count; i++) { ogm_ast_tree_print_helper( tree->m_sub + i, indent + 1 ); } } void ogm_ast_tree_print( const ogm_ast_t* tree ) { ogm_ast_tree_print_helper(tree, 0); }
#include <unistd.h> #include <cstddef> #include <set> #include <string> #include <vector> #include<iostream> #include "system.h" using std::set; using std::size_t; using std::string; using std::vector; Processor& System::Cpu() { cpu_ = Processor(); return cpu_; } vector<Process>& System::Processes() { for(auto pid:LinuxParser::Pids()){ Process p(pid); processes_.push_back(p); } std::sort(processes_.begin(), processes_.end()); return processes_; } std::string System::Kernel() { return LinuxParser::Kernel(); } float System::MemoryUtilization() { return LinuxParser::MemoryUtilization(); } std::string System::OperatingSystem() { return LinuxParser::OperatingSystem(); } int System::RunningProcesses() { return LinuxParser::RunningProcesses(); } int System::TotalProcesses() { return LinuxParser::TotalProcesses(); } long int System::UpTime() { return LinuxParser::UpTime(); }
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r8 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x1109f, %rbx nop nop nop nop cmp %r13, %r13 mov $0x6162636465666768, %r15 movq %r15, %xmm3 movups %xmm3, (%rbx) nop inc %rbp lea addresses_WT_ht+0xcc6f, %rsi lea addresses_WC_ht+0x2169, %rdi clflush (%rdi) nop nop nop nop inc %r8 mov $78, %rcx rep movsw nop nop nop nop nop xor %rbp, %rbp lea addresses_normal_ht+0x63cf, %r13 nop nop nop nop nop inc %r15 mov (%r13), %cx nop nop nop nop xor %r8, %r8 lea addresses_D_ht+0x18ecf, %rsi lea addresses_WC_ht+0xa19f, %rdi clflush (%rdi) sub %r15, %r15 mov $90, %rcx rep movsq nop nop nop nop add %rdi, %rdi lea addresses_UC_ht+0xa44f, %r8 nop xor %rbx, %rbx and $0xffffffffffffffc0, %r8 movaps (%r8), %xmm4 vpextrq $1, %xmm4, %rbp nop nop xor $51308, %rcx lea addresses_D_ht+0x1cecf, %rcx xor $30516, %rdi mov $0x6162636465666768, %r13 movq %r13, %xmm3 movups %xmm3, (%rcx) nop nop nop nop nop xor $18433, %rbx lea addresses_normal_ht+0xfbcf, %rbp nop nop nop nop nop sub $53486, %r15 movl $0x61626364, (%rbp) nop nop nop sub %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %r9 push %rax push %rcx push %rdx // Store lea addresses_A+0x2e4f, %r10 nop nop nop nop nop cmp %rdx, %rdx mov $0x5152535455565758, %r13 movq %r13, (%r10) nop nop nop nop nop inc %r10 // Faulty Load lea addresses_WT+0x4e4f, %rcx add $63875, %r9 movb (%rcx), %r14b lea oracles, %rdx and $0xff, %r14 shlq $12, %r14 mov (%rdx,%r14,1), %r14 pop %rdx pop %rcx pop %rax pop %r9 pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_WT', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 8, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_WT', 'same': True, 'size': 1, 'congruent': 0, 'NT': True, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': True, 'size': 2, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'39': 21829} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
; ******************************************************************************************** ; ******************************************************************************************** ; ; Name : findchange.asm ; Purpose : .. ; Created : 15th Nov 1991 ; Updated : 4th Jan 2021 ; Authors : Fred Bowen ; ; ******************************************************************************************** ; ******************************************************************************************** ; FIND "string" [,line_range] ; CHANGE "oldstring" TO "newstring" [,line_range] ; ; where <"> delimiter can be any character, but only ; double-quotes will prevent tokenization of strings. ; ; N.B.: I am assuming that lines cannot be greater than 255 chars, as is ; the case where the line was entered "normally", that is, using LINGET. find rmb7 op ; FIND flag !text $2c change smb7 op ; CHANGE flag rmb6 op ; reset change-all mode jsr errind ; report error if not in direct mode jsr chrgot ; get delimeter ldx #0 ; evaluate string args jsr delimit_string ; string1 lda fstr1+2 +lbeq fcerr ; error if string1 null bbr7 op,l86_1 ; branch if no string2 jsr chrget ; pick up required 'to' token cmp #to_token +lbne snerr ; error if missing jsr chrget +lbeq snerr ; error if eol ldx #3 jsr delimit_string ; string2 l86_1 jsr chrget ; line number range given? beq l86_2 ; no, eol jsr chkcom ; yes, pick up required comma l86_2 jsr range ; set up line number range (lowtr,linnum) jsr tto ; save txtptr for restoration when done rmb7 helper ; clear 'help' flag for 'p1line' lda helper pha rmb4 helper ; temporarily disable token highlighting smb5 helper ; set 'find' flag for 'p1line' bra find_loop_1 ; begin find_loop ldy #0 ; move to next line (copy link bytes to lowtr) jsr indlow tax iny jsr indlow stx lowtr sta lowtr+1 find_loop_1 ldy #1 jsr indlow ; check link bne l87_1 ; not null- continue dey jsr indlow +lbeq find_exit ; null- exit l87_1 ldy #2 jsr indlow ; check line number tax iny jsr indlow cmp linnum+1 bne l87_2 cpx linnum beq l87_3 ; line is <= last line requested, continue l87_2 +lbcs find_exit ; line is > last line requested, exit l87_3 ldx #3 ; set initial position - 1 (past link & line#) stx fndpnt find_loop_2 jsr _stop ; check stop key +lbeq find_break ; exit if down ldx fndpnt ; duh, where are we? clc txa ; program: adc lowtr ; txtptr = line start + position in line sta txtptr lda #0 adc lowtr+1 sta txtptr+1 ; search string: ldz #0 ; at the beginning l88_1 jsr chargt ; get next character from text beq find_loop ; eol (no match this line) inx ; bump pointer to next character cmp (fstr1),z ; character match? ind okay- buffer bne l88_1 ; no stx fndpnt ; yes- save next position l88_2 inz ; bump position in search string cpz fstr1+2 ; string match? bcs print_line ; yes jsr chargt beq find_loop ; no- eol cmp (fstr1),z ; ind okay- buffer bne find_loop_2 ; no- rewind to beginning of search string beq l88_2 ; maybe- still more chars to compare ; Print the line of text at LOWTR, highlighting the section of code ; beginning at LOWTR+FNDPNT and running for FIND_COUNT characters. print_line jsr crdo ; get a new display line lda fstr1+2 ; length of string to highlight sta find_count ldy #2 jsr indlow ; get ms byte of line number tax iny jsr indlow ; get ls byte jsr p1line ; print #, space, and the line of code bbr7 op,find_loop_2 ; Find op? branch if so and continue search ; Change operation ; Query the user and replace string1 with string2 if he wants to. ; Options are 'Y' (yes), '*' (do all), 'CR' (quit), anything else means no. change_line bbs6 op,l89_1 ; branch if change-all mode set jsr _primm ; prompt & get response !text cr," CHANGE? ",0 jsr response_get cmp #'Y' beq l89_1 ; yes, change it cmp #cr +lbeq find_exit ; cr only, abort entire operation cmp #'*' bne find_loop_2 ; *, change all. else don't change smb6 op ; Replace string1 with string2. Requires moving text up/down beginning at ; LOWTR+FNDPNT+(LEN(string1)-LEN(string2)) through TEXT_TOP and copying ; string1 into text beginning at LOWTR+FNDPNT for LEN(string2) characters. l89_1 lda text_top ; setup upper address of text to move (index2) sta index2 lda text_top+1 ; TEXT_TOP sta index2+1 clc ; setup lower address of text to move (index1) lda fndpnt adc lowtr sta index1 ; LOWTR+FNDPNT lda #0 sta argmo ; count hi adc lowtr+1 sta index1+1 sec ; calc number of chars to insert/delete lda fstr1+2 ; LEN(string1)-LEN(string2) sbc fstr2+2 beq l89_6 ; branch if string1 = string2 (no move) bpl l89_4 ; branch if string1 > string2 (delete) ; else string1 < string2 (insert) neg ; Move memory up to make room for larger string2 sta count ldy #0 ; first check for line too long jsr indlow adc count taz iny jsr indlow ; (link+#chr)-line_sa must be <256 adc #0 tay sec tza sbc lowtr tya sbc lowtr+1 +lbne errlen ; error, line > 255 characters clc ; now check for sufficient memory ldy text_top+1 lda count adc text_top bcc l89_2 iny l89_2 cpy max_mem_0+1 bcc l89_3 ; result is less than top-of-memory: ok +lbne omerr ; msb > top, overflow cmp max_mem_0 ; msb's the same, test lsb's +lbcs omerr ; lsb >= top, overflow l89_3 sta text_top sty text_top+1 ; set new top of text pointer jsr moveup ; make room bra l89_6 ; go copy string2 into area l89_4 sta count ; Move memory down for smaller string2 ldy text_top+1 lda text_top sec sbc count bcs l89_5 dey l89_5 sta text_top sty text_top+1 ; set new top of text pointer jsr movedown ; squish out excess space l89_6 lda fstr2+2 ; Copy string2 into text beq l89_8 ; branch if null, nothing to copy sta find_count ; how many characters to copy ldx #lowtr ldy fndpnt ; index into text ldz #0 ; index into string2 l89_7 lda (fstr2),z ; ind okay- buffer jsr sta_far_ram0 ; do the copy iny inz dec find_count bne l89_7 l89_8 jsr link_program ; relink program clc lda fndpnt ; place find position after new text adc fstr2+2 dec sta fndpnt +lbra find_loop_2 ; and resume searching find_exit jsr crdo ; normal exit pla sta helper ; restore token highlight status rmb5 helper ; remove 'find' flag +lbra direct_mode_exit ; done find_omerr ; out of memory ldx #errom !text $2c find_errlen ; string too long ldx #errls sec !text $89 find_break ; stop key break clc pla sta helper ; restore token highlight status rmb5 helper ; remove 'find' flag +lbcc break_exit ; [910925] +lbra error delimit_string ; command is in buffer, .x = ptr to strptr sta match ; delimiter character lda txtptr ; point to first character in string inc ; (never wraps- string in input buffer) sta fstr1,x ; set pointer to string data lda txtptr+1 sta fstr1+1,x lda #$ff ; set string length sta fstr1+2,x l90_1 inc fstr1+2,x jsr chargt ; build string +lbeq snerr ; error if eol encountered inside string cmp match bne l90_1 ; continue until matching delimiter found rts ;.end puctrl jsr frmstr ; do frmevl,frestr. return with a=len, index=~string tay dey cpy #4 +lbcs fcerr ; len > 4 is illegal value error l91_1 jsr indin1_ram1 ; lda (index),y sta puchrs,y dey bpl l91_1 rts ;.end ; ******************************************************************************************** ; ; Date Changes ; ==== ======= ; ; ********************************************************************************************
; A081270: Diagonal of triangular spiral in A051682. ; 3,16,38,69,109,158,216,283,359,444,538,641,753,874,1004,1143,1291,1448,1614,1789,1973,2166,2368,2579,2799,3028,3266,3513,3769,4034,4308,4591,4883,5184,5494,5813,6141,6478,6824,7179,7543,7916,8298,8689,9089,9498,9916,10343,10779,11224,11678,12141,12613,13094,13584,14083,14591,15108,15634,16169,16713,17266,17828,18399,18979,19568,20166,20773,21389,22014,22648,23291,23943,24604,25274,25953,26641,27338,28044,28759,29483,30216,30958,31709,32469,33238,34016,34803,35599,36404,37218,38041,38873,39714,40564,41423,42291,43168,44054,44949 mul $0,9 add $0,9 bin $0,2 div $0,9 sub $0,1
; Thanks to Kazuto for developing the original QS code that inspired this one QuickSwap: ; We perform all other checks only if we are pushing L or R in order to have minimal ; perf impact, since this runs every frame LDA.b $F6 : AND #$30 : BEQ .done XBA ; stash away the value for after the checks. LDA.l QuickSwapFlag : BEQ .done LDA.w $0202 : BEQ .done ; Skip everything if we don't have any items ;TODO add romtype and race rom checks here LDA.l AllowConvenienceSpeedSettings : AND.b #$01 : BEQ .done PHX XBA ; restore the stashed value CMP.b #$30 : BNE + ; If prossing both L and R this frame, then go directly to the special swap code LDX.w $0202 : BRA .special_swap + BIT #$10 : BEQ + ; Only pressed R JSR.w RCode LDA.b $F2 : BIT #$20 : BNE .special_swap ; Still holding L from a previous frame BRA .store + ; Only pressed L JSR.w LCode LDA.b $F2 : BIT #$10 : BNE .special_swap ; Still holding R from a previous frame BRA .store .special_swap CPX.b #$02 : BEQ + ; boomerang CPX.b #$01 : BEQ + ; bow CPX.b #$05 : BEQ + ; powder CPX.b #$0D : BEQ + ; flute BRA .store + STX $0202 : JSL ProcessMenuButtons_y_pressed .store LDA.b #$20 : STA.w $012F STX $0202 JSL HUD_RefreshIconLong PLX .done LDA.b $F6 : AND.b #$40 ;what we wrote over RTL RCode: LDA.w $0202 : TAX - CPX.b #$0F : BNE + ; incrementing into bottle LDX.b #$00 : BRA ++ + CPX.b #$10 : BNE + ; incrementing bottle LDA.l $7EF34F : TAX -- : ++ CPX.b #$04 : BEQ .noMoreBottles INX LDA.l $7EF35B,X : BEQ -- TXA : STA.l $7EF34F LDX #$10 RTS .noMoreBottles LDX #$11 BRA .nextItem + CPX.b #$14 : BNE + : LDX.b #$00 ;will wrap around to 1 + INX .nextItem JSL.l IsItemAvailable : BEQ - RTS LCode: LDA.w $0202 : TAX - CPX.b #$11 : BNE + ; decrementing into bottle LDX.b #$05 : BRA ++ + CPX.b #$10 : BNE + ; decrementing bottle LDA.l $7EF34F : TAX -- : ++ CPX.b #$01 : BEQ .noMoreBottles DEX LDA.l $7EF35B,X : BEQ -- TXA : STA.l $7EF34F LDX.b #$10 RTS .noMoreBottles LDX.b #$0F : BRA .nextItem + CPX.b #$01 : BNE + : LDX.b #$15 ; will wrap around to $14 + DEX .nextItem JSL.l IsItemAvailable : BEQ - RTS
; A101601: G.f.: c(3x)^3, c(x) the g.f. of A000108. ; Submitted by Christian Krause ; 1,9,81,756,7290,72171,729729,7505784,78298974,826489170,8811646074,94753804536,1026499549140,11192793160815,122744496427425,1352917116177840,14979996753469110,166542316847391870 add $0,1 mov $1,$0 seq $0,151383 ; Number of walks within N^2 (the first quadrant of Z^2) starting at (0,0), ending on the vertical axis and consisting of 2 n steps taken from {(-1, -1), (-1, 0), (-1, 1), (1, 1)} mul $0,$1 add $1,2 div $0,$1
#include "dll.h" #include <cstring> ice::Library* LIBRARY = NULL; char ERROR_MESSAGE[512]; bool dll_initialize(void) { if (dll_is_initialized()) { return true; } try { memset(ERROR_MESSAGE, '\0', sizeof(ERROR_MESSAGE)/sizeof(ERROR_MESSAGE[0])); #if (defined(_WIN32) || defined(__WIN32__)) LIBRARY = new ice::Library("icsneo40.dll"); #else LIBRARY = new ice::Library("libicsneoapi.so"); #endif } catch (ice::Exception& ex) { strcpy(ERROR_MESSAGE, ex.whatString().c_str()); return false; } return true; } bool dll_is_initialized(void) { return LIBRARY != NULL; } void dll_uninitialize(void) { if (!dll_is_initialized()) { return; } delete LIBRARY; } char* dll_get_error(char* error_msg) { strcpy(error_msg, ERROR_MESSAGE); return error_msg; } ice::Library* dll_get_library(void) { dll_initialize(); return LIBRARY; }
; A013830: a(n) = 4^(5*n + 1). ; 4,4096,4194304,4294967296,4398046511104,4503599627370496,4611686018427387904,4722366482869645213696,4835703278458516698824704,4951760157141521099596496896,5070602400912917605986812821504,5192296858534827628530496329220096,5316911983139663491615228241121378304,5444517870735015415413993718908291383296,5575186299632655785383929568162090376495104,5708990770823839524233143877797980545530986496,5846006549323611672814739330865132078623730171904,5986310706507378352962293074805895248510699696029696 mul $0,5 add $0,1 mov $1,4 pow $1,$0 mov $0,$1
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2018 * * * * 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 <modules/globebrowsing/src/tileprovider.h> #include <modules/globebrowsing/globebrowsingmodule.h> #include <modules/globebrowsing/src/asynctiledataprovider.h> #include <modules/globebrowsing/src/geodeticpatch.h> #include <modules/globebrowsing/src/layermanager.h> #include <modules/globebrowsing/src/memoryawaretilecache.h> #include <modules/globebrowsing/src/rawtiledatareader.h> #include <openspace/engine/globals.h> #include <openspace/engine/moduleengine.h> #include <openspace/util/factorymanager.h> #include <openspace/util/timemanager.h> #include <ghoul/filesystem/file.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/font/fontmanager.h> #include <ghoul/font/fontrenderer.h> #include <ghoul/io/texture/texturereader.h> #include <ghoul/logging/logmanager.h> #include <fstream> #include "cpl_minixml.h" namespace ghoul { template <> openspace::globebrowsing::tileprovider::TemporalTileProvider::TimeFormatType from_string(const std::string& string) { using namespace openspace::globebrowsing::tileprovider; if (string == "YYYY-MM-DD") { return TemporalTileProvider::TimeFormatType::YYYY_MM_DD; } else if (string == "YYYY-MM-DDThh:mm:ssZ") { return TemporalTileProvider::TimeFormatType::YYYY_MM_DDThhColonmmColonssZ; } else if (string == "YYYY-MM-DDThh_mm_ssZ") { return TemporalTileProvider::TimeFormatType::YYYY_MM_DDThh_mm_ssZ; } else if (string == "YYYYMMDD_hhmmss") { return TemporalTileProvider::TimeFormatType::YYYYMMDD_hhmmss; } else if (string == "YYYYMMDD_hhmm") { return TemporalTileProvider::TimeFormatType::YYYYMMDD_hhmm; } else { throw ghoul::RuntimeError("Unknown timeformat " + string); } } } // namespace ghoul namespace openspace::globebrowsing::tileprovider { namespace { std::unique_ptr<ghoul::opengl::Texture> DefaultTileTexture; Tile DefaultTile = Tile{ nullptr, std::nullopt, Tile::Status::Unavailable }; constexpr const char* KeyFilePath = "FilePath"; namespace defaultprovider { constexpr const char* KeyPerformPreProcessing = "PerformPreProcessing"; constexpr const char* KeyTilePixelSize = "TilePixelSize"; constexpr const char* KeyPadTiles = "PadTiles"; constexpr openspace::properties::Property::PropertyInfo FilePathInfo = { "FilePath", "File Path", "The path of the GDAL file or the image file that is to be used in this tile " "provider." }; constexpr openspace::properties::Property::PropertyInfo TilePixelSizeInfo = { "TilePixelSize", "Tile Pixel Size", "This value is the preferred size (in pixels) for each tile. Choosing the right " "value is a tradeoff between more efficiency (larger images) and better quality " "(smaller images). The tile pixel size has to be smaller than the size of the " "complete image if a single image is used." }; } // namespace defaultprovider namespace singleimageprovider { constexpr openspace::properties::Property::PropertyInfo FilePathInfo = { "FilePath", "File Path", "The file path that is used for this image provider. The file must point to an " "image that is then loaded and used for all tiles." }; } // namespace singleimageprovider namespace sizereferenceprovider { constexpr const char* KeyRadii = "Radii"; } // namespace sizereferenceprovider namespace byindexprovider { constexpr const char* KeyDefaultProvider = "DefaultProvider"; constexpr const char* KeyProviders = "IndexTileProviders"; constexpr const char* KeyTileIndex = "TileIndex"; constexpr const char* KeyTileProvider = "TileProvider"; } // namespace byindexprovider namespace bylevelprovider { constexpr const char* KeyProviders = "LevelTileProviders"; constexpr const char* KeyMaxLevel = "MaxLevel"; constexpr const char* KeyTileProvider = "TileProvider"; constexpr const char* KeyLayerGroupID = "LayerGroupID"; } // namespace bylevelprovider namespace temporal { constexpr const char* KeyBasePath = "BasePath"; constexpr const char* UrlTimePlaceholder = "${OpenSpaceTimeId}"; constexpr const char* TimeStart = "OpenSpaceTimeStart"; constexpr const char* TimeEnd = "OpenSpaceTimeEnd"; constexpr const char* TimeResolution = "OpenSpaceTimeResolution"; constexpr const char* TimeFormat = "OpenSpaceTimeIdFormat"; constexpr openspace::properties::Property::PropertyInfo FilePathInfo = { "FilePath", "File Path", "This is the path to the XML configuration file that describes the temporal tile " "information." }; } // namespace temporal // // DefaultTileProvider // void initAsyncTileDataReader(DefaultTileProvider& t, TileTextureInitData initData) { t.asyncTextureDataProvider = std::make_unique<AsyncTileDataProvider>( t.name, std::make_unique<RawTileDataReader>( t.filePath, initData, RawTileDataReader::PerformPreprocessing(t.performPreProcessing) ) ); } void initTexturesFromLoadedData(DefaultTileProvider& t) { if (t.asyncTextureDataProvider) { std::optional<RawTile> tile = t.asyncTextureDataProvider->popFinishedRawTile(); if (tile) { const cache::ProviderTileKey key = { tile->tileIndex, t.uniqueIdentifier }; ghoul_assert(!t.tileCache->exist(key), "Tile must not be existing in cache"); t.tileCache->createTileAndPut(key, std::move(tile.value())); } } } // // TextTileProvider // void initialize(TextTileProvider& t) { t.font = global::fontManager.font("Mono", static_cast<float>(t.fontSize)); t.fontRenderer = ghoul::fontrendering::FontRenderer::createDefault(); t.fontRenderer->setFramebufferSize(glm::vec2(t.initData.dimensions)); glGenFramebuffers(1, &t.fbo); } void deinitialize(TextTileProvider& t) { glDeleteFramebuffers(1, &t.fbo); } Tile tile(TextTileProvider& t, const TileIndex& tileIndex) { cache::ProviderTileKey key = { tileIndex, t.uniqueIdentifier }; Tile tile = t.tileCache->get(key); if (!tile.texture) { ghoul::opengl::Texture* texture = t.tileCache->texture(t.initData); // Keep track of defaultFBO and viewport to be able to reset state when done GLint defaultFBO; GLint viewport[4]; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); glGetIntegerv(GL_VIEWPORT, viewport); // Render to texture glBindFramebuffer(GL_FRAMEBUFFER, t.fbo); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, *texture, 0 ); GLsizei w = static_cast<GLsizei>(texture->width()); GLsizei h = static_cast<GLsizei>(texture->height()); glViewport(0, 0, w, h); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT); t.fontRenderer->render(*t.font, t.textPosition, t.text, t.textColor); glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); tile = Tile{ texture, std::nullopt, Tile::Status::OK }; t.tileCache->put(key, t.initData.hashKey, tile); } return tile; } void reset(TextTileProvider& t) { t.tileCache->clear(); } // // TileProviderByLevel // TileProvider* levelProvider(TileProviderByLevel& t, int level) { if (!t.levelTileProviders.empty()) { int clampedLevel = glm::clamp( level, 0, static_cast<int>(t.providerIndices.size() - 1) ); int idx = t.providerIndices[clampedLevel]; return t.levelTileProviders[idx].get(); } else { return nullptr; } } // // TemporalTileProvider // std::string timeStringify(TemporalTileProvider::TimeFormatType type, const Time& t) { switch (type) { case TemporalTileProvider::TimeFormatType::YYYY_MM_DD: return t.ISO8601().substr(0, 10); case TemporalTileProvider::TimeFormatType::YYYYMMDD_hhmmss: { std::string ts = t.ISO8601().substr(0, 19); // YYYY_MM_DDThh_mm_ss -> YYYYMMDD_hhmmss ts.erase(std::remove(ts.begin(), ts.end(), '-'), ts.end()); ts.erase(std::remove(ts.begin(), ts.end(), ':'), ts.end()); replace(ts.begin(), ts.end(), 'T', '_'); return ts; } case TemporalTileProvider::TimeFormatType::YYYYMMDD_hhmm: { std::string ts = t.ISO8601().substr(0, 16); // YYYY_MM_DDThh_mm -> YYYYMMDD_hhmm ts.erase(std::remove(ts.begin(), ts.end(), '-'), ts.end()); ts.erase(std::remove(ts.begin(), ts.end(), ':'), ts.end()); replace(ts.begin(), ts.end(), 'T', '_'); return ts; } case TemporalTileProvider::TimeFormatType::YYYY_MM_DDThhColonmmColonssZ: return t.ISO8601().substr(0, 19) + "Z"; case TemporalTileProvider::TimeFormatType::YYYY_MM_DDThh_mm_ssZ: { std::string timeString = t.ISO8601().substr(0, 19) + "Z"; replace(timeString.begin(), timeString.end(), ':', '_'); return timeString; } default: throw ghoul::MissingCaseException(); } } std::unique_ptr<TileProvider> initTileProvider(TemporalTileProvider& t, TemporalTileProvider::TimeKey timekey) { static const std::vector<std::string> IgnoredTokens = { // From: http://www.gdal.org/frmt_wms.html "${x}", "${y}", "${z}", "${version}", "${format}", "${layer}" }; std::string xmlTemplate(t.gdalXmlTemplate); const size_t pos = xmlTemplate.find(temporal::UrlTimePlaceholder); const size_t numChars = strlen(temporal::UrlTimePlaceholder); // @FRAGILE: This will only find the first instance. Dangerous if that instance is // commented out ---abock const std::string timeSpecifiedXml = xmlTemplate.replace(pos, numChars, timekey); std::string gdalDatasetXml = timeSpecifiedXml; FileSys.expandPathTokens(gdalDatasetXml, IgnoredTokens); t.initDict.setValue<std::string>(KeyFilePath, gdalDatasetXml); return std::make_unique<DefaultTileProvider>(t.initDict); } TileProvider* getTileProvider(TemporalTileProvider& t, const TemporalTileProvider::TimeKey& timekey) { const auto it = t.tileProviderMap.find(timekey); if (it != t.tileProviderMap.end()) { return it->second.get(); } else { std::unique_ptr<TileProvider> tileProvider = initTileProvider(t, timekey); initialize(*tileProvider); TileProvider* res = tileProvider.get(); t.tileProviderMap[timekey] = std::move(tileProvider); return res; } } TileProvider* getTileProvider(TemporalTileProvider& t, const Time& time) { Time tCopy(time); if (t.timeQuantizer.quantize(tCopy, true)) { TemporalTileProvider::TimeKey timeKey = timeStringify(t.timeFormat, tCopy); try { return getTileProvider(t, timeKey); } catch (const ghoul::RuntimeError& e) { LERRORC("TemporalTileProvider", e.message); return nullptr; } } return nullptr; } void ensureUpdated(TemporalTileProvider& t) { if (!t.currentTileProvider) { update(t); } } std::string xmlValue(TemporalTileProvider& t, CPLXMLNode* node, const std::string& key, const std::string& defaultVal) { CPLXMLNode* n = CPLSearchXMLNode(node, key.c_str()); if (!n) { throw ghoul::RuntimeError( fmt::format("Unable to parse file {}. {} missing", t.filePath.value(), key) ); } const bool hasValue = n && n->psChild && n->psChild->pszValue; return hasValue ? n->psChild->pszValue : defaultVal; } std::string consumeTemporalMetaData(TemporalTileProvider& t, const std::string& xml) { CPLXMLNode* node = CPLParseXMLString(xml.c_str()); std::string timeStart = xmlValue(t, node, temporal::TimeStart, "2000 Jan 1"); std::string timeResolution = xmlValue(t, node, temporal::TimeResolution, "2d"); std::string timeEnd = xmlValue(t, node, temporal::TimeEnd, "Today"); std::string timeIdFormat = xmlValue( t, node, temporal::TimeFormat, "YYYY-MM-DDThh:mm:ssZ" ); Time start; start.setTime(std::move(timeStart)); Time end(Time::now()); if (timeEnd == "Yesterday") { end.advanceTime(-60.0 * 60.0 * 24.0); // Go back one day } else if (timeEnd != "Today") { end.setTime(std::move(timeEnd)); } try { t.timeQuantizer = TimeQuantizer(start, end, timeResolution); } catch (const ghoul::RuntimeError& e) { throw ghoul::RuntimeError(fmt::format( "Could not create time quantizer for Temporal GDAL dataset '{}'. {}", t.filePath.value(), e.message )); } t.timeFormat = ghoul::from_string<TemporalTileProvider::TimeFormatType>(timeIdFormat); CPLXMLNode* gdalNode = CPLSearchXMLNode(node, "GDAL_WMS"); if (gdalNode) { std::string gdalDescription = CPLSerializeXMLTree(gdalNode); return gdalDescription; } else { gdalNode = CPLSearchXMLNode(node, "FilePath"); std::string gdalDescription = std::string(gdalNode->psChild->pszValue); return gdalDescription; } } bool readFilePath(TemporalTileProvider& t) { std::ifstream in(t.filePath.value().c_str()); std::string xml; if (in.is_open()) { // read file xml = std::string( std::istreambuf_iterator<char>(in), (std::istreambuf_iterator<char>()) ); } else { // Assume that it is already an xml xml = t.filePath; } // File path was not a path to a file but a GDAL config or empty ghoul::filesystem::File f(t.filePath); if (FileSys.fileExists(f)) { t.initDict.setValue<std::string>(temporal::KeyBasePath, f.directoryName()); } t.gdalXmlTemplate = consumeTemporalMetaData(t, xml); return true; } } // namespace unsigned int TileProvider::NumTileProviders = 0; // // General functions // void initializeDefaultTile() { ghoul_assert(!DefaultTile.texture, "Default tile should not have been created"); using namespace ghoul::opengl; // Create pixel data TileTextureInitData initData( 8, 8, GL_UNSIGNED_BYTE, Texture::Format::RGBA, TileTextureInitData::PadTiles::No, TileTextureInitData::ShouldAllocateDataOnCPU::Yes ); char* pixels = new char[initData.totalNumBytes]; memset(pixels, 0, initData.totalNumBytes * sizeof(char)); // Create ghoul texture DefaultTileTexture = std::make_unique<Texture>(initData.dimensions); DefaultTileTexture->setDataOwnership(Texture::TakeOwnership::Yes); DefaultTileTexture->setPixelData(pixels); DefaultTileTexture->uploadTexture(); DefaultTileTexture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); // Create tile DefaultTile = Tile{ DefaultTileTexture.get(), std::nullopt, Tile::Status::OK }; } void deinitializeDefaultTile() { DefaultTileTexture = nullptr; } std::unique_ptr<TileProvider> createFromDictionary(layergroupid::TypeID layerTypeID, const ghoul::Dictionary& dictionary) { const char* type = layergroupid::LAYER_TYPE_NAMES[static_cast<int>(layerTypeID)]; auto factory = FactoryManager::ref().factory<TileProvider>(); std::unique_ptr<TileProvider> result = factory->create(type, dictionary); return result; } TileProvider::TileProvider() : properties::PropertyOwner({ "tileProvider" }) {} DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) : filePath(defaultprovider::FilePathInfo, "") , tilePixelSize(defaultprovider::TilePixelSizeInfo, 32, 32, 2048) { type = Type::DefaultTileProvider; tileCache = global::moduleEngine.module<GlobeBrowsingModule>()->tileCache(); name = "Name unspecified"; if (dictionary.hasKeyAndValue<std::string>("Name")) { name = dictionary.value<std::string>("Name"); } std::string _loggerCat = "DefaultTileProvider (" + name + ")"; // 1. Get required Keys filePath = dictionary.value<std::string>(KeyFilePath); layerGroupID = dictionary.value<layergroupid::GroupID>("LayerGroupID"); // 2. Initialize default values for any optional Keys // getValue does not work for integers int pixelSize = 0; if (dictionary.hasKeyAndValue<double>(defaultprovider::KeyTilePixelSize)) { pixelSize = static_cast<int>( dictionary.value<double>(defaultprovider::KeyTilePixelSize) ); LDEBUG(fmt::format("Default pixel size overridden: {}", pixelSize)); } if (dictionary.hasKeyAndValue<bool>(defaultprovider::KeyPadTiles)) { padTiles = dictionary.value<bool>(defaultprovider::KeyPadTiles); } TileTextureInitData initData( tileTextureInitData(layerGroupID, padTiles, pixelSize) ); tilePixelSize = initData.dimensions.x; // Only preprocess height layers by default switch (layerGroupID) { case layergroupid::GroupID::HeightLayers: performPreProcessing = true; break; default: performPreProcessing = false; break; } if (dictionary.hasKeyAndValue<bool>(defaultprovider::KeyPerformPreProcessing)) { performPreProcessing = dictionary.value<bool>( defaultprovider::KeyPerformPreProcessing ); LDEBUG(fmt::format( "Default PerformPreProcessing overridden: {}", performPreProcessing )); } initAsyncTileDataReader(*this, initData); addProperty(filePath); addProperty(tilePixelSize); } SingleImageProvider::SingleImageProvider(const ghoul::Dictionary& dictionary) : filePath(singleimageprovider::FilePathInfo) { type = Type::SingleImageTileProvider; filePath = dictionary.value<std::string>(KeyFilePath); addProperty(filePath); reset(*this); } TextTileProvider::TextTileProvider(const TileTextureInitData& initData, size_t fontSize) : initData(initData) , fontSize(fontSize) { tileCache = global::moduleEngine.module<GlobeBrowsingModule>()->tileCache(); } SizeReferenceTileProvider::SizeReferenceTileProvider(const ghoul::Dictionary& dictionary) : TextTileProvider(tileTextureInitData(layergroupid::GroupID::ColorLayers, false)) { type = Type::SizeReferenceTileProvider; font = global::fontManager.font("Mono", static_cast<float>(fontSize)); if (dictionary.hasKeyAndValue<glm::dvec3>(sizereferenceprovider::KeyRadii)) { ellipsoid = dictionary.value<glm::dvec3>(sizereferenceprovider::KeyRadii); } } TileIndexTileProvider::TileIndexTileProvider(const ghoul::Dictionary&) : TextTileProvider(tileTextureInitData(layergroupid::GroupID::ColorLayers, false)) { type = Type::TileIndexTileProvider; } TileProviderByIndex::TileProviderByIndex(const ghoul::Dictionary& dictionary) { type = Type::ByIndexTileProvider; const ghoul::Dictionary& defaultProviderDict = dictionary.value<ghoul::Dictionary>( byindexprovider::KeyDefaultProvider ); layergroupid::TypeID typeID; if (defaultProviderDict.hasKeyAndValue<std::string>("Type")) { const std::string& t = defaultProviderDict.value<std::string>("Type"); typeID = ghoul::from_string<layergroupid::TypeID>(t); if (typeID == layergroupid::TypeID::Unknown) { throw ghoul::RuntimeError("Unknown layer type: " + t); } } else { typeID = layergroupid::TypeID::DefaultTileLayer; } defaultTileProvider = createFromDictionary(typeID, defaultProviderDict); const ghoul::Dictionary& indexProvidersDict = dictionary.value<ghoul::Dictionary>( byindexprovider::KeyProviders ); for (size_t i = 1; i <= indexProvidersDict.size(); i++) { ghoul::Dictionary indexProviderDict = indexProvidersDict.value<ghoul::Dictionary>( std::to_string(i) ); ghoul::Dictionary tileIndexDict = indexProviderDict.value<ghoul::Dictionary>( byindexprovider::KeyTileIndex ); ghoul::Dictionary providerDict = indexProviderDict.value<ghoul::Dictionary>( byindexprovider::KeyTileProvider ); constexpr const char* KeyLevel = "Level"; constexpr const char* KeyX = "X"; constexpr const char* KeyY = "Y"; int level = static_cast<int>(tileIndexDict.value<double>(KeyLevel)); int x = static_cast<int>(tileIndexDict.value<double>(KeyX)); int y = static_cast<int>(tileIndexDict.value<double>(KeyY)); const TileIndex tileIndex(x, y, level); layergroupid::TypeID providerTypeID = layergroupid::TypeID::DefaultTileLayer; if (defaultProviderDict.hasKeyAndValue<std::string>("Type")) { const std::string& t = defaultProviderDict.value<std::string>("Type"); providerTypeID = ghoul::from_string<layergroupid::TypeID>(t); if (providerTypeID == layergroupid::TypeID::Unknown) { throw ghoul::RuntimeError("Unknown layer type: " + t); } } std::unique_ptr<TileProvider> stp = createFromDictionary( providerTypeID, providerDict ); TileIndex::TileHashKey key = tileIndex.hashKey(); tileProviderMap.insert(std::make_pair(key, std::move(stp))); } } TileProviderByLevel::TileProviderByLevel(const ghoul::Dictionary& dictionary) { type = Type::ByLevelTileProvider; layergroupid::GroupID layerGroupID = dictionary.value<layergroupid::GroupID>( bylevelprovider::KeyLayerGroupID ); if (dictionary.hasKeyAndValue<ghoul::Dictionary>(bylevelprovider::KeyProviders)) { ghoul::Dictionary providers = dictionary.value<ghoul::Dictionary>( bylevelprovider::KeyProviders ); for (size_t i = 1; i <= providers.size(); i++) { ghoul::Dictionary levelProviderDict = providers.value<ghoul::Dictionary>( std::to_string(i) ); double floatMaxLevel = levelProviderDict.value<double>( bylevelprovider::KeyMaxLevel ); int maxLevel = static_cast<int>(std::round(floatMaxLevel)); ghoul::Dictionary providerDict = levelProviderDict.value<ghoul::Dictionary>( bylevelprovider::KeyTileProvider ); providerDict.setValue(bylevelprovider::KeyLayerGroupID, layerGroupID); layergroupid::TypeID typeID; if (providerDict.hasKeyAndValue<std::string>("Type")) { const std::string& typeString = providerDict.value<std::string>("Type"); typeID = ghoul::from_string<layergroupid::TypeID>(typeString); if (typeID == layergroupid::TypeID::Unknown) { throw ghoul::RuntimeError("Unknown layer type: " + typeString); } } else { typeID = layergroupid::TypeID::DefaultTileLayer; } std::unique_ptr<TileProvider> tp = std::unique_ptr<TileProvider>( createFromDictionary(typeID, providerDict) ); std::string provId = providerDict.value<std::string>("Identifier"); tp->setIdentifier(provId); std::string providerName = providerDict.value<std::string>("Name"); tp->setGuiName(providerName); addPropertySubOwner(tp.get()); levelTileProviders.push_back(std::move(tp)); // Ensure we can represent the max level if (static_cast<int>(providerIndices.size()) < maxLevel) { providerIndices.resize(maxLevel + 1, -1); } // map this level to the tile provider index providerIndices[maxLevel] = static_cast<int>(levelTileProviders.size()) - 1; } } // Fill in the gaps (value -1 ) in provider indices, from back to end for (int i = static_cast<int>(providerIndices.size()) - 2; i >= 0; --i) { if (providerIndices[i] == -1) { providerIndices[i] = providerIndices[i + 1]; } } } TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) : initDict(dictionary) , filePath(temporal::FilePathInfo) { type = Type::TemporalTileProvider; filePath = dictionary.value<std::string>(KeyFilePath); addProperty(filePath); successfulInitialization = readFilePath(*this); if (!successfulInitialization) { LERRORC("TemporalTileProvider", "Unable to read file " + filePath.value()); } } bool initialize(TileProvider& tp) { ghoul_assert(!tp.isInitialized, "TileProvider can only be initialized once."); tp.uniqueIdentifier = tp.NumTileProviders++; if (tp.NumTileProviders == std::numeric_limits<unsigned int>::max()) { --tp.NumTileProviders; return false; } tp.isInitialized = true; switch (tp.type) { case Type::DefaultTileProvider: break; case Type::SingleImageTileProvider: break; case Type::SizeReferenceTileProvider: { SizeReferenceTileProvider& t = static_cast<SizeReferenceTileProvider&>(tp); initialize(t); break; } case Type::TileIndexTileProvider: { TileIndexTileProvider& t = static_cast<TileIndexTileProvider&>(tp); initialize(t); break; } case Type::ByIndexTileProvider: break; case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); bool success = true; for (const std::unique_ptr<TileProvider>& prov : t.levelTileProviders) { success &= initialize(*prov); } return success; } case Type::TemporalTileProvider: break; default: throw ghoul::MissingCaseException(); } return true; } bool deinitialize(TileProvider& tp) { switch (tp.type) { case Type::DefaultTileProvider: break; case Type::SingleImageTileProvider: break; case Type::SizeReferenceTileProvider: { SizeReferenceTileProvider& t = static_cast<SizeReferenceTileProvider&>(tp); deinitialize(t); break; } case Type::TileIndexTileProvider: { TileIndexTileProvider& t = static_cast<TileIndexTileProvider&>(tp); deinitialize(t); break; } case Type::ByIndexTileProvider: break; case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); bool success = true; for (const std::unique_ptr<TileProvider>& prov : t.levelTileProviders) { success &= deinitialize(*prov); } return success; } case Type::TemporalTileProvider: break; default: throw ghoul::MissingCaseException(); } return true; } Tile tile(TileProvider& tp, const TileIndex& tileIndex) { switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); if (t.asyncTextureDataProvider) { if (tileIndex.level > maxLevel(t)) { return Tile{ nullptr, std::nullopt, Tile::Status::OutOfRange }; } const cache::ProviderTileKey key = { tileIndex, t.uniqueIdentifier }; const Tile tile = t.tileCache->get(key); if (!tile.texture) { t.asyncTextureDataProvider->enqueueTileIO(tileIndex); } return tile; } else { return Tile{ nullptr, std::nullopt, Tile::Status::Unavailable }; } } case Type::SingleImageTileProvider: { SingleImageProvider& t = static_cast<SingleImageProvider&>(tp); return t.tile; } case Type::SizeReferenceTileProvider: { SizeReferenceTileProvider& t = static_cast<SizeReferenceTileProvider&>(tp); const GeodeticPatch patch(tileIndex); const bool aboveEquator = patch.isNorthern(); const double lat = aboveEquator ? patch.minLat() : patch.maxLat(); const double lon1 = patch.minLon(); const double lon2 = patch.maxLon(); int l = static_cast<int>(t.ellipsoid.longitudalDistance(lat, lon1, lon2)); const bool useKm = l > 9999; if (useKm) { l /= 1000; } l = static_cast<int>(std::round(l)); if (useKm) { l *= 1000; } double tileLongitudalLength = l; const char* unit; if (tileLongitudalLength > 9999) { tileLongitudalLength *= 0.001; unit = "km"; } else { unit = "m"; } t.text = fmt::format(" {:.0f} {:s}", tileLongitudalLength, unit); t.textPosition = { 0.f, aboveEquator ? t.fontSize / 2.f : t.initData.dimensions.y - 3.f * t.fontSize / 2.f }; t.textColor = glm::vec4(1.f); return tile(t, tileIndex); } case Type::TileIndexTileProvider: { TileIndexTileProvider& t = static_cast<TileIndexTileProvider&>(tp); t.text = fmt::format( "level: {}\nx: {}\ny: {}", tileIndex.level, tileIndex.x, tileIndex.y ); t.textPosition = glm::vec2( t.initData.dimensions.x / 4 - (t.initData.dimensions.x / 32) * log10(1 << tileIndex.level), t.initData.dimensions.y / 2 + t.fontSize ); t.textColor = glm::vec4(1.f); return tile(t, tileIndex); } case Type::ByIndexTileProvider: { TileProviderByIndex& t = static_cast<TileProviderByIndex&>(tp); const auto it = t.tileProviderMap.find(tileIndex.hashKey()); const bool hasProvider = it != t.tileProviderMap.end(); return hasProvider ? tile(*it->second, tileIndex) : Tile(); } case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); TileProvider* provider = levelProvider(t, tileIndex.level); if (provider) { return tile(*provider, tileIndex); } else { return Tile(); } } case Type::TemporalTileProvider: { TemporalTileProvider& t = static_cast<TemporalTileProvider&>(tp); if (t.successfulInitialization) { ensureUpdated(t); return tile(*t.currentTileProvider, tileIndex); } else { return Tile(); } } default: throw ghoul::MissingCaseException(); } } Tile::Status tileStatus(TileProvider& tp, const TileIndex& index) { switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); if (t.asyncTextureDataProvider) { const RawTileDataReader& rawTileDataReader = t.asyncTextureDataProvider->rawTileDataReader(); if (index.level > rawTileDataReader.maxChunkLevel()) { return Tile::Status::OutOfRange; } const cache::ProviderTileKey key = { index, t.uniqueIdentifier }; return t.tileCache->get(key).status; } else { return Tile::Status::Unavailable; } } case Type::SingleImageTileProvider: { SingleImageProvider& t = static_cast<SingleImageProvider&>(tp); return t.tile.status; } case Type::SizeReferenceTileProvider: return Tile::Status::OK; case Type::TileIndexTileProvider: return Tile::Status::OK; case Type::ByIndexTileProvider: { TileProviderByIndex& t = static_cast<TileProviderByIndex&>(tp); const auto it = t.tileProviderMap.find(index.hashKey()); const bool hasProvider = it != t.tileProviderMap.end(); return hasProvider ? tileStatus(*it->second, index) : Tile::Status::Unavailable; } case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); TileProvider* provider = levelProvider(t, index.level); return provider ? tileStatus(*provider, index) : Tile::Status::Unavailable; } case Type::TemporalTileProvider: { TemporalTileProvider& t = static_cast<TemporalTileProvider&>(tp); if (t.successfulInitialization) { ensureUpdated(t); return tileStatus(*t.currentTileProvider, index); } else { return Tile::Status::Unavailable; } } default: throw ghoul::MissingCaseException(); } } TileDepthTransform depthTransform(TileProvider& tp) { switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); if (t.asyncTextureDataProvider) { return t.asyncTextureDataProvider->rawTileDataReader().depthTransform(); } else { return { 1.f, 0.f }; } } case Type::SingleImageTileProvider: return { 0.f, 1.f }; case Type::SizeReferenceTileProvider: return { 0.f, 1.f }; case Type::TileIndexTileProvider: return { 0.f, 1.f }; case Type::ByIndexTileProvider: { TileProviderByIndex& t = static_cast<TileProviderByIndex&>(tp); return depthTransform(*t.defaultTileProvider); } case Type::ByLevelTileProvider: return { 0.f, 1.f }; case Type::TemporalTileProvider: { TemporalTileProvider& t = static_cast<TemporalTileProvider&>(tp); if (t.successfulInitialization) { ensureUpdated(t); return depthTransform(*t.currentTileProvider); } else { return { 1.f, 0.f }; } } default: throw ghoul::MissingCaseException(); } } void update(TileProvider& tp) { switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); if (!t.asyncTextureDataProvider) { break; } t.asyncTextureDataProvider->update(); initTexturesFromLoadedData(t); if (t.asyncTextureDataProvider->shouldBeDeleted()) { t.asyncTextureDataProvider = nullptr; initAsyncTileDataReader( t, tileTextureInitData(t.layerGroupID, t.padTiles, t.tilePixelSize) ); } break; } case Type::SingleImageTileProvider: break; case Type::SizeReferenceTileProvider: break; case Type::TileIndexTileProvider: break; case Type::ByIndexTileProvider: { TileProviderByIndex& t = static_cast<TileProviderByIndex&>(tp); using K = TileIndex::TileHashKey; using V = std::unique_ptr<TileProvider>; for (std::pair<const K, V>& it : t.tileProviderMap) { update(*it.second); } update(*t.defaultTileProvider); break; } case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); for (const std::unique_ptr<TileProvider>& provider : t.levelTileProviders) { update(*provider); } break; } case Type::TemporalTileProvider: { TemporalTileProvider& t = static_cast<TemporalTileProvider&>(tp); if (t.successfulInitialization) { TileProvider* newCurrent = getTileProvider(t, global::timeManager.time()); if (newCurrent) { t.currentTileProvider = newCurrent; } update(*t.currentTileProvider); } break; } default: throw ghoul::MissingCaseException(); } } void reset(TileProvider& tp) { switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); t.tileCache->clear(); if (t.asyncTextureDataProvider) { t.asyncTextureDataProvider->prepareToBeDeleted(); } else { initAsyncTileDataReader( t, tileTextureInitData(t.layerGroupID, t.padTiles, t.tilePixelSize) ); } break; } case Type::SingleImageTileProvider: { SingleImageProvider& t = static_cast<SingleImageProvider&>(tp); if (t.filePath.value().empty()) { return; } t.tileTexture = ghoul::io::TextureReader::ref().loadTexture(t.filePath); if (!t.tileTexture) { throw ghoul::RuntimeError( fmt::format("Unable to load texture '{}'", t.filePath.value()) ); } Tile::Status tileStatus = Tile::Status::OK; t.tileTexture->uploadTexture(); t.tileTexture->setFilter( ghoul::opengl::Texture::FilterMode::AnisotropicMipMap ); t.tile = Tile{ t.tileTexture.get(), std::nullopt, tileStatus }; break; } case Type::SizeReferenceTileProvider: { SizeReferenceTileProvider& t = static_cast<SizeReferenceTileProvider&>(tp); reset(t); break; } case Type::TileIndexTileProvider: { TileIndexTileProvider& t = static_cast<TileIndexTileProvider&>(tp); reset(t); break; } case Type::ByIndexTileProvider: { TileProviderByIndex& t = static_cast<TileProviderByIndex&>(tp); using K = TileIndex::TileHashKey; using V = std::unique_ptr<TileProvider>; for (std::pair<const K, V>& it : t.tileProviderMap) { reset(*it.second); } reset(*t.defaultTileProvider); break; } case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); for (const std::unique_ptr<TileProvider>& provider : t.levelTileProviders) { reset(*provider); } break; } case Type::TemporalTileProvider: { TemporalTileProvider& t = static_cast<TemporalTileProvider&>(tp); if (t.successfulInitialization) { using K = TemporalTileProvider::TimeKey; using V = std::unique_ptr<TileProvider>; for (std::pair<const K, V>& it : t.tileProviderMap) { reset(*it.second); } } break; } default: throw ghoul::MissingCaseException(); } } int maxLevel(TileProvider& tp) { switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); // 22 is the current theoretical maximum based on the number of hashes that // are possible to uniquely identify a tile. See ProviderTileHasher in // memoryawaretilecache.h return t.asyncTextureDataProvider ? t.asyncTextureDataProvider->rawTileDataReader().maxChunkLevel() : 22; } case Type::SingleImageTileProvider: return 1337; // unlimited case Type::SizeReferenceTileProvider: return 1337; // unlimited case Type::TileIndexTileProvider: return 1337; // unlimited case Type::ByIndexTileProvider: { TileProviderByIndex& t = static_cast<TileProviderByIndex&>(tp); return maxLevel(*t.defaultTileProvider); } case Type::ByLevelTileProvider: { TileProviderByLevel& t = static_cast<TileProviderByLevel&>(tp); return static_cast<int>(t.providerIndices.size() - 1); } case Type::TemporalTileProvider: { TemporalTileProvider& t = static_cast<TemporalTileProvider&>(tp); if (t.successfulInitialization) { ensureUpdated(t); return maxLevel(*t.currentTileProvider); } else { return 0; } } default: throw ghoul::MissingCaseException(); } } float noDataValueAsFloat(TileProvider& tp) { ghoul_assert(tp.isInitialized, "TileProvider was not initialized."); switch (tp.type) { case Type::DefaultTileProvider: { DefaultTileProvider& t = static_cast<DefaultTileProvider&>(tp); return t.asyncTextureDataProvider ? t.asyncTextureDataProvider->noDataValueAsFloat() : std::numeric_limits<float>::min(); } case Type::SingleImageTileProvider: return std::numeric_limits<float>::min(); case Type::SizeReferenceTileProvider: return std::numeric_limits<float>::min(); case Type::TileIndexTileProvider: return std::numeric_limits<float>::min(); case Type::ByIndexTileProvider: return std::numeric_limits<float>::min(); case Type::ByLevelTileProvider: return std::numeric_limits<float>::min(); case Type::TemporalTileProvider: return std::numeric_limits<float>::min(); default: throw ghoul::MissingCaseException(); } } ChunkTile chunkTile(TileProvider& tp, TileIndex tileIndex, int parents, int maxParents) { ghoul_assert(tp.isInitialized, "TileProvider was not initialized."); auto ascendToParent = [](TileIndex& tileIndex, TileUvTransform& uv) { uv.uvOffset *= 0.5; uv.uvScale *= 0.5; uv.uvOffset += tileIndex.positionRelativeParent(); tileIndex.x /= 2; tileIndex.y /= 2; tileIndex.level--; }; TileUvTransform uvTransform = { glm::vec2(0.f, 0.f), glm::vec2(1.f, 1.f) }; // Step 1. Traverse 0 or more parents up the chunkTree as requested by the caller for (int i = 0; i < parents && tileIndex.level > 1; i++) { ascendToParent(tileIndex, uvTransform); } maxParents -= parents; // Step 2. Traverse 0 or more parents up the chunkTree to make sure we're inside // the range of defined data. int maximumLevel = maxLevel(tp); while (tileIndex.level > maximumLevel) { ascendToParent(tileIndex, uvTransform); maxParents--; } if (maxParents < 0) { return ChunkTile{ Tile(), uvTransform, TileDepthTransform() }; } // Step 3. Traverse 0 or more parents up the chunkTree until we find a chunk that // has a loaded tile ready to use. while (tileIndex.level > 1) { Tile t = tile(tp, tileIndex); if (t.status != Tile::Status::OK) { if (--maxParents < 0) { return ChunkTile{ Tile(), uvTransform, TileDepthTransform() }; } ascendToParent(tileIndex, uvTransform); } else { return ChunkTile{ std::move(t), uvTransform, TileDepthTransform() }; } } return ChunkTile{ Tile(), uvTransform, TileDepthTransform() }; } ChunkTilePile chunkTilePile(TileProvider& tp, TileIndex tileIndex, int pileSize) { ghoul_assert(tp.isInitialized, "TileProvider was not initialized."); ghoul_assert(pileSize >= 0, "pileSize must be positive"); ChunkTilePile chunkTilePile(pileSize); for (int i = 0; i < pileSize; ++i) { chunkTilePile[i] = chunkTile(tp, tileIndex, i); if (chunkTilePile[i].tile.status == Tile::Status::Unavailable) { if (i > 0) { // First iteration chunkTilePile[i].tile = chunkTilePile[i - 1].tile; chunkTilePile[i].uvTransform.uvOffset = chunkTilePile[i - 1].uvTransform.uvOffset; chunkTilePile[i].uvTransform.uvScale = chunkTilePile[i - 1].uvTransform.uvScale; } else { chunkTilePile[i].tile = DefaultTile; chunkTilePile[i].uvTransform.uvOffset = { 0.f, 0.f }; chunkTilePile[i].uvTransform.uvScale = { 1.f, 1.f }; } } } return chunkTilePile; } } // namespace openspace::globebrowsing::tileprovider
; A299960: a(n) = ( 4^(2*n+1) + 1 )/5. ; Submitted by Jon Maiga ; 1,13,205,3277,52429,838861,13421773,214748365,3435973837,54975581389,879609302221,14073748835533,225179981368525,3602879701896397,57646075230342349,922337203685477581,14757395258967641293,236118324143482260685,3777893186295716170957 mov $2,16 pow $2,$0 mov $0,$2 div $0,15 mul $0,12 add $0,1
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ namespace Multiplayer { inline bool operator ==(const ConstNetworkEntityHandle& lhs, AZStd::nullptr_t) { return !lhs.Exists(); } inline bool operator ==(AZStd::nullptr_t, const ConstNetworkEntityHandle& rhs) { return !rhs.Exists(); } inline bool operator !=(const ConstNetworkEntityHandle& lhs, AZStd::nullptr_t) { return lhs.Exists(); } inline bool operator !=(AZStd::nullptr_t, const ConstNetworkEntityHandle& rhs) { return rhs.Exists(); } inline bool operator==(const ConstNetworkEntityHandle& lhs, const AZ::Entity* rhs) { return lhs.m_entity == rhs; } inline bool operator==(const AZ::Entity* lhs, const ConstNetworkEntityHandle& rhs) { return operator==(rhs, lhs); } inline bool operator!=(const ConstNetworkEntityHandle& lhs, const AZ::Entity* rhs) { return lhs.m_entity != rhs; } inline bool operator!=(const AZ::Entity* lhs, const ConstNetworkEntityHandle& rhs) { return operator!=(rhs, lhs); } inline NetEntityId ConstNetworkEntityHandle::GetNetEntityId() const { return m_netEntityId; } template <class ComponentType> inline const ComponentType* ConstNetworkEntityHandle::FindComponent() const { if (const AZ::Entity* entity{ GetEntity() }) { return entity->template FindComponent<ComponentType>(); } return nullptr; } inline bool ConstNetworkEntityHandle::Compare(const ConstNetworkEntityHandle& lhs, const ConstNetworkEntityHandle& rhs) { return lhs.m_netEntityId < rhs.m_netEntityId; } inline void NetworkEntityHandle::Init() { if (AZ::Entity* entity{ GetEntity() }) { entity->Init(); } } inline void NetworkEntityHandle::Activate() { if (AZ::Entity* entity{ GetEntity() }) { entity->Activate(); } } inline void NetworkEntityHandle::Deactivate() { if (AZ::Entity* entity{ GetEntity() }) { entity->Deactivate(); } } template <typename ControllerType> inline ControllerType* NetworkEntityHandle::FindController() { return static_cast<ControllerType*>(FindController(ControllerType::ComponentType::RTTI_Type())); } template <typename ComponentType> inline ComponentType* NetworkEntityHandle::FindComponent() { if (AZ::Entity* entity{ GetEntity() }) { return entity->template FindComponent<ComponentType>(); } return nullptr; } } //! AZStd::hash support. namespace AZStd { template <> class hash<Multiplayer::NetworkEntityHandle> { public: size_t operator()(const Multiplayer::NetworkEntityHandle &rhs) const { return hash<Multiplayer::NetEntityId>()(rhs.GetNetEntityId()); } }; template <> class hash<Multiplayer::ConstNetworkEntityHandle> { public: size_t operator()(const Multiplayer::ConstNetworkEntityHandle &rhs) const { return hash<Multiplayer::NetEntityId>()(rhs.GetNetEntityId()); } }; }
; A063142: Dimension of the space of weight 2n cusp forms for Gamma_0( 74 ). ; 8,27,45,65,83,103,121,141,159,179,197,217,235,255,273,293,311,331,349,369,387,407,425,445,463,483,501,521,539,559,577,597,615,635,653,673,691,711,729,749,767,787,805,825,843,863,881,901,919 mul $0,19 add $0,1 div $0,2 mov $1,1 sub $1,$0 trn $0,$1 mov $1,$0 add $1,8
; A254377: Characteristic function of A230709: a(n) = 1 if n is either evil (A001969) or even odious (A128309), otherwise 0 (when n is odd odious). ; 1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1 dif $0,-2 max $0,0 seq $0,10060 ; Thue-Morse sequence: let A_k denote the first 2^k terms; then A_0 = 0 and for k >= 0, A_{k+1} = A_k B_k, where B_k is obtained from A_k by interchanging 0's and 1's. bin $1,$0 mov $0,$1
;=============================================================================== ; Copyright 2014-2019 Intel Corporation ; All Rights Reserved. ; ; If this software was obtained under the Intel Simplified Software License, ; the following terms apply: ; ; The source code, information and material ("Material") contained herein is ; owned by Intel Corporation or its suppliers or licensors, and title to such ; Material remains with Intel Corporation or its suppliers or licensors. The ; Material contains proprietary information of Intel or its suppliers and ; licensors. The Material is protected by worldwide copyright laws and treaty ; provisions. No part of the Material may be used, copied, reproduced, ; modified, published, uploaded, posted, transmitted, distributed or disclosed ; in any way without Intel's prior express written permission. No license under ; any patent, copyright or other intellectual property rights in the Material ; is granted to or conferred upon you, either expressly, by implication, ; inducement, estoppel or otherwise. Any license under such intellectual ; property rights must be express and approved by Intel in writing. ; ; Unless otherwise agreed by Intel in writing, you may not remove or alter this ; notice or any other notice embedded in Materials by Intel or Intel's ; suppliers or licensors in any way. ; ; ; If this software was obtained under the Apache License, Version 2.0 (the ; "License"), the following terms apply: ; ; 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. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; Message block processing according to SHA256 ; ; Content: ; UpdateSHA256 ; ; .686P .387 .XMM .MODEL FLAT,C INCLUDE asmdefs.inc INCLUDE ia_emm.inc INCLUDE pcpvariant.inc IF (_ENABLE_ALG_SHA256_) IF (_SHA_NI_ENABLING_ EQ _FEATURE_OFF_) OR (_SHA_NI_ENABLING_ EQ _FEATURE_TICKTOCK_) IF (_IPP GE _IPP_G9) IFDEF IPP_PIC LD_ADDR MACRO reg:REQ, addr:REQ LOCAL LABEL call LABEL LABEL: pop reg sub reg, LABEL-addr ENDM ELSE LD_ADDR MACRO reg:REQ, addr:REQ lea reg, addr ENDM ENDIF XMM_SHUFB_BSWAP textequ <xmm6> W0 textequ <xmm0> W4 textequ <xmm1> W8 textequ <xmm2> W12 textequ <xmm3> SIG1 textequ <xmm4> SIG0 textequ <xmm5> X textequ <xmm6> W textequ <xmm7> regTbl textequ <ebx> ;; we are considering x, y, z are polynomials over GF(2) ;; & - multiplication ;; ^ - additive ;; operations ;; ;; Chj(x,y,z) = (x&y) ^ (~x & z) ;; = (x&y) ^ ((1^x) &z) ;; = (x&y) ^ (z ^ x&z) ;; = x&y ^ z ^ x&z ;; = x&(y^z) ^z ;; Chj MACRO F:REQ, X:REQ,Y:REQ,Z:REQ mov F, Y xor F, Z and F, X xor F, Z ENDM ;; ;; Maj(x,y,z) = (x&y) ^ (x&z) ^ (y&z) ;; = (x&y) ^ (x&z) ^ (y&z) ^ (z&z) ^z // note: ((z&z) ^z) = 0 ;; = x&(y^z) ^ z&(y^z) ^z ;; = (x^z)&(y^z) ^z ;; Maj MACRO F:REQ, X:REQ,Y:REQ,Z:REQ mov F, X xor F, Z xor Z, Y and F, Z xor Z, Y xor F, Z ENDM ROTR MACRO X, n shrd X,X, n ;;ror X, n ENDM ;; ;; Summ0(x) = ROR(x,2) ^ ROR(x,13) ^ ROR(x,22) ;; Summ0 MACRO F:REQ, X:REQ, T:REQ mov F, X ROTR F, 2 mov T, X ROTR T, 13 xor F, T ROTR T, (22-13) xor F, T ENDM ;; ;; Summ1(x) = ROR(x,6) ^ ROR(x,11) ^ ROR(x,25) ;; Summ1 MACRO F:REQ, X:REQ, T:REQ mov F, X ROTR F, 6 mov T, X ROTR T, 11 xor F, T ROTR T, (25-11) xor F, T ENDM ;; ;; regular round (i): ;; ;; T1 = h + Sigma1(e) + Ch(e,f,g) + K[i] + W[i] ;; T2 = Sigma0(a) + Maj(a,b,c) ;; h = g ;; g = f ;; f = e ;; e = d + T1 ;; d = c ;; c = b ;; b = a ;; a = T1+T2 ;; ;; or ;; ;; h += Sigma1(e) + Ch(e,f,g) + K[i] + W[i] (==T1) ;; d += h ;; T2 = Sigma0(a) + Maj(a,b,c) ;; h += T2 ;; and following textual shift {a,b,c,d,e,f,g,h} => {h,a,b,c,d,e,f,g} ;; ROUND MACRO nr, hashBuff, wBuff, F1,F2, T1,T2 ;;A,B,C,D,E,F,G,H, T1 Summ1 F1, eax, T1 Chj F2, eax,<[hashBuff+((vF-nr) and 7)*sizeof(dword)]>,<[hashBuff+((vG-nr) and 7)*sizeof(dword)]> mov eax, [hashBuff+((vH-nr) and 7)*sizeof(dword)] add eax, F1 add eax, F2 add eax, dword ptr [wBuff+(nr and 3)*sizeof(dword)] mov F1, dword ptr [hashBuff+((vB-nr) and 7)*sizeof(dword)] mov T1, dword ptr [hashBuff+((vC-nr) and 7)*sizeof(dword)] Maj F2, edx,F1, T1 Summ0 F1, edx, T1 lea edx, [F1+F2] add edx,eax ; T2+T1 add eax,[hashBuff+((vD-nr) and 7)*sizeof(dword)] ; T1+d mov [hashBuff+((vH-nr) and 7)*sizeof(dword)],edx mov [hashBuff+((vD-nr) and 7)*sizeof(dword)],eax ENDM ;; ;; W[i] = Sigma1(W[i-2]) + W[i-7] + Sigma0(W[i-15]) + W[i-16], i=16,..,63 ;; ;;for next rounds 16,17,18 and 19: ;; W[0] <= W[16] = Sigma1(W[14]) + W[ 9] + Sigma0(W[1]) + W[0] ;; W[1] <= W[17] = Sigma1(W[15]) + W[10] + Sigma0(W[2]) + W[1] ;; W[2] <= W[18] = Sigma1(W[ 0]) + W[11] + Sigma0(W[3]) + W[1] ;; W[3] <= W[19] = Sigma1(W[ 1]) + W[12] + Sigma0(W[4]) + W[2] ;; ;; the process is repeated exactly because texual round of W[] ;; ;; Sigma1() and Sigma0() functions are defined as following: ;; Sigma1(X) = ROR(X,17)^ROR(X,19)^SHR(X,10) ;; Sigma0(X) = ROR(X, 7)^ROR(X,18)^SHR(X, 3) ;; UPDATE_W MACRO xS, xS0, xS4, xS8, xS12, SIGMA1, SIGMA0,X vpshufd X, xS12, 11111010b ;; SIGMA1 = {W[15],W[15],W[14],W[14]} vpsrld SIGMA1, X, 10 vpsrlq X, X, 17 vpxor SIGMA1, SIGMA1, X vpsrlq X, X, (19-17) vpxor SIGMA1, SIGMA1, X vpshufd X, xS0, 10100101b ;; SIGMA0 = {W[2],W[2],W[1],W[1]} vpsrld SIGMA0, X, 3 vpsrlq X, X, 7 vpxor SIGMA0, SIGMA0, X vpsrlq X, X, (18-7) vpxor SIGMA0, SIGMA0, X vpshufd xS, xS0, 01010000b ;; {W[ 1],W[ 1],W[ 0],W[ 0]} vpaddd SIGMA1, SIGMA1, SIGMA0 vpshufd X, xS8, 10100101b ;; {W[10],W[10],W[ 9],W[ 9]} vpaddd xS, xS, SIGMA1 vpaddd xS, xS, X vpshufd X, xS, 10100000b ;; SIGMA1 = {W[1],W[1],W[0],W[0]} vpsrld SIGMA1, X, 10 vpsrlq X, X, 17 vpxor SIGMA1, SIGMA1, X vpsrlq X, X, (19-17) vpxor SIGMA1, SIGMA1, X vpalignr X, xS4, xS0, (3*sizeof(dword)) ;; SIGMA0 = {W[4],W[4],W[3],W[3]} vpshufd X, X, 01010000b vpsrld SIGMA0, X, 3 vpsrlq X, X, 7 vpxor SIGMA0, SIGMA0, X vpsrlq X, X, (18-7) vpxor SIGMA0, SIGMA0, X vpalignr X, xS12, xS8, (3*sizeof(dword)) ;; {W[14],W[13],W[12],W[11]} vpshufd xS0, xS0, 11111010b ;; {W[ 3],W[ 3],W[ 2],W[ 2]} vpaddd SIGMA1, SIGMA1, SIGMA0 vpshufd X, X, 01010000b ;; {W[12],W[12],W[11],W[11]} vpaddd xS0, xS0, SIGMA1 vpaddd xS0, xS0, X vpshufd xS, xS, 10001000b ;; {W[1],W[0],W[1],W[0]} vpshufd xS0, xS0, 10001000b ;; {W[3],W[2],W[3],W[2]} vpalignr xS0, xS0, xS, (2*sizeof(dword)) ;; {W[3],W[2],W[1],W[0]} ENDM IPPCODE SEGMENT 'CODE' ALIGN (IPP_ALIGN_FACTOR) ALIGN IPP_ALIGN_FACTOR SWP_BYTE: pByteSwp DB 3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; UpdateSHA256(Ipp32u digest[], Ipp8u dataBlock[], int datalen, Ipp32u K_256[]) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ALIGN IPP_ALIGN_FACTOR IPPASM UpdateSHA256 PROC NEAR C PUBLIC \ USES esi edi ebx,\ pHash: PTR DWORD,\ ; pointer to hash pData: PTR BYTE,\ ; pointer to data block dataLen: DWORD,\ ; data length pTbl: PTR DWORD ; pointer to the SHA256 const table MBS_SHA256 equ (64) hSize = sizeof(dword)*8 ; size of hash wSize = sizeof(oword) ; W values queue (dwords) cntSize = sizeof(dword) ; local counter hashOff = 0 ; hash address wOff = hashOff+hSize ; W values offset cntOff = wOff+wSize stackSize = (hSize+wSize+cntSize) ; stack size sub esp, stackSize ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; process next data block ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; sha256_block_loop: mov eax, pHash ; pointer to the hash vmovdqu W0, oword ptr [eax] ; load initial hash value vmovdqu W4, oword ptr [eax+sizeof(oword)] vmovdqu oword ptr [esp+hashOff], W0 vmovdqu oword ptr [esp+hashOff+sizeof(oword)*1], W4 mov eax, pData ; pointer to the data block mov regTbl, pTbl ; pointer to SHA256 table (points K_256[] constants) ;vmovdqa XMM_SHUFB_BSWAP, oword ptr pByteSwp ; load shuffle mask LD_ADDR ecx, SWP_BYTE movdqa XMM_SHUFB_BSWAP, oword ptr[ecx+(pByteSwp-SWP_BYTE)] vmovdqu W0, oword ptr [eax] ; load buffer content vmovdqu W4, oword ptr [eax+sizeof(oword)] vmovdqu W8, oword ptr [eax+sizeof(oword)*2] vmovdqu W12,oword ptr [eax+sizeof(oword)*3] vA = 0 vB = 1 vC = 2 vD = 3 vE = 4 vF = 5 vG = 6 vH = 7 mov eax, [esp+hashOff+vE*sizeof(dword)] mov edx, [esp+hashOff+vA*sizeof(dword)] ;; perform 0-3 regular rounds vpshufb W0, W0, XMM_SHUFB_BSWAP ; swap input vpaddd W, W0, oword ptr [regTbl+sizeof(oword)*0] ; T += K_SHA256[0-3] vmovdqu oword ptr [esp+wOff], W ROUND 0, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 1, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 2, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 3, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ;; perform next 4-7 regular rounds vpshufb W4, W4, XMM_SHUFB_BSWAP ; swap input vpaddd W, W4, oword ptr [regTbl+sizeof(oword)*1] ; T += K_SHA256[4-7] vmovdqu oword ptr [esp+wOff], W ROUND 4, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 5, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 6, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 7, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ;; perform next 8-11 regular rounds vpshufb W8, W8, XMM_SHUFB_BSWAP ; swap input vpaddd W, W8, oword ptr [regTbl+sizeof(oword)*2] ; T += K_SHA256[8-11] vmovdqu oword ptr [esp+wOff], W ROUND 8, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 9, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 10, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 11, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ;; perform next 12-15 regular rounds vpshufb W12, W12, XMM_SHUFB_BSWAP ; swap input vpaddd W, W12, oword ptr [regTbl+sizeof(oword)*3] ; T += K_SHA256[12-15] vmovdqu oword ptr [esp+wOff], W ROUND 12, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 13, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 14, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 15, <esp+hashOff>,<esp+wOff>, esi,edi,ecx mov dword ptr [esp+cntOff], (64-16) ; init counter loop_16_63: add regTbl, sizeof(oword)*4 ; update SHA_256 pointer UPDATE_W W, W0, W4, W8, W12, SIG1,SIG0,X ; round: 16*i - 16*i+3 vpaddd W, W0, oword ptr [regTbl+sizeof(oword)*0] ; T += K_SHA256[16-19] vmovdqu oword ptr [esp+wOff], W ROUND 16, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 17, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 18, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 19, <esp+hashOff>,<esp+wOff>, esi,edi,ecx UPDATE_W W, W4, W8, W12,W0, SIG1,SIG0,X ; round: 20*i 20*i+3 vpaddd W, W4, oword ptr [regTbl+sizeof(oword)*1] ; T += K_SHA256[20-23] vmovdqu oword ptr [esp+wOff], W ROUND 20, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 21, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 22, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 23, <esp+hashOff>,<esp+wOff>, esi,edi,ecx UPDATE_W W, W8, W12,W0, W4, SIG1,SIG0,X ; round: 24*i - 24*i+3 vpaddd W, W8, oword ptr [regTbl+sizeof(oword)*2] ; T += K_SHA256[24-27] vmovdqu oword ptr [esp+wOff], W ROUND 24, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 25, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 26, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 27, <esp+hashOff>,<esp+wOff>, esi,edi,ecx UPDATE_W W, W12,W0, W4, W8, SIG1,SIG0,X ; round: 28*i - 28*i+3 vpaddd W, W12, oword ptr [regTbl+sizeof(oword)*3]; T += K_SHA256[28-31] vmovdqu oword ptr [esp+wOff], W ROUND 28, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 29, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 30, <esp+hashOff>,<esp+wOff>, esi,edi,ecx ROUND 31, <esp+hashOff>,<esp+wOff>, esi,edi,ecx sub dword ptr [esp+cntOff], 16 jg loop_16_63 mov eax, pHash ; pointer to the hash vmovdqu W0, oword ptr [esp+hashOff] vmovdqu W4, oword ptr [esp+hashOff+sizeof(oword)*1] ; update hash vmovdqu W, oword ptr [eax] vpaddd W, W, W0 vmovdqu oword ptr [eax], W vmovdqu W, oword ptr [eax+sizeof(oword)] vpaddd W, W, W4 vmovdqu oword ptr [eax+sizeof(oword)], W add pData, MBS_SHA256 sub dataLen, MBS_SHA256 jg sha256_block_loop add esp, stackSize ret IPPASM UpdateSHA256 ENDP ENDIF ;; _IPP32E_G9 and above ENDIF ;; _FEATURE_OFF_ / _FEATURE_TICKTOCK_ ENDIF ;; _ENABLE_ALG_SHA256_ END
TT START 0 USING *,0 USING *,1 EXTRN PRNT ENTRY FOF BCW EQU X'54' ADDRESS OF CHANNEL 5 BCW DEV EQU X'A8' MUX CHAN 5 DEV 0 ADDRESS TST EQU * OPEN PRNT BAL 14,PW PRINT THE WELCOME MSG * * DISPLAY HALT CODE 1 AND WAIT FOR OPERATOR TO ENTER TEST # * LOOP MSG X'0001',REPLY TEST EQU LOOP+7 * MAKE SURE TEST # IS VALID CLI TEST,0 TEST # = 0 BC 8,IT YES, DISPLAY ERROR CLI TEST,16 TEST # > 16? BC 2,IT YES, DISPLAY ERROR * GET THE ADDRESS OF THE TEST ROUTINE MVC THW+1(1),TEST GET THE TEST # LH 9,THW MULTIPLY BY 2 AH 9,THW AH 9,JTA ADD ADDR OF JUMP TABLE LH 9,0(,9) GET ADDR OF TEST RTN FROM TABLE * ECHO THE TEST # TO THE PRINTER MVI TLN,C' ' CLI TEST,9 IF TEST # > 9 THEN BC 13,L1 MVI TLN,C'1' SET FIRST DIGIT TO 1 LH 8,THW DECR TEST # BY 10 SH 8,HW10 STH 8,THW MVC TEST(1),THW+1 L1 EQU * MVC TLN+1(1),TEST SET THE (POSSIBLY) SECOND DIGIT OI TLN+1,X'F0' CNTRL PRNT,SP,0,2 BAL 14,BCL MVC PBFR(18),TL PUT PRNT,PBFR CNTRL PRNT,SP,0,1 * EXECUTE THE TEST BC 15,0(,9) GO DO THE TEST CLOSE PRNT DONE EQU * MSG X'1FFF' BC 15,DONE * * WRITE THE WELCOME MESSAGE TO THE PRINTER * PW EQU * STH 14,PWR+2 SAVE RTN ADDR CNTRL PRNT,SK,7 FORM FEED BAL 14,BCL CLEAR PRINT BUFFER CNTRL PRNT,SP,0,2 PRINT W1 WITH BLANK LINE AFTER MVC PBFR(35),W1 PUT PRNT,PBFR CNTRL PRNT,SP,0,1 PRINT AVAILABLE TEST LIST BAL 14,BCL MVC PBFR(20),W2 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(10),W3 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(11),W4 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(10),W5 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(11),W6 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(19),W7 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(25),W8 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(24),W9 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(26),W10 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(25),W11 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(20),W12 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(26),W13 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(14),W14 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(12),W15 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(22),W16 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(20),W17 PUT PRNT,PBFR BAL 14,BCL MVC PBFR(11),W18 PUT PRNT,PBFR CNTRL PRNT,SP,1,2 BAL 14,BCL MVC PBFR(85),W99 PUT PRNT,PBFR CNTRL PRNT,SP,0,1 PWR BC 15,0 MODIFIED WITH RTN ADDR ABOVE * * CLEAR THE PRINTER BUFFER TO SPACES * BCL EQU * MVI PBFR,C' ' MVC PBFR+1(131),PBFR BC 15,0(,14) * * CLEAR THE BCW TO ZEROS * BCWC EQU * MVI BCW,0 MVI BCW+1,0 MVC BCW+2(2),TBA BC 15,0(,14) * * PRINT INVALID TEST # ERROR * IT EQU * BAL 14,BCL MVC PBFR(14),ITE PUT PRNT,PBFR BC 15,LOOP * * FORM OVERFLOW HANDLER * FOF EQU * STH 14,FOFR+2 SAVE RETURN ADDRESS CNTRL PRNT,SK,7 PAGE EJECT FOFR BC 15,0 RETURN TO ORIGINAL CALLER * * 'TEST' COMMAND * T1 EQU * BAL 14,BCL MVC PBFR(20),T1L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF 0,DEV ISSUE TEST COMMAND BC 7,PCS ERROR BAL 13,PS DUMP STATUS BYTE BC 15,LOOP * * 'SENSE' COMMAND * T2 EQU * BAL 14,BCL MVC PBFR(21),T2L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'04',DEV ISSUE SENSE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BAL 13,PS PRINT THE STATUS BYTE BAL 13,PN DUMP SENSE BYTES BC 15,LOOP * * 'READ FORWARD' COMMAND * T3 EQU * BAL 14,BCL MVC PBFR(20),T3L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW OI BCW,1 SET BLOCK SIZE TO 256 XIOF X'02',DEV ISSUE READ COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR TM ST,X'01' EXCEPTION SET? BC 14,T3D NO, ALL OK BAL 14,BCL PROBABLY EOF MVC PBFR(3),EOF PUT PRNT,PBFR BC 15,LOOP T3D EQU * MVC PBFR,TBFR DUMP 1ST 132 BYTES OF BUFFER PUT PRNT,PBFR BC 15,LOOP * * 'WRITE' COMMAND * T4 EQU * BAL 14,BCL MVC PBFR(21),T4L PUT PRNT,PBFR * FILL A 256 BYTE BLOCK WITH DATA MVC TBFR(1),BN+1 MVC TBFR+1(255),TBFR * BUMP THE CHARACTER USED TO FILL THE BUFFER AI BN,1 CLI BN+1,C'9' > 9? BC 13,T4A NO MVI BN+1,C'1' YES, RESET TO 1 T4A EQU * BAL 13,WAIT WAIT FOR I/O TO COMPLETE BAL 14,BCWC CLEAR THE BCW OI BCW,1 SET LENGTH TO 256 BYTES XIOF X'01',DEV ISSUE THE WRITE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'READ BACKWARD' COMMAND * T5 EQU * BAL 14,BCL MVC PBFR(29),T5L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW OI BCW,1 SET BLOCK SIZE TO 256 OI BCW,X'40' SET REVERSE DIRECTION BIT MVC BCW+2(2),TBE SET HIGH BUFFER ADDRESS XIOF X'0C',DEV ISSUE READ BACKWARD COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR TM ST,X'01' EXCEPTION SET? BC 14,T5D NO, ALL OK BAL 14,BCL PROBABLY EOF MVC PBFR(3),EOF PUT PRNT,PBFR BC 15,LOOP T5D EQU * MVC PBFR,TBFR DUMP 1ST 132 BYTES OF BUFFER PUT PRNT,PBFR BC 15,LOOP * * 'FORWARD SPACE BLOCK' COMMAND * T6 EQU * BAL 14,BCL MVC PBFR(35),T6L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'37',DEV ISSUE FORWARD SPACE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR TM ST,X'01' EXCEPTION SET? BC 14,LOOP NO, ALL OK BAL 14,BCL PROBABLY EOF MVC PBFR(3),EOF PUT PRNT,PBFR BC 15,LOOP * * 'FORWARD SPACE FILE' COMMAND * T7 EQU * BAL 14,BCL MVC PBFR(34),T7L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'3F',DEV ISSUE FORWARD SPACE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR TM ST,X'01' EXCEPTION SET? BC 14,LOOP NO, ALL OK BAL 14,BCL PROBABLY EOF MVC PBFR(3),EOF PUT PRNT,PBFR BC 15,LOOP * * 'BACK SPACE BLOCK" COMMAND * T8 EQU * BAL 14,BCL MVC PBFR(32),T8L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'27',DEV ISSUE BACK SPACE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR TM ST,X'01' EXCEPTION SET? BC 14,LOOP NO, ALL OK BAL 14,BCL PROBABLY EOF MVC PBFR(3),EOF PUT PRNT,PBFR BC 15,LOOP * * 'BACK SPACE FILE' COMMAND * T9 EQU * BAL 14,BCL MVC PBFR(31),T9L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'2F',DEV ISSUE BACK SPACE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR TM ST,X'01' EXCEPTION SET? BC 14,LOOP NO, ALL OK BAL 14,BCL PROBABLY EOF MVC PBFR(3),EOF PUT PRNT,PBFR BC 15,LOOP * * 'INHIBIT STATUS' COMMAND * T10 EQU * BAL 14,BCL MVC PBFR(22),T10L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'10',DEV ISSUE INHIBIT STATUS COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'RESET INHIBIT STATUS' COMMAND * T11 EQU * BAL 14,BCL MVC PBFR(28),T11L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BAL 14,BCWC CLEAR THE BCW XIOF X'20',DEV ISSUE RESET INHIBIT STATUS CMD BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'MODE SET' COMMAND * T12 EQU * BAL 14,BCL MVC PBFR(16),T12L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'03',DEV ISSUE MODE SET BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'REWIND' COMMAND * T13 EQU * BAL 14,BCL MVC PBFR(14),T13L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'07',DEV ISSUE REWIND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'REWIND WITH LOCK' COMMAND * T14 EQU * BAL 14,BCL MVC PBFR(24),T14L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'0F',DEV ISSUE WRITE TAPE MARK BC 7,PCS ERROR BAL 13,WAIT WAIT FOR COMMAND TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'WRITE TAPE MARK' COMMAND * T15 EQU * BAL 14,BCL MVC PBFR(22),T15L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'1F',DEV ISSUE WRITE TAPE MARK BC 7,PCS ERROR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * 'ERASE' COMMAND * T16 EQU * BAL 14,BCL MVC PBFR(13),T16L PUT PRNT,PBFR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BAL 14,BCWC CLEAR THE BCW XIOF X'17',DEV ISSUE ERASE COMMAND BC 7,PCS ERROR BAL 13,WAIT WAIT FOR I/O TO COMPLETE BC 7,PCS ERROR BC 15,LOOP * * WAIT FOR TAPE TO BE NOT BUSY * WAIT EQU * TIO ST,DEV BC 2,WAIT BUSY, KEEP WAITING BC 15,0(,13) * * PRINT CONDITION CODE * PC EQU * BC 8,POK BC 4,PREJ BC 2,PBSY BAL 14,BCL MVC PBFR(14),PCC3 BC 15,PC1 POK EQU * BAL 14,BCL MVC PBFR(16),PCC0 BC 15,PC1 PREJ EQU * BAL 14,BCL MVC PBFR(16),PCC1 BC 15,PC1 PBSY EQU * BAL 14,BCL MVC PBFR(4),PCC2 PC1 EQU * PUT PRNT,PBFR BC 15,0(,13) * * PRINT STATUS CODE * PS EQU * BAL 14,BCL MVC PBFR(91),STAT TM ST,X'80' BC 1,PS1 MVI PBFR,C' ' MVC PBFR+1(9),PBFR PS1 EQU * TM ST,X'40' BC 1,PS2 MVI PBFR+10,C' ' MVC PBFR+11(15),PBFR+10 PS2 TM ST,X'20' BC 1,PS3 MVI PBFR+26,C' ' MVC PBFR+27(16),PBFR+26 PS3 EQU * TM ST,X'10' BC 1,PS4 MVI PBFR+43,C' ' MVC PBFR+44(4),PBFR+43 PS4 EQU * TM ST,X'08' BC 1,PS5 MVI PBFR+48,C' ' MVC PBFR+49(11),PBFR+48 PS5 EQU * TM ST,X'04' BC 1,PS6 MVI PBFR+60,C' ' MVC PBFR+61(10),PBFR+60 PS6 EQU * TM ST,X'02' BC 1,PS7 MVI PBFR+71,C' ' MVC PBFR+72(10),PBFR+71 PS7 TM ST,X'01' BC 1,PS8 MVI PBFR+82,C' ' MVC PBFR+83(8),PBFR+82 PS8 EQU * PUT PRNT,PBFR BC 15,0(,13) * * PRINT CONDITION CODE & STATUS * PCS EQU * BAL 13,PC TIO ST,DEV GET MOST RECENT STATUS BAL 13,PS BC 15,LOOP * * PRINT SENSE BYTES * PN EQU * BAL 14,BCL MVC PBFR(126),SB0 TM TBFR,X'80' BC 1,PN01 MVI PBFR,C' ' MVC PBFR+1(16),PBFR PN01 EQU * TM TBFR,X'40' BC 1,PN02 MVI PBFR+17,C' ' MVC PBFR+18(21),PBFR+17 PN02 EQU * TM TBFR,X'20' BC 1,PN03 MVI PBFR+39,C' ' MVC PBFR+40(13),PBFR+39 PN03 EQU * TM TBFR,X'10' BC 1,PN04 MVI PBFR+53,C' ' MVC PBFR+54(15),PBFR+53 PN04 EQU * TM TBFR,X'08' BC 1,PN05 MVI PBFR+69,C' ' MVC PBFR+70(10),PBFR+69 PN05 EQU * TM TBFR,X'04' BC 1,PN06 MVI PBFR+80,C' ' MVC PBFR+81(9),PBFR+80 PN06 EQU * TM TBFR,X'02' BC 1,PN07 MVI PBFR+90,C' ' MVC PBFR+91(15),PBFR+90 PN07 EQU * TM TBFR,X'01' BC 1,PN08 MVI PBFR+106,C' ' MVC PBFR+107(19),PBFR+106 PN08 EQU * PUT PRNT,PBFR BAL 14,BCL MVC PBFR(69),SB1 TM TBFR+1,X'80' BC 1,PN11 MVI PBFR,C' ' MVC PBFR+1(5),PBFR PN11 EQU * TM TBFR+1,X'40' BC 1,PN12 MVI PBFR+6,C' ' MVC PBFR+7(8),PBFR+6 PN12 EQU * TM TBFR+1,X'20' BC 1,PN13 MVI PBFR+15,C' ' MVC PBFR+16(8),PBFR+15 PN13 EQU * TM TBFR+1,X'10' BC 1,PN14 MVI PBFR+24,C' ' MVC PBFR+25(7),PBFR+24 PN14 EQU * TM TBFR+1,X'08' BC 1,PN15 MVI PBFR+32,C' ' MVC PBFR+33(10),PBFR+32 PN15 EQU * TM TBFR+1,X'04' BC 1,PN16 MVI PBFR+43,C' ' MVC PBFR+44(8),PBFR+43 PN16 EQU * TM TBFR+1,X'02' BC 1,PN17 MVI PBFR+52,C' ' MVC PBFR+53(12),PBFR+52 PN17 EQU * TM TBFR+1,X'01' BC 1,PN18 MVI PBFR+65,C' ' MVC PBFR+66(3),PBFR+65 PN18 EQU * PUT PRNT,PBFR BAL 14,BCL MVC PBFR(65),SB3 TM TBFR+3,X'80' BC 1,PN31 MVI PBFR,C' ' MVC PBFR+1(13),PBFR PN31 EQU * TM TBFR+3,X'40' BC 1,PN32 MVI PBFR+14,C' ' MVC PBFR+15(8),PBFR+14 PN32 EQU * TM TBFR+3,X'20' BC 1,PN33 MVI PBFR+23,C' ' MVC PBFR+24(4),PBFR+23 PN33 EQU * TM TBFR+3,X'10' BC 1,PN34 MVI PBFR+28,C' ' MVC PBFR+29(14),PBFR+28 PN34 EQU * TM TBFR+3,X'08' BC 1,PN35 MVI PBFR+43,C' ' MVC PBFR+44(14),PBFR+43 PN35 EQU * TM TBFR+3,X'02' BC 1,PN36 MVI PBFR+58,C' ' MVC PBFR+59(6),PBFR+58 PN36 EQU * PUT PRNT,PBFR BAL 14,BCL MVC PBFR(45),SB4 TM TBFR+4,X'80' BC 1,PN41 MVI PBFR,C' ' MVC PBFR+1(13),PBFR PN41 EQU * TM TBFR+4,X'40' BC 1,PN42 MVI PBFR+14,C' ' MVC PBFR+15(14),PBFR+14 PN42 EQU * TM TBFR+4,X'04' BC 1,PN43 MVI PBFR+29,C' ' MVC PBFR+30(5),PBFR+29 PN43 EQU * TM TBFR+4,X'02' BC 1,PN44 MVI PBFR+35,C' ' MVC PBFR+36(9),PBFR+35 PN44 EQU * PUT PRNT,PBFR BC 15,0(,13) * * JUMP TABLE FOR TESTS * JT DC YL2(LOOP) DC YL2(T1) DC YL2(T2) DC YL2(T3) DC YL2(T4) DC YL2(T5) DC YL2(T6) DC YL2(T7) DC YL2(T8) DC YL2(T9) DC YL2(T10) DC YL2(T11) DC YL2(T12) DC YL2(T13) DC YL2(T14) DC YL2(T15) DC YL2(T16) JTA DC YL2(JT) THW DC YL2(0) HW10 DC YL2(10) ST DS CL2 BN DC CL2' 1' PBFR DS CL132 ITE DC C'INVALID TEST #' PCC0 DC C'COMMAND ACCEPTED' PCC1 DC C'COMMAND REJECTED' PCC2 DC C'BUSY' PCC3 DC C'INVALID DEVICE' W1 DC C'UNIVAC 9200/9300' DC C' EMULATOR TAPE T' DC C'EST' W2 DC C'AVAILABLE TESTS ' DC C'ARE:' W3 DC C' 1 - TEST' W4 DC C' 2 - SENSE' W5 DC C' 3 - READ' W6 DC C' 4 - WRITE' W7 DC C' 5 - READ BACKW' DC C'ARD' W8 DC C' 6 - FORWARD SP' DC C'ACE BLOCK' W9 DC C' 7 - FORWARD SP' DC C'ACE FILE' W10 DC C' 8 - BACKWARD S' DC C'PACE BLOCK' W11 DC C' 9 - BACKWARD S' DC C'PACE FILE' W12 DC C' 10 - INHIBIT ST' DC C'ATUS' W13 DC C' 11 - RESET INHI' DC C'BIT STATUS' W14 DC C' 12 - MODE SET' W15 DC C' 13 - REWIND' W16 DC C' 14 - REWIND WIT' DC C'H LOCK' W17 DC C' 15 - WRITE TAPE' DC C'MARK' W18 DC C' 16 - ERASE' W99 DC C'ENTER THE TEST #' DC C' INTO MEMORY LOC' DC C'ATION 4 USING TH' DC C'E DATA ENTRY SWI' DC C'TCHES AND PRESS ' DC C'START' TL DC C'TEST # ' TLN DS CL2 DC C' SELECTED' T1L DC C'ISSUING TEST COM' DC C'MAND' T2L DC C'ISSUING SENSE CO' DC C'MMAND' T3L DC C'ISSUING READ COM' DC C'MAND' T4L DC C'ISSUING WRITE CO' DC C'MMAND' T5L DC C'ISSUING READ BAC' DC C'KWARD COMMAND' T6L DC C'ISSUING FORWARD ' DC C'SPACE BLOCK COMM' DC C'AND' T7L DC C'ISSUING FORWARD ' DC C'SPACE FILE COMMA' DC C'ND' T8L DC C'ISSUING BACK SPA' DC C'CE BLOCK COMMAND' T9L DC C'ISSUING BACK SPA' DC C'CE FILE COMMAND' T10L DC C'ISSUING INHIBIT ' DC C'STATUS' T11L DC C'ISSUING RESET IN' DC C'HIBIT STATUS' T12L DC C'ISSUING MODE SET' T13L DC C'ISSUING REWIND' T14L DC C'ISSUING REWIND W' DC C'ITH LOCK' T15L DC C'ISSUING WRITE TA' DC C'PEMARK' T16L DC C'ISSUING ERASE' STAT DC C'ATTENTION-STATUS' DC C' MODIFIER-CONTRO' DC C'L UNIT END-BUSY-' DC C'CHANNEL END-DEVI' DC C'CE END-UNIT CHEC' DC C'K-EXCEPTION' SB0 DC C'INVALID FUNCTION' DC C'-INTERVENTION RE' DC C'QUIRED-BUS OUT C' DC C'HECK-EQUIPMENT C' DC C'HECK-DATA CHECK-' DC C'DATA LATE-WORD C' DC C'OUNT ZERO-DATA C' DC C'ONVERTER CHECK' SB1 DC C'NOISE-STATUS A-S' DC C'TATUS B-7 TRACK-' DC C'LOAD POINT-TAPE ' DC C'END-FILE PROTECT' DC C'-BUSY' SB2 DC C' ' SB3 DC C'VP READ ERROR-LP' DC C' ERROR-SKEW-CRC ' DC C'READ ERROR-VP WR' DC C'ITE ERROR-REVERS' DC C'E' SB4 DC C'RUNAWAY CHECK-MO' DC C'VEMENT ERROR-STA' DC C'LL-TAPE ERROR' EOF DC CL3'EOF' TBA DC YL2(TBFR) TBE DC YL2(TBFR+255) TBFR EQU * ORG *+8192 END TST
; A249038: Number of odd terms in first n terms of A249036. ; 1,1,1,2,2,2,3,4,4,5,5,5,6,7,7,7,8,9,9,10,10,11,11,11,12,13,13,13,14,15,15,15,16,17,17,17,18,19,19,20,20,21,21,22,22,23,23,23,24,25,25,25,26,27,27,27,28,29,29,29,30,31,31,31,32,33,33,33,34,35,35,35,36,37,37,37,38,39 lpb $0 mov $2,$0 sub $0,1 seq $2,249036 ; a(1)=1, a(2)=2; thereafter a(n) = a(n-1-(number of even terms so far)) + a(n-1-(number of odd terms so far)). mod $2,2 add $1,$2 lpe add $1,1 mov $0,$1
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1994 -- All Rights Reserved GEOWORKS CONFIDENTIAL PROJECT: Network extensions MODULE: Socket library FILE: socketMisc.asm AUTHOR: Eric Weber, May 25, 1994 ROUTINES: Name Description ---- ----------- EXT SocketEntry Entry point for library INT SocketSetupTimeout Convert a delta timeout value into an absolute time INT SocketPTimedSem P a semaphore in an environment with a timeout INT SocketGetTimeout Compute time remaining in a timeout INT SocketControlStartRead Start reading the control block INT SocketControlEndRead Stop reading the control block INT SocketControlStartWrite Start an update to the control block INT SocketControlEndWrite End an update to the control block INT SocketControlReadToWrite Upgrade our control block lock INT SocketControlWriteToRead downgrade our control block lock INT SocketControlSuspendLock Release either a read or write lock INT SocketControlResumeLock Restore the lock on the control segment suspended earlier EXT SocketCheckQueue See if there are any packets in a queue EXT SocketEnqueue Put a packet onto a queue EXT SocketDequeuePackets Pop some packets off the queue EXT SocketAllocQueue Allocate a data queue for a socket EXT SocketFreeQueue Free a socket's data queue GLB DomainNameToIniCat Translate a domain name (DBCS) to a .INI category name (SBCS) GLB DomainNameToIniCatLow Translate a domain name (DBCS) to a .INI category name (SBCS) GLB DomainNameDone Done with domain .INI category name from DomainNameToIniCat() GLB DomainNameDoneLow Done with domain .INI category name from DomainNameToIniCat() REVISION HISTORY: Name Date Description ---- ---- ----------- EW 5/25/94 Initial revision DESCRIPTION: Miscelaneous routines $Id: socketMisc.asm,v 1.25 97/04/21 20:49:46 simon Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlLockType etype word SCLT_READ enum SocketControlLockType SCLT_WRITE enum SocketControlLockType SocketQueues segment lmem LMEM_TYPE_GENERAL, mask LMF_RETURN_ERRORS SocketQueues ends udata segment lockType SocketControlLockType udata ends UtilCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Entry point for library CALLED BY: EXTERNAL (kernel) PASS: di = LibraryCallType RETURN: carry = set on error DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 6/ 6/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketEntry proc far ForceRef SocketEntry uses ax,bx,cx,dx,si,di,bp,ds .enter ; ; get dgroup ; mov bx, handle dgroup call MemDerefDS ; ; initialize the library on ATTACH ; cmp di, LCT_ATTACH jne notAttach call PacketAttach jc done call LoadAttach call ControlAttach call SocketGetInitParameters jmp done ; ; clean up after sloppy apps on CLIENT_EXIT ; notAttach: cmp di, LCT_CLIENT_EXIT jne notClientDetach call FreeClientSockets ; ; free everything on DETACH ; notClientDetach: cmp di, LCT_DETACH jne done call PacketDetach done: .leave ret SocketEntry endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketGetInitParameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Read assorted parameters from init file CALLED BY: SocketEntry PASS: ds - socket dgroup RETURN: nothing DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/16/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketGetInitParameters proc near uses ax,bx,cx,dx,si,di,bp .enter ; ; read driver-close-delay ; mov si, offset ds:[socketCategory] mov cx, ds mov dx, offset ds:[driverCloseDelayKey] mov ax, DEFAULT_DRIVER_CLOSE_DELAY ; default value call InitFileReadInteger ; ax = time (seconds) mov cx, 60 ; # ticks per second mul cx jnc delayInRange mov ax, 0xffff ; value in .INI too big, use ; max. possible value delayInRange: mov ds:[driverCloseDelay], ax ; ; read send timeout ; mov cx, ds mov dx, offset ds:[sendTimeoutKey] mov ax, DEFAULT_SEND_TIMEOUT call InitFileReadInteger mov cx, 60 mul cx jnc timeoutInRange mov ax, 0xffff ; value in .INI too big, use ; max. possible value clc timeoutInRange: mov ds:[sendTimeout], ax .leave ret SocketGetInitParameters endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketSetupTimeout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Convert a delta timeout value into an absolute time CALLED BY: (INTERNAL) SocketAccept, SocketCheckReady, SocketConnect, SocketRecvLow PASS: ss:ax - address to write timeout ss:bp - timeout in ticks 0 to never block SOCKET_NO_TIMEOUT to block forever RETURN: ss:ax - initialized to drop dead time DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 6/ 6/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ .assert SOCKET_NO_TIMEOUT eq -1 ; any value other then -1 will break the following code SocketSetupTimeout proc far uses ax,bx,cx,dx,bp,di .enter ; ; if bp is -1, timeout should be -1 also ; mov bp, ss:[bp] mov di, ax mov ss:[di].low, bp mov ss:[di].high, bp cmp bp, SOCKET_NO_TIMEOUT je done ; ; don't allow timeouts > 32767 ; EC < tst bp > EC < ERROR_S EXCESSIVE_TIMEOUT > ; ; compute the time at which to time out ; call TimerGetCount ; bxax = time since startup EC < tstdw bxax > EC < ERROR_Z TIMEOUT_FAULT > clr dx mov cx, bp ; dxcx = timeout interval adddw bxax, dxcx ; bxax = drop dead time ; ; assuming it's reasonable, write it out ; EC < ERROR_O EXCESSIVE_TIMEOUT > EC < cmpdw bxax, SOCKET_NO_TIMEOUT > EC < ERROR_E TIMEOUT_FAULT > movdw ss:[di], bxax ; remember timeout info done: .leave ret SocketSetupTimeout endp FixedCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketPTimedSem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: P a semaphore in an environment with a timeout CALLED BY: (INTERNAL) SocketCheckReady, SocketConnect, SocketLockForCreateLink, SocketPreAccept, SocketRecvLow PASS: bx - handle of semaphore ss:cx - time at which to time out RETURN: carry - set if timed out ax - SE_TIMED_OUT if carry set, otherwise preserved DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 5/25/94 Initial version brianc 10/22/98 Moved into fixed code for resolver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketPTimedSem proc far uses cx,dx,bp .enter EC < Assert fptr sscx > ; ; first make sure we really have a timeout ; mov dx,ax ; save initial ax jcxz noTimeout mov bp,cx cmpdw ss:[bp], SOCKET_NO_TIMEOUT je noTimeout ; ; we do, so figure out how much time we have left ; push bx call TimerGetCount ; bxax = time subdw bxax, ss:[bp] ; -bxax = time remaining jge timeout ; we're out of time negdw bxax ; bxax = time remaining ; ; if its more then a word, we did something wrong ; EC < tst bx > EC < ERROR_NZ EXCESSIVE_TIMEOUT > ; ; go ahead and P the semaphore ; mov cx, ax pop bx call ThreadPTimedSem ; ; check the outcome of the P operation ; tst ax ; errors? clc jz done ; if not, exit EC < cmp ax, SE_TIMEOUT > EC < ERROR_NE UNEXPECTED_SEMAPHORE_ERROR > stc mov dx, SE_TIMED_OUT ; semaphore timed out done: mov ax,dx .leave ret ; ; don't bother looking at the semaphore - the timeout has already ; expired ; timeout: pop bx stc mov dx, SE_TIMED_OUT jmp done ; ; the user wants to wait forever... ; noTimeout: push ax call ThreadPSem ; ax = SemaphoreError EC < tst ax > EC < ERROR_NZ UNEXPECTED_SEMAPHORE_ERROR > pop ax clc jmp done SocketPTimedSem endp FixedCode ends COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketGetTimeout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Compute time remaining in a timeout CALLED BY: (INTERNAL) SocketCreateLink, SocketDataConnect, SocketPostDataAccept PASS: ss:cx - time at which to time out RETURN: cx - ticks remaining util timeout DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 6/17/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketGetTimeout proc far uses ax,bx,bp .enter ; ; first make sure we really have a timeout ; jcxz noTimeout mov bp,cx mov cx, -1 cmpdw ss:[bp], SOCKET_NO_TIMEOUT je done ; ; we do, so figure out how much time we have left ; call TimerGetCount ; bxax = time subdw bxax, ss:[bp] ; -bxax = time remaining jge timeout ; we're out of time negdw bxax ; bxax = time remaining ; ; if its more then a word, we did something wrong ; EC < tst bx > EC < ERROR_NZ EXCESSIVE_TIMEOUT > ; ; return value to user ; mov cx, ax clc done: .leave ret noTimeout: mov cx,-1 clc jmp done timeout: stc jmp done SocketGetTimeout endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlStartRead %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Start reading the control block CALLED BY: (INTERNAL) ECCheckOutgoingPacket, ECCheckSocket, ReceiveLinkDataPacket, SocketCheckListen, SocketCheckMediumConnection, SocketDataPacket, SocketGetPeerName, SocketGetSocketName, SocketLinkPacket, SocketRecv, SocketRecvLow, SocketSend PASS: nothing RETURN: ds - control segment DESTROYED: nothing SIDE EFFECTS: may block PSEUDO CODE/STRATEGY: Reading is permitted as long as no thread is currently modifying the data structures. REVISION HISTORY: Name Date Description ---- ---- ----------- EW 4/26/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlStartRead proc far uses ax,bx,es pushf .enter ; ; lock the control segment ; mov bx, handle SocketControl call MemLockShared mov ds,ax ; ; record lock ; mov bx, handle dgroup call MemDerefES mov es:[lockType], SCLT_READ done:: .leave popf ret SocketControlStartRead endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlEndRead %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Stop reading the control block CALLED BY: (INTERNAL) ECCheckOutgoingPacket, ECCheckSocket, ReceiveLinkDataPacket, SocketCheckListen, SocketCheckMediumConnection, SocketDataPacket, SocketLinkGetMediumForLink, SocketLinkPacket, SocketPassOption, SocketQueryAddress, SocketRecv, SocketRecvLow, SocketSend PASS: nothing RETURN: nothing (flags preserved) DESTROYED: if EC and segment error checking on, and either DS or ES is the control segment, it will be replaced by NULL_SEGMENT SIDE EFFECTS: PSEUDO CODE/STRATEGY: If this is the last reader, allow writers in again. REVISION HISTORY: Name Date Description ---- ---- ----------- EW 4/26/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlEndRead proc far uses bx .enter ; ; unlock the control block ; mov bx, handle SocketControl call MemUnlockShared .leave ret SocketControlEndRead endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlStartWrite %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Start an update to the control block CALLED BY: (INTERNAL) CloseLinkThread, ConnectionControlReply, FreeListenQueueCallback, ReceiveUrgentDataPacket, RemoveDomainThread, SocketAccept, SocketActivateLoadOnMsg, SocketAddDomain, SocketAddLoadOnMsgMem, SocketBind, SocketBindInDomain, SocketCheckMediumConnection, SocketCheckReady, SocketClearConnection, SocketClose, SocketCloseDomainMedium, SocketCloseLink, SocketCloseSend, SocketConnect, SocketConnectRequest, SocketConnectionClosed, SocketCreate, SocketCreateLink, SocketDataConnect, SocketDataGetInfo, SocketFullClose, SocketGetAddressController, SocketGetAddressMedium, SocketGetAddressSize, SocketGetDomainMedia, SocketGetSocketOption, SocketInterrupt, SocketLinkClosed, SocketLinkGetMediumForLink, SocketLinkOpened, SocketListen, SocketLoadDriver, SocketLockForCreateLink, SocketOpenDomainMedium, SocketPassOption, SocketPostDataAccept, SocketPreAccept, SocketQueryAddress, SocketRemoveDomainLow, SocketRemoveLoadOnMsgMem, SocketResolve, SocketSendClose, SocketSetSocketOption PASS: nothing RETURN: ds - control segment DESTROYED: nothing (flags preserved) SIDE EFFECTS: PSEUDO CODE/STRATEGY: Writing is permitted only when no other thread is reading or writing the control block. REVISION HISTORY: Name Date Description ---- ---- ----------- EW 4/26/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlStartWrite proc far pushf uses ax,bx,es .enter ; ; lock the control block ; mov bx, handle SocketControl call MemLockExcl mov ds,ax ; ; record lock ; mov bx, handle dgroup call MemDerefES mov es:[lockType], SCLT_WRITE .leave popf ret SocketControlStartWrite endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlEndWrite %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: End an update to the control block CALLED BY: (INTERNAL) CloseLinkThread, ConnectionControlReply, FreeListenQueueCallback, ReceiveUrgentDataPacket, RemoveDomainThread, SocketAccept, SocketActivateLoadOnMsg, SocketAddDomain, SocketAddLoadOnMsgMem, SocketBind, SocketBindInDomain, SocketCheckMediumConnection, SocketCheckReady, SocketClearConnection, SocketClose, SocketCloseDomainMedium, SocketCloseLink, SocketCloseSend, SocketConnect, SocketConnectRequest, SocketConnectionClosed, SocketCreate, SocketCreateLink, SocketDataConnect, SocketDataGetInfo, SocketFullClose, SocketGetAddressController, SocketGetAddressMedium, SocketGetAddressSize, SocketGetDomainMedia, SocketGetPeerName, SocketGetSocketName, SocketGetSocketOption, SocketInterrupt, SocketLinkClosed, SocketLinkOpened, SocketListen, SocketLoadDriver, SocketLockForCreateLink, SocketOpenDomainMedium, SocketPostDataAccept, SocketPreAccept, SocketRemoveDomainLow, SocketRemoveLoadOnMsgMem, SocketResolve, SocketSendClose, SocketSetSocketOption PASS: nothing RETURN: nothing (flags preserved) DESTROYED: if EC and segment error checking on, and either DS or ES is the control segment, it will be replaced by NULL_SEGMENT SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 4/26/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlEndWrite proc far uses bx .enter mov bx, handle SocketControl call MemUnlockExcl .leave ret SocketControlEndWrite endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlReadToWrite %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Upgrade our control block lock CALLED BY: (INTERNAL) ReceiveConnectionControlPacket, SocketSend PASS: nothing RETURN: ds, es = fixed up to possibly new block location, if they were pointing to the block on entry. DESTROYED: nothing (flags preserved) SIDE EFFECTS: If the block is locked shared by other threads, this will block and the memory block may move on the heap before exclusive access is granted. PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 7/ 1/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlReadToWrite proc far uses ax,bx,dx pushf .enter ; ; upgrade the lock ; mov bx, handle SocketControl call MemUpgradeSharedLock ; ; update the lock type in dgroup ; push es mov bx, handle dgroup call MemDerefES mov es:[lockType], SCLT_WRITE pop es .leave popf ret SocketControlReadToWrite endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlWriteToRead %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: downgrade our control block lock CALLED BY: (INTERNAL) ReceiveConnectionControlPacket, SocketLinkGetMediumForLink PASS: nothing RETURN: nothing DESTROYED: nothing (flags preserved) SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 7/ 1/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlWriteToRead proc far uses ax,bx pushf .enter mov bx, handle SocketControl call MemDowngradeExclLock push es mov bx, handle dgroup call MemDerefES mov es:[lockType], SCLT_READ pop es .leave popf ret SocketControlWriteToRead endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlSuspendLock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Release either a read or write lock CALLED BY: (INTERNAL) SocketEnqueue, SocketSend PASS: nothing RETURN: ax - data for SocketControlResumeLock DESTROYED: Non-EC: Nothing (flags preserved) EC: Nothing (flags preserved), except, possibly for DS and ES: If segment error-checking is on, and either DS or ES is pointing to a block that has become unlocked, then this register will be set to NULL_SEGMENT upon return from this procedure. SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 8/ 2/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlSuspendLock proc far pushf uses bx .enter ; ; get lock type ; push es mov bx, handle dgroup call MemDerefES mov ax, es:[lockType] pop es ; ; unlock block ; mov bx, handle SocketControl call MemUnlockShared .leave popf ret SocketControlSuspendLock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketControlResumeLock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Restore the lock on the control segment suspended earlier CALLED BY: (INTERNAL) SocketEnqueue, SocketSend PASS: ax - data from SocketControlSuspendLock RETURN: ds - control segment DESTROYED: nothing - flags preserved SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 8/ 2/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketControlResumeLock proc far pushf uses ax,bx,dx,es .enter ; ; get dgroup ; mov bx, handle dgroup call MemDerefES ; ; do the appropriate lock ; mov bx, handle SocketControl cmp ax, SCLT_READ je read call MemLockExcl mov es:[lockType], SCLT_WRITE jmp pastLock read: call MemLockShared mov es:[lockType], SCLT_READ pastLock: ; ; return segment ; mov ds,ax .leave popf ret SocketControlResumeLock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketCheckQueue %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: See if there are any packets in a queue CALLED BY: (EXTERNAL) SocketCheckReadyHere, SocketRecvLow PASS: ds:di - SocketInfo RETURN: carry - set if queue is empty DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 10/ 8/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketCheckQueue proc far uses bx,cx,si,di,ds .enter mov bx, handle SocketQueues mov si, ds:[di].SI_dataQueue mov cx, NO_WAIT call QueueDequeueLock ; ds:di = element jc done call QueueAbortDequeue clc done: .leave ret SocketCheckQueue endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketEnqueue %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Put a packet onto a queue CALLED BY: (EXTERNAL) ReceiveDatagramDataPacket, ReceiveLinkDataPacket, ReceiveSequencedDataPacket PASS: ds:si - SocketInfo cxdx - packet ax - packet size control block must be locked RETURN: carry - set on error ds - control segment dxcx - size remaining in queue DESTROYED: nothing SIDE EFFECTS: may invalidate control block pointers PSEUDO CODE/STRATEGY: If queue is full, will wait indefinately for it for something to be dequeued. In this case, the control block will be unlocked and other threads can manipulate it. REVISION HISTORY: Name Date Description ---- ---- ----------- EW 8/ 3/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketEnqueue proc far uses ax,bx,bp,di,es .enter ; ; If discard flag is set, just drop the packet, and set ; the return values as if the queue was empty. In fact, there ; is probably still data in there, but since we are discarding ; we will never actually fill the queue. ; test ds:[si].SI_flags, mask SF_DISCARD jz enqueue movdw axcx, cxdx call HugeLMemFree movdw dxcx, ds:[si].SI_maxQueueSize jmp abort ; ; compute space remaining in queue ; enqueue: clr bx adddw ds:[si].SI_curQueueSize, bxax movdw bxax, ds:[si].SI_maxQueueSize subdw bxax, ds:[si].SI_curQueueSize jnc sizeOK clrdw bxax ; cur > max sizeOK: pushdw bxax ; ; find the queue ; mov si, ds:[si].SI_dataQueue EC < tst si > EC < ERROR_Z CORRUPT_SOCKET > mov bx, handle SocketQueues ; ^lbx:si = queue ; ; try to lock the queue ; mov bp,cx ; ^lbp:dx = packet mov cx, RESIZE_QUEUE call QueueEnqueueLock ; ds:di = element jc lockFailed ; ; insert element and unlock ; movdw ds:[di], bpdx call QueueEnqueueUnlock ; ; get control segment ; mov bx, handle SocketControl call MemDerefDS done: popdw dxcx abort: .leave ret lockFailed: ; ; we should only be here because the queue couldn't be resized ; EC < cmp cx, QE_TOO_BIG > EC < ERROR_NE UNEXPECTED_QUEUE_ERROR > ; ; release control segment and lock queue ; call SocketControlSuspendLock mov cx, FOREVER_WAIT call QueueEnqueueLock movdw ds:[di], bpdx ; write queue elt ; ; release queue and relock control segment ; call QueueEnqueueUnlock call SocketControlResumeLock jmp done SocketEnqueue endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketDequeuePackets %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Pop some packets off the queue CALLED BY: (EXTERNAL) SocketGetData PASS: ^lbx:si - queue cx - number of packets to dequeue RETURN: cx - combined size of packet chunks DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 8/ 3/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketDequeuePackets proc far uses dx,bp,di,ds .enter clr bp jcxz done mov dx,cx top: ; ; pop one element from the queue ; mov cx, RESIZE_QUEUE call QueueDequeueLock ; ds:di = element ERROR_C UNEXPECTED_QUEUE_ERROR movdw axcx, ds:[di] call HugeLMemFree add bp,cx call QueueDequeueUnlock ; ; repeat until done ; dec dx jnz top done: mov cx,bp .leave ret SocketDequeuePackets endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketAllocQueue %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Allocate a data queue for a socket CALLED BY: (EXTERNAL) SocketBindLow, SocketConnect, SocketDataConnect, SocketPostDataAccept, SocketPostLinkAccept PASS: ds - control segment *ds:bx - SocketInfo RETURN: carry set if allocation failed DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 8/ 2/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketAllocQueue proc far uses ax,bx,cx,dx,si,di .enter ; ; validate ; mov si, bx EC < call ECCheckSocketLow > ; ; figure out the maximum combined space of the send and receive ; queues, in Kilobytes ; mov di, ds:[si] EC < tst ds:[di].SI_maxQueueSize.high > EC < ERROR_NZ UNREASONABLE_QUEUE_SIZE > mov ax, ds:[di].SI_maxQueueSize.low add ax, ds:[di].SI_maxSendSize ; might overflow so... rcr ax ; bring carry back in mov cl, 9 shr ax, cl ; rotate 9 more times mov cx, ax ; cx = size in KB ; ; There are two advantages to reserving heap space in the name ; of the UI, rather than whatever thread we happen to be on: ; 1. this thread may belong to a non-application geode ; 2. we don't have to worry about changing the reservation ; if the socket owner changes ; mov ax, SGIT_UI_PROCESS call SysGetInfo ; ax = UI geode han ; ; reserve heap space for the queue size determined above ; request:: mov bx, ax call GeodeRequestSpace jnc requestOK WARNING CANT_RESERVE_SPACE clr ds:[di].SI_queueToken jmp alloc requestOK: mov ds:[di].SI_queueToken, bx ; ; allocate the queue ; alloc: mov bx, handle SocketQueues mov ax, size optr ; queue of optrs mov cl, INITIAL_DATA_QUEUE_LENGTH ; initial length mov dx, MAX_DATA_QUEUE_LENGTH ; max length call QueueLMemCreate ; ^hbx:cx = queue jc failed ; ; store it in socket and return ; mov ds:[di].SI_dataQueue, cx done: .leave ret ; ; if we couldn't allocate, return the space we reserved ; failed: mov bx, ds:[di].SI_queueToken call GeodeReturnSpace stc jmp done SocketAllocQueue endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketFreeQueue %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Free a socket's data queue CALLED BY: SocketFreeLow, SocketDataConnect, SocketFreeLow, SocketRegisterConnection PASS: *ds:bx - SocketInfo RETURN: nothing DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/23/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketFreeQueue proc far uses bx,cx,si .enter ; ; check the socket ; EC < mov si, bx > EC < call ECCheckSocketLow > ; ; locate the queue ; mov si, ds:[bx] clr cx xchg cx, ds:[si].SI_dataQueue jcxz done ; ; clear any remaining packets ; push bx mov bx, handle SocketQueues mov si, cx mov cx, SEGMENT_CS mov dx, offset SocketFreeQueueCallback call QueueEnum ; ; free the queue ; mov cx, si ; ^lbx:cx = queue call QueueLMemDestroy ; ; release any reservations ; pop bx ; *ds:bx = socket mov si, ds:[bx] clr bx xchg bx, ds:[si].SI_queueToken tst bx jz done call GeodeReturnSpace done: .leave ret SocketFreeQueue endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SocketFreeQueueCallback %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Free a packet from a queue CALLED BY: SocketFreeQueue (via QueueEnum) PASS: es:si - current element RETURN: carry set to abort enum DESTROYED: ax SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 3/ 4/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SocketFreeQueueCallback proc far uses cx .enter movdw axcx, es:[si] call HugeLMemFree clc .leave ret SocketFreeQueueCallback endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DomainNameToIniCat %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Translate a domain name (DBCS) to a .INI category name (SBCS) CALLED BY: (GLOBAL) ConvDomainNameToIniCat PASS: ds:si = Domain name RETURN: ds:si = .INI category DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: Users of ConvDomainNameToIniCat must also have a corresponding incantation of ConvDomainNameDone. If you change this, see also DomainNameToIniCat() in: Library/Config/Pref/prefClass.asm REVISION HISTORY: Name Date Description ---- ---- ----------- VM 12/ 7/93 Initial version eca 7/8/94 re-named, re-wrote %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DomainNameToIniCat proc far DBCS < call DomainNameToIniCatLow > ret DomainNameToIniCat endp if DBCS_PCGEOS DomainNameToIniCatLow proc near uses ax, bx, cx, dx, es, di .enter ; ; Allocate a buffer for the .INI category ; mov ax, (size DomainNameStruct) mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK call MemAlloc push bx mov es, ax clr di CheckHack <(offset DNS_blockHandle) eq 0> mov ax, bx ;ax <- block handle stosw CheckHack <(offset DNS_namePtr.low) eq 2> mov ax, si stosw CheckHack <(offset DNS_namePtr.high) eq 4> mov ax, ds stosw CheckHack <(offset DNS_iniCat) eq 6> ; ; Convert the string into SBCS ; clr cx ;cx <- length (SBCS) push di charLoop: LocalGetChar ax, dssi ;ax <- character LocalCmpChar ax, 0x80 ;ASCII? jbe gotChar ;branch if so ; ; For non-ASCII, stick in a couple of hex digits. The digits aren't ; in the correct order and they aren't all there, but it doesn't ; matter as long as they are consistent ; call toHexDigits DBCS < mov al, ah ;al <- high byte > DBCS < call toHexDigits > jmp charLoop gotChar: stosb ;store SBCS character inc cx ;cx <- one more character tst al jnz charLoop ; ; Return ds:si as a ptr to the .INI category name ; segmov ds, es ;ds:si <- ptr to category name pop si pop bx ;bx <- buffer handle .leave ret toHexDigits: push ax ; ; Second hex digit ; push ax andnf al, 0x0f ;al <- low nibble call convHexDigit pop ax ; ; First hex digit ; shr al, 1 shr al, 1 shr al, 1 shr al, 1 ;al <- high nibble call convHexDigit pop ax retn convHexDigit: add al, '0' cmp al, '9' jbe gotDig add al, 'A'-'9'-1 gotDig: stosb inc cx ;cx <- one more character retn DomainNameToIniCatLow endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DomainNameDone %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Done with domain .INI category name from DomainNameToIniCat() CALLED BY: (GLOBAL) ConvDomainNameDone PASS: ds:si - .INI category RETURN: ds:si - registers passed to DomainNameToIniCat DESTROYED: none (flags preserved) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 7/ 8/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DomainNameDone proc far DBCS < call DomainNameDoneLow > ret DomainNameDone endp if DBCS_PCGEOS DomainNameDoneLow proc near uses bx .enter pushf mov bx, ds:DNS_blockHandle ;bx <- our handle mov si, ds:DNS_namePtr.low mov ds, ds:DNS_namePtr.high ;ds:si <- ori. ptr call MemFree popf .leave ret DomainNameDoneLow endp endif UtilCode ends
; A100102: 2^(2*n)-(2*n-1). ; 2,3,13,59,249,1015,4085,16371,65521,262127,1048557,4194283,16777193,67108839,268435429,1073741795,4294967265,17179869151,68719476701,274877906907,1099511627737,4398046511063,17592186044373,70368744177619 mul $0,2 mov $1,2 pow $1,$0 sub $1,$0 add $1,1 mov $0,$1
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { if (root == NULL) { return res; } dfs(root, sum, 0); return res; } vector<vector<int>> res; vector<int> vec; void dfs(TreeNode* root, int sum, int ans) { if (root == NULL) { return; } ans += root->val; vec.push_back(root->val); if (root->left == NULL && root->right == NULL) { if (sum == ans) { res.push_back(vec); } vec.pop_back(); return; } dfs(root->left, sum, ans); dfs(root->right, sum, ans); vec.pop_back(); } };
; 2018 July feilipu SECTION code_clib SECTION code_math PUBLIC l_z80n_mulu_40_32x8 l_z80n_mulu_40_32x8: ; multiplication of 32-bit number and 8-bit number into a 40-bit product ; ; enter : a = 8-bit multiplier = x ; dehl = 32-bit multiplicand = y ; ; exit : adehl = 40-bit product ; carry reset ; ; uses : af, bc, de, hl, af' ld b,d ; relocate DE ld c,e ld e,l ; x0 ld d,a mul de ; y*x0 ex af,af ;'accumulator ld l,e ;'p0 ld a,d ;'p1 carry ex af,af ld e,h ; x1 ld d,a mul de ; y*x1 ex af,af add a,e ld h,a ;'p1 ld a,d ;'p2 carry ex af,af ld e,c ld d,a mul de ; y*x2 ex af,af adc a,e ld c,a ;'p2 ld a,d ;'p3 carry ex af,af ld e,b ld d,a mul de ; y*x3 ex af,af adc a,e ld b,a ;'p3 ld a,d ;'p4 carry adc a,0 ;'final carry ld d,b ; return DE ld e,c ret
; A133086: Row sums of triangle A133085. ; 1,4,10,26,64,152,352,800,1792,3968,8704,18944,40960,88064,188416,401408,851968,1802240,3801088,7995392,16777216,35127296,73400320,153092096,318767104,662700032,1375731712,2852126720,5905580032,12213813248,25232932864,52076478464,107374182400,221190815744,455266533376,936302870528,1924145348608,3951369912320,8108898254848,16630113370112,34084860461056,69818988363776,142936511610880,292470092988416,598134325510144,1222656930086912,2498090418307072,5101733952880640 mov $2,3 mov $3,$0 add $3,1 add $3,$0 mov $1,$3 add $1,$0 sub $0,1 lpb $0 sub $0,1 add $1,$2 mov $2,$1 lpe
; A040683: Continued fraction for sqrt(710). ; Submitted by Jamie Morken(s3.) ; 26,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1,52,1,1,1,4,1,1,1 mov $1,126 mov $2,$0 dif $2,2 lpb $0 mov $0,0 mov $1,4 gcd $1,$2 pow $1,4 lpe div $1,5 mov $0,$1 add $0,1
/*************************************************************************** * base.cpp is part of Math gric Library * Copyright (C) 2007-2014 Alexey Balakin <mathgl.abalakin@gmail.ru> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "mgl2/font.h" #include "mgl2/base_cf.h" #include "mgl2/base.h" //----------------------------------------------------------------------------- // // C interfaces // //----------------------------------------------------------------------------- bool mglPrintWarn = true; void MGL_EXPORT mgl_suppress_warn(int on) { mglPrintWarn = !on; } void MGL_EXPORT mgl_suppress_warn_(int *on) { mgl_suppress_warn(*on); } void MGL_EXPORT mgl_set_quality(HMGL gr, int qual) { gr->SetQuality(qual); } void MGL_EXPORT mgl_set_quality_(uintptr_t *gr, int *qual) { _GR_->SetQuality(*qual); } int MGL_EXPORT_PURE mgl_get_quality(HMGL gr) { return gr->GetQuality(); } int MGL_EXPORT_PURE mgl_get_quality_(uintptr_t *gr) { return _GR_->GetQuality(); } int MGL_EXPORT_PURE mgl_is_frames(HMGL gr) { return gr->get(MGL_VECT_FRAME) && !(gr->GetQuality()&MGL_DRAW_LMEM); } void MGL_EXPORT mgl_set_draw_reg(HMGL gr, long nx, long ny, long m) { gr->SetDrawReg(nx,ny,m); } void MGL_EXPORT mgl_set_draw_reg_(uintptr_t *gr, int *nx, int *ny, int *m) { _GR_->SetDrawReg(*nx,*ny,*m); } //----------------------------------------------------------------------------- int MGL_EXPORT_PURE mgl_get_flag(HMGL gr, uint32_t flag) { return gr->get(flag); } int MGL_EXPORT_PURE mgl_get_flag_(uintptr_t *gr, unsigned long *flag) { return _GR_->get(*flag); } void MGL_EXPORT mgl_set_flag(HMGL gr, int val, uint32_t flag) { gr->set(val,flag); } void MGL_EXPORT mgl_set_flag_(uintptr_t *gr, int *val, unsigned long *flag) { _GR_->set(*val,*flag); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_color(char id, double r, double g, double b) { for(long i=0;mglColorIds[i].id;i++) if(mglColorIds[i].id==id) mglColorIds[i].col = mglColor(r,g,b); } void MGL_EXPORT mgl_set_color_(char *id, mreal *r, mreal *g, mreal *b, int) { mgl_set_color(*id,*r,*g,*b); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_def_sch(HMGL gr, const char *sch) { gr->SetDefScheme(sch); } void MGL_EXPORT mgl_set_def_sch_(uintptr_t *gr, const char *sch,int l) { char *s=new char[l+1]; memcpy(s,sch,l); s[l]=0; mgl_set_def_sch(_GR_, s); delete []s; } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_plotid(HMGL gr, const char *id) { gr->PlotId = id; } void MGL_EXPORT mgl_set_plotid_(uintptr_t *gr, const char *id,int l) { char *s=new char[l+1]; memcpy(s,id,l); s[l]=0; _GR_->PlotId = s; delete []s; } MGL_EXPORT_PURE const char *mgl_get_plotid(HMGL gr) { return gr->PlotId.c_str(); } int MGL_EXPORT mgl_get_plotid_(uintptr_t *gr, char *out, int len) { const char *res = mgl_get_plotid(_GR_); if(out) strncpy(out,res,len); return strlen(res); } //----------------------------------------------------------------------------- MGL_EXPORT_PURE const char *mgl_get_mess(HMGL gr) { return gr->Mess.c_str(); } int MGL_EXPORT mgl_get_mess_(uintptr_t *gr, char *out, int len) { const char *res = mgl_get_mess(_GR_); if(out) strncpy(out,res,len); return strlen(res); } int MGL_EXPORT_PURE mgl_get_warn(HMGL gr) { return gr->GetWarn(); } void MGL_EXPORT mgl_set_warn(HMGL gr, int code, const char *txt) { gr->SetWarn(code,txt); } extern bool mglPrintWarn; void MGL_EXPORT mgl_set_global_warn(const char *txt) { if(txt && *txt) { mglGlobalMess += txt; mglGlobalMess += '\n'; if(mglPrintWarn) fprintf(stderr,"Global message - %s\n",txt); } } void MGL_EXPORT mgl_set_global_warn_(const char *txt, int l) { char *s=new char[l+1]; memcpy(s,txt,l); s[l]=0; mgl_set_global_warn(s); delete []s; } MGL_EXPORT_PURE const char *mgl_get_global_warn() { return mglGlobalMess.c_str(); } int MGL_EXPORT mgl_get_global_warn_(char *out, int len) { const char *res = mgl_get_global_warn(); if(out) strncpy(out,res,len); return strlen(res); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_origin(HMGL gr, double x0, double y0, double z0) { gr->SetOrigin(x0,y0,z0); } void MGL_EXPORT mgl_set_palette(HMGL gr, const char *colors) { gr->SetPalette(colors); } void MGL_EXPORT mgl_set_meshnum(HMGL gr, int num) { gr->SetMeshNum(num); } void MGL_EXPORT mgl_set_facenum(HMGL gr, int num) { gr->FaceNum=num; } void MGL_EXPORT mgl_set_alpha_default(HMGL gr, double alpha) { gr->SetAlphaDef(alpha); } void MGL_EXPORT mgl_set_light_dif(HMGL gr, int enable) { gr->SetDifLight(enable); } void MGL_EXPORT mgl_clear_unused(HMGL gr) { gr->ClearUnused(); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_rdc_acc(HMGL gr, int reduce) { gr->SetReduceAcc(reduce); } void MGL_EXPORT mgl_highlight(HMGL gr, int id) { gr->Highlight(id); } void MGL_EXPORT mgl_set_cut(HMGL gr, int cut) { gr->SetCut(cut); } void MGL_EXPORT mgl_set_cut_box(HMGL gr, double x1,double y1,double z1,double x2,double y2,double z2) { gr->SetCutBox(x1,y1,z1,x2,y2,z2); } void MGL_EXPORT mgl_set_cutoff(HMGL gr, const char *EqC) { gr->CutOff(EqC); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_ternary(HMGL gr, int enable) { gr->Ternary(enable); } void MGL_EXPORT mgl_set_range_val(HMGL gr, char dir, double v1,double v2) { if(dir=='c' || dir=='a') gr->CRange(v1,v2); else if(dir=='x') gr->XRange(v1,v2); else if(dir=='y') gr->YRange(v1,v2); else if(dir=='z') gr->ZRange(v1,v2); } void MGL_EXPORT mgl_add_range_val(HMGL gr, char dir, double v1,double v2) { if(dir=='c' || dir=='a') gr->CRange(v1,v2,true); else if(dir=='x') gr->XRange(v1,v2,true); else if(dir=='y') gr->YRange(v1,v2,true); else if(dir=='z') gr->ZRange(v1,v2,true); } void MGL_EXPORT mgl_set_range_dat(HMGL gr, char dir, HCDT a, int add) { if(dir=='c' || dir=='a') gr->CRange(a,add); else if(dir=='x') gr->XRange(a,add); else if(dir=='y') gr->YRange(a,add); else if(dir=='z') gr->ZRange(a,add); } void MGL_EXPORT mgl_set_ranges(HMGL gr, double x1, double x2, double y1, double y2, double z1, double z2) { gr->SetRanges(x1,x2,y1,y2,z1,z2); } void MGL_EXPORT mgl_set_auto_ranges(HMGL gr, double x1, double x2, double y1, double y2, double z1, double z2, double c1, double c2) { gr->SetAutoRanges(x1,x2,y1,y2,z1,z2,c1,c2); } void MGL_EXPORT mgl_set_func(HMGL gr, const char *EqX,const char *EqY,const char *EqZ,const char *EqA) { gr->SetFunc(EqX,EqY,EqZ,EqA); } void MGL_EXPORT mgl_set_coor(HMGL gr, int how) { gr->SetCoor(how); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_bar_width(HMGL gr, double width) { gr->SetBarWidth(width); } //----------------------------------------------------------------------------- // // Fortran interfaces // //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_rdc_acc_(uintptr_t *gr, int *reduce) { _GR_->SetReduceAcc(*reduce); } void MGL_EXPORT mgl_highlight_(uintptr_t *gr, int *id) { _GR_->Highlight(*id); } void MGL_EXPORT mgl_set_origin_(uintptr_t *gr, mreal *x0, mreal *y0, mreal *z0) { _GR_->SetOrigin(*x0,*y0,*z0); } int MGL_EXPORT_PURE mgl_get_warn_(uintptr_t *gr) { return _GR_->GetWarn(); } void MGL_EXPORT mgl_set_warn_(uintptr_t *gr, int *code, const char *txt, int l) { char *s=new char[l+1]; memcpy(s,txt,l); s[l]=0; _GR_->SetWarn(*code, s); delete []s; } void MGL_EXPORT mgl_set_palette_(uintptr_t *gr, const char *colors, int l) { char *s=new char[l+1]; memcpy(s,colors,l); s[l]=0; _GR_->SetPalette(s); delete []s; } void MGL_EXPORT mgl_set_meshnum_(uintptr_t *gr, int *num) { _GR_->SetMeshNum(*num); } void MGL_EXPORT mgl_set_facenum_(uintptr_t *gr, int *num) { _GR_->FaceNum=*num; } void MGL_EXPORT mgl_set_alpha_default_(uintptr_t *gr, mreal *alpha) { _GR_->SetAlphaDef(*alpha); } void MGL_EXPORT mgl_set_light_dif_(uintptr_t *gr, int *enable) { _GR_->SetDifLight(*enable); } void MGL_EXPORT mgl_clear_unused_(uintptr_t *gr) { _GR_->ClearUnused(); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_cut_box_(uintptr_t *gr, mreal *x1, mreal *y1, mreal *z1, mreal *x2, mreal *y2, mreal *z2) { _GR_->SetCutBox(*x1,*y1,*z1,*x2,*y2,*z2); } void MGL_EXPORT mgl_set_cut_(uintptr_t *gr, int *cut) { _GR_->SetCut(*cut); } void MGL_EXPORT mgl_set_cutoff_(uintptr_t *gr, const char *EqC, int l) { char *s=new char[l+1]; memcpy(s,EqC,l); s[l]=0; _GR_->CutOff(s); delete []s; } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_ternary_(uintptr_t *gr, int *enable) { _GR_->Ternary(*enable); } void MGL_EXPORT mgl_set_range_val_(uintptr_t *gr, const char *dir, mreal *v1, mreal *v2,int) { mgl_set_range_val(_GR_,*dir,*v1,*v2); } void MGL_EXPORT mgl_add_range_val_(uintptr_t *gr, const char *dir, mreal *v1, mreal *v2,int) { mgl_add_range_val(_GR_,*dir,*v1,*v2); } void MGL_EXPORT mgl_set_range_dat_(uintptr_t *gr, const char *dir, uintptr_t *a, int *add,int) { mgl_set_range_dat(_GR_,*dir,_DA_(a),*add); } void MGL_EXPORT mgl_set_ranges_(uintptr_t *gr, mreal *x1, mreal *x2, mreal *y1, mreal *y2, mreal *z1, mreal *z2) { _GR_->SetRanges(*x1,*x2,*y1,*y2,*z1,*z2); } void MGL_EXPORT mgl_set_auto_ranges_(uintptr_t *gr, mreal *x1, mreal *x2, mreal *y1, mreal *y2, mreal *z1, mreal *z2, mreal *c1, mreal *c2) { _GR_->SetAutoRanges(*x1,*x2,*y1,*y2,*z1,*z2,*c1,*c2); } void MGL_EXPORT mgl_set_func_(uintptr_t *gr, const char *EqX,const char *EqY,const char *EqZ,const char *EqA,int lx,int ly,int lz,int la) { char *sx=new char[lx+1]; memcpy(sx,EqX,lx); sx[lx]=0; char *sy=new char[ly+1]; memcpy(sy,EqY,ly); sy[ly]=0; char *sz=new char[lz+1]; memcpy(sz,EqZ,lz); sz[lz]=0; char *sa=new char[la+1]; memcpy(sa,EqA,la); sa[la]=0; _GR_->SetFunc(sx,sy,sz,sa); delete []sx; delete []sy; delete []sz; delete []sa; } void MGL_EXPORT mgl_set_coor_(uintptr_t *gr, int *how) { _GR_->SetCoor(*how); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_tick_rotate(HMGL gr, int enable){ gr->SetTickRotate(enable); } void MGL_EXPORT mgl_set_tick_skip(HMGL gr, int enable) { gr->SetTickSkip(enable); } void MGL_EXPORT mgl_set_tick_rotate_(uintptr_t *gr,int *enable){ _GR_->SetTickRotate(*enable); } void MGL_EXPORT mgl_set_tick_skip_(uintptr_t *gr, int *enable) { _GR_->SetTickSkip(*enable); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_rotated_text(HMGL gr, int enable) { gr->SetRotatedText(enable); } void MGL_EXPORT mgl_set_mark_size(HMGL gr, double size) { gr->SetMarkSize(size); } void MGL_EXPORT mgl_set_arrow_size(HMGL gr, double size) { gr->SetArrowSize(size); } void MGL_EXPORT mgl_set_font_size(HMGL gr, double size) { gr->SetFontSize(size); } void MGL_EXPORT mgl_set_font_def(HMGL gr, const char *fnt) { gr->SetFontDef(fnt); } void MGL_EXPORT mgl_load_font(HMGL gr, const char *name, const char *path) { gr->LoadFont(name,path); } void MGL_EXPORT mgl_copy_font(HMGL gr, HMGL gr_from) { gr->CopyFont(gr_from); } void MGL_EXPORT mgl_restore_font(HMGL gr) { gr->RestoreFont(); } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_set_bar_width_(uintptr_t *gr, mreal *width) { _GR_->SetBarWidth(*width); } void MGL_EXPORT mgl_set_rotated_text_(uintptr_t *gr, int *rotated) { _GR_->SetRotatedText(*rotated); } void MGL_EXPORT mgl_set_mark_size_(uintptr_t *gr, mreal *size) { _GR_->SetMarkSize(*size); } void MGL_EXPORT mgl_set_arrow_size_(uintptr_t *gr, mreal *size) { _GR_->SetArrowSize(*size); } void MGL_EXPORT mgl_set_font_size_(uintptr_t *gr, mreal *size) { _GR_->SetFontSize(*size); } void MGL_EXPORT mgl_set_font_def_(uintptr_t *gr, const char *name, int l) { char *s=new char[l+1]; memcpy(s,name,l); s[l]=0; _GR_->SetFontDef(s); delete []s; } void MGL_EXPORT mgl_load_font_(uintptr_t *gr, char *name, char *path, int l,int n) { char *s=new char[l+1]; memcpy(s,name,l); s[l]=0; char *d=new char[n+1]; memcpy(d,path,n); d[n]=0; _GR_->LoadFont(s,d); delete []s; delete []d; } void MGL_EXPORT mgl_copy_font_(uintptr_t *gr, uintptr_t *gr_from) { _GR_->CopyFont((mglBase *)(*gr_from)); } void MGL_EXPORT mgl_restore_font_(uintptr_t *gr) { _GR_->RestoreFont(); } //----------------------------------------------------------------------------- extern mglFont mglDefFont; void MGL_EXPORT mgl_def_font(const char *name, const char *path) { mglDefFont.Load(name,path); } void MGL_EXPORT mgl_def_font_(const char *name, const char *path,int l,int n) { char *s=new char[l+1]; memcpy(s,name,l); s[l]=0; char *d=new char[n+1]; memcpy(d,path,n); d[n]=0; mglDefFont.Load(name,path); delete []s; delete []d; } //----------------------------------------------------------------------------- int MGL_EXPORT mgl_check_version(const char *ver) { double v=0; int r = sscanf(ver,"2.%lg",&v); return r<1 || v>MGL_VER2; } int MGL_EXPORT mgl_check_version_(const char *ver, int l) { char *s=new char[l+1]; memcpy(s,ver,l); s[l]=0; int r=mgl_check_version(s); delete []s; return r; } //----------------------------------------------------------------------------- void MGL_EXPORT mgl_start_group(HMGL gr, const char *s) { gr->StartAutoGroup(s); } void MGL_EXPORT mgl_end_group(HMGL gr) { gr->EndGroup(); } void MGL_EXPORT mgl_start_group_(uintptr_t *gr, const char *name,int l) { char *s=new char[l+1]; memcpy(s,name,l); s[l]=0; _GR_->StartAutoGroup(s); delete []s; } void MGL_EXPORT mgl_end_group_(uintptr_t *gr) { _GR_->EndGroup(); } //----------------------------------------------------------------------------- #include <stdarg.h> bool mglTestMode=false; void MGL_EXPORT mgl_test_txt(const char *str, ...) { if(mglTestMode) { char buf[256]; va_list lst; va_start(lst,str); vsnprintf(buf,256,str,lst); buf[255]=0; va_end(lst); printf("TEST: %s\n",buf); fflush(stdout); } } void MGL_EXPORT mgl_set_test_mode(int enable) { mglTestMode=enable; } //--------------------------------------------------------------------------- long MGL_EXPORT mgl_use_graph(HMGL gr, int inc) { if(!gr) return 0; gr->InUse+=inc; return gr->InUse; } long MGL_EXPORT mgl_use_graph_(uintptr_t *gr, int *inc) { return mgl_use_graph(_GR_,*inc); } //--------------------------------------------------------------------------- void MGL_EXPORT mgl_set_ambbr(HMGL gr, double i) { gr->SetAmbient(i); } void MGL_EXPORT mgl_set_ambbr_(uintptr_t *gr, mreal *i){ _GR_->SetAmbient(*i); } //--------------------------------------------------------------------------- void MGL_EXPORT mgl_set_difbr(HMGL gr, double i) { gr->SetDiffuse(i); } void MGL_EXPORT mgl_set_difbr_(uintptr_t *gr, mreal *i){ _GR_->SetDiffuse(*i); } //--------------------------------------------------------------------------- void MGL_EXPORT mgl_zoom_axis(HMGL gr, double x1,double y1,double z1,double c1,double x2,double y2,double z2,double c2) { gr->ZoomAxis(mglPoint(x1,y1,z1,c1), mglPoint(x2,y2,z2,c2)); } void MGL_EXPORT mgl_zoom_axis_(uintptr_t *gr, mreal *x1, mreal *y1, mreal *z1, mreal *c1, mreal *x2, mreal *y2, mreal *z2, mreal *c2) { _GR_->ZoomAxis(mglPoint(*x1,*y1,*z1,*c1), mglPoint(*x2,*y2,*z2,*c2)); } //--------------------------------------------------------------------------- extern uint64_t mgl_mask_def[16]; void MGL_EXPORT mgl_set_mask(char id, const char *mask) { const char *msk = MGL_MASK_ID, *s = mglchr(msk, id); if(s) { uint64_t val = (mask && *mask) ? strtoull(mask,NULL,16) : mgl_mask_def[s-msk]; mgl_mask_val[s-msk] = val; } } void MGL_EXPORT mgl_set_mask_(const char *id, const char *mask,int,int l) { char *s=new char[l+1]; memcpy(s,mask,l); s[l]=0; mgl_set_mask(*id,s); delete []s; } //--------------------------------------------------------------------------- void MGL_EXPORT mgl_set_mask_val(char id, uint64_t mask) { const char *msk = MGL_MASK_ID, *s = mglchr(msk, id); if(s) mgl_mask_val[s-msk]=mask; } void MGL_EXPORT mgl_set_mask_val_(const char *id, uint64_t *mask,int) { mgl_set_mask_val(*id,*mask); } //--------------------------------------------------------------------------- void MGL_EXPORT mgl_set_mask_angle(HMGL gr, int angle) { gr->SetMaskAngle(angle); } void MGL_EXPORT mgl_set_mask_angle_(uintptr_t *gr, int *angle) { _GR_->SetMaskAngle(*angle); } //--------------------------------------------------------------------------- void MGL_EXPORT mgl_ask_stop(HMGL gr, int stop) { gr->AskStop(stop); } void MGL_EXPORT mgl_ask_stop_(uintptr_t *gr, int *stop){ _GR_->AskStop(*stop); } int MGL_EXPORT mgl_need_stop(HMGL gr) { return gr->NeedStop(); } int MGL_EXPORT mgl_need_stop_(uintptr_t *gr) { return _GR_->NeedStop();} void MGL_EXPORT mgl_set_event_func(HMGL gr, void (*func)(void *), void *par) { gr->SetEventFunc(func,par); } //---------------------------------------------------------------------------
CinnabarIslandObject: db $43 ; border block db $5 ; warps db $3, $6, $1, MANSION_1 db $3, $12, $0, CINNABAR_GYM db $9, $6, $0, CINNABAR_LAB_1 db $b, $b, $0, CINNABAR_POKECENTER db $b, $f, $0, CINNABAR_MART db $5 ; signs db $5, $9, $3 ; CinnabarIslandText3 db $b, $10, $4 ; MartSignText db $b, $c, $5 ; PokeCenterSignText db $b, $9, $6 ; CinnabarIslandText6 db $3, $d, $7 ; CinnabarIslandText7 db $2 ; objects object SPRITE_GIRL, $c, $5, WALK, $2, $1 ; person object SPRITE_GAMBLER, $e, $6, STAY, NONE, $2 ; person ; warp-to EVENT_DISP CINNABAR_ISLAND_WIDTH, $3, $6 ; MANSION_1 EVENT_DISP CINNABAR_ISLAND_WIDTH, $3, $12 ; CINNABAR_GYM EVENT_DISP CINNABAR_ISLAND_WIDTH, $9, $6 ; CINNABAR_LAB_1 EVENT_DISP CINNABAR_ISLAND_WIDTH, $b, $b ; CINNABAR_POKECENTER EVENT_DISP CINNABAR_ISLAND_WIDTH, $b, $f ; CINNABAR_MART
#include <assert.h> #include <fstream> #include "imageloader.h" using namespace std; Image::Image(char* ps, int w, int h) : pixels(ps), width(w), height(h) { } Image::~Image() { delete[] pixels; } namespace { //Converts a four-character array to an integer, using little-endian form int toInt(const char* bytes) { return (int)(((unsigned char)bytes[3] << 24) | ((unsigned char)bytes[2] << 16) | ((unsigned char)bytes[1] << 8) | (unsigned char)bytes[0]); } //Converts a two-character array to a short, using little-endian form short toShort(const char* bytes) { return (short)(((unsigned char)bytes[1] << 8) | (unsigned char)bytes[0]); } //Reads the next four bytes as an integer, using little-endian form int readInt(ifstream &input) { char buffer[4]; input.read(buffer, 4); return toInt(buffer); } //Reads the next two bytes as a short, using little-endian form short readShort(ifstream &input) { char buffer[2]; input.read(buffer, 2); return toShort(buffer); } //Just like auto_ptr, but for arrays template<class T> class auto_array { private: T* array; mutable bool isReleased; public: explicit auto_array(T* array_ = NULL) : array(array_), isReleased(false) { } auto_array(const auto_array<T> &aarray) { array = aarray.array; isReleased = aarray.isReleased; aarray.isReleased = true; } ~auto_array() { if (!isReleased && array != NULL) { delete[] array; } } T* get() const { return array; } T &operator*() const { return *array; } void operator=(const auto_array<T> &aarray) { if (!isReleased && array != NULL) { delete[] array; } array = aarray.array; isReleased = aarray.isReleased; aarray.isReleased = true; } T* operator->() const { return array; } T* release() { isReleased = true; return array; } void reset(T* array_ = NULL) { if (!isReleased && array != NULL) { delete[] array; } array = array_; } T* operator+(int i) { return array + i; } T &operator[](int i) { return array[i]; } }; } Image* loadBMP(const char* filename) { ifstream input; input.open(filename, ifstream::binary); assert(!input.fail() || !"Could not find file"); char buffer[2]; input.read(buffer, 2); assert(buffer[0] == 'B' && buffer[1] == 'M' || !"Not a bitmap file"); input.ignore(8); int dataOffset = readInt(input); //Read the header int headerSize = readInt(input); int width; int height; switch(headerSize) { case 40: //V3 width = readInt(input); height = readInt(input); input.ignore(2); assert(readShort(input) == 24 || !"Image is not 24 bits per pixel"); assert(readShort(input) == 0 || !"Image is compressed"); break; case 12: //OS/2 V1 width = readShort(input); height = readShort(input); input.ignore(2); assert(readShort(input) == 24 || !"Image is not 24 bits per pixel"); break; case 64: //OS/2 V2 assert(!"Can't load OS/2 V2 bitmaps"); break; case 108: //Windows V4 assert(!"Can't load Windows V4 bitmaps"); break; case 124: //Windows V5 assert(!"Can't load Windows V5 bitmaps"); break; default: assert(!"Unknown bitmap format"); } //Read the data int bytesPerRow = ((width * 3 + 3) / 4) * 4 - (width * 3 % 4); int size = bytesPerRow * height; auto_array<char> pixels(new char[size]); input.seekg(dataOffset, ios_base::beg); input.read(pixels.get(), size); //Get the data into the right format auto_array<char> pixels2(new char[width * height * 3]); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { for(int c = 0; c < 3; c++) { pixels2[3 * (width * y + x) + c] = pixels[bytesPerRow * y + 3 * x + (2 - c)]; } } } input.close(); return new Image(pixels2.release(), width, height); }
_TEXT SEGMENT PUBLIC co_swap co_swap PROC mov [rdx],rsp mov rsp,[rcx] pop rax mov [rdx+ 8],rbp mov [rdx+16],rsi mov [rdx+24],rdi mov [rdx+32],rbx mov [rdx+40],r12 mov [rdx+48],r13 mov [rdx+56],r14 mov [rdx+64],r15 movaps [rdx+ 80],xmm6 movaps [rdx+ 96],xmm7 movaps [rdx+112],xmm8 add rdx,112 movaps [rdx+ 16],xmm9 movaps [rdx+ 32],xmm10 movaps [rdx+ 48],xmm11 movaps [rdx+ 64],xmm12 movaps [rdx+ 80],xmm13 movaps [rdx+ 96],xmm14 movaps [rdx+112],xmm15 mov rbp,[rcx+ 8] mov rsi,[rcx+16] mov rdi,[rcx+24] mov rbx,[rcx+32] mov r12,[rcx+40] mov r13,[rcx+48] mov r14,[rcx+56] mov r15,[rcx+64] movaps xmm6, [rcx+ 80] movaps xmm7, [rcx+ 96] movaps xmm8, [rcx+112] add rcx,112 movaps xmm9, [rcx+ 16] movaps xmm10,[rcx+ 32] movaps xmm11,[rcx+ 48] movaps xmm12,[rcx+ 64] movaps xmm13,[rcx+ 80] movaps xmm14,[rcx+ 96] movaps xmm15,[rcx+112] jmp rax co_swap ENDP _TEXT ENDS END
//===- lib/MC/MCWin64EH.cpp - MCWin64EH implementation --------------------===// // // 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 "llvm/MC/MCWin64EH.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCObjectStreamer.h" #include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Win64EH.h" using namespace llvm; // NOTE: All relocations generated here are 4-byte image-relative. static uint8_t CountOfUnwindCodes(std::vector<WinEH::Instruction> &Insns) { uint8_t Count = 0; for (const auto &I : Insns) { switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) { default: llvm_unreachable("Unsupported unwind code"); case Win64EH::UOP_PushNonVol: case Win64EH::UOP_AllocSmall: case Win64EH::UOP_SetFPReg: case Win64EH::UOP_PushMachFrame: Count += 1; break; case Win64EH::UOP_SaveNonVol: case Win64EH::UOP_SaveXMM128: Count += 2; break; case Win64EH::UOP_SaveNonVolBig: case Win64EH::UOP_SaveXMM128Big: Count += 3; break; case Win64EH::UOP_AllocLarge: Count += (I.Offset > 512 * 1024 - 8) ? 3 : 2; break; } } return Count; } static void EmitAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS) { MCContext &Context = Streamer.getContext(); const MCExpr *Diff = MCBinaryExpr::createSub(MCSymbolRefExpr::create(LHS, Context), MCSymbolRefExpr::create(RHS, Context), Context); Streamer.emitValue(Diff, 1); } static void EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin, WinEH::Instruction &inst) { uint8_t b2; uint16_t w; b2 = (inst.Operation & 0x0F); switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) { default: llvm_unreachable("Unsupported unwind code"); case Win64EH::UOP_PushNonVol: EmitAbsDifference(streamer, inst.Label, begin); b2 |= (inst.Register & 0x0F) << 4; streamer.emitInt8(b2); break; case Win64EH::UOP_AllocLarge: EmitAbsDifference(streamer, inst.Label, begin); if (inst.Offset > 512 * 1024 - 8) { b2 |= 0x10; streamer.emitInt8(b2); w = inst.Offset & 0xFFF8; streamer.emitInt16(w); w = inst.Offset >> 16; } else { streamer.emitInt8(b2); w = inst.Offset >> 3; } streamer.emitInt16(w); break; case Win64EH::UOP_AllocSmall: b2 |= (((inst.Offset - 8) >> 3) & 0x0F) << 4; EmitAbsDifference(streamer, inst.Label, begin); streamer.emitInt8(b2); break; case Win64EH::UOP_SetFPReg: EmitAbsDifference(streamer, inst.Label, begin); streamer.emitInt8(b2); break; case Win64EH::UOP_SaveNonVol: case Win64EH::UOP_SaveXMM128: b2 |= (inst.Register & 0x0F) << 4; EmitAbsDifference(streamer, inst.Label, begin); streamer.emitInt8(b2); w = inst.Offset >> 3; if (inst.Operation == Win64EH::UOP_SaveXMM128) w >>= 1; streamer.emitInt16(w); break; case Win64EH::UOP_SaveNonVolBig: case Win64EH::UOP_SaveXMM128Big: b2 |= (inst.Register & 0x0F) << 4; EmitAbsDifference(streamer, inst.Label, begin); streamer.emitInt8(b2); if (inst.Operation == Win64EH::UOP_SaveXMM128Big) w = inst.Offset & 0xFFF0; else w = inst.Offset & 0xFFF8; streamer.emitInt16(w); w = inst.Offset >> 16; streamer.emitInt16(w); break; case Win64EH::UOP_PushMachFrame: if (inst.Offset == 1) b2 |= 0x10; EmitAbsDifference(streamer, inst.Label, begin); streamer.emitInt8(b2); break; } } static void EmitSymbolRefWithOfs(MCStreamer &streamer, const MCSymbol *Base, const MCSymbol *Other) { MCContext &Context = streamer.getContext(); const MCSymbolRefExpr *BaseRef = MCSymbolRefExpr::create(Base, Context); const MCSymbolRefExpr *OtherRef = MCSymbolRefExpr::create(Other, Context); const MCExpr *Ofs = MCBinaryExpr::createSub(OtherRef, BaseRef, Context); const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::create(Base, MCSymbolRefExpr::VK_COFF_IMGREL32, Context); streamer.emitValue(MCBinaryExpr::createAdd(BaseRefRel, Ofs, Context), 4); } static void EmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info) { MCContext &context = streamer.getContext(); streamer.emitValueToAlignment(4); EmitSymbolRefWithOfs(streamer, info->Function, info->Begin); EmitSymbolRefWithOfs(streamer, info->Function, info->End); streamer.emitValue(MCSymbolRefExpr::create(info->Symbol, MCSymbolRefExpr::VK_COFF_IMGREL32, context), 4); } static void EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info) { // If this UNWIND_INFO already has a symbol, it's already been emitted. if (info->Symbol) return; MCContext &context = streamer.getContext(); MCSymbol *Label = context.createTempSymbol(); streamer.emitValueToAlignment(4); streamer.emitLabel(Label); info->Symbol = Label; // Upper 3 bits are the version number (currently 1). uint8_t flags = 0x01; if (info->ChainedParent) flags |= Win64EH::UNW_ChainInfo << 3; else { if (info->HandlesUnwind) flags |= Win64EH::UNW_TerminateHandler << 3; if (info->HandlesExceptions) flags |= Win64EH::UNW_ExceptionHandler << 3; } streamer.emitInt8(flags); if (info->PrologEnd) EmitAbsDifference(streamer, info->PrologEnd, info->Begin); else streamer.emitInt8(0); uint8_t numCodes = CountOfUnwindCodes(info->Instructions); streamer.emitInt8(numCodes); uint8_t frame = 0; if (info->LastFrameInst >= 0) { WinEH::Instruction &frameInst = info->Instructions[info->LastFrameInst]; assert(frameInst.Operation == Win64EH::UOP_SetFPReg); frame = (frameInst.Register & 0x0F) | (frameInst.Offset & 0xF0); } streamer.emitInt8(frame); // Emit unwind instructions (in reverse order). uint8_t numInst = info->Instructions.size(); for (uint8_t c = 0; c < numInst; ++c) { WinEH::Instruction inst = info->Instructions.back(); info->Instructions.pop_back(); EmitUnwindCode(streamer, info->Begin, inst); } // For alignment purposes, the instruction array will always have an even // number of entries, with the final entry potentially unused (in which case // the array will be one longer than indicated by the count of unwind codes // field). if (numCodes & 1) { streamer.emitInt16(0); } if (flags & (Win64EH::UNW_ChainInfo << 3)) EmitRuntimeFunction(streamer, info->ChainedParent); else if (flags & ((Win64EH::UNW_TerminateHandler|Win64EH::UNW_ExceptionHandler) << 3)) streamer.emitValue(MCSymbolRefExpr::create(info->ExceptionHandler, MCSymbolRefExpr::VK_COFF_IMGREL32, context), 4); else if (numCodes == 0) { // The minimum size of an UNWIND_INFO struct is 8 bytes. If we're not // a chained unwind info, if there is no handler, and if there are fewer // than 2 slots used in the unwind code array, we have to pad to 8 bytes. streamer.emitInt32(0); } } void llvm::Win64EH::UnwindEmitter::Emit(MCStreamer &Streamer) const { // Emit the unwind info structs first. for (const auto &CFI : Streamer.getWinFrameInfos()) { MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection); Streamer.SwitchSection(XData); ::EmitUnwindInfo(Streamer, CFI.get()); } // Now emit RUNTIME_FUNCTION entries. for (const auto &CFI : Streamer.getWinFrameInfos()) { MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection); Streamer.SwitchSection(PData); EmitRuntimeFunction(Streamer, CFI.get()); } } void llvm::Win64EH::UnwindEmitter::EmitUnwindInfo( MCStreamer &Streamer, WinEH::FrameInfo *info) const { // Switch sections (the static function above is meant to be called from // here and from Emit(). MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection); Streamer.SwitchSection(XData); ::EmitUnwindInfo(Streamer, info); } static int64_t GetAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS) { MCContext &Context = Streamer.getContext(); const MCExpr *Diff = MCBinaryExpr::createSub(MCSymbolRefExpr::create(LHS, Context), MCSymbolRefExpr::create(RHS, Context), Context); MCObjectStreamer *OS = (MCObjectStreamer *)(&Streamer); // It should normally be possible to calculate the length of a function // at this point, but it might not be possible in the presence of certain // unusual constructs, like an inline asm with an alignment directive. int64_t value; if (!Diff->evaluateAsAbsolute(value, OS->getAssembler())) report_fatal_error("Failed to evaluate function length in SEH unwind info"); return value; } static uint32_t ARM64CountOfUnwindCodes(ArrayRef<WinEH::Instruction> Insns) { uint32_t Count = 0; for (const auto &I : Insns) { switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) { default: llvm_unreachable("Unsupported ARM64 unwind code"); case Win64EH::UOP_AllocSmall: Count += 1; break; case Win64EH::UOP_AllocMedium: Count += 2; break; case Win64EH::UOP_AllocLarge: Count += 4; break; case Win64EH::UOP_SaveR19R20X: Count += 1; break; case Win64EH::UOP_SaveFPLRX: Count += 1; break; case Win64EH::UOP_SaveFPLR: Count += 1; break; case Win64EH::UOP_SaveReg: Count += 2; break; case Win64EH::UOP_SaveRegP: Count += 2; break; case Win64EH::UOP_SaveRegPX: Count += 2; break; case Win64EH::UOP_SaveRegX: Count += 2; break; case Win64EH::UOP_SaveLRPair: Count += 2; break; case Win64EH::UOP_SaveFReg: Count += 2; break; case Win64EH::UOP_SaveFRegP: Count += 2; break; case Win64EH::UOP_SaveFRegX: Count += 2; break; case Win64EH::UOP_SaveFRegPX: Count += 2; break; case Win64EH::UOP_SetFP: Count += 1; break; case Win64EH::UOP_AddFP: Count += 2; break; case Win64EH::UOP_Nop: Count += 1; break; case Win64EH::UOP_End: Count += 1; break; case Win64EH::UOP_SaveNext: Count += 1; break; case Win64EH::UOP_TrapFrame: Count += 1; break; case Win64EH::UOP_PushMachFrame: Count += 1; break; case Win64EH::UOP_Context: Count += 1; break; case Win64EH::UOP_ClearUnwoundToCall: Count += 1; break; } } return Count; } // Unwind opcode encodings and restrictions are documented at // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling static void ARM64EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin, WinEH::Instruction &inst) { uint8_t b, reg; switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) { default: llvm_unreachable("Unsupported ARM64 unwind code"); case Win64EH::UOP_AllocSmall: b = (inst.Offset >> 4) & 0x1F; streamer.emitInt8(b); break; case Win64EH::UOP_AllocMedium: { uint16_t hw = (inst.Offset >> 4) & 0x7FF; b = 0xC0; b |= (hw >> 8); streamer.emitInt8(b); b = hw & 0xFF; streamer.emitInt8(b); break; } case Win64EH::UOP_AllocLarge: { uint32_t w; b = 0xE0; streamer.emitInt8(b); w = inst.Offset >> 4; b = (w & 0x00FF0000) >> 16; streamer.emitInt8(b); b = (w & 0x0000FF00) >> 8; streamer.emitInt8(b); b = w & 0x000000FF; streamer.emitInt8(b); break; } case Win64EH::UOP_SetFP: b = 0xE1; streamer.emitInt8(b); break; case Win64EH::UOP_AddFP: b = 0xE2; streamer.emitInt8(b); b = (inst.Offset >> 3); streamer.emitInt8(b); break; case Win64EH::UOP_Nop: b = 0xE3; streamer.emitInt8(b); break; case Win64EH::UOP_SaveR19R20X: b = 0x20; b |= (inst.Offset >> 3) & 0x1F; streamer.emitInt8(b); break; case Win64EH::UOP_SaveFPLRX: b = 0x80; b |= ((inst.Offset - 1) >> 3) & 0x3F; streamer.emitInt8(b); break; case Win64EH::UOP_SaveFPLR: b = 0x40; b |= (inst.Offset >> 3) & 0x3F; streamer.emitInt8(b); break; case Win64EH::UOP_SaveReg: assert(inst.Register >= 19 && "Saved reg must be >= 19"); reg = inst.Register - 19; b = 0xD0 | ((reg & 0xC) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | (inst.Offset >> 3); streamer.emitInt8(b); break; case Win64EH::UOP_SaveRegX: assert(inst.Register >= 19 && "Saved reg must be >= 19"); reg = inst.Register - 19; b = 0xD4 | ((reg & 0x8) >> 3); streamer.emitInt8(b); b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1); streamer.emitInt8(b); break; case Win64EH::UOP_SaveRegP: assert(inst.Register >= 19 && "Saved registers must be >= 19"); reg = inst.Register - 19; b = 0xC8 | ((reg & 0xC) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | (inst.Offset >> 3); streamer.emitInt8(b); break; case Win64EH::UOP_SaveRegPX: assert(inst.Register >= 19 && "Saved registers must be >= 19"); reg = inst.Register - 19; b = 0xCC | ((reg & 0xC) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1); streamer.emitInt8(b); break; case Win64EH::UOP_SaveLRPair: assert(inst.Register >= 19 && "Saved reg must be >= 19"); reg = inst.Register - 19; assert((reg % 2) == 0 && "Saved reg must be 19+2*X"); reg /= 2; b = 0xD6 | ((reg & 0x7) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | (inst.Offset >> 3); streamer.emitInt8(b); break; case Win64EH::UOP_SaveFReg: assert(inst.Register >= 8 && "Saved dreg must be >= 8"); reg = inst.Register - 8; b = 0xDC | ((reg & 0x4) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | (inst.Offset >> 3); streamer.emitInt8(b); break; case Win64EH::UOP_SaveFRegX: assert(inst.Register >= 8 && "Saved dreg must be >= 8"); reg = inst.Register - 8; b = 0xDE; streamer.emitInt8(b); b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1); streamer.emitInt8(b); break; case Win64EH::UOP_SaveFRegP: assert(inst.Register >= 8 && "Saved dregs must be >= 8"); reg = inst.Register - 8; b = 0xD8 | ((reg & 0x4) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | (inst.Offset >> 3); streamer.emitInt8(b); break; case Win64EH::UOP_SaveFRegPX: assert(inst.Register >= 8 && "Saved dregs must be >= 8"); reg = inst.Register - 8; b = 0xDA | ((reg & 0x4) >> 2); streamer.emitInt8(b); b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1); streamer.emitInt8(b); break; case Win64EH::UOP_End: b = 0xE4; streamer.emitInt8(b); break; case Win64EH::UOP_SaveNext: b = 0xE6; streamer.emitInt8(b); break; case Win64EH::UOP_TrapFrame: b = 0xE8; streamer.emitInt8(b); break; case Win64EH::UOP_PushMachFrame: b = 0xE9; streamer.emitInt8(b); break; case Win64EH::UOP_Context: b = 0xEA; streamer.emitInt8(b); break; case Win64EH::UOP_ClearUnwoundToCall: b = 0xEC; streamer.emitInt8(b); break; } } // Returns the epilog symbol of an epilog with the exact same unwind code // sequence, if it exists. Otherwise, returns nulltpr. // EpilogInstrs - Unwind codes for the current epilog. // Epilogs - Epilogs that potentialy match the current epilog. static MCSymbol* FindMatchingEpilog(const std::vector<WinEH::Instruction>& EpilogInstrs, const std::vector<MCSymbol *>& Epilogs, const WinEH::FrameInfo *info) { for (auto *EpilogStart : Epilogs) { auto InstrsIter = info->EpilogMap.find(EpilogStart); assert(InstrsIter != info->EpilogMap.end() && "Epilog not found in EpilogMap"); const auto &Instrs = InstrsIter->second; if (Instrs.size() != EpilogInstrs.size()) continue; bool Match = true; for (unsigned i = 0; i < Instrs.size(); ++i) if (Instrs[i].Operation != EpilogInstrs[i].Operation || Instrs[i].Offset != EpilogInstrs[i].Offset || Instrs[i].Register != EpilogInstrs[i].Register) { Match = false; break; } if (Match) return EpilogStart; } return nullptr; } static void simplifyOpcodes(std::vector<WinEH::Instruction> &Instructions, bool Reverse) { unsigned PrevOffset = -1; unsigned PrevRegister = -1; auto VisitInstruction = [&](WinEH::Instruction &Inst) { // Convert 2-byte opcodes into equivalent 1-byte ones. if (Inst.Operation == Win64EH::UOP_SaveRegP && Inst.Register == 29) { Inst.Operation = Win64EH::UOP_SaveFPLR; Inst.Register = -1; } else if (Inst.Operation == Win64EH::UOP_SaveRegPX && Inst.Register == 29) { Inst.Operation = Win64EH::UOP_SaveFPLRX; Inst.Register = -1; } else if (Inst.Operation == Win64EH::UOP_SaveRegPX && Inst.Register == 19 && Inst.Offset <= 248) { Inst.Operation = Win64EH::UOP_SaveR19R20X; Inst.Register = -1; } else if (Inst.Operation == Win64EH::UOP_AddFP && Inst.Offset == 0) { Inst.Operation = Win64EH::UOP_SetFP; } else if (Inst.Operation == Win64EH::UOP_SaveRegP && Inst.Register == PrevRegister + 2 && Inst.Offset == PrevOffset + 16) { Inst.Operation = Win64EH::UOP_SaveNext; Inst.Register = -1; Inst.Offset = 0; // Intentionally not creating UOP_SaveNext for float register pairs, // as current versions of Windows (up to at least 20.04) is buggy // regarding SaveNext for float pairs. } // Update info about the previous instruction, for detecting if // the next one can be made a UOP_SaveNext if (Inst.Operation == Win64EH::UOP_SaveR19R20X) { PrevOffset = 0; PrevRegister = 19; } else if (Inst.Operation == Win64EH::UOP_SaveRegPX) { PrevOffset = 0; PrevRegister = Inst.Register; } else if (Inst.Operation == Win64EH::UOP_SaveRegP) { PrevOffset = Inst.Offset; PrevRegister = Inst.Register; } else if (Inst.Operation == Win64EH::UOP_SaveNext) { PrevRegister += 2; PrevOffset += 16; } else { PrevRegister = -1; PrevOffset = -1; } }; // Iterate over instructions in a forward order (for prologues), // backwards for epilogues (i.e. always reverse compared to how the // opcodes are stored). if (Reverse) { for (auto It = Instructions.rbegin(); It != Instructions.rend(); It++) VisitInstruction(*It); } else { for (WinEH::Instruction &Inst : Instructions) VisitInstruction(Inst); } } static int checkPackedEpilog(MCStreamer &streamer, WinEH::FrameInfo *info, int PrologCodeBytes) { // Can only pack if there's one single epilog if (info->EpilogMap.size() != 1) return -1; const std::vector<WinEH::Instruction> &Epilog = info->EpilogMap.begin()->second; // Can pack if the epilog is a subset of the prolog but not vice versa if (Epilog.size() > info->Instructions.size()) return -1; // Check that the epilog actually is a perfect match for the end (backwrds) // of the prolog. for (int I = Epilog.size() - 1; I >= 0; I--) { if (info->Instructions[I] != Epilog[Epilog.size() - 1 - I]) return -1; } // Check that the epilog actually is at the very end of the function, // otherwise it can't be packed. uint32_t DistanceFromEnd = (uint32_t)GetAbsDifference( streamer, info->FuncletOrFuncEnd, info->EpilogMap.begin()->first); if (DistanceFromEnd / 4 != Epilog.size()) return -1; int Offset = Epilog.size() == info->Instructions.size() ? 0 : ARM64CountOfUnwindCodes(ArrayRef<WinEH::Instruction>( &info->Instructions[Epilog.size()], info->Instructions.size() - Epilog.size())); // Check that the offset and prolog size fits in the first word; it's // unclear whether the epilog count in the extension word can be taken // as packed epilog offset. if (Offset > 31 || PrologCodeBytes > 124) return -1; info->EpilogMap.clear(); return Offset; } static bool tryPackedUnwind(WinEH::FrameInfo *info, uint32_t FuncLength, int PackedEpilogOffset) { if (PackedEpilogOffset == 0) { // Fully symmetric prolog and epilog, should be ok for packed format. // For CR=3, the corresponding synthesized epilog actually lacks the // SetFP opcode, but unwinding should work just fine despite that // (if at the SetFP opcode, the unwinder considers it as part of the // function body and just unwinds the full prolog instead). } else if (PackedEpilogOffset == 1) { // One single case of differences between prolog and epilog is allowed: // The epilog can lack a single SetFP that is the last opcode in the // prolog, for the CR=3 case. if (info->Instructions.back().Operation != Win64EH::UOP_SetFP) return false; } else { // Too much difference between prolog and epilog. return false; } unsigned RegI = 0, RegF = 0; int Predecrement = 0; enum { Start, Start2, IntRegs, FloatRegs, InputArgs, StackAdjust, FrameRecord, End } Location = Start; bool StandaloneLR = false, FPLRPair = false; int StackOffset = 0; int Nops = 0; // Iterate over the prolog and check that all opcodes exactly match // the canonical order and form. A more lax check could verify that // all saved registers are in the expected locations, but not enforce // the order - that would work fine when unwinding from within // functions, but not be exactly right if unwinding happens within // prologs/epilogs. for (const WinEH::Instruction &Inst : info->Instructions) { switch (Inst.Operation) { case Win64EH::UOP_End: if (Location != Start) return false; Location = Start2; break; case Win64EH::UOP_SaveR19R20X: if (Location != Start2) return false; Predecrement = Inst.Offset; RegI = 2; Location = IntRegs; break; case Win64EH::UOP_SaveRegX: if (Location != Start2) return false; Predecrement = Inst.Offset; if (Inst.Register == 19) RegI += 1; else if (Inst.Register == 30) StandaloneLR = true; else return false; // Odd register; can't be any further int registers. Location = FloatRegs; break; case Win64EH::UOP_SaveRegPX: // Can't have this in a canonical prologue. Either this has been // canonicalized into SaveR19R20X or SaveFPLRX, or it's an unsupported // register pair. // It can't be canonicalized into SaveR19R20X if the offset is // larger than 248 bytes, but even with the maximum case with // RegI=10/RegF=8/CR=1/H=1, we end up with SavSZ = 216, which should // fit into SaveR19R20X. // The unwinding opcodes can't describe the otherwise seemingly valid // case for RegI=1 CR=1, that would start with a // "stp x19, lr, [sp, #-...]!" as that fits neither SaveRegPX nor // SaveLRPair. return false; case Win64EH::UOP_SaveRegP: if (Location != IntRegs || Inst.Offset != 8 * RegI || Inst.Register != 19 + RegI) return false; RegI += 2; break; case Win64EH::UOP_SaveReg: if (Location != IntRegs || Inst.Offset != 8 * RegI) return false; if (Inst.Register == 19 + RegI) RegI += 1; else if (Inst.Register == 30) StandaloneLR = true; else return false; // Odd register; can't be any further int registers. Location = FloatRegs; break; case Win64EH::UOP_SaveLRPair: if (Location != IntRegs || Inst.Offset != 8 * RegI || Inst.Register != 19 + RegI) return false; RegI += 1; StandaloneLR = true; Location = FloatRegs; break; case Win64EH::UOP_SaveFRegX: // Packed unwind can't handle prologs that only save one single // float register. return false; case Win64EH::UOP_SaveFReg: if (Location != FloatRegs || RegF == 0 || Inst.Register != 8 + RegF || Inst.Offset != 8 * (RegI + (StandaloneLR ? 1 : 0) + RegF)) return false; RegF += 1; Location = InputArgs; break; case Win64EH::UOP_SaveFRegPX: if (Location != Start2 || Inst.Register != 8) return false; Predecrement = Inst.Offset; RegF = 2; Location = FloatRegs; break; case Win64EH::UOP_SaveFRegP: if ((Location != IntRegs && Location != FloatRegs) || Inst.Register != 8 + RegF || Inst.Offset != 8 * (RegI + (StandaloneLR ? 1 : 0) + RegF)) return false; RegF += 2; Location = FloatRegs; break; case Win64EH::UOP_SaveNext: if (Location == IntRegs) RegI += 2; else if (Location == FloatRegs) RegF += 2; else return false; break; case Win64EH::UOP_Nop: if (Location != IntRegs && Location != FloatRegs && Location != InputArgs) return false; Location = InputArgs; Nops++; break; case Win64EH::UOP_AllocSmall: case Win64EH::UOP_AllocMedium: if (Location != Start2 && Location != IntRegs && Location != FloatRegs && Location != InputArgs && Location != StackAdjust) return false; // Can have either a single decrement, or a pair of decrements with // 4080 and another decrement. if (StackOffset == 0) StackOffset = Inst.Offset; else if (StackOffset != 4080) return false; else StackOffset += Inst.Offset; Location = StackAdjust; break; case Win64EH::UOP_SaveFPLRX: // Not allowing FPLRX after StackAdjust; if a StackAdjust is used, it // should be followed by a FPLR instead. if (Location != Start2 && Location != IntRegs && Location != FloatRegs && Location != InputArgs) return false; StackOffset = Inst.Offset; Location = FrameRecord; FPLRPair = true; break; case Win64EH::UOP_SaveFPLR: // This can only follow after a StackAdjust if (Location != StackAdjust || Inst.Offset != 0) return false; Location = FrameRecord; FPLRPair = true; break; case Win64EH::UOP_SetFP: if (Location != FrameRecord) return false; Location = End; break; } } if (RegI > 10 || RegF > 8) return false; if (StandaloneLR && FPLRPair) return false; if (FPLRPair && Location != End) return false; if (Nops != 0 && Nops != 4) return false; int H = Nops == 4; int IntSZ = 8 * RegI; if (StandaloneLR) IntSZ += 8; int FpSZ = 8 * RegF; // RegF not yet decremented int SavSZ = (IntSZ + FpSZ + 8 * 8 * H + 0xF) & ~0xF; if (Predecrement != SavSZ) return false; if (FPLRPair && StackOffset < 16) return false; if (StackOffset % 16) return false; uint32_t FrameSize = (StackOffset + SavSZ) / 16; if (FrameSize > 0x1FF) return false; assert(RegF != 1 && "One single float reg not allowed"); if (RegF > 0) RegF--; // Convert from actual number of registers, to value stored assert(FuncLength <= 0x7FF && "FuncLength should have been checked earlier"); int Flag = 0x01; // Function segments not supported yet int CR = FPLRPair ? 3 : StandaloneLR ? 1 : 0; info->PackedInfo |= Flag << 0; info->PackedInfo |= (FuncLength & 0x7FF) << 2; info->PackedInfo |= (RegF & 0x7) << 13; info->PackedInfo |= (RegI & 0xF) << 16; info->PackedInfo |= (H & 0x1) << 20; info->PackedInfo |= (CR & 0x3) << 21; info->PackedInfo |= (FrameSize & 0x1FF) << 23; return true; } // Populate the .xdata section. The format of .xdata on ARM64 is documented at // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling static void ARM64EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info, bool TryPacked = true) { // If this UNWIND_INFO already has a symbol, it's already been emitted. if (info->Symbol) return; // If there's no unwind info here (not even a terminating UOP_End), the // unwind info is considered bogus and skipped. If this was done in // response to an explicit .seh_handlerdata, the associated trailing // handler data is left orphaned in the xdata section. if (info->empty()) { info->EmitAttempted = true; return; } if (info->EmitAttempted) { // If we tried to emit unwind info before (due to an explicit // .seh_handlerdata directive), but skipped it (because there was no // valid information to emit at the time), and it later got valid unwind // opcodes, we can't emit it here, because the trailing handler data // was already emitted elsewhere in the xdata section. streamer.getContext().reportError( SMLoc(), "Earlier .seh_handlerdata for " + info->Function->getName() + " skipped due to no unwind info at the time " "(.seh_handlerdata too early?), but the function later " "did get unwind info that can't be emitted"); return; } simplifyOpcodes(info->Instructions, false); for (auto &I : info->EpilogMap) simplifyOpcodes(I.second, true); MCContext &context = streamer.getContext(); MCSymbol *Label = context.createTempSymbol(); streamer.emitValueToAlignment(4); streamer.emitLabel(Label); info->Symbol = Label; int64_t RawFuncLength; if (!info->FuncletOrFuncEnd) { report_fatal_error("FuncletOrFuncEnd not set"); } else { // FIXME: GetAbsDifference tries to compute the length of the function // immediately, before the whole file is emitted, but in general // that's impossible: the size in bytes of certain assembler directives // like .align and .fill is not known until the whole file is parsed and // relaxations are applied. Currently, GetAbsDifference fails with a fatal // error in that case. (We mostly don't hit this because inline assembly // specifying those directives is rare, and we don't normally try to // align loops on AArch64.) // // There are two potential approaches to delaying the computation. One, // we could emit something like ".word (endfunc-beginfunc)/4+0x10800000", // as long as we have some conservative estimate we could use to prove // that we don't need to split the unwind data. Emitting the constant // is straightforward, but there's no existing code for estimating the // size of the function. // // The other approach would be to use a dedicated, relaxable fragment, // which could grow to accommodate splitting the unwind data if // necessary. This is more straightforward, since it automatically works // without any new infrastructure, and it's consistent with how we handle // relaxation in other contexts. But it would require some refactoring // to move parts of the pdata/xdata emission into the implementation of // a fragment. We could probably continue to encode the unwind codes // here, but we'd have to emit the pdata, the xdata header, and the // epilogue scopes later, since they depend on whether the we need to // split the unwind data. RawFuncLength = GetAbsDifference(streamer, info->FuncletOrFuncEnd, info->Begin); } if (RawFuncLength > 0xFFFFF) report_fatal_error("SEH unwind data splitting not yet implemented"); uint32_t FuncLength = (uint32_t)RawFuncLength / 4; uint32_t PrologCodeBytes = ARM64CountOfUnwindCodes(info->Instructions); uint32_t TotalCodeBytes = PrologCodeBytes; int PackedEpilogOffset = checkPackedEpilog(streamer, info, PrologCodeBytes); if (PackedEpilogOffset >= 0 && !info->HandlesExceptions && FuncLength <= 0x7ff && TryPacked) { // Matching prolog/epilog and no exception handlers; check if the // prolog matches the patterns that can be described by the packed // format. // info->Symbol was already set even if we didn't actually write any // unwind info there. Keep using that as indicator that this unwind // info has been generated already. if (tryPackedUnwind(info, FuncLength, PackedEpilogOffset)) return; } // Process epilogs. MapVector<MCSymbol *, uint32_t> EpilogInfo; // Epilogs processed so far. std::vector<MCSymbol *> AddedEpilogs; for (auto &I : info->EpilogMap) { MCSymbol *EpilogStart = I.first; auto &EpilogInstrs = I.second; uint32_t CodeBytes = ARM64CountOfUnwindCodes(EpilogInstrs); MCSymbol* MatchingEpilog = FindMatchingEpilog(EpilogInstrs, AddedEpilogs, info); if (MatchingEpilog) { assert(EpilogInfo.find(MatchingEpilog) != EpilogInfo.end() && "Duplicate epilog not found"); EpilogInfo[EpilogStart] = EpilogInfo.lookup(MatchingEpilog); // Clear the unwind codes in the EpilogMap, so that they don't get output // in the logic below. EpilogInstrs.clear(); } else { EpilogInfo[EpilogStart] = TotalCodeBytes; TotalCodeBytes += CodeBytes; AddedEpilogs.push_back(EpilogStart); } } // Code Words, Epilog count, E, X, Vers, Function Length uint32_t row1 = 0x0; uint32_t CodeWords = TotalCodeBytes / 4; uint32_t CodeWordsMod = TotalCodeBytes % 4; if (CodeWordsMod) CodeWords++; uint32_t EpilogCount = PackedEpilogOffset >= 0 ? PackedEpilogOffset : info->EpilogMap.size(); bool ExtensionWord = EpilogCount > 31 || TotalCodeBytes > 124; if (!ExtensionWord) { row1 |= (EpilogCount & 0x1F) << 22; row1 |= (CodeWords & 0x1F) << 27; } if (info->HandlesExceptions) // X row1 |= 1 << 20; if (PackedEpilogOffset >= 0) // E row1 |= 1 << 21; row1 |= FuncLength & 0x3FFFF; streamer.emitInt32(row1); // Extended Code Words, Extended Epilog Count if (ExtensionWord) { // FIXME: We should be able to split unwind info into multiple sections. // FIXME: We should share epilog codes across epilogs, where possible, // which would make this issue show up less frequently. if (CodeWords > 0xFF || EpilogCount > 0xFFFF) report_fatal_error("SEH unwind data splitting not yet implemented"); uint32_t row2 = 0x0; row2 |= (CodeWords & 0xFF) << 16; row2 |= (EpilogCount & 0xFFFF); streamer.emitInt32(row2); } // Epilog Start Index, Epilog Start Offset for (auto &I : EpilogInfo) { MCSymbol *EpilogStart = I.first; uint32_t EpilogIndex = I.second; uint32_t EpilogOffset = (uint32_t)GetAbsDifference(streamer, EpilogStart, info->Begin); if (EpilogOffset) EpilogOffset /= 4; uint32_t row3 = EpilogOffset; row3 |= (EpilogIndex & 0x3FF) << 22; streamer.emitInt32(row3); } // Emit prolog unwind instructions (in reverse order). uint8_t numInst = info->Instructions.size(); for (uint8_t c = 0; c < numInst; ++c) { WinEH::Instruction inst = info->Instructions.back(); info->Instructions.pop_back(); ARM64EmitUnwindCode(streamer, info->Begin, inst); } // Emit epilog unwind instructions for (auto &I : info->EpilogMap) { auto &EpilogInstrs = I.second; for (uint32_t i = 0; i < EpilogInstrs.size(); i++) { WinEH::Instruction inst = EpilogInstrs[i]; ARM64EmitUnwindCode(streamer, info->Begin, inst); } } int32_t BytesMod = CodeWords * 4 - TotalCodeBytes; assert(BytesMod >= 0); for (int i = 0; i < BytesMod; i++) streamer.emitInt8(0xE3); if (info->HandlesExceptions) streamer.emitValue( MCSymbolRefExpr::create(info->ExceptionHandler, MCSymbolRefExpr::VK_COFF_IMGREL32, context), 4); } static void ARM64EmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info) { MCContext &context = streamer.getContext(); streamer.emitValueToAlignment(4); EmitSymbolRefWithOfs(streamer, info->Function, info->Begin); if (info->PackedInfo) streamer.emitInt32(info->PackedInfo); else streamer.emitValue( MCSymbolRefExpr::create(info->Symbol, MCSymbolRefExpr::VK_COFF_IMGREL32, context), 4); } void llvm::Win64EH::ARM64UnwindEmitter::Emit(MCStreamer &Streamer) const { // Emit the unwind info structs first. for (const auto &CFI : Streamer.getWinFrameInfos()) { WinEH::FrameInfo *Info = CFI.get(); if (Info->empty()) continue; MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection); Streamer.SwitchSection(XData); ARM64EmitUnwindInfo(Streamer, Info); } // Now emit RUNTIME_FUNCTION entries. for (const auto &CFI : Streamer.getWinFrameInfos()) { WinEH::FrameInfo *Info = CFI.get(); // ARM64EmitUnwindInfo above clears the info struct, so we can't check // empty here. But if a Symbol is set, we should create the corresponding // pdata entry. if (!Info->Symbol) continue; MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection); Streamer.SwitchSection(PData); ARM64EmitRuntimeFunction(Streamer, Info); } } void llvm::Win64EH::ARM64UnwindEmitter::EmitUnwindInfo( MCStreamer &Streamer, WinEH::FrameInfo *info) const { // Called if there's an .seh_handlerdata directive before the end of the // function. This forces writing the xdata record already here - and // in this case, the function isn't actually ended already, but the xdata // record needs to know the function length. In these cases, if the funclet // end hasn't been marked yet, the xdata function length won't cover the // whole function, only up to this point. if (!info->FuncletOrFuncEnd) { Streamer.SwitchSection(info->TextSection); info->FuncletOrFuncEnd = Streamer.emitCFILabel(); } // Switch sections (the static function above is meant to be called from // here and from Emit(). MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection); Streamer.SwitchSection(XData); ARM64EmitUnwindInfo(Streamer, info, false); }
; A292545: Number of 6-cycles in the n-Sierpinski tetrahedron graph. ; 0,218,876,3504,14016,56064,224256,897024,3588096,14352384,57409536,229638144,918552576,3674210304,14696841216,58787364864,235149459456,940597837824,3762391351296,15049565405184,60198261620736,240793046482944,963172185931776,3852688743727104 mov $2,$0 mov $5,2 lpb $5 mov $0,$2 sub $5,1 add $0,$5 sub $0,1 mul $0,2 mov $4,3 lpb $0 sub $0,1 add $4,35 mul $4,2 lpe mov $3,$5 trn $4,4 mov $6,$4 lpb $3 mov $1,$6 sub $3,1 lpe lpe lpb $2 sub $1,$6 mov $2,0 lpe
; A034714: Dirichlet convolution of squares with themselves. ; 1,8,18,48,50,144,98,256,243,400,242,864,338,784,900,1280,578,1944,722,2400,1764,1936,1058,4608,1875,2704,2916,4704,1682,7200,1922,6144,4356,4624,4900,11664,2738,5776,6084,12800,3362,14112,3698,11616,12150,8464,4418,23040,7203,15000,10404,16224,5618,23328,12100,25088,12996,13456,6962,43200,7442,15376,23814,28672,16900,34848,8978,27744,19044,39200,10082,62208,10658,21904,33750,34656,23716,48672,12482,64000,32805,26896,13778,84672,28900,29584,30276,61952,15842,97200,33124,50784,34596,35344,36100 mov $1,1 add $1,$0 seq $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n. pow $1,2 mul $1,$0 mov $0,$1
; =============================================================== ; Dec 2013 ; =============================================================== ; ; int obstack_grow0(struct obstack *ob, void *data, size_t size) ; ; Grow the current object by appending size bytes read from ; address data followed by a NUL char. ; ; =============================================================== SECTION code_alloc_obstack PUBLIC obstack_grow0_callee obstack_grow0_callee: pop hl pop bc pop de ex (sp),hl INCLUDE "alloc/obstack/z80/asm_obstack_grow0.asm"
#include "PrecompiledHeaders.h" #include "JoystickDX.h" #include "DeviceItem.h" #include "Core.h" #include "Window.h" //IMPLEMENT_AND_REGISTER_CLASS_INFO(JoystickDX, JoystickDevice, Input); IMPLEMENT_CLASS_INFO(JoystickDX) BOOL CALLBACK EnumJoystickObjectsCallback( const DIDEVICEOBJECTINSTANCEA* instancea , VOID* pContext ) { // enum joystick deviceItem JoystickDX* localjoystick=(JoystickDX*)pContext; if(instancea->guidType == GUID_Button) { localjoystick->IncButtonCount(); } else if((instancea->guidType == GUID_XAxis) || (instancea->guidType == GUID_YAxis) || (instancea->guidType == GUID_ZAxis)) { localjoystick->UseAxis(); } else if((instancea->guidType == GUID_RxAxis) || (instancea->guidType == GUID_RyAxis) || (instancea->guidType == GUID_RzAxis)) { localjoystick->UseRotation(); } else if(instancea->guidType == GUID_POV ) { localjoystick->IncPOVCount(); } else { printf("%s\n",instancea->tszName); } return DIENUM_CONTINUE; } JoystickDX::JoystickDX(const kstl::string& name,CLASS_NAME_TREE_ARG) : JoystickDevice(name,PASS_CLASS_NAME_TREE_ARG) , mDirectInputJoystick(0) , mAxisIndex(-1) , mRotationIndex(-1) { } JoystickDX::~JoystickDX() { if(mDirectInputJoystick) { mDirectInputJoystick->Release(); } } bool JoystickDX::Aquire() { if (JoystickDevice::Aquire()) { mDirectInputJoystick->SetCooperativeLevel((mInputWindow ? (HWND)mInputWindow->GetHandle() : NULL), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); mDirectInputJoystick->Acquire(); return true; } return false; } bool JoystickDX::Release() { if (JoystickDevice::Release()) { mDirectInputJoystick->Unacquire(); return true; } return false; } void JoystickDX::UpdateDevice() { HRESULT hr; DIJOYSTATE2 dijs2; // DirectInput joystick state structure if( NULL == mDirectInputJoystick ) return; // Get the input's device state, and put the state in dims ZeroMemory( &dijs2, sizeof(dijs2) ); hr = mDirectInputJoystick->GetDeviceState( sizeof(DIJOYSTATE2), &dijs2 ); if( FAILED(hr) ) { return; } unsigned int currentDevice=0; unsigned int currentButton; for(currentButton=0;currentButton<mButtonsCount;currentButton++) { mDeviceItems[currentDevice++]->getState()->SetValue(dijs2.rgbButtons[currentButton]& 0x80); } // axis if(mAxisIndex!=-1) { Point3D p((kfloat)(dijs2.lX-32768)/32768.0f,(kfloat)(dijs2.lY-32768)/32768.0f,(kfloat)(dijs2.lZ-32768)/32768.0f); mDeviceItems[mAxisIndex]->getState()->SetValue(p); } if(mRotationIndex!=-1) { Point3D p((kfloat)(dijs2.lRx-32768)/32768.0f,(kfloat)(dijs2.lRy-32768)/32768.0f,(kfloat)(dijs2.lRz-32768)/32768.0f); mDeviceItems[mRotationIndex]->getState()->SetValue(p); } currentDevice+=mAxisCount; for(currentButton=0;currentButton<mPovCount;currentButton++) { mDeviceItems[currentDevice++]->getState()->SetValue((int)dijs2.rgdwPOV[currentButton]); } } void JoystickDX::DoInputDeviceDescription() { mDirectInputJoystick->EnumObjects(EnumJoystickObjectsCallback,this,DIDFT_ALL); if(mAxisIndex!=-1) mAxisCount++; if(mRotationIndex!=-1) mAxisCount++; mDeviceItemsCount=mButtonsCount+mPovCount+mAxisCount; DeviceItem** devicearray=new DeviceItem*[mDeviceItemsCount]; unsigned int currentDevice=0; unsigned int currentButton; for(currentButton=0;currentButton<mButtonsCount;currentButton++) { devicearray[currentDevice++]=new DeviceItem(DeviceItemState<int>(0)); } if(mAxisIndex) { mAxisIndex=currentDevice++; devicearray[mAxisIndex]=new DeviceItem(DeviceItemState<Point3D>(Point3D())); } if(mRotationIndex) { mRotationIndex=currentDevice++; devicearray[mRotationIndex]=new DeviceItem(DeviceItemState<Point3D>(Point3D())); } unsigned int currentPOV; for(currentPOV=0;currentPOV<mPovCount;currentPOV++) { devicearray[currentDevice++]=new DeviceItem(DeviceItemState<int>(0)); } InitItems(mDeviceItemsCount,devicearray); for(currentButton=0;currentButton<mDeviceItemsCount;currentButton++) { delete devicearray[currentButton]; } delete[] devicearray; mDirectInputJoystick->SetDataFormat(&c_dfDIJoystick2); }
// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2017-2018 The GoByte Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "darksend.h" #include "governance-vote.h" #include "masternodeman.h" #include "util.h" #include <boost/lexical_cast.hpp> std::string CGovernanceVoting::ConvertOutcomeToString(vote_outcome_enum_t nOutcome) { switch(nOutcome) { case VOTE_OUTCOME_NONE: return "NONE"; break; case VOTE_OUTCOME_YES: return "YES"; break; case VOTE_OUTCOME_NO: return "NO"; break; case VOTE_OUTCOME_ABSTAIN: return "ABSTAIN"; break; } return "error"; } std::string CGovernanceVoting::ConvertSignalToString(vote_signal_enum_t nSignal) { string strReturn = "NONE"; switch(nSignal) { case VOTE_SIGNAL_NONE: strReturn = "NONE"; break; case VOTE_SIGNAL_FUNDING: strReturn = "FUNDING"; break; case VOTE_SIGNAL_VALID: strReturn = "VALID"; break; case VOTE_SIGNAL_DELETE: strReturn = "DELETE"; break; case VOTE_SIGNAL_ENDORSED: strReturn = "ENDORSED"; break; case VOTE_SIGNAL_NOOP1: strReturn = "NOOP1"; break; case VOTE_SIGNAL_NOOP2: strReturn = "NOOP2"; break; case VOTE_SIGNAL_NOOP3: strReturn = "NOOP3"; break; case VOTE_SIGNAL_NOOP4: strReturn = "NOOP4"; break; case VOTE_SIGNAL_NOOP5: strReturn = "NOOP5"; break; case VOTE_SIGNAL_NOOP6: strReturn = "NOOP6"; break; case VOTE_SIGNAL_NOOP7: strReturn = "NOOP7"; break; case VOTE_SIGNAL_NOOP8: strReturn = "NOOP8"; break; case VOTE_SIGNAL_NOOP9: strReturn = "NOOP9"; break; case VOTE_SIGNAL_NOOP10: strReturn = "NOOP10"; break; case VOTE_SIGNAL_NOOP11: strReturn = "NOOP11"; break; case VOTE_SIGNAL_CUSTOM1: strReturn = "CUSTOM1"; break; case VOTE_SIGNAL_CUSTOM2: strReturn = "CUSTOM2"; break; case VOTE_SIGNAL_CUSTOM3: strReturn = "CUSTOM3"; break; case VOTE_SIGNAL_CUSTOM4: strReturn = "CUSTOM4"; break; case VOTE_SIGNAL_CUSTOM5: strReturn = "CUSTOM5"; break; case VOTE_SIGNAL_CUSTOM6: strReturn = "CUSTOM6"; break; case VOTE_SIGNAL_CUSTOM7: strReturn = "CUSTOM7"; break; case VOTE_SIGNAL_CUSTOM8: strReturn = "CUSTOM8"; break; case VOTE_SIGNAL_CUSTOM9: strReturn = "CUSTOM9"; break; case VOTE_SIGNAL_CUSTOM10: strReturn = "CUSTOM10"; break; case VOTE_SIGNAL_CUSTOM11: strReturn = "CUSTOM11"; break; case VOTE_SIGNAL_CUSTOM12: strReturn = "CUSTOM12"; break; case VOTE_SIGNAL_CUSTOM13: strReturn = "CUSTOM13"; break; case VOTE_SIGNAL_CUSTOM14: strReturn = "CUSTOM14"; break; case VOTE_SIGNAL_CUSTOM15: strReturn = "CUSTOM15"; break; case VOTE_SIGNAL_CUSTOM16: strReturn = "CUSTOM16"; break; case VOTE_SIGNAL_CUSTOM17: strReturn = "CUSTOM17"; break; case VOTE_SIGNAL_CUSTOM18: strReturn = "CUSTOM18"; break; case VOTE_SIGNAL_CUSTOM19: strReturn = "CUSTOM19"; break; case VOTE_SIGNAL_CUSTOM20: strReturn = "CUSTOM20"; break; } return strReturn; } vote_outcome_enum_t CGovernanceVoting::ConvertVoteOutcome(std::string strVoteOutcome) { vote_outcome_enum_t eVote = VOTE_OUTCOME_NONE; if(strVoteOutcome == "yes") { eVote = VOTE_OUTCOME_YES; } else if(strVoteOutcome == "no") { eVote = VOTE_OUTCOME_NO; } else if(strVoteOutcome == "abstain") { eVote = VOTE_OUTCOME_ABSTAIN; } return eVote; } vote_signal_enum_t CGovernanceVoting::ConvertVoteSignal(std::string strVoteSignal) { vote_signal_enum_t eSignal = VOTE_SIGNAL_NONE; if(strVoteSignal == "funding") { eSignal = VOTE_SIGNAL_FUNDING; } else if(strVoteSignal == "valid") { eSignal = VOTE_SIGNAL_VALID; } if(strVoteSignal == "delete") { eSignal = VOTE_SIGNAL_DELETE; } if(strVoteSignal == "endorsed") { eSignal = VOTE_SIGNAL_ENDORSED; } if(eSignal != VOTE_SIGNAL_NONE) { return eSignal; } // ID FIVE THROUGH CUSTOM_START ARE TO BE USED BY GOVERNANCE ENGINE / TRIGGER SYSTEM // convert custom sentinel outcomes to integer and store try { int i = boost::lexical_cast<int>(strVoteSignal); if(i < VOTE_SIGNAL_CUSTOM1 || i > VOTE_SIGNAL_CUSTOM20) { eSignal = VOTE_SIGNAL_NONE; } else { eSignal = vote_signal_enum_t(i); } } catch(std::exception const & e) { std::ostringstream ostr; ostr << "CGovernanceVote::ConvertVoteSignal: error : " << e.what() << std::endl; LogPrintf(ostr.str().c_str()); } return eSignal; } CGovernanceVote::CGovernanceVote() : fValid(true), fSynced(false), nVoteSignal(int(VOTE_SIGNAL_NONE)), vinMasternode(), nParentHash(), nVoteOutcome(int(VOTE_OUTCOME_NONE)), nTime(0), vchSig() {} CGovernanceVote::CGovernanceVote(CTxIn vinMasternodeIn, uint256 nParentHashIn, vote_signal_enum_t eVoteSignalIn, vote_outcome_enum_t eVoteOutcomeIn) : fValid(true), fSynced(false), nVoteSignal(eVoteSignalIn), vinMasternode(vinMasternodeIn), nParentHash(nParentHashIn), nVoteOutcome(eVoteOutcomeIn), nTime(GetAdjustedTime()), vchSig() {} void CGovernanceVote::Relay() const { CInv inv(MSG_GOVERNANCE_OBJECT_VOTE, GetHash()); RelayInv(inv, PROTOCOL_VERSION); } bool CGovernanceVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string strError; std::string strMessage = vinMasternode.prevout.ToStringShort() + "|" + nParentHash.ToString() + "|" + boost::lexical_cast<std::string>(nVoteSignal) + "|" + boost::lexical_cast<std::string>(nVoteOutcome) + "|" + boost::lexical_cast<std::string>(nTime); if(!darkSendSigner.SignMessage(strMessage, vchSig, keyMasternode)) { LogPrintf("CGovernanceVote::Sign -- SignMessage() failed\n"); return false; } if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CGovernanceVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CGovernanceVote::IsValid(bool fSignatureCheck) const { if(nTime > GetTime() + (60*60)) { LogPrint("gobject", "CGovernanceVote::IsValid -- vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", GetHash().ToString(), nTime, GetTime() + (60*60)); return false; } // support up to 50 actions (implemented in sentinel) if(nVoteSignal > MAX_SUPPORTED_VOTE_SIGNAL) { LogPrint("gobject", "CGovernanceVote::IsValid -- Client attempted to vote on invalid signal(%d) - %s\n", nVoteSignal, GetHash().ToString()); return false; } // 0=none, 1=yes, 2=no, 3=abstain. Beyond that reject votes if(nVoteOutcome > 3) { LogPrint("gobject", "CGovernanceVote::IsValid -- Client attempted to vote on invalid outcome(%d) - %s\n", nVoteSignal, GetHash().ToString()); return false; } masternode_info_t infoMn = mnodeman.GetMasternodeInfo(vinMasternode); if(!infoMn.fInfoValid) { LogPrint("gobject", "CGovernanceVote::IsValid -- Unknown Masternode - %s\n", vinMasternode.prevout.ToStringShort()); return false; } if(!fSignatureCheck) return true; std::string strError; std::string strMessage = vinMasternode.prevout.ToStringShort() + "|" + nParentHash.ToString() + "|" + boost::lexical_cast<std::string>(nVoteSignal) + "|" + boost::lexical_cast<std::string>(nVoteOutcome) + "|" + boost::lexical_cast<std::string>(nTime); if(!darkSendSigner.VerifyMessage(infoMn.pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CGovernanceVote::IsValid -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool operator==(const CGovernanceVote& vote1, const CGovernanceVote& vote2) { bool fResult = ((vote1.vinMasternode == vote2.vinMasternode) && (vote1.nParentHash == vote2.nParentHash) && (vote1.nVoteOutcome == vote2.nVoteOutcome) && (vote1.nVoteSignal == vote2.nVoteSignal) && (vote1.nTime == vote2.nTime)); return fResult; } bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2) { bool fResult = (vote1.vinMasternode < vote2.vinMasternode); if(!fResult) { return false; } fResult = (vote1.vinMasternode == vote2.vinMasternode); fResult = fResult && (vote1.nParentHash < vote2.nParentHash); if(!fResult) { return false; } fResult = fResult && (vote1.nParentHash == vote2.nParentHash); fResult = fResult && (vote1.nVoteOutcome < vote2.nVoteOutcome); if(!fResult) { return false; } fResult = fResult && (vote1.nVoteOutcome == vote2.nVoteOutcome); fResult = fResult && (vote1.nVoteSignal == vote2.nVoteSignal); if(!fResult) { return false; } fResult = fResult && (vote1.nVoteSignal == vote2.nVoteSignal); fResult = fResult && (vote1.nTime < vote2.nTime); return fResult; }
; A118742: Numbers n for which the expression n!/(n+1) is an integer. ; 0,5,7,8,9,11,13,14,15,17,19,20,21,23,24,25,26,27,29,31,32,33,34,35,37,38,39,41,43,44,45,47,48,49,50,51,53,54,55,56,57,59,61,62,63,64,65,67,68,69,71,73,74,75,76,77,79,80,81,83,84,85,86,87,89,90,91,92,93,94,95,97 seq $0,72668 ; Numbers one less than composite numbers. mov $1,$0 pow $1,2 sub $1,$0 lpb $0 max $0,$1 dif $0,2 bin $0,3 mov $1,$2 lpe
// A simple program to draw a ball sprite to screen at left/upper corner // Steps: // 1) Load sprite data into RAM since program can't load data from ROM directly // 2) Initialize variables to point to source (sprite) and destination (screen) addresses // 3) Loop copying source to destination // Load sprite into RAM[1000-1015] @0 D=A @1000 M=D @992 D=A @1001 M=D @4088 D=A @1002 M=D @8188 D=A @1003 M=D @16382 D=A @1004 M=D @16382 D=A @1005 M=D @32767 D=A @1006 M=D @32767 D=A @1007 M=D @32767 D=A @1008 M=D @32767 D=A @1009 M=D @32767 D=A @1010 M=D @16382 D=A @1011 M=D @16382 D=A @1012 M=D @8188 D=A @1013 M=D @4088 D=A @1014 M=D @992 D=A @1015 M=D // init variables @1000 D=A @psrc M=D @SCREEN D=A @pdst M=D @16 D=A @nrows M=D // loop until nrows == 0 (DRAW_LOOP) @nrows D=M @END_DRAW_LOOP D;JEQ // D = *psrc; *pdst = D @psrc A=M D=M @pdst A=M M=D // update counter and pointers @32 D=A @pdst M=D+M @psrc M=M+1 @nrows M=M-1 // end loop @DRAW_LOOP 0;JMP (END_DRAW_LOOP) (BREAK) @BREAK 0;JMP
#if LOGGING #ifndef LOGGER #define LOGGER #include <string> #include <fstream> namespace logger { extern const std::string path ; extern std::ofstream out ; void flush() ; } #endif #endif
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/browser_plugin/browser_plugin_bindings.h" #include <cstdlib> #include <string> #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "content/common/browser_plugin/browser_plugin_constants.h" #include "content/public/renderer/v8_value_converter.h" #include "content/renderer/browser_plugin/browser_plugin.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebBindings.h" #include "third_party/WebKit/public/web/WebDOMMessageEvent.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebPluginContainer.h" #include "third_party/WebKit/public/web/WebView.h" #include "third_party/npapi/bindings/npapi.h" #include "v8/include/v8.h" using blink::WebBindings; using blink::WebElement; using blink::WebDOMEvent; using blink::WebDOMMessageEvent; using blink::WebPluginContainer; using blink::WebString; namespace content { namespace { BrowserPluginBindings* GetBindings(NPObject* object) { return static_cast<BrowserPluginBindings::BrowserPluginNPObject*>(object)-> message_channel.get(); } std::string StringFromNPVariant(const NPVariant& variant) { if (!NPVARIANT_IS_STRING(variant)) return std::string(); const NPString& np_string = NPVARIANT_TO_STRING(variant); return std::string(np_string.UTF8Characters, np_string.UTF8Length); } bool StringToNPVariant(const std::string &in, NPVariant *variant) { size_t length = in.size(); NPUTF8 *chars = static_cast<NPUTF8 *>(malloc(length)); if (!chars) { VOID_TO_NPVARIANT(*variant); return false; } memcpy(chars, in.c_str(), length); STRINGN_TO_NPVARIANT(chars, length, *variant); return true; } // Depending on where the attribute comes from it could be a string, int32, // or a double. Javascript tends to produce an int32 or a string, but setting // the value from the developer tools console may also produce a double. int IntFromNPVariant(const NPVariant& variant) { int value = 0; switch (variant.type) { case NPVariantType_Double: value = NPVARIANT_TO_DOUBLE(variant); break; case NPVariantType_Int32: value = NPVARIANT_TO_INT32(variant); break; case NPVariantType_String: base::StringToInt(StringFromNPVariant(variant), &value); break; default: break; } return value; } //------------------------------------------------------------------------------ // Implementations of NPClass functions. These are here to: // - Implement src attribute. //------------------------------------------------------------------------------ NPObject* BrowserPluginBindingsAllocate(NPP npp, NPClass* the_class) { return new BrowserPluginBindings::BrowserPluginNPObject; } void BrowserPluginBindingsDeallocate(NPObject* object) { BrowserPluginBindings::BrowserPluginNPObject* instance = static_cast<BrowserPluginBindings::BrowserPluginNPObject*>(object); delete instance; } bool BrowserPluginBindingsHasMethod(NPObject* np_obj, NPIdentifier name) { if (!np_obj) return false; BrowserPluginBindings* bindings = GetBindings(np_obj); if (!bindings) return false; return bindings->HasMethod(name); } bool BrowserPluginBindingsInvoke(NPObject* np_obj, NPIdentifier name, const NPVariant* args, uint32 arg_count, NPVariant* result) { if (!np_obj) return false; BrowserPluginBindings* bindings = GetBindings(np_obj); if (!bindings) return false; return bindings->InvokeMethod(name, args, arg_count, result); } bool BrowserPluginBindingsInvokeDefault(NPObject* np_obj, const NPVariant* args, uint32 arg_count, NPVariant* result) { NOTIMPLEMENTED(); return false; } bool BrowserPluginBindingsHasProperty(NPObject* np_obj, NPIdentifier name) { if (!np_obj) return false; BrowserPluginBindings* bindings = GetBindings(np_obj); if (!bindings) return false; return bindings->HasProperty(name); } bool BrowserPluginBindingsGetProperty(NPObject* np_obj, NPIdentifier name, NPVariant* result) { if (!np_obj) return false; if (!result) return false; // All attributes from here on rely on the bindings, so retrieve it once and // return on failure. BrowserPluginBindings* bindings = GetBindings(np_obj); if (!bindings) return false; return bindings->GetProperty(name, result); } bool BrowserPluginBindingsSetProperty(NPObject* np_obj, NPIdentifier name, const NPVariant* variant) { if (!np_obj) return false; if (!variant) return false; // All attributes from here on rely on the bindings, so retrieve it once and // return on failure. BrowserPluginBindings* bindings = GetBindings(np_obj); if (!bindings) return false; if (variant->type == NPVariantType_Null) return bindings->RemoveProperty(np_obj, name); return bindings->SetProperty(np_obj, name, variant); } bool BrowserPluginBindingsEnumerate(NPObject *np_obj, NPIdentifier **value, uint32_t *count) { NOTIMPLEMENTED(); return true; } NPClass browser_plugin_message_class = { NP_CLASS_STRUCT_VERSION, &BrowserPluginBindingsAllocate, &BrowserPluginBindingsDeallocate, NULL, &BrowserPluginBindingsHasMethod, &BrowserPluginBindingsInvoke, &BrowserPluginBindingsInvokeDefault, &BrowserPluginBindingsHasProperty, &BrowserPluginBindingsGetProperty, &BrowserPluginBindingsSetProperty, NULL, &BrowserPluginBindingsEnumerate, }; } // namespace // BrowserPluginMethodBinding -------------------------------------------------- class BrowserPluginMethodBinding { public: BrowserPluginMethodBinding(const char name[], uint32 arg_count) : name_(name), arg_count_(arg_count) { } virtual ~BrowserPluginMethodBinding() {} bool MatchesName(NPIdentifier name) const { return WebBindings::getStringIdentifier(name_.c_str()) == name; } uint32 arg_count() const { return arg_count_; } virtual bool Invoke(BrowserPluginBindings* bindings, const NPVariant* args, NPVariant* result) = 0; private: std::string name_; uint32 arg_count_; DISALLOW_COPY_AND_ASSIGN(BrowserPluginMethodBinding); }; class BrowserPluginBindingAttach: public BrowserPluginMethodBinding { public: BrowserPluginBindingAttach() : BrowserPluginMethodBinding( browser_plugin::kMethodInternalAttach, 1) { } virtual bool Invoke(BrowserPluginBindings* bindings, const NPVariant* args, NPVariant* result) OVERRIDE { if (!bindings->instance()->render_view()) return false; scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create()); v8::Handle<v8::Value> obj(blink::WebBindings::toV8Value(&args[0])); scoped_ptr<base::Value> value( converter->FromV8Value(obj, bindings->instance()->render_view()-> GetWebView()->mainFrame()->mainWorldScriptContext())); if (!value) return false; if (!value->IsType(Value::TYPE_DICTIONARY)) return false; scoped_ptr<base::DictionaryValue> extra_params( static_cast<base::DictionaryValue*>(value.release())); bindings->instance()->Attach(extra_params.Pass()); return true; } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginBindingAttach); }; class BrowserPluginBindingAttachWindowTo : public BrowserPluginMethodBinding { public: BrowserPluginBindingAttachWindowTo() : BrowserPluginMethodBinding( browser_plugin::kMethodInternalAttachWindowTo, 2) { } virtual bool Invoke(BrowserPluginBindings* bindings, const NPVariant* args, NPVariant* result) OVERRIDE { blink::WebNode node; WebBindings::getNode(NPVARIANT_TO_OBJECT(args[0]), &node); int window_id = IntFromNPVariant(args[1]); BOOLEAN_TO_NPVARIANT(BrowserPlugin::AttachWindowTo(node, window_id), *result); return true; } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginBindingAttachWindowTo); }; // BrowserPluginPropertyBinding ------------------------------------------------ class BrowserPluginPropertyBinding { public: explicit BrowserPluginPropertyBinding(const char name[]) : name_(name) {} virtual ~BrowserPluginPropertyBinding() {} const std::string& name() const { return name_; } bool MatchesName(NPIdentifier name) const { return WebBindings::getStringIdentifier(name_.c_str()) == name; } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) = 0; virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) = 0; virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) = 0; // Updates the DOM Attribute value with the current property value. void UpdateDOMAttribute(BrowserPluginBindings* bindings, std::string new_value) { bindings->instance()->UpdateDOMAttribute(name(), new_value); } private: std::string name_; DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBinding); }; class BrowserPluginPropertyBindingAutoSize : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingAutoSize() : BrowserPluginPropertyBinding(browser_plugin::kAttributeAutoSize) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { bool auto_size = bindings->instance()->GetAutoSizeAttribute(); BOOLEAN_TO_NPVARIANT(auto_size, *result); return true; } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { std::string value = StringFromNPVariant(*variant); if (!bindings->instance()->HasDOMAttribute(name())) { UpdateDOMAttribute(bindings, value); bindings->instance()->ParseAutoSizeAttribute(); } else { UpdateDOMAttribute(bindings, value); } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); bindings->instance()->ParseAutoSizeAttribute(); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingAutoSize); }; class BrowserPluginPropertyBindingContentWindow : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingContentWindow() : BrowserPluginPropertyBinding(browser_plugin::kAttributeContentWindow) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { NPObject* obj = bindings->instance()->GetContentWindow(); if (obj) { result->type = NPVariantType_Object; result->value.objectValue = WebBindings::retainObject(obj); } return true; } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { return false; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE {} private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingContentWindow); }; class BrowserPluginPropertyBindingMaxHeight : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingMaxHeight() : BrowserPluginPropertyBinding(browser_plugin::kAttributeMaxHeight) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { int max_height = bindings->instance()->GetMaxHeightAttribute(); INT32_TO_NPVARIANT(max_height, *result); return true; } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { int new_value = IntFromNPVariant(*variant); if (bindings->instance()->GetMaxHeightAttribute() != new_value) { UpdateDOMAttribute(bindings, base::IntToString(new_value)); bindings->instance()->ParseSizeContraintsChanged(); } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); bindings->instance()->ParseSizeContraintsChanged(); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingMaxHeight); }; class BrowserPluginPropertyBindingMaxWidth : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingMaxWidth() : BrowserPluginPropertyBinding(browser_plugin::kAttributeMaxWidth) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { int max_width = bindings->instance()->GetMaxWidthAttribute(); INT32_TO_NPVARIANT(max_width, *result); return true; } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { int new_value = IntFromNPVariant(*variant); if (bindings->instance()->GetMaxWidthAttribute() != new_value) { UpdateDOMAttribute(bindings, base::IntToString(new_value)); bindings->instance()->ParseSizeContraintsChanged(); } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); bindings->instance()->ParseSizeContraintsChanged(); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingMaxWidth); }; class BrowserPluginPropertyBindingMinHeight : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingMinHeight() : BrowserPluginPropertyBinding(browser_plugin::kAttributeMinHeight) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { int min_height = bindings->instance()->GetMinHeightAttribute(); INT32_TO_NPVARIANT(min_height, *result); return true; } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { int new_value = IntFromNPVariant(*variant); if (bindings->instance()->GetMinHeightAttribute() != new_value) { UpdateDOMAttribute(bindings, base::IntToString(new_value)); bindings->instance()->ParseSizeContraintsChanged(); } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); bindings->instance()->ParseSizeContraintsChanged(); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingMinHeight); }; class BrowserPluginPropertyBindingMinWidth : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingMinWidth() : BrowserPluginPropertyBinding(browser_plugin::kAttributeMinWidth) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { int min_width = bindings->instance()->GetMinWidthAttribute(); INT32_TO_NPVARIANT(min_width, *result); return true; } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { int new_value = IntFromNPVariant(*variant); if (bindings->instance()->GetMinWidthAttribute() != new_value) { UpdateDOMAttribute(bindings, base::IntToString(new_value)); bindings->instance()->ParseSizeContraintsChanged(); } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); bindings->instance()->ParseSizeContraintsChanged(); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingMinWidth); }; class BrowserPluginPropertyBindingName : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingName() : BrowserPluginPropertyBinding(browser_plugin::kAttributeName) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { std::string name = bindings->instance()->GetNameAttribute(); return StringToNPVariant(name, result); } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { std::string new_value = StringFromNPVariant(*variant); if (bindings->instance()->GetNameAttribute() != new_value) { UpdateDOMAttribute(bindings, new_value); bindings->instance()->ParseNameAttribute(); } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); bindings->instance()->ParseNameAttribute(); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingName); }; class BrowserPluginPropertyBindingPartition : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingPartition() : BrowserPluginPropertyBinding(browser_plugin::kAttributePartition) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { std::string partition_id = bindings->instance()->GetPartitionAttribute(); return StringToNPVariant(partition_id, result); } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { std::string new_value = StringFromNPVariant(*variant); std::string old_value = bindings->instance()->GetPartitionAttribute(); if (old_value != new_value) { UpdateDOMAttribute(bindings, new_value); std::string error_message; if (!bindings->instance()->ParsePartitionAttribute(&error_message)) { // Reset to old value on error. UpdateDOMAttribute(bindings, old_value); // Exceptions must be set as the last operation before returning to // script. WebBindings::setException( np_obj, static_cast<const NPUTF8 *>(error_message.c_str())); return false; } } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { std::string error_message; if (bindings->instance()->CanRemovePartitionAttribute(&error_message)) { bindings->instance()->RemoveDOMAttribute(name()); } else { WebBindings::setException( np_obj, static_cast<const NPUTF8 *>(error_message.c_str())); } } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingPartition); }; class BrowserPluginPropertyBindingSrc : public BrowserPluginPropertyBinding { public: BrowserPluginPropertyBindingSrc() : BrowserPluginPropertyBinding(browser_plugin::kAttributeSrc) { } virtual bool GetProperty(BrowserPluginBindings* bindings, NPVariant* result) OVERRIDE { std::string src = bindings->instance()->GetSrcAttribute(); return StringToNPVariant(src, result); } virtual bool SetProperty(BrowserPluginBindings* bindings, NPObject* np_obj, const NPVariant* variant) OVERRIDE { std::string new_value = StringFromNPVariant(*variant); // We should not be issuing navigation IPCs if we attempt to set the // src property to the empty string. Instead, we want to simply restore // the src attribute back to its old value. if (new_value.empty()) { return true; } std::string old_value = bindings->instance()->GetSrcAttribute(); // If the new value was empty then we're effectively resetting the // attribute to the old value here. This will be picked up by <webview>'s // mutation observer and will restore the src attribute after it has been // removed. UpdateDOMAttribute(bindings, new_value); std::string error_message; if (!bindings->instance()->ParseSrcAttribute(&error_message)) { // Reset to old value on error. UpdateDOMAttribute(bindings, old_value); // Exceptions must be set as the last operation before returning to // script. WebBindings::setException( np_obj, static_cast<const NPUTF8 *>(error_message.c_str())); return false; } return true; } virtual void RemoveProperty(BrowserPluginBindings* bindings, NPObject* np_obj) OVERRIDE { bindings->instance()->RemoveDOMAttribute(name()); } private: DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingSrc); }; // BrowserPluginBindings ------------------------------------------------------ BrowserPluginBindings::BrowserPluginNPObject::BrowserPluginNPObject() { } BrowserPluginBindings::BrowserPluginNPObject::~BrowserPluginNPObject() { } BrowserPluginBindings::BrowserPluginBindings(BrowserPlugin* instance) : instance_(instance), np_object_(NULL), weak_ptr_factory_(this) { NPObject* obj = WebBindings::createObject(instance->pluginNPP(), &browser_plugin_message_class); np_object_ = static_cast<BrowserPluginBindings::BrowserPluginNPObject*>(obj); np_object_->message_channel = weak_ptr_factory_.GetWeakPtr(); method_bindings_.push_back(new BrowserPluginBindingAttach); method_bindings_.push_back(new BrowserPluginBindingAttachWindowTo); property_bindings_.push_back(new BrowserPluginPropertyBindingAutoSize); property_bindings_.push_back(new BrowserPluginPropertyBindingContentWindow); property_bindings_.push_back(new BrowserPluginPropertyBindingMaxHeight); property_bindings_.push_back(new BrowserPluginPropertyBindingMaxWidth); property_bindings_.push_back(new BrowserPluginPropertyBindingMinHeight); property_bindings_.push_back(new BrowserPluginPropertyBindingMinWidth); property_bindings_.push_back(new BrowserPluginPropertyBindingName); property_bindings_.push_back(new BrowserPluginPropertyBindingPartition); property_bindings_.push_back(new BrowserPluginPropertyBindingSrc); } BrowserPluginBindings::~BrowserPluginBindings() { WebBindings::releaseObject(np_object_); } bool BrowserPluginBindings::HasMethod(NPIdentifier name) const { for (BindingList::const_iterator iter = method_bindings_.begin(); iter != method_bindings_.end(); ++iter) { if ((*iter)->MatchesName(name)) return true; } return false; } bool BrowserPluginBindings::InvokeMethod(NPIdentifier name, const NPVariant* args, uint32 arg_count, NPVariant* result) { for (BindingList::iterator iter = method_bindings_.begin(); iter != method_bindings_.end(); ++iter) { if ((*iter)->MatchesName(name) && (*iter)->arg_count() == arg_count) return (*iter)->Invoke(this, args, result); } return false; } bool BrowserPluginBindings::HasProperty(NPIdentifier name) const { for (PropertyBindingList::const_iterator iter = property_bindings_.begin(); iter != property_bindings_.end(); ++iter) { if ((*iter)->MatchesName(name)) return true; } return false; } bool BrowserPluginBindings::SetProperty(NPObject* np_obj, NPIdentifier name, const NPVariant* variant) { for (PropertyBindingList::iterator iter = property_bindings_.begin(); iter != property_bindings_.end(); ++iter) { if ((*iter)->MatchesName(name)) { if ((*iter)->SetProperty(this, np_obj, variant)) { return true; } break; } } return false; } bool BrowserPluginBindings::RemoveProperty(NPObject* np_obj, NPIdentifier name) { for (PropertyBindingList::iterator iter = property_bindings_.begin(); iter != property_bindings_.end(); ++iter) { if ((*iter)->MatchesName(name)) { (*iter)->RemoveProperty(this, np_obj); return true; } } return false; } bool BrowserPluginBindings::GetProperty(NPIdentifier name, NPVariant* result) { for (PropertyBindingList::iterator iter = property_bindings_.begin(); iter != property_bindings_.end(); ++iter) { if ((*iter)->MatchesName(name)) return (*iter)->GetProperty(this, result); } return false; } } // namespace content
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2016 Google Inc. All rights reserved. // http://ceres-solver.org/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: vitus@google.com (Michael Vitus) // // An example of solving a graph-based formulation of Simultaneous Localization // and Mapping (SLAM). It reads a 2D pose graph problem definition file in the // g2o format, formulates and solves the Ceres optimization problem, and outputs // the original and optimized poses to file for plotting. #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> #include "angle_manifold.h" #include "ceres/ceres.h" #include "common/read_g2o.h" #include "gflags/gflags.h" #include "glog/logging.h" #include "pose_graph_2d_error_term.h" #include "types.h" DEFINE_string(input, "", "The pose graph definition filename in g2o format."); namespace ceres::examples { namespace { // Constructs the nonlinear least squares optimization problem from the pose // graph constraints. void BuildOptimizationProblem(const std::vector<Constraint2d>& constraints, std::map<int, Pose2d>* poses, ceres::Problem* problem) { CHECK(poses != nullptr); CHECK(problem != nullptr); if (constraints.empty()) { LOG(INFO) << "No constraints, no problem to optimize."; return; } ceres::LossFunction* loss_function = nullptr; ceres::Manifold* angle_manifold = AngleManifold::Create(); for (const auto& constraint : constraints) { auto pose_begin_iter = poses->find(constraint.id_begin); CHECK(pose_begin_iter != poses->end()) << "Pose with ID: " << constraint.id_begin << " not found."; auto pose_end_iter = poses->find(constraint.id_end); CHECK(pose_end_iter != poses->end()) << "Pose with ID: " << constraint.id_end << " not found."; const Eigen::Matrix3d sqrt_information = constraint.information.llt().matrixL(); // Ceres will take ownership of the pointer. ceres::CostFunction* cost_function = PoseGraph2dErrorTerm::Create( constraint.x, constraint.y, constraint.yaw_radians, sqrt_information); problem->AddResidualBlock(cost_function, loss_function, &pose_begin_iter->second.x, &pose_begin_iter->second.y, &pose_begin_iter->second.yaw_radians, &pose_end_iter->second.x, &pose_end_iter->second.y, &pose_end_iter->second.yaw_radians); problem->SetManifold(&pose_begin_iter->second.yaw_radians, angle_manifold); problem->SetManifold(&pose_end_iter->second.yaw_radians, angle_manifold); } // The pose graph optimization problem has three DOFs that are not fully // constrained. This is typically referred to as gauge freedom. You can apply // a rigid body transformation to all the nodes and the optimization problem // will still have the exact same cost. The Levenberg-Marquardt algorithm has // internal damping which mitigate this issue, but it is better to properly // constrain the gauge freedom. This can be done by setting one of the poses // as constant so the optimizer cannot change it. auto pose_start_iter = poses->begin(); CHECK(pose_start_iter != poses->end()) << "There are no poses."; problem->SetParameterBlockConstant(&pose_start_iter->second.x); problem->SetParameterBlockConstant(&pose_start_iter->second.y); problem->SetParameterBlockConstant(&pose_start_iter->second.yaw_radians); } // Returns true if the solve was successful. bool SolveOptimizationProblem(ceres::Problem* problem) { CHECK(problem != nullptr); ceres::Solver::Options options; options.max_num_iterations = 100; options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY; ceres::Solver::Summary summary; ceres::Solve(options, problem, &summary); std::cout << summary.FullReport() << '\n'; return summary.IsSolutionUsable(); } // Output the poses to the file with format: ID x y yaw_radians. bool OutputPoses(const std::string& filename, const std::map<int, Pose2d>& poses) { std::fstream outfile; outfile.open(filename.c_str(), std::istream::out); if (!outfile) { std::cerr << "Error opening the file: " << filename << '\n'; return false; } for (const auto& pair : poses) { outfile << pair.first << " " << pair.second.x << " " << pair.second.y << ' ' << pair.second.yaw_radians << '\n'; } return true; } } // namespace } // namespace ceres::examples int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true); CHECK(FLAGS_input != "") << "Need to specify the filename to read."; std::map<int, ceres::examples::Pose2d> poses; std::vector<ceres::examples::Constraint2d> constraints; CHECK(ceres::examples::ReadG2oFile(FLAGS_input, &poses, &constraints)) << "Error reading the file: " << FLAGS_input; std::cout << "Number of poses: " << poses.size() << '\n'; std::cout << "Number of constraints: " << constraints.size() << '\n'; CHECK(ceres::examples::OutputPoses("poses_original.txt", poses)) << "Error outputting to poses_original.txt"; ceres::Problem problem; ceres::examples::BuildOptimizationProblem(constraints, &poses, &problem); CHECK(ceres::examples::SolveOptimizationProblem(&problem)) << "The solve was not successful, exiting."; CHECK(ceres::examples::OutputPoses("poses_optimized.txt", poses)) << "Error outputting to poses_original.txt"; return 0; }
// Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2020 The Xcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/xcoin-config.h> #endif #include <clientversion.h> #include <coins.h> #include <consensus/consensus.h> #include <core_io.h> #include <key_io.h> #include <keystore.h> #include <policy/policy.h> #include <policy/rbf.h> #include <primitives/transaction.h> #include <script/script.h> #include <script/sign.h> #include <univalue.h> #include <util.h> #include <utilmoneystr.h> #include <utilstrencodings.h> #include <memory> #include <stdio.h> #include <boost/algorithm/string.hpp> static bool fCreateBlank; static std::map<std::string,UniValue> registers; static const int CONTINUE_EXECUTION=-1; static void SetupXcoinTxArgs() { gArgs.AddArg("-?", "This help message", false, OptionsCategory::OPTIONS); gArgs.AddArg("-create", "Create new, empty TX.", false, OptionsCategory::OPTIONS); gArgs.AddArg("-json", "Select JSON output", false, OptionsCategory::OPTIONS); gArgs.AddArg("-txid", "Output only the hex-encoded transaction id of the resultant transaction.", false, OptionsCategory::OPTIONS); SetupChainParamsBaseOptions(); gArgs.AddArg("delin=N", "Delete input N from TX", false, OptionsCategory::COMMANDS); gArgs.AddArg("delout=N", "Delete output N from TX", false, OptionsCategory::COMMANDS); gArgs.AddArg("in=TXID:VOUT(:SEQUENCE_NUMBER)", "Add input to TX", false, OptionsCategory::COMMANDS); gArgs.AddArg("locktime=N", "Set TX lock time to N", false, OptionsCategory::COMMANDS); gArgs.AddArg("nversion=N", "Set TX version to N", false, OptionsCategory::COMMANDS); gArgs.AddArg("outaddr=VALUE:ADDRESS", "Add address-based output to TX", false, OptionsCategory::COMMANDS); gArgs.AddArg("outdata=[VALUE:]DATA", "Add data-based output to TX", false, OptionsCategory::COMMANDS); gArgs.AddArg("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", "Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. " "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. " "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", false, OptionsCategory::COMMANDS); gArgs.AddArg("outpubkey=VALUE:PUBKEY[:FLAGS]", "Add pay-to-pubkey output to TX. " "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. " "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", false, OptionsCategory::COMMANDS); gArgs.AddArg("outscript=VALUE:SCRIPT[:FLAGS]", "Add raw script output to TX. " "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. " "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", false, OptionsCategory::COMMANDS); gArgs.AddArg("replaceable(=N)", "Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)", false, OptionsCategory::COMMANDS); gArgs.AddArg("sign=SIGHASH-FLAGS", "Add zero or more signatures to transaction. " "This command requires JSON registers:" "prevtxs=JSON object, " "privatekeys=JSON object. " "See signrawtransaction docs for format of sighash flags, JSON objects.", false, OptionsCategory::COMMANDS); gArgs.AddArg("load=NAME:FILENAME", "Load JSON file FILENAME into register NAME", false, OptionsCategory::REGISTER_COMMANDS); gArgs.AddArg("set=NAME:JSON-STRING", "Set register NAME to given JSON-STRING", false, OptionsCategory::REGISTER_COMMANDS); // Hidden gArgs.AddArg("-h", "", false, OptionsCategory::HIDDEN); gArgs.AddArg("-help", "", false, OptionsCategory::HIDDEN); } // // This function returns either one of EXIT_ codes when it's expected to stop the process or // CONTINUE_EXECUTION when it's expected to continue further. // static int AppInitRawTx(int argc, char* argv[]) { // // Parameters // SetupXcoinTxArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str()); return EXIT_FAILURE; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } fCreateBlank = gArgs.GetBoolArg("-create", false); if (argc < 2 || HelpRequested(gArgs)) { // First part of help message is specific to this utility std::string strUsage = PACKAGE_NAME " xcoin-tx utility version " + FormatFullVersion() + "\n\n" + "Usage: xcoin-tx [options] <hex-tx> [commands] Update hex-encoded xcoin transaction\n" + "or: xcoin-tx [options] -create [commands] Create hex-encoded xcoin transaction\n" + "\n"; strUsage += gArgs.GetHelpMessage(); fprintf(stdout, "%s", strUsage.c_str()); if (argc < 2) { fprintf(stderr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } return CONTINUE_EXECUTION; } static void RegisterSetJson(const std::string& key, const std::string& rawJson) { UniValue val; if (!val.read(rawJson)) { std::string strErr = "Cannot parse JSON for key " + key; throw std::runtime_error(strErr); } registers[key] = val; } static void RegisterSet(const std::string& strInput) { // separate NAME:VALUE in string size_t pos = strInput.find(':'); if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw std::runtime_error("Register input requires NAME:VALUE"); std::string key = strInput.substr(0, pos); std::string valStr = strInput.substr(pos + 1, std::string::npos); RegisterSetJson(key, valStr); } static void RegisterLoad(const std::string& strInput) { // separate NAME:FILENAME in string size_t pos = strInput.find(':'); if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw std::runtime_error("Register load requires NAME:FILENAME"); std::string key = strInput.substr(0, pos); std::string filename = strInput.substr(pos + 1, std::string::npos); FILE *f = fopen(filename.c_str(), "r"); if (!f) { std::string strErr = "Cannot open file " + filename; throw std::runtime_error(strErr); } // load file chunks into one big buffer std::string valStr; while ((!feof(f)) && (!ferror(f))) { char buf[4096]; int bread = fread(buf, 1, sizeof(buf), f); if (bread <= 0) break; valStr.insert(valStr.size(), buf, bread); } int error = ferror(f); fclose(f); if (error) { std::string strErr = "Error reading file " + filename; throw std::runtime_error(strErr); } // evaluate as JSON buffer register RegisterSetJson(key, valStr); } static CAmount ExtractAndValidateValue(const std::string& strValue) { CAmount value; if (!ParseMoney(strValue, value)) throw std::runtime_error("invalid TX output value"); return value; } static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newVersion; if (!ParseInt64(cmdVal, &newVersion) || newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION) throw std::runtime_error("Invalid TX version requested: '" + cmdVal + "'"); tx.nVersion = (int) newVersion; } static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newLocktime; if (!ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL || newLocktime > 0xffffffffLL) throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal + "'"); tx.nLockTime = (unsigned int) newLocktime; } static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested index int64_t inIdx; if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size())) { throw std::runtime_error("Invalid TX input index '" + strInIdx + "'"); } // set the nSequence to MAX_INT - 2 (= RBF opt in flag) int cnt = 0; for (CTxIn& txin : tx.vin) { if (strInIdx == "" || cnt == inIdx) { if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) { txin.nSequence = MAX_BIP125_RBF_SEQUENCE; } } ++cnt; } } static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput) { std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); // separate TXID:VOUT in string if (vStrInputParts.size()<2) throw std::runtime_error("TX input missing separator"); // extract and validate TXID std::string strTxid = vStrInputParts[0]; if ((strTxid.size() != 64) || !IsHex(strTxid)) throw std::runtime_error("invalid TX input txid"); uint256 txid(uint256S(strTxid)); static const unsigned int minTxOutSz = 9; static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz); // extract and validate vout const std::string& strVout = vStrInputParts[1]; int64_t vout; if (!ParseInt64(strVout, &vout) || vout < 0 || vout > static_cast<int64_t>(maxVout)) throw std::runtime_error("invalid TX input vout '" + strVout + "'"); // extract the optional sequence number uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max(); if (vStrInputParts.size() > 2) nSequenceIn = std::stoul(vStrInputParts[2]); // append to transaction input list CTxIn txin(txid, vout, CScript(), nSequenceIn); tx.vin.push_back(txin); } static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:ADDRESS std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); if (vStrInputParts.size() != 2) throw std::runtime_error("TX output missing or too many separators"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // extract and validate ADDRESS std::string strAddr = vStrInputParts[1]; CTxDestination destination = DecodeDestination(strAddr); if (!IsValidDestination(destination)) { throw std::runtime_error("invalid TX output address"); } CScript scriptPubKey = GetScriptForDestination(destination); // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:PUBKEY[:FLAGS] std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) throw std::runtime_error("TX output missing or too many separators"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // Extract and validate PUBKEY CPubKey pubkey(ParseHex(vStrInputParts[1])); if (!pubkey.IsFullyValid()) throw std::runtime_error("invalid TX output pubkey"); CScript scriptPubKey = GetScriptForRawPubKey(pubkey); // Extract and validate FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts[2]; bSegWit = (flags.find('W') != std::string::npos); bScriptHash = (flags.find('S') != std::string::npos); } if (bSegWit) { if (!pubkey.IsCompressed()) { throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs"); } // Call GetScriptForWitness() to build a P2WSH scriptPubKey scriptPubKey = GetScriptForWitness(scriptPubKey); } if (bScriptHash) { // Get the ID for the script, and then construct a P2SH destination for it. scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey)); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS] std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); // Check that there are enough parameters if (vStrInputParts.size()<3) throw std::runtime_error("Not enough multisig parameters"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // Extract REQUIRED uint32_t required = stoul(vStrInputParts[1]); // Extract NUMKEYS uint32_t numkeys = stoul(vStrInputParts[2]); // Validate there are the correct number of pubkeys if (vStrInputParts.size() < numkeys + 3) throw std::runtime_error("incorrect number of multisig pubkeys"); if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required) throw std::runtime_error("multisig parameter mismatch. Required " \ + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures."); // extract and validate PUBKEYs std::vector<CPubKey> pubkeys; for(int pos = 1; pos <= int(numkeys); pos++) { CPubKey pubkey(ParseHex(vStrInputParts[pos + 2])); if (!pubkey.IsFullyValid()) throw std::runtime_error("invalid TX output pubkey"); pubkeys.push_back(pubkey); } // Extract FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == numkeys + 4) { std::string flags = vStrInputParts.back(); bSegWit = (flags.find('W') != std::string::npos); bScriptHash = (flags.find('S') != std::string::npos); } else if (vStrInputParts.size() > numkeys + 4) { // Validate that there were no more parameters passed throw std::runtime_error("Too many parameters"); } CScript scriptPubKey = GetScriptForMultisig(required, pubkeys); if (bSegWit) { for (CPubKey& pubkey : pubkeys) { if (!pubkey.IsCompressed()) { throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs"); } } // Call GetScriptForWitness() to build a P2WSH scriptPubKey scriptPubKey = GetScriptForWitness(scriptPubKey); } if (bScriptHash) { if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) { throw std::runtime_error(strprintf( "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE)); } // Get the ID for the script, and then construct a P2SH destination for it. scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey)); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput) { CAmount value = 0; // separate [VALUE:]DATA in string size_t pos = strInput.find(':'); if (pos==0) throw std::runtime_error("TX output value not specified"); if (pos != std::string::npos) { // Extract and validate VALUE value = ExtractAndValidateValue(strInput.substr(0, pos)); } // extract and validate DATA std::string strData = strInput.substr(pos + 1, std::string::npos); if (!IsHex(strData)) throw std::runtime_error("invalid TX output data"); std::vector<unsigned char> data = ParseHex(strData); CTxOut txout(value, CScript() << OP_RETURN << data); tx.vout.push_back(txout); } static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput) { // separate VALUE:SCRIPT[:FLAGS] std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); if (vStrInputParts.size() < 2) throw std::runtime_error("TX output missing separator"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // extract and validate script std::string strScript = vStrInputParts[1]; CScript scriptPubKey = ParseScript(strScript); // Extract FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts.back(); bSegWit = (flags.find('W') != std::string::npos); bScriptHash = (flags.find('S') != std::string::npos); } if (scriptPubKey.size() > MAX_SCRIPT_SIZE) { throw std::runtime_error(strprintf( "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE)); } if (bSegWit) { scriptPubKey = GetScriptForWitness(scriptPubKey); } if (bScriptHash) { if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) { throw std::runtime_error(strprintf( "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE)); } scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey)); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested deletion index int64_t inIdx; if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size())) { throw std::runtime_error("Invalid TX input index '" + strInIdx + "'"); } // delete input from transaction tx.vin.erase(tx.vin.begin() + inIdx); } static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx) { // parse requested deletion index int64_t outIdx; if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >= static_cast<int64_t>(tx.vout.size())) { throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'"); } // delete output from transaction tx.vout.erase(tx.vout.begin() + outIdx); } static const unsigned int N_SIGHASH_OPTS = 6; static const struct { const char *flagStr; int flags; } sighashOptions[N_SIGHASH_OPTS] = { {"ALL", SIGHASH_ALL}, {"NONE", SIGHASH_NONE}, {"SINGLE", SIGHASH_SINGLE}, {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY}, {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY}, {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY}, }; static bool findSighashFlags(int& flags, const std::string& flagStr) { flags = 0; for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) { if (flagStr == sighashOptions[i].flagStr) { flags = sighashOptions[i].flags; return true; } } return false; } static CAmount AmountFromValue(const UniValue& value) { if (!value.isNum() && !value.isStr()) throw std::runtime_error("Amount is not a number or string"); CAmount amount; if (!ParseFixedPoint(value.getValStr(), 8, &amount)) throw std::runtime_error("Invalid amount"); if (!MoneyRange(amount)) throw std::runtime_error("Amount out of range"); return amount; } static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr) { int nHashType = SIGHASH_ALL; if (flagStr.size() > 0) if (!findSighashFlags(nHashType, flagStr)) throw std::runtime_error("unknown sighash flag/sign option"); // mergedTx will end up with all the signatures; it // starts as a clone of the raw tx: CMutableTransaction mergedTx{tx}; const CMutableTransaction txv{tx}; CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); if (!registers.count("privatekeys")) throw std::runtime_error("privatekeys register variable must be set."); CBasicKeyStore tempKeystore; UniValue keysObj = registers["privatekeys"]; for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) { if (!keysObj[kidx].isStr()) throw std::runtime_error("privatekey not a std::string"); CKey key = DecodeSecret(keysObj[kidx].getValStr()); if (!key.IsValid()) { throw std::runtime_error("privatekey not valid"); } tempKeystore.AddKey(key); } // Add previous txouts given in the RPC call: if (!registers.count("prevtxs")) throw std::runtime_error("prevtxs register variable must be set."); UniValue prevtxsObj = registers["prevtxs"]; { for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) { UniValue prevOut = prevtxsObj[previdx]; if (!prevOut.isObject()) throw std::runtime_error("expected prevtxs internal object"); std::map<std::string, UniValue::VType> types = { {"txid", UniValue::VSTR}, {"vout", UniValue::VNUM}, {"scriptPubKey", UniValue::VSTR}, }; if (!prevOut.checkObject(types)) throw std::runtime_error("prevtxs internal object typecheck fail"); uint256 txid = ParseHashStr(prevOut["txid"].get_str(), "txid"); const int nOut = prevOut["vout"].get_int(); if (nOut < 0) throw std::runtime_error("vout must be positive"); COutPoint out(txid, nOut); std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { const Coin& coin = view.AccessCoin(out); if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) { std::string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw std::runtime_error(err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = 0; if (prevOut.exists("amount")) { newcoin.out.nValue = AmountFromValue(prevOut["amount"]); } newcoin.nHeight = 1; view.AddCoin(out, std::move(newcoin), true); } // if redeemScript given and private keys given, // add redeemScript to the tempKeystore so it can be signed: if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) && prevOut.exists("redeemScript")) { UniValue v = prevOut["redeemScript"]; std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } const CKeyStore& keystore = tempKeystore; bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const Coin& coin = view.AccessCoin(txin.prevout); if (coin.IsSpent()) { continue; } const CScript& prevPubKey = coin.out.scriptPubKey; const CAmount& amount = coin.out.nValue; SignatureData sigdata = DataFromTransaction(mergedTx, i, coin.out); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) ProduceSignature(keystore, MutableTransactionSignatureCreator(&mergedTx, i, amount, nHashType), prevPubKey, sigdata); UpdateInput(txin, sigdata); } tx = mergedTx; } class Secp256k1Init { ECCVerifyHandle globalVerifyHandle; public: Secp256k1Init() { ECC_Start(); } ~Secp256k1Init() { ECC_Stop(); } }; static void MutateTx(CMutableTransaction& tx, const std::string& command, const std::string& commandVal) { std::unique_ptr<Secp256k1Init> ecc; if (command == "nversion") MutateTxVersion(tx, commandVal); else if (command == "locktime") MutateTxLocktime(tx, commandVal); else if (command == "replaceable") { MutateTxRBFOptIn(tx, commandVal); } else if (command == "delin") MutateTxDelInput(tx, commandVal); else if (command == "in") MutateTxAddInput(tx, commandVal); else if (command == "delout") MutateTxDelOutput(tx, commandVal); else if (command == "outaddr") MutateTxAddOutAddr(tx, commandVal); else if (command == "outpubkey") { ecc.reset(new Secp256k1Init()); MutateTxAddOutPubKey(tx, commandVal); } else if (command == "outmultisig") { ecc.reset(new Secp256k1Init()); MutateTxAddOutMultiSig(tx, commandVal); } else if (command == "outscript") MutateTxAddOutScript(tx, commandVal); else if (command == "outdata") MutateTxAddOutData(tx, commandVal); else if (command == "sign") { ecc.reset(new Secp256k1Init()); MutateTxSign(tx, commandVal); } else if (command == "load") RegisterLoad(commandVal); else if (command == "set") RegisterSet(commandVal); else throw std::runtime_error("unknown command"); } static void OutputTxJSON(const CTransaction& tx) { UniValue entry(UniValue::VOBJ); TxToUniv(tx, uint256(), entry); std::string jsonOutput = entry.write(4); fprintf(stdout, "%s\n", jsonOutput.c_str()); } static void OutputTxHash(const CTransaction& tx) { std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) fprintf(stdout, "%s\n", strHexHash.c_str()); } static void OutputTxHex(const CTransaction& tx) { std::string strHex = EncodeHexTx(tx); fprintf(stdout, "%s\n", strHex.c_str()); } static void OutputTx(const CTransaction& tx) { if (gArgs.GetBoolArg("-json", false)) OutputTxJSON(tx); else if (gArgs.GetBoolArg("-txid", false)) OutputTxHash(tx); else OutputTxHex(tx); } static std::string readStdin() { char buf[4096]; std::string ret; while (!feof(stdin)) { size_t bread = fread(buf, 1, sizeof(buf), stdin); ret.append(buf, bread); if (bread < sizeof(buf)) break; } if (ferror(stdin)) throw std::runtime_error("error reading stdin"); boost::algorithm::trim_right(ret); return ret; } static int CommandLineRawTx(int argc, char* argv[]) { std::string strPrint; int nRet = 0; try { // Skip switches; Permit common stdin convention "-" while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) { argc--; argv++; } CMutableTransaction tx; int startArg; if (!fCreateBlank) { // require at least one param if (argc < 2) throw std::runtime_error("too few parameters"); // param: hex-encoded xcoin transaction std::string strHexTx(argv[1]); if (strHexTx == "-") // "-" implies standard input strHexTx = readStdin(); if (!DecodeHexTx(tx, strHexTx, true)) throw std::runtime_error("invalid transaction encoding"); startArg = 2; } else startArg = 1; for (int i = startArg; i < argc; i++) { std::string arg = argv[i]; std::string key, value; size_t eqpos = arg.find('='); if (eqpos == std::string::npos) key = arg; else { key = arg.substr(0, eqpos); value = arg.substr(eqpos + 1); } MutateTx(tx, key, value); } OutputTx(tx); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRawTx()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); try { int ret = AppInitRawTx(argc, argv); if (ret != CONTINUE_EXECUTION) return ret; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRawTx()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "AppInitRawTx()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRawTx(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRawTx()"); } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRawTx()"); } return ret; }
.MODEL SMALL .STACK 100H .DATA STRING DB "I love cat$" VOWEL DB ? .CODE MAIN PROC MOV AX, @DATA MOV DS, AX MOV SI, OFFSET STRING MOV BL, 00 BACK: MOV AL, [SI] CMP AL,'$' JZ FINAL CMP AL,'A' JZ COUNT CMP AL,'E' JZ COUNT CMP AL,'I' JZ COUNT CMP AL,'O' JZ COUNT CMP AL,'U' JZ COUNT CMP AL,'a' JZ COUNT CMP AL,'e' JZ COUNT CMP AL,'i' JZ COUNT CMP AL,'o' JZ COUNT CMP AL,'u' JZ COUNT INC SI JMP BACK COUNT: INC BL MOV VOWEL, BL INC SI JMP BACK FINAL: MOV AH, 4CH INT 21H MAIN ENDP END
SECTION rodata_font_fzx PUBLIC _ff_ao_Dutch _ff_ao_Dutch: BINARY "font/fzx/fonts/ao/Dutch/Dutch.fzx"
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args=""/> <%docstring> Invokes the syscall vfork. See 'man 2 vfork' for more information. Arguments: </%docstring> ${syscall('SYS_vfork')}
#include <avr/io.h> int main() { while (1) { } return 0; }
/* Stream Converters * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include <string.h> #include "Exceptions.h" #include "AlignedVector.tpp" #include "StreamConverters.h" #include <iostream> using std::cout; using std::endl; namespace PokemonAutomation{ StreamConverter::StreamConverter( size_t object_size_in, size_t object_size_out, size_t buffer_capacity ) : m_object_size_in(object_size_in) , m_object_size_out(object_size_out) , m_buffer_capacity(buffer_capacity) , m_buffer(object_size_out * buffer_capacity) {} StreamConverter::~StreamConverter(){} void StreamConverter::operator+=(StreamListener& listener){ if (listener.object_size != m_object_size_out){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching object size."); } m_listeners.insert(&listener); } void StreamConverter::operator-=(StreamListener& listener){ m_listeners.erase(&listener); } void StreamConverter::push_objects(const void* data, size_t objects){ while (objects > 0){ size_t block = std::min(objects, m_buffer_capacity); convert(m_buffer.data(), data, block); data = (char*)data + block * m_object_size_in; objects -= block; for (StreamListener* listener : m_listeners){ listener->on_objects(m_buffer.data(), block); } } } //void print_u8(const uint8_t* ptr, size_t len); MisalignedStreamConverter::MisalignedStreamConverter( size_t object_size_in, size_t object_size_out, size_t buffer_capacity ) : m_object_size_in(object_size_in) , m_object_size_out(object_size_out) , m_edge(object_size_in) , m_buffer_capacity(buffer_capacity) , m_buffer(object_size_out * buffer_capacity) {} MisalignedStreamConverter::~MisalignedStreamConverter(){} void MisalignedStreamConverter::operator+=(StreamListener& listener){ if (listener.object_size != m_object_size_out){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching object size."); } m_listeners.insert(&listener); } void MisalignedStreamConverter::operator-=(StreamListener& listener){ m_listeners.erase(&listener); } void MisalignedStreamConverter::push_bytes(const void* data, size_t bytes){ // cout << "push: "; // print_u8((uint8_t*)data, bytes); // Fill the edge block. if (m_edge_size > 0){ // cout << "m_edge_size = " << m_edge_size << endl; size_t block = std::min(m_object_size_in - m_edge_size, bytes); memcpy(m_edge.data() + m_edge_size, data, block); m_edge_size += block; data = (char*)data + block; bytes -= block; } size_t stored = 0; // Process completed edge block. if (m_edge_size >= m_object_size_in){ // print_u8((uint8_t*)m_edge.data(), m_edge_size); convert(m_buffer.data() + stored * m_object_size_out, m_edge.data(), 1); m_edge_size = 0; stored++; } size_t objects = bytes / m_object_size_in; while (stored + objects > 0){ size_t block = std::min(objects, m_buffer_capacity - stored); // cout << "stored = " << stored << endl; // cout << "block = " << block << endl; // print_u8((uint8_t*)data, block * m_object_size_in); convert(m_buffer.data() + stored * m_object_size_out, data, block); data = (char*)data + block * m_object_size_in; bytes -= block * m_object_size_in; stored += block; objects -= block; for (StreamListener* listener : m_listeners){ listener->on_objects(m_buffer.data(), stored); } stored = 0; } // cout << "left = " << bytes << endl; // Copy remaining bytes into edge buffer. memcpy(m_edge.data(), data, bytes); m_edge_size = bytes; } }
; ================================================================ ; DevSound - a Game Boy music system by DevEd ; ; Copyright (c) 2017 - 2018 DevEd ; ; 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. ; ================================================================ ; Uncomment the following line to enable custom hooks. ; UseCustomHooks set 1 ; Uncomment the following line if you want the DevSound player code to be in ROM0 instead of its own bank. ; Could be useful for multibank setups. ; TODO: Make some tweaks to song data format to allow for multiple banks ; UseROM0 set 1 ; Uncomment the following line if you want to include song data elsewhere. ; Could be useful for multibank setups. ; TODO: Make some tweaks to song data format to allow for multiple banks ; DontIncludeSongData set 1 ; Comment the following line to disable SFX support (via FX Hammer). ; Useful if you want to use your own sound effect system. ; (Note that DevSound may require some minor modifications if you ; want to use your own SFX system.) UseFXHammer set 1 ; Uncomment this to disable all time-consuming features ; This includes: wave buffer, PWM, random wave, zombie mode, ; wave volume scaling, channel volume ; WARNING: Any songs that use the additional features will crash DevSound! ; DemoSceneMode set 1 ; Uncomment this to to disable wave volume scaling. ; PROS: Less CPU usage ; CONS: Less volume control for CH3 ; NoWaveVolumeScaling set 1 ; Uncomment this to disable zombie mode (for compatibility ; with old emulators such as VBA). ; NOTE: Zombie mode is known to be problematic with certain ; GBC CPU revisions. If you want your game/demo to be ; compatible with all GBC hardware revisions, I would ; recommend disabling this. ; PROS: Less CPU usage ; Compatible with old emulators such as VBA ; CONS: Volume envelopes will sound "dirtier" ; DisableZombieMode set 1 ; Comment this line to enable Deflemask compatibility hacks. DisableDeflehacks set 1 ; Uncomment this line for a simplified echo buffer. Useful if RAM usage ; is a concern. ; PROS: Less RAM usage ; CONS: Echo delay will be disabled ; SimpleEchoBuffer set 1 if !def(UseFXHammerDisasm) FXHammer_SFXCH2 equ $c7cc FXHammer_SFXCH4 equ $c7d9 endc DevSound: include "DevSound_Vars.asm" include "DevSound_Consts.asm" include "DevSound_Macros.asm" if !def(UseROM0) SECTION "DevSound",ROMX else SECTION "DevSound",ROM0 endc if !def(UseCustomHooks) DevSound_JumpTable: DS_Init: jp DevSound_Init DS_Play: jp DevSound_Play DS_Stop: jp DevSound_Stop DS_Fade: jp DevSound_Fade DS_ExternalCommand: jp DevSound_ExternalCommand endc ; Driver thumbprint db "DevSound GB music player by DevEd | email: deved8@gmail.com" ; ================================================================ ; Init routine ; INPUT: a = ID of song to init ; ================================================================ DevSound_Init: di push af ; Preserve song ID xor a ldh [rNR52],a ; disable sound ld [PWMEnabled],a ld [RandomizerEnabled],a ld [WaveBufUpdateFlag],a ; init sound RAM area ld de,DefaultRegTable ld hl,InitVarsStart ld c,DSVarsEnd-InitVarsStart .initLoop ld a,[de] ld [hl+],a inc de dec c jr nz,.initLoop xor a ld c,DSBufVarsEnd-DSBufVars .initLoop2 ld [hl+],a dec c jr nz,.initLoop2 ; load default waveform ld hl,DefaultWave call LoadWave ; clear buffers call ClearWaveBuffer call ClearArpBuffer call ClearEchoBuffers pop af add a ld e,a adc a,0 sub e ld d,a ; set up song pointers ld hl,SongPointerTable add hl,de ld a,[hl+] ld h,[hl] ld l,a ld a,[hl+] ld [CH1Ptr],a ld a,[hl+] ld [CH1Ptr+1],a ld a,[hl+] ld [CH2Ptr],a ld a,[hl+] ld [CH2Ptr+1],a ld a,[hl+] ld [CH3Ptr],a ld a,[hl+] ld [CH3Ptr+1],a ld a,[hl+] ld [CH4Ptr],a ld a,[hl+] ld [CH4Ptr+1],a ld a,low(DummyChannel) ld [CH1RetPtr],a ld [CH2RetPtr],a ld [CH3RetPtr],a ld [CH4RetPtr],a ld a,high(DummyChannel) ld [CH1RetPtr+1],a ld [CH2RetPtr+1],a ld [CH3RetPtr+1],a ld [CH4RetPtr+1],a ld a,$11 ld [CH1Pan],a ld [CH2Pan],a ld [CH3Pan],a ld [CH4Pan],a ld a,15 ld [CH1ChanVol],a ld [CH2ChanVol],a ld [CH3ChanVol],a ld [CH4ChanVol],a ; get tempo ld hl,SongSpeedTable add hl,de ld a,[hl+] dec a ld [GlobalSpeed1],a ld a,[hl] dec a ld [GlobalSpeed2],a ld a,%10000000 ldh [rNR52],a ld a,$FF ldh [rNR51],a ld a,7 ld [GlobalVolume],a ; if visualizer is enabled, init it too if def(Visualizer) if !def(DemoSceneMode) && !def(NoWaveVolumeScaling) CopyBytes DefaultWave,VisualizerTempWave,16 endc call VisualizerInit endc reti ; ================================================================ ; External command processing routine ; INPUT: a = command ID ; bc = parameters ; ================================================================ DevSound_ExternalCommand: cp (.commandTableEnd-.commandTable)/2 ret nc ; if command ID is out of bounds, exit ld hl,.commandTable add a add l ld l,a jr nc,.nocarry inc h .nocarry ld a,[hl+] ld h,[hl] ld l,a jp hl .commandTable dw .dummy ; $00 - dummy dw .setSpeed ; $01 - set speed dw .muteChannel ; $02 - mute given sound channel (TODO) .commandTableEnd .setSpeed ld a,b ld [GlobalSpeed1],a ld a,c ld [GlobalSpeed2],a ; ret .muteChannel ; TODO ; ld a,c ; and 3 .dummy ret ; ================================================================ ; Stop routine ; ================================================================ DevSound_Stop: ld c,low(rNR52) xor a ld [c],a ; disable sound output (resets all sound regs) set 7,a ld [c],a ; enable sound output dec c xor a ld [CH1Enabled],a ld [CH2Enabled],a ld [CH3Enabled],a ld [CH4Enabled],a ld [SoundEnabled],a dec a ; Set a to $FF ld [c],a ; all sound channels to left+right speakers dec c and $77 ld [c],a ; VIN output off + master volume max ; if visualizer is enabled, init it too (to make everything zero) if def(Visualizer) jp VisualizerInit else ret endc ; ================================================================ ; Fade routine ; Note: if planning to call both this and DS_Init, call this first. ; ================================================================ DevSound_Fade: and 3 cp 3 ret z ; 3 is an invalid value, silently ignore it inc a ; Increment... set 2,a ; Mark this fade as the first ld [FadeType],a ld a,7 ld [FadeTimer],a ret ; ================================================================ ; Play routine ; ================================================================ DevSound_Play: ; Since this routine is called during an interrupt (which may ; happen in the middle of a routine), preserve all register ; values just to be safe. ; Other registers are saved at `.doUpdate`. push af ld a,[SoundEnabled] and a jr nz,.doUpdate ; if sound is enabled, jump ahead pop af ret .doUpdate push bc push de push hl ; do stuff with sync tick ld a,[SyncTick] and a jr z,.getSongTimer dec a ld [SyncTick],a .getSongTimer ld a,[GlobalTimer] ; get global timer and a ; is GlobalTimer non-zero? jr nz,.noupdate ; if yes, don't update ld a,[TickCount] ; get current tick count xor 1 ; toggle between 0 and 1 ld [TickCount],a ; store it in RAM jr nz,.odd ; if a is 1, jump .even ld a,[GlobalSpeed2] jr .setTimer .odd ld a,[GlobalSpeed1] .setTimer ld [GlobalTimer],a ; store timer value jr UpdateCH1 ; continue ahead .noupdate dec a ; subtract 1 from timer ld [GlobalTimer],a ; store timer value jp DoneUpdating ; done ; ================================================================ UpdateChannel: macro IS_PULSE_CHANNEL equ (\1 == 1) || (\1 == 2) IS_WAVE_CHANNEL equ \1 == 3 IS_NOISE_CHANNEL equ \1 == 4 ld a,[CH\1Enabled] and a jp z,CH\1Updated ; if channel is disabled, skip to next one ld a,[CH\1Tick] and a jr z,.continue ; if channel tick = 0, then jump ahead dec a ; otherwise... ld [CH\1Tick],a ; decrement channel tick... jp CH\1Updated ; ...and do echo buffer. .continue ld hl,CH\1Ptr ; get pointer ld a,[hl+] ld h,[hl] ld l,a CH\1_CheckByte: ld a,[hl+] ; get byte cp $ff ; if $ff... jp z,.endChannel cp $c9 ; if $c9... jp z,.retSection cp release ; if release jp z,.release cp ___ ; if null note... jp z,.nullnote cp echo ; if echo jp z,.echo bit 7,a ; if command... jp nz,.getCommand ; if we have a note... if !IS_NOISE_CHANNEL ld b,a xor a ld [CH\1DoEcho],a ld a,b endc .getNote if IS_NOISE_CHANNEL ld [CH\1ModeBackup],a else ld [CH\1NoteBackup],a ; set note ld b,a ld a,[CH\1NotePlayed] and a jr nz,.skipfill ld a,b call CH\1FillEchoBuffer .skipfill endc ld a,[hl+] ; get note length dec a ; subtract 1 ld [CH\1Tick],a ; set channel tick ld a,l ; store back current pos ld [CH\1Ptr],a ld a,h ld [CH\1Ptr+1],a if !IS_NOISE_CHANNEL ld a,[CH\1PortaType] dec a ; if toneporta, don't reset everything jr z,.noreset endc if !IS_WAVE_CHANNEL if ((\1 == 2) || (\1 == 4)) && UseFXHammer ld a,[FXHammer_SFXCH\1] cp 3 jr z,.noupdate endc xor a else ld a, $FF ld [CH\1Wave],a ld a,[CH\1ComputedVol] ; Fix for volume not updating when unpausing endc ldh [rNR\12],a .noupdate xor a if IS_NOISE_CHANNEL ld [CH\1NoisePos],a if !def(DisableDeflehacks) ld [CH\1WavePos],a endc else ld [CH\1ArpPos],a ; reset arp position inc a ld [CH\1VibPos],a ; reset vibrato position ld hl,CH\1VibPtr ld a,[hl+] ld h,[hl] ld l,a ld a,[hl] ; get vibrato delay ld [CH\1VibDelay],a ; set delay endc xor a ld hl,CH\1Reset if !IS_NOISE_CHANNEL bit 0,[hl] jr nz,.noreset_checkvol if IS_PULSE_CHANNEL ld [CH\1PulsePos],a elif IS_WAVE_CHANNEL ld [CH\1WavePos],a endc .noreset_checkvol endc bit 1,[hl] jr nz,.noreset ld [CH\1VolPos],a if !IS_WAVE_CHANNEL ld [CH\1VolLoop],a endc .noreset ld a,[CH\1NoteCount] inc a ld [CH\1NoteCount],a ld b,a ; check if instrument mode is 1 (alternating) ld a,[CH\1InsMode] and a jr z,.noInstrumentChange ld a,b rra jr nc,.notodd ld a,[CH\1Ins1] jr .odd .notodd ld a,[CH\1Ins2] .odd call CH\1_SetInstrument .noInstrumentChange if !IS_NOISE_CHANNEL ld hl,CH\1Reset set 7,[hl] ; signal the start of note for pitch bend endc jp CH\1Updated .endChannel xor a ld [CH\1Enabled],a jp CH\1Updated .retSection ld hl,CH\1RetPtr ld a,[hl+] ld [CH\1Ptr],a ld a,[hl] ld [CH\1Ptr+1],a jp UpdateCH\1 .echo ; Not applicable to CH4 if !IS_NOISE_CHANNEL ld b,a ld a,1 ld [CH\1DoEcho],a ld a,b jp .getNote endc .nullnote if !IS_NOISE_CHANNEL xor a ld [CH\1DoEcho],a endc ld a,[hl+] dec a ld [CH\1Tick],a ; set tick ld a,l ; store back current pos ld [CH\1Ptr],a ld a,h ld [CH\1Ptr+1],a jp CH\1Updated .release ; follows FamiTracker's behavior except only the volume table will be affected if !IS_NOISE_CHANNEL xor a ld [CH\1DoEcho],a endc ld a,[hl+] dec a ld [CH\1Tick],a ; set tick ld a,l ; store back current pos ld [CH\1Ptr],a ld a,h ld [CH\1Ptr+1],a ld hl,CH\1VolPtr ld a,[hl+] ld h,[hl] ld l,a ld b,0 .releaseloop ld a,[hl+] inc b cp $ff jr z,.norelease cp $fe jr nz,.releaseloop ld a,b inc a ld [CH\1VolPos],a .norelease jp CH\1Updated .getCommand if !IS_NOISE_CHANNEL ld b,a xor a ld [CH\1DoEcho],a ld a,b endc cp DummyCommand jp nc, CH\1_CheckByte ; Not needed because function performs "add a" which discards bit 7 ; sub $80 ; subtract 128 from command value call JumpTableBelow dw .setInstrument dw .setLoopPoint dw .gotoLoopPoint dw .callSection dw .setChannelPtr dw .pitchBendUp dw .pitchBendDown dw .setSweep dw .setPan dw .setSpeed dw .setInsAlternate if IS_WAVE_CHANNEL && !def(DemoSceneMode) dw .randomizeWave else dw CH\1_CheckByte endc dw .combineWaves dw .enablePWM dw .enableRandomizer if IS_WAVE_CHANNEL && !def(DemoSceneMode) dw .disableAutoWave else dw CH\1_CheckByte endc dw .arp dw .toneporta dw .chanvol dw .setSyncTick dw .setEchoDelay dw .setRepeatPoint dw .repeatSection dw .setMontyMode .setInstrument ld a,[hl+] ; get ID of instrument to switch to push hl ; preserve HL call CH\1_SetInstrument pop hl ; restore HL xor a ld [CH\1InsMode],a ; reset instrument mode jp CH\1_CheckByte .setLoopPoint ld a,l ld [CH\1LoopPtr],a ld a,h ld [CH\1LoopPtr+1],a jp CH\1_CheckByte .gotoLoopPoint ld hl,CH\1LoopPtr ; get loop pointer ld a,[hl+] ld [CH\1Ptr],a ld a,[hl] ld [CH\1Ptr+1],a jp UpdateCH\1 .callSection ld a,[hl+] ld [CH\1Ptr],a ld a,[hl+] ld [CH\1Ptr+1],a ld a,l ld [CH\1RetPtr],a ld a,h ld [CH\1RetPtr+1],a jp UpdateCH\1 .setChannelPtr ld a,[hl+] ld [CH\1Ptr],a ld a,[hl] ld [CH\1Ptr+1],a jp UpdateCH\1 if !IS_NOISE_CHANNEL .pitchBendUp ld a,[hl+] ld [CH\1PortaSpeed],a and a jr z,.loadPortaType ld a,2 jr .loadPortaType .pitchBendDown ld a,[hl+] ld [CH\1PortaSpeed],a and a jr z,.loadPortaType ld a,3 jr .loadPortaType .toneporta ld a,[hl+] ld [CH\1PortaSpeed],a and a jr z,.loadPortaType ld a,1 .loadPortaType ld [CH\1PortaType],a jp CH\1_CheckByte endc if \1 == 1 .setSweep ld a,[hl+] ld [CH\1Sweep],a jp CH\1_CheckByte endc .setPan ld a,[hl+] ld [CH\1Pan],a jp CH\1_CheckByte .setSpeed ld a,[hl+] dec a ld [GlobalSpeed1],a ld a,[hl+] dec a ld [GlobalSpeed2],a jp CH\1_CheckByte .setInsAlternate ld a,[hl+] ld [CH\1Ins1],a ld a,[hl+] ld [CH\1Ins2],a ld a,1 ld [CH\1InsMode],a jp CH\1_CheckByte if IS_WAVE_CHANNEL && !def(DemoSceneMode) .randomizeWave push hl call _RandomizeWave pop hl jp CH\1_CheckByte .combineWaves push bc ld a,[hl+] ld c,a ld a,[hl+] ld b,a ld a,[hl+] ld e,a ld a,[hl+] ld d,a push hl call _CombineWaves pop hl pop bc jp CH\1_CheckByte .enablePWM push hl call ClearWaveBuffer pop hl ld a,[hl+] ld [PWMVol],a ld a,[hl+] ld [PWMSpeed],a ld a,$ff ld [WavePos],a xor a ld [PWMDir],a ld [RandomizerEnabled],a inc a ld [PWMEnabled],a ld [PWMTimer],a jp CH\1_CheckByte .enableRandomizer push hl call ClearWaveBuffer pop hl ld a,[hl+] ld [RandomizerSpeed],a xor a ld [PWMEnabled],a inc a ld [RandomizerTimer],a ld [RandomizerEnabled],a jp CH\1_CheckByte .disableAutoWave xor a ld [PWMEnabled],a ld [RandomizerEnabled],a jp CH\1_CheckByte else .combineWaves inc hl inc hl .enablePWM if IS_NOISE_CHANNEL .arp endc inc hl .enableRandomizer endc if IS_NOISE_CHANNEL .pitchBendUp .pitchBendDown .toneporta .setEchoDelay endc if \1 != 1 .setSweep endc inc hl jp CH\1_CheckByte .setSyncTick ld a,[hl+] ld [SyncTick],a jp CH\1_CheckByte .chanvol ld a,[hl+] and $f ld [CH\1ChanVol],a jp CH\1_CheckByte if !IS_NOISE_CHANNEL .arp call DoArp jp CH\1_CheckByte .setEchoDelay ld a,[hl+] and $3f ld [CH\1EchoDelay],a jp CH\1_CheckByte endc .setRepeatPoint ld a,l ld [CH\1RepeatPtr],a ld a,h ld [CH\1RepeatPtr+1],a jp CH\1_CheckByte .repeatSection ld a,[CH\1RepeatCount] and a ; section currently repeating? jr z,.notrepeating dec a ld [CH\1RepeatCount],a and a jr z,.stoprepeating inc hl jr .dorepeat .notrepeating ld a,[hl+] dec a ld [CH\1RepeatCount],a ld a,1 ld [CH\1DoRepeat],a .dorepeat ld hl,CH\1RepeatPtr ; get loop pointer ld a,[hl+] ld [CH\1Ptr],a ld a,[hl] ld [CH\1Ptr+1],a jp UpdateCH\1 .stoprepeating xor a ld [CH\1DoRepeat],a .norepeat inc hl jp CH\1_CheckByte .setMontyMode ld a,[hl+] and $7f ; upper bit is used as a flag ld [CH\1MontyMode],a ld [CH\1MontyTimer],a jp CH\1_CheckByte CH\1_SetInstrument: ld hl,InstrumentTable ld e,a ld d,0 add hl,de add hl,de ld a,[hl+] ld h,[hl] ld l,a ; no reset flag ld a,[hl+] and 3 ld [CH\1Reset],a ld b,a ; vol table ld a,[hl+] ld [CH\1VolPtr],a ld a,[hl+] ld [CH\1VolPtr+1],a ; arp table ld a,[hl+] if IS_NOISE_CHANNEL ld [CH\1NoisePtr],a else ld [CH\1ArpPtr],a endc ld a,[hl+] if IS_NOISE_CHANNEL ld [CH\1NoisePtr+1],a else ld [CH\1ArpPtr+1],a endc if !IS_NOISE_CHANNEL || !def(DisableDeflehacks) ; pulse table ld a,[hl+] if IS_PULSE_CHANNEL ld [CH\1PulsePtr],a else ld [CH\1WavePtr],a endc ld a,[hl+] if IS_PULSE_CHANNEL ld [CH\1PulsePtr+1],a else ld [CH\1WavePtr+1],a endc endc if !IS_NOISE_CHANNEL ; vib table ld a,[hl+] ld [CH\1VibPtr],a ld a,[hl+] ld [CH\1VibPtr+1],a ld hl,CH\1VibPtr ld a,[hl+] ld h,[hl] ld l,a ld a,[hl] ld [CH\1VibDelay],a endc ret CH\1Updated: PURGE IS_PULSE_CHANNEL PURGE IS_WAVE_CHANNEL PURGE IS_NOISE_CHANNEL endm ; ================================================================ UpdateCH1: UpdateChannel 1 UpdateCH2: UpdateChannel 2 UpdateCH3: UpdateChannel 3 UpdateCH4: UpdateChannel 4 ; ================================================================ DoneUpdating: call DoEchoBuffers ; update panning ld a,[CH4Pan] add a ld b,a ld a,[CH3Pan] or b add a ld b,a ld a,[CH2Pan] or b add a ld b,a ld a,[CH1Pan] or b ldh [rNR51],a ; update global volume + fade system ld a,[FadeType] ld b,a and 3 ; Check if no fade jr z,.updateVolume ; Update volume bit 2,b ; Check if on first fade jr z,.notfirstfade res 2,b ld a,b ld [FadeType],a dec a dec a ; If fading in (value 2), volume is 0 ; otherwise, it's 7 jr z,.gotfirstfadevolume ld a,7 .gotfirstfadevolume ld [GlobalVolume],a .notfirstfade ld a,[FadeTimer] and a jr z,.doupdate dec a ld [FadeTimer],a jr .updateVolume .fadeout ld a,[GlobalVolume] and a jr z,.fadeFinished .decrementVolume dec a ld [GlobalVolume],a jr .directlyUpdateVolume .fadein ld a,[GlobalVolume] cp 7 jr z,.fadeFinished inc a ld [GlobalVolume],a jr .directlyUpdateVolume .doupdate ld a,7 ld [FadeTimer],a ld a,[FadeType] and 3 dec a jr z,.fadeout dec a jr z,.fadein dec a ld a,[GlobalVolume] jr nz,.directlyUpdateVolume .fadeoutstop and a jr nz,.decrementVolume call DevSound_Stop xor a .fadeFinished ; a is zero ld [FadeType],a .updateVolume ld a,[GlobalVolume] .directlyUpdateVolume and 7 ld b,a swap a or b ldh [rNR50],a ; ================================================================ UpdateRegisters: macro ld a,[CH\1Enabled] and a jp z,CH\1RegistersUpdated if ((\1 == 2) || (\1 == 4)) && UseFXHammer ld a,[FXHammer_SFXCH\1] cp 3 jr z,.norest endc if \1 != 4 ld a,[CH\1NoteBackup] ld [CH\1Note],a else ld a,[CH\1ModeBackup] ld [CH\1Mode],a endc cp rest jr nz,.norest ld a,[CH\1IsResting] and a jp nz,.done xor a ldh [rNR\12],a if \1 == 3 ld [CH\1Vol],a ld [CH\1ComputedVol],a elif def(Visualizer) ld [CH\1OutputLevel],a ld [CH\1TempEnvelope],a endc ldh a,[rNR\14] or %10000000 ldh [rNR\14],a ld a,1 ld [CH\1IsResting],a jp .done .norest xor a ld [CH\1IsResting],a ; update arps .updatearp ; Deflemask compatibility: if pitch bend is active, don't update arp and force the transpose of 0 if \1 != 4 && !def(DisableDeflehacks) ld a,[CH\1PortaType] and a jr z,.noskiparp xor a ld [CH\1Transpose],a jr .continue endc .noskiparp if \1 != 4 ld hl,CH\1ArpPtr else ld hl,CH\1NoisePtr endc ld a,[hl+] ld h,[hl] ld l,a if \1 != 4 ld a,[CH\1ArpPos] else ld a,[CH\1NoisePos] endc add l ld l,a jr nc,.nocarry inc h .nocarry ld a,[hl+] cp $fe jr nz,.noloop ld a,[hl] if \1 != 4 ld [CH\1ArpPos],a else ld [CH\1NoisePos],a endc jr .updatearp .noloop cp $ff jr z,.continue cp $80 jr nc,.absolute sla a sra a jr .donearp .absolute and $7f if \1 != 4 ld [CH\1Note],a else ld [CH\1Mode],a endc xor a .donearp ld [CH\1Transpose],a .noreset if \1 != 4 ld hl,CH\1ArpPos else ld hl,CH\1NoisePos endc inc [hl] .continue if \1 == 1 ; update sweep ld a,[CH\1Sweep] ldh [rNR\10],a elif \1 == 3 ld a,$80 ldh [rNR\10],a endc if \1 == 4 if !def(DisableDeflehacks) ld hl,CH\1WavePtr ld a,[hl+] ld h,[hl] ld l,a ld a,[CH\1WavePos] add l ld l,a jr nc,.nocarry3 inc h .nocarry3 ld a,[hl+] cp $ff jr z,.updateNote ld [CH\1Wave],a ld a,[CH\1WavePos] inc a ld [CH\1WavePos],a ld a,[hl+] cp $fe jr nz,.updateNote ld a,[hl] ld [CH\1WavePos],a endc elif \1 != 3 ; update pulse ld hl,CH\1PulsePtr ld a,[hl+] ld h,[hl] ld l,a ld a,[CH\1PulsePos] add l ld l,a jr nc,.nocarry2 inc h .nocarry2 ld a,[hl+] cp $ff jr z,.updateNote ; convert pulse value and 3 ; make sure value does not exceed 3 if def(Visualizer) ld [CH\1Pulse],a endc rrca ; rotate right rrca ; "" "" if (\1 == 2) && UseFXHammer ld e,a ld a,[FXHammer_SFXCH\1] cp 3 jr z,.noreset2 ld a,e endc ldh [rNR\11],a ; transfer to register .noreset2 ld a,[CH\1PulsePos] inc a ld [CH\1PulsePos],a ld a,[hl+] cp $fe jr nz,.updateNote ld a,[hl] ld [CH\1PulsePos],a endc ; get note .updateNote if \1 != 4 ld a,[CH\1DoEcho] and a jr z,.skipecho ld a,[CH\1EchoDelay] ld b,a ld a,[EchoPos] sub b and $3f ld hl,CH\1EchoBuffer add l ld l,a jr nc,.nocarry3 inc h .nocarry3 ld a,[hl] cp $4a jr nz,.getfrequency ; TODO: Prevent null byte from being played jr .getfrequency .skipecho ld a,[CH\1PortaType] cp 2 jr c,.skippitchbend ld a,[CH\1Reset] bit 7,a jr z,.pitchbend .skippitchbend if \1 == 1 ld a,[CH\1Sweep] and $70 jr z,.noskipsweep ld a,[CH\1Reset] bit 7,a jp z,.updateVolume .noskipsweep endc ld a,[CH\1Transpose] ld b,a ld a,[CH\1Note] add b .getfrequency ld c,a ld b,0 ld hl,FreqTable add hl,bc add hl,bc ld a,[hl+] ld e,a ld [CH\1MontyFreq],a ld a,[hl] ld d,a ld [CH\1MontyFreq+1],a ld a,[CH\1PortaType] cp 2 jr c,.updateVibTable ld a,e ld [CH\1TempFreq],a ld a,d ld [CH\1TempFreq+1],a .updateVibTable ld a,[CH\1VibDelay] and a jr z,.doVib dec a ld [CH\1VibDelay],a jr .setFreq .doVib ld hl,CH\1VibPtr ld a,[hl+] ld h,[hl] ld l,a ld a,[CH\1VibPos] add l ld l,a jr nc,.nocarry4 inc h .nocarry4 ld a,[hl+] cp $80 jr nz,.noloop2 ld a,[hl+] ld [CH\1VibPos],a jr .doVib .noloop2 ld [CH\1FreqOffset],a ld a,[CH\1VibPos] inc a ld [CH\1VibPos],a jr .getPitchOffset .pitchbend ld a,[CH\1PortaSpeed] ld b,a ld a,[CH\1PortaType] and 1 jr nz,.sub2 ld a,[CH\1TempFreq] add b ld e,a ld a,[CH\1TempFreq+1] jr nc,.nocarry6 inc a .nocarry6 ld d,a cp 8 jr c,.pitchbenddone ld de,$7ff jr .pitchbenddone .sub2 ld a,[CH\1TempFreq] sub b ld e,a ld a,[CH\1TempFreq+1] jr nc,.nocarry7 dec a .nocarry7 ld d,a cp 8 jr c,.pitchbenddone ld de,0 .pitchbenddone ld hl,CH\1TempFreq ld a,e ld [hl+],a ld [hl],d .getPitchOffset ld a,[CH\1FreqOffset] bit 7,a jr nz,.sub add e ld e,a jr nc,.setFreq inc d jr .setFreq .sub ld c,a ld a,e add c ld e,a .setFreq ld a,[CH\1MontyMode] and a ; is Monty mode on? jr z,.nomonty ; if not, skip ld a,[CH\1MontyTimer] dec a jr nz,.montyset ld a,[CH\1MontyMode] and $7f ; strip monty flag ld [CH\1MontyTimer],a jr .montycontinue .montyset: ld [CH\1MontyTimer],a ld a,[CH\1MontyMode] jr .montycheck .montycontinue ld a,[CH\1MontyMode] xor %10000000 ; flip monty flag ld [CH\1MontyMode],a .montycheck bit 7,a ; is flag set? jr nz,.nomonty ld hl,CH\1MontyFreq ; use base pitch ld a,[hl+] ld d,[hl] ld e,a ; TODO: Work out vibrato jr .donesetFreq .nomonty ld hl,CH\1TempFreq ; use calculated pitch .dogetpitchoffset ld a,[CH\1PortaType] and a jr z,.normal dec a ld a,e jr nz,.donesetFreq ; toneporta ld a,[hl+] ld h,[hl] ld l,a ld a,[CH\1PortaSpeed] ld c,a ld b,0 ld a,h cp d jr c,.lt jr nz,.gt ld a,l cp e jr z,.tonepordone jr c,.lt .gt ld a,l sub c ld l,a jr nc,.nocarry8 dec h .nocarry8 ld a,h cp d jr c,.clamp jr nz,.tonepordone ld a,l cp e jr c,.clamp jr .tonepordone .lt add hl,bc ld a,h cp d jr c,.tonepordone jr nz,.clamp ld a,l cp e jr c,.tonepordone .clamp ld h,d ld l,e .tonepordone ld a,l ld [CH\1TempFreq],a if def(Visualizer) ld [CH\1ComputedFreq],a endc if \1 != 2 || !UseFXHammer ldh [rNR\13],a endc ld a,h ld d,a ; for later restart uses ld [CH\1TempFreq+1],a if def(Visualizer) ld [CH\1ComputedFreq+1],a endc if \1 != 2 || !UseFXHammer ldh [rNR\14],a elif UseFXHammer ld a,[FXHammer_SFXCH\1] cp 3 jr z,.updateVolume ld a,l ldh [rNR\13],a ld a,h ldh [rNR\14],a endc jr .updateVolume .normal ld a,e ld [hl+],a ld [hl],d .donesetFreq if \1 == 2 && UseFXHammer ld a,[FXHammer_SFXCH\1] cp 3 ld a,e jr z,.updateVolume endc if def(Visualizer) ld [CH\1ComputedFreq],a endc ldh [rNR\13],a ld a,d if def(Visualizer) ld [CH\1ComputedFreq+1],a endc ldh [rNR\14],a else ; don't do per noise mode arp clamping if deflemask compatibility mode ; is disabled so that relative arp with noise mode change is possible ld a,[CH\1Mode] CLAMP_VALUE = 90 if !def(DisableDeflehacks) CLAMP_VALUE = 45 cp CLAMP_VALUE ld c,0 jr c,.noise15_2 sub CLAMP_VALUE inc c .noise15_2 endc ld b,a ld a,[CH\1Transpose] bit 7,a jr nz,.minus if !def(DisableDeflehacks) cp CLAMP_VALUE jr c,.noise15_3 sub CLAMP_VALUE ld c,1 .noise15_3 endc add b cp CLAMP_VALUE jr c,.noclamp ld a,CLAMP_VALUE - 1 jr .noclamp .minus add b cp CLAMP_VALUE jr c,.noclamp xor a .noclamp if !def(DisableDeflehacks) ld b,a ld a,[CH\1Wave] or c and a jr z,.noise15 ld a,CLAMP_VALUE .noise15 add b endc if def(Visualizer) ld [CH\1Noise],a endc ld hl,NoiseTable add l ld l,a jr nc,.nocarry2 inc h .nocarry2 if UseFXHammer ld a,[FXHammer_SFXCH\1] cp 3 jr z,.updateVolume endc ld a,[hl+] ldh [rNR\13],a endc ; update volume .updateVolume ld hl,CH\1Reset res 7,[hl] ld hl,CH\1VolPtr ld a,[hl+] ld h,[hl] ld l,a if \1 != 3 ld a,[CH\1VolLoop] inc a ; ended jp z,.done endc ld a,[CH\1VolPos] add l ld l,a jr nc,.nocarry5 inc h .nocarry5 ld a,[hl+] cp $ff jr z,.loadlast cp $fd jp z,.done ld b,a if !def(DemoSceneMode) if !def(DisableZombieMode) || (\1 == 3) ld a,[CH\1ChanVol] push hl call MultiplyVolume pop hl endc if !def(DisableZombieMode) && (\1 != 3) ld a,[CH\1VolLoop] dec a jr z,.zombieatpos0 ld a,[CH\1VolPos] and a jr z,.zombinit .zombieatpos0 endc endc ld a,[CH\1Vol] sub b jr z,.noreset3 if \1 != 3 if !def(DemoSceneMode) && !def(DisableZombieMode) or ~$0f ld c,a ld a,b ld [CH\1Vol],a if def(Visualizer) ld [CH\1OutputLevel],a endc ld a,8 .zombloop ldh [rNR\12],a inc c jr nz,.zombloop jr .noreset3 .zombinit endc ld a,b ld [CH\1Vol],a if def(Visualizer) ld [CH\1OutputLevel],a endc swap a or 8 ldh [rNR\12],a if def(Visualizer) && (\1 != 3) xor a ld [CH\1TempEnvelope],a endc ld a,d or $80 ldh [rNR\14],a .noreset3 else ld a,b ld [CH\1Vol],a if def(DemoSceneMode) || def(NoWaveVolumeScaling) and a jr z,.skip cp 8 ld b,%00100000 jr nc,.skip cp 4 ld b,%01000000 jr nc,.skip ld b,%01100000 .skip ld a,[CH\1ComputedVol] cp b jr z,.noreset3 ld a,b ld [CH\1ComputedVol],a ld [rNR\12],a ld a,d or $80 ldh [rNR\14],a .noreset3 else ld a,1 .noreset3 ld [WaveBufUpdateFlag],a endc endc ld a,[CH\1VolPos] inc a ld [CH\1VolPos],a ld a,[hl+] cp $fe jr nz,.done ld a,[hl] ld [CH\1VolPos],a if \1 != 3 if !def(DemoSceneMode) && !def(DisableZombieMode) ld a,1 ld [CH\1VolLoop],a endc jr .done .loadlast ld a,[hl] if !def(DemoSceneMode) && !def(DisableZombieMode) push af swap a and $f ld b,a ld a,[CH\1ChanVol] call MultiplyVolume swap b pop af and $f or b endc ldh [rNR\12],a if def(Visualizer) ld b,a and $f ld [CH\1TempEnvelope],a and $7 inc a ld [CH\1EnvelopeCounter],a ld a,b swap a and $f ld [CH\1OutputLevel],a endc ld a,d or $80 ldh [rNR\14],a ld a,$ff ld [CH\1VolLoop],a else .loadlast endc .done if \1 == 3 ; Update wave ld hl,CH\1WavePtr ld a,[hl+] ld h,[hl] ld l,a ld a,[CH\1WavePos] add l ld l,a jr nc,.nocarry2 inc h .nocarry2 ld a,[hl+] cp $ff ; table end? jr z,.updatebuffer ld b,a ld a,[CH\1Wave] cp b if def(DemoSceneMode) || def(NoWaveVolumeScaling) jr z,.noreset2 ld a,b ld [CH\1Wave],a cp $c0 push hl if def(DemoSceneMode) jr z,.noreset2 ; if value = $c0, ignore (since this feature is disabled in DemoSceneMode) else ld hl,WaveBuffer jr z,.wavebuf endc ld c,b ld b,0 ld hl,WaveTable add hl,bc add hl,bc ld a,[hl+] ld h,[hl] ld l,a .wavebuf call LoadWave pop hl ld a,d or %10000000 ldh [rNR\34],a .noreset2 else ld c,0 jr z,.noreset2 ld a,b ld [CH\1Wave],a ld c,1 .noreset2 ld a,[WaveBufUpdateFlag] or c ld [WaveBufUpdateFlag],a endc ld a,[CH\1WavePos] inc a ld [CH\1WavePos],a ld a,[hl+] cp $fe jr nz,.updatebuffer ld a,[hl] ld [CH\1WavePos],a .updatebuffer if !def(DemoSceneMode) call DoPWM call DoRandomizer if !def(NoWaveVolumeScaling) ld a,[WaveBufUpdateFlag] and a jp z,.noupdate ld a,[CH\1Wave] cp $c0 ; if value = $c0, use wave buffer jr nz,.notwavebuf ld bc,WaveBuffer jr .multiplyvolume .notwavebuf ld c,a ld b,0 ld hl,WaveTable add hl,bc add hl,bc ld a,[hl+] ld b,[hl] ld c,a .multiplyvolume if def(Visualizer) push bc ld hl,VisualizerTempWave ld e,16 .visuwavecopyloop ld a,[bc] inc bc cpl ld [hl+],a dec e jr nz,.visuwavecopyloop pop bc endc ld a,[CH\1Vol] and a jr z,.mute cp 8 ld e,%00100000 jr nc,.skip add a inc a cp 8 ld e,%01000000 jr nc,.skip add a inc a ld e,%01100000 .skip push de srl a push af ld l, a ld h, 0 add hl, hl ; x2 add hl, hl ; x4 add hl, hl ; x8 add hl, hl ; x16 ld de, VolumeTable add hl, de ld d,h ld e,l pop af ld a,16 ld hl,ComputedWaveBuffer jr nc,.multnormal .multswapped push af ld a,[bc] call MultiplyVolume_ swap a and $f ld [hl],a ld a,[bc] inc bc swap a call MultiplyVolume_ and $f0 or [hl] ld [hl+],a pop af dec a jr nz,.multswapped jr .multdone .multnormal push af ld a,[bc] call MultiplyVolume_ and $f ld [hl],a ld a,[bc] inc bc swap a call MultiplyVolume_ and $f swap a or [hl] ld [hl+],a pop af dec a jr nz,.multnormal .multdone pop de ld a,e .mute ld [CH\1ComputedVol],a ld [rNR\12],a and a call nz,LoadWave xor a ld [WaveBufUpdateFlag],a ld a,d or $80 ldh [rNR\14],a .noupdate endc endc endc CH\1RegistersUpdated: endm CH1_UpdateRegisters: UpdateRegisters 1 CH2_UpdateRegisters: UpdateRegisters 2 CH3_UpdateRegisters: UpdateRegisters 3 CH4_UpdateRegisters: UpdateRegisters 4 DoneUpdatingRegisters: pop hl pop de pop bc pop af ret ; ================================================================ ; Wave routines ; ================================================================ LoadWave: if !def(DemoSceneMode) && !def(NoWaveVolumeScaling) ld hl,ComputedWaveBuffer elif def(Visualizer) push hl ld bc,VisualizerTempWave ld e,16 .visuwavecopyloop ld a,[hl+] cpl ld [bc],a inc bc dec e jr nz,.visuwavecopyloop pop hl endc ldh a,[rNR51] ld c,a and %10111011 ; Remove CH3 from final mixing while it's disabled ldh [rNR51],a ; prevents spike on GBA xor a ldh [rNR30],a ; disable CH3 CUR_WAVE = _AUD3WAVERAM rept 16 ld a, [hl+] ; get byte from hl ldh [CUR_WAVE], a ; copy to wave ram CUR_WAVE = CUR_WAVE + 1 endr PURGE CUR_WAVE ld a,%10000000 ldh [rNR30],a ; enable CH3 ld a,c ldh [rNR51],a ret ClearWaveBuffer: ld b,$20 ; spill to WaveBuffer too xor a ld hl,ComputedWaveBuffer .loop ld [hl+],a dec b jr nz,.loop ret if !def(DemoSceneMode) ; Combine two waves. ; INPUT: bc = first wave address ; de = second wave address _CombineWaves: ld hl,WaveBuffer .loop push hl ld a,[bc] and $f ld l,a ld a,[de] and $f add l rra ld l,a ld a,[bc] inc bc and $f0 ld h,a ld a,[de] inc de and $f0 add h rra and $f0 or l pop hl ld [hl+],a ld a,l cp LOW(WaveBuffer+16) jr nz, .loop ld a,[WaveBufUpdateFlag] or 1 ld [WaveBufUpdateFlag],a ret DoRandomizer: ld a,[RandomizerEnabled] and a ret z ; if randomizer is disabled, return ld a,[RandomizerTimer] dec a ld [RandomizerTimer],a ret nz ld a,[RandomizerSpeed] ld [RandomizerTimer],a ; Fall through ; Randomize the wave buffer _RandomizeWave: push de ld hl,NoiseData ld de,WaveBuffer ld b,$10 ld a,[WavePos] inc a ld [WavePos],a add l ld l,a jr nc,.nocarry inc h .nocarry ld a,[hl+] ld hl,NoiseData add l ld l,a jr nc,.loop inc h .loop ld a,[hl+] ld [de],a inc de dec b jr nz,.loop ld a,[WaveBufUpdateFlag] or 1 ld [WaveBufUpdateFlag],a pop de ret ; Do PWM DoPWM: ld a,[PWMEnabled] and a ret z ; if PWM is not enabled, return ld a,[PWMTimer] dec a ld [PWMTimer],a ret nz ld a,[PWMSpeed] ld [PWMTimer],a ld a,[PWMDir] and a ld a,[WavePos] jr nz,.decPos .incPos inc a ld [WavePos],a cp $1e jr nz,.continue ld a,[PWMDir] xor 1 ld [PWMDir],a jr .continue .decPos dec a ld [WavePos],a jr nz,.continue2 ld a,[PWMDir] xor 1 ld [PWMDir],a jr .continue2 .continue ld hl,WaveBuffer ld a,[WavePos] rra push af and $f add l ld l,a jr nc,.nocarry inc h .nocarry pop af jr nc,.even .odd ld a,[hl] ld b,a ld a,[PWMVol] or b jr .done .continue2 ld hl,WaveBuffer ld a,[WavePos] inc a rra push af and $f add l ld l,a jr nc,.nocarry2 inc h .nocarry2 pop af jr nc,.odd2 .even ld a,[PWMVol] swap a jr .done .odd2 xor a .done ld [hl],a ld a,[WaveBufUpdateFlag] or 1 ld [WaveBufUpdateFlag],a ret endc ; ================================================================ ; Echo buffer routines ; ================================================================ DoEchoBuffers: .ch1 ld hl,CH1EchoBuffer ld a,[EchoPos] add l ld l,a jr nc,.nocarry inc h .nocarry ld a,[CH1Note] ld b,a cp echo jr nz,.continue1 ld a,___ jr .skiptranspose .continue1 ld a,[CH1Transpose] add b ld b,a .skiptranspose ld [hl],a .ch2 ld hl,CH2EchoBuffer ld a,[EchoPos] add l ld l,a jr nc,.nocarry2 inc h .nocarry2 ld a,[CH2Note] ld b,a cp echo jr nz,.continue2 ld a,___ jr .skiptranspose2 .continue2 ld a,[CH2Transpose] add b ld b,a .skiptranspose2 ld [hl],a .ch3 ld hl,CH3EchoBuffer ld a,[EchoPos] add l ld l,a jr nc,.nocarry3 inc h .nocarry3 ld a,[CH3Note] ld b,a cp echo jr nz,.continue3 ld a,___ jr .skiptranspose3 .continue3 ld a,[CH3Transpose] add b ld b,a .skiptranspose3 ld [hl],a ld a,[EchoPos] inc a and $3f ld [EchoPos],a ret ClearEchoBuffers: ld hl,CH1EchoBuffer ld b,(EchoPos-1)-CH1EchoBuffer xor a .loop ld [hl+],a dec b jr nz,.loop ld [EchoPos],a ld [CH1EchoDelay],a ld [CH2EchoDelay],a ld [CH3EchoDelay],a ld [CH1NotePlayed],a ld [CH2NotePlayed],a ld [CH3NotePlayed],a ret ; INPUT: a = note CH1FillEchoBuffer: push hl ld b,a ld a,1 ld [CH1NotePlayed],a ld a,b ld hl,CH1EchoBuffer jr DoFillEchoBuffer CH2FillEchoBuffer: push hl ld b,a ld a,1 ld [CH2NotePlayed],a ld a,b ld hl,CH2EchoBuffer jr DoFillEchoBuffer CH3FillEchoBuffer: push hl ld b,a ld a,1 ld [CH3NotePlayed],a ld a,b ld hl,CH3EchoBuffer ; fall through to DoFillEchoBuffer DoFillEchoBuffer: ld b,64 .loop ld [hl+],a dec b jr nz,.loop pop hl ret ; ================================================================ ; Misc routines ; ================================================================ JumpTableBelow: ; since the return pointer is now at the start of table, ; we can manipulate it to return to the address in the table instead pop bc push hl add a ; It is recommended to use this to keep optimizations on the four channel's jumptables add c ld l,a jr nc,.nocarry inc b .nocarry ld h,b ld a,[hl+] ld b,[hl] ld c,a pop hl push bc ret ClearArpBuffer: ld hl,arp_Buffer ld [hl],$ff inc hl ld b,7 xor a .loop ld [hl+],a dec b jr nz,.loop ret DoArp: ld de,arp_Buffer xor a ld [de], a inc de ld a,[hl+] and a jr nz,.slow .fast ld a,[hl] swap a and $f ld [de],a inc de ld a,[hl+] and $f jr .continue .slow xor a ld [de],a inc de ld a,[hl] swap a and $f ld [de],a inc de ld [de],a inc de ld a,[hl+] and $f ld [de],a inc de .continue ld [de],a inc de ld a,$fe ld [de],a inc de xor a ld [de],a ret if !def(DemoSceneMode) MultiplyVolume: srl b push af ld l,b ld h,0 add hl,hl ; x2 add hl,hl ; x4 add hl,hl ; x8 add hl,hl ; x16 ld bc,VolumeTable add hl,bc ld c,a ld b,0 add hl,bc pop af ld a,[hl] jr nc,.noswap swap a .noswap and $f ld b,a ret MultiplyVolume_: ; short version of MultiplyVolume for ch3 wave update push de and $f add e ld e,a jr nc,.nocarry inc d .nocarry ld a,[de] pop de ret endc ; ================================================================ ; Frequency table ; ================================================================ FreqTable: ; C-x C#x D-x D#x E-x F-x F#x G-x G#x A-x A#x B-x dw $02c,$09c,$106,$16b,$1c9,$223,$277,$2c6,$312,$356,$39b,$3da ; octave 1 dw $416,$44e,$483,$4b5,$4e5,$511,$53b,$563,$589,$5ac,$5ce,$5ed ; octave 2 dw $60a,$627,$642,$65b,$672,$689,$69e,$6b2,$6c4,$6d6,$6e7,$6f7 ; octave 3 dw $706,$714,$721,$72d,$739,$744,$74f,$759,$762,$76b,$773,$77b ; octave 4 dw $783,$78a,$790,$797,$79d,$7a2,$7a7,$7ac,$7b1,$7b6,$7ba,$7be ; octave 5 dw $7c1,$7c4,$7c8,$7cb,$7ce,$7d1,$7d4,$7d6,$7d9,$7db,$7dd,$7df ; octave 6 dw $7e1,$7e3,$7e4,$7e6,$7e7,$7e9,$7ea,$7eb,$7ec,$7ed,$7ee,$7ef ; octave 7 (not used directly, is slightly out of tune) NoiseTable: ; taken from deflemask db $a4 ; 15 steps db $97,$96,$95,$94,$87,$86,$85,$84,$77,$76,$75,$74,$67,$66,$65,$64 db $57,$56,$55,$54,$47,$46,$45,$44,$37,$36,$35,$34,$27,$26,$25,$24 db $17,$16,$15,$14,$07,$06,$05,$04,$03,$02,$01,$00 db $ac ; 7 steps db $9f,$9e,$9d,$9c,$8f,$8e,$8d,$8c,$7f,$7e,$7d,$7c,$6f,$6e,$6d,$6c db $5f,$5e,$5d,$5c,$4f,$4e,$4d,$4c,$3f,$3e,$3d,$3c,$2f,$2e,$2d,$2c db $1f,$1e,$1d,$1c,$0f,$0e,$0d,$0c,$0b,$0a,$09,$08 if !def(DemoSceneMode) VolumeTable: ; used for volume multiplication db $00,$00,$00,$00,$00,$00,$00,$00 ; 10 db $10,$10,$10,$10,$10,$10,$10,$10 db $00,$00,$00,$00,$10,$11,$11,$11 ; 32 db $21,$21,$21,$22,$32,$32,$32,$32 db $00,$00,$10,$11,$11,$21,$22,$22 ; 54 db $32,$32,$33,$43,$43,$44,$54,$54 db $00,$00,$11,$11,$22,$22,$32,$33 ; 76 db $43,$44,$54,$54,$65,$65,$76,$76 db $00,$00,$11,$21,$22,$33,$43,$44 ; 98 db $54,$55,$65,$76,$77,$87,$98,$98 db $00,$11,$11,$22,$33,$43,$44,$55 ; ba db $65,$76,$77,$87,$98,$a9,$a9,$ba db $00,$11,$22,$33,$43,$44,$55,$66 ; dc db $76,$87,$98,$99,$a9,$ba,$cb,$dc db $00,$11,$22,$33,$44,$55,$66,$77 ; fe db $87,$98,$a9,$ba,$cb,$dc,$ed,$fe endc ; ================================================================ ; misc stuff ; ================================================================ DefaultRegTable: ; global flags db 0,7,0,0,0,0,0,1,1,1,1,1,0,0,0,0 ; ch1 dw DummyTable,DummyTable,DummyTable,DummyTable,DummyTable db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ; ch2 dw DummyTable,DummyTable,DummyTable,DummyTable,DummyTable db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ; ch3 dw DummyTable,DummyTable,DummyTable,DummyTable,DummyTable db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ; ch4 if def(DisableDeflehacks) dw DummyTable,DummyTable,DummyTable db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 else dw DummyTable,DummyTable,DummyTable,DummyTable db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 endc DefaultWave: db $01,$23,$45,$67,$89,$ab,$cd,$ef,$fe,$dc,$ba,$98,$76,$54,$32,$10 NoiseData: incbin "NoiseData.bin" ; ================================================================ ; Dummy data ; ================================================================ DummyTable: db $ff,0 vib_Dummy: db 0,0,$80,1 DummyChannel: db EndChannel ; ================================================================ ; Song data ; ================================================================ if !def(DontIncludeSongData) include "DevSound_SongData.asm" endc
; A080820: Least m such that m^2 >= n*(n+1)/2. ; 1,2,3,4,4,5,6,6,7,8,9,9,10,11,11,12,13,14,14,15,16,16,17,18,19,19,20,21,21,22,23,23,24,25,26,26,27,28,28,29,30,31,31,32,33,33,34,35,35,36,37,38,38,39,40,40,41,42,43,43,44,45,45,46,47,48,48,49,50,50,51,52,52,53,54,55,55,56,57,57,58,59,60,60,61,62,62,63,64,64,65,66,67,67,68,69,69,70,71,72,72,73,74,74,75,76,77,77,78,79,79,80,81,81,82,83,84,84,85,86,86,87,88,89,89,90,91,91,92,93,93,94,95,96,96,97,98,98,99,100,101,101,102,103,103,104,105,106,106,107,108,108,109,110,110,111,112,113,113,114,115,115,116,117,118,118,119,120,120,121,122,122,123,124,125,125,126,127,127,128,129,130,130,131,132,132,133,134,134,135,136,137,137,138,139,139,140,141,142,142,143,144,144,145,146,147,147,148,149,149,150,151,151,152,153,154,154,155,156,156,157,158,159,159,160,161,161,162,163,163,164,165,166,166,167,168,168,169,170,171,171,172,173,173,174,175,176,176,177,178 mov $14,$0 mov $16,2 lpb $16 clr $0,14 mov $0,$14 sub $16,1 add $0,$16 sub $0,1 mov $11,$0 mov $13,$0 add $13,1 lpb $13 mov $0,$11 sub $13,1 sub $0,$13 mov $9,2 lpb $9 sub $9,1 add $0,$9 sub $0,1 mov $2,$0 bin $2,2 lpb $2 sub $2,$0 sub $0,1 sub $2,1 sub $2,$0 lpe mov $1,$0 mov $10,$9 lpb $10 mov $8,$1 sub $10,1 lpe lpe mov $1,$8 add $1,1 add $12,$1 lpe mov $1,$12 mov $17,$16 lpb $17 mov $15,$1 sub $17,1 lpe lpe lpb $14 mov $14,0 sub $15,$1 lpe mov $1,$15
/* * Copyright (C) 2017 Shaiya Genesis <http://www.shaiyagenesis.com/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "SelectCharacterPacketHandler.h" #include <genesis/common/networking/packets/PacketBuilder.h> #include <genesis/common/packets/Opcodes.h> #include <genesis/common/database/Opcodes.h> #include <genesis/game/world/GameWorld.h> #include <genesis/game/world/pulse/task/impl/LoadCharacterGameWorldTask.h> #include <string> // The packet handler implementation namespace using namespace Genesis::Game::Io::Packets::Impl; /** * Handles an incoming request to enter the game world with a character * * @param session * The session instance * * @param length * The length of the packet * * @param opcode * The opcode of the incoming packet * * @param data * The packet data */ bool SelectCharacterPacketHandler::handle(Genesis::Common::Networking::Server::Session::ServerSession* session, unsigned int length, unsigned short opcode, unsigned char* data) { // If the length is not valid if (length != 4) return true; // The character id unsigned int character_id; // Copy the character id std::memcpy(&character_id, data, sizeof(character_id)); // The client instance auto db_client = Genesis::Game::World::GameWorld::get_instance()->get_db_client(); // The player instance auto player = Genesis::Game::World::GameWorld::get_instance()->get_player_for_index(session->get_game_index()); // Push the task to the worker Genesis::Game::World::GameWorld::get_instance()->push_task(new Genesis::Game::World::Pulse::Task::Impl::LoadCharacterGameWorldTask(player, character_id)); // Return true return true; }
; Based on http://problemkaputt.de/2k6specs.htm ; Write addresses VSYNC = $00 ; ......1. vertical sync set-clear VBLANK = $01 ; 11....1. vertical blank set-clear WSYNC = $02 ; <strobe> wait for leading edge of horizontal blank RSYNC = $03 ; <strobe> reset horizontal sync counter NUSIZ0 = $04 ; ..111111 number-size player-missile 0 NUSIZ1 = $05 ; ..111111 number-size player-missile 1 COLUP0 = $06 ; 1111111. color-lum player 0 and missile 0 COLUP1 = $07 ; 1111111. color-lum player 1 and missile 1 COLUPF = $08 ; 1111111. color-lum playfield and ball COLUBK = $09 ; 1111111. color-lum background CTRLPF = $0A ; ..11.111 control playfield ball size & collisions REFP0 = $0B ; ....1... reflect player 0 REFP1 = $0C ; ....1... reflect player 1 PF0 = $0D ; 1111.... playfield register byte 0 PF1 = $0E ; 11111111 playfield register byte 1 PF2 = $0F ; 11111111 playfield register byte 2 RESP0 = $10 ; <strobe> reset player 0 RESP1 = $11 ; <strobe> reset player 1 RESM0 = $12 ; <strobe> reset missile 0 RESM1 = $13 ; <strobe> reset missile 1 RESBL = $14 ; <strobe> reset ball AUDC0 = $15 ; ....1111 audio control 0 AUDC1 = $16 ; ....1111 audio control 1 AUDF0 = $17 ; ...11111 audio frequency 0 AUDF1 = $18 ; ...11111 audio frequency 1 AUDV0 = $19 ; ....1111 audio volume 0 AUDV1 = $1A ; ....1111 audio volume 1 GRP0 = $1B ; 11111111 graphics player 0 GRP1 = $1C ; 11111111 graphics player 1 ENAM0 = $1D ; ......1. graphics (enable) missile 0 ENAM1 = $1E ; ......1. graphics (enable) missile 1 ENABL = $1F ; ......1. graphics (enable) ball HMP0 = $20 ; 1111.... horizontal motion player 0 HMP1 = $21 ; 1111.... horizontal motion player 1 HMM0 = $22 ; 1111.... horizontal motion missile 0 HMM1 = $23 ; 1111.... horizontal motion missile 1 HMBL = $24 ; 1111.... horizontal motion ball VDELP0 = $25 ; .......1 vertical delay player 0 VDELP1 = $26 ; .......1 vertical delay player 1 VDELBL = $27 ; .......1 vertical delay ball RESMP0 = $28 ; ......1. reset missile 0 to player 0 RESMP1 = $29 ; ......1. reset missile 1 to player 1 HMOVE = $2A ; <strobe> apply horizontal motion HMCLR = $2B ; <strobe> clear horizontal motion registers CXCLR = $2C ; <strobe> clear collision latches ; Read addresses CXM0P = $30 ; 11...... read collision M0-P1, M0-P0 (Bit 7,6) CXM1P = $31 ; 11...... read collision M1-P0, M1-P1 CXP0FB = $32 ; 11...... read collision P0-PF, P0-BL CXP1FB = $33 ; 11...... read collision P1-PF, P1-BL CXM0FB = $34 ; 11...... read collision M0-PF, M0-BL CXM1FB = $35 ; 11...... read collision M1-PF, M1-BL CXBLPF = $36 ; 1....... read collision BL-PF, unused CXPPMM = $37 ; 11...... read collision P0-P1, M0-M1 INPT0 = $38 ; 1....... read pot port INPT1 = $39 ; 1....... read pot port INPT2 = $3A ; 1....... read pot port INPT3 = $3B ; 1....... read pot port INPT4 = $3C ; 1....... read input INPT5 = $3D ; 1....... read input
INCLUDE "graphics/grafix.inc" SECTION code_clib PUBLIC getmaxx PUBLIC _getmaxx EXTERN __gal_mode .getmaxx ._getmaxx ld a,(__gal_mode) and a ld hl, +63 ret z ld hl,255 ret
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 30/9/98 ; ; ; $Id: uncircle.asm $ ; ; Usage: uncircle(int x, int y, int radius, int skip); SECTION code_graphics PUBLIC uncircle PUBLIC _uncircle EXTERN uncircle_callee EXTERN ASMDISP_UNCIRCLE_CALLEE .uncircle ._uncircle push ix ld ix,2 add ix,sp ld e,(ix+2) ;skip ld d,(ix+4) ;radius ld c,(ix+6) ;y ld b,(ix+8) ;x jp uncircle_callee + ASMDISP_UNCIRCLE_CALLEE
; char *ulltoa(uint64_t num, char *buf, int radix) SECTION code_clib SECTION code_stdlib PUBLIC _ulltoa EXTERN asm_ulltoa _ulltoa: pop af pop hl pop de exx pop hl pop de pop ix exx pop bc push bc push hl push de push hl push de push hl push af jp asm_ulltoa
; A193592: Triangle read by rows having n-th row 1, n, n-1, n-2,..., 2, 1 for n>=0. ; 1,1,1,1,2,1,1,3,2,1,1,4,3,2,1,1,5,4,3,2,1,1,6,5,4,3,2,1,1,7,6,5,4,3,2,1,1,8,7,6,5,4,3,2,1,1,9,8,7,6,5,4,3,2,1,1,10,9,8,7,6,5,4,3,2,1,1,11,10,9,8,7,6,5,4,3,2,1,1,12,11,10,9,8,7,6,5,4,3,2,1 lpb $0,1 mov $1,$2 trn $1,$0 add $2,1 trn $0,$2 lpe add $1,1
/****************************************************************************** * * Project: GML Reader * Purpose: Code to translate between GML and OGR geometry forms. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2002, Frank Warmerdam * Copyright (c) 2009-2014, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***************************************************************************** * * Independent Security Audit 2003/04/17 Andrey Kiselev: * Completed audit of this module. All functions may be used without buffer * overflows and stack corruptions with any kind of input data. * * Security Audit 2003/03/28 warmerda: * Completed security audit. I believe that this module may be safely used * to parse, arbitrary GML potentially provided by a hostile source without * compromising the system. * */ #include "cpl_port.h" #include "ogr_api.h" #include <cctype> #include <cmath> #include <cstdlib> #include <cstring> #include "cpl_conv.h" #include "cpl_error.h" #include "cpl_minixml.h" #include "cpl_string.h" #include "ogr_core.h" #include "ogr_geometry.h" #include "ogr_p.h" #include "ogr_spatialref.h" #include "ogr_srs_api.h" #include "ogrsf_frmts/xplane/ogr_xplane_geo_utils.h" CPL_CVSID("$Id: gml2ogrgeometry.cpp 37129 2017-01-12 21:15:15Z rouault $"); #if HAVE_CXX11 constexpr double kdfD2R = M_PI / 180.0; constexpr double kdf2PI = 2.0 * M_PI; #else static const double kdfD2R = M_PI / 180.0; static const double kdf2PI = 2.0 * M_PI; #endif /************************************************************************/ /* GMLGetCoordTokenPos() */ /************************************************************************/ static const char* GMLGetCoordTokenPos( const char* pszStr, const char** ppszNextToken ) { char ch; while( true ) { ch = *pszStr; if( ch == '\0' ) { *ppszNextToken = NULL; return NULL; } else if( !(ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ' || ch == ',') ) break; pszStr++; } const char* pszToken = pszStr; while( (ch = *pszStr) != '\0' ) { if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ' || ch == ',' ) { *ppszNextToken = pszStr; return pszToken; } pszStr++; } *ppszNextToken = NULL; return pszToken; } /************************************************************************/ /* BareGMLElement() */ /* */ /* Returns the passed string with any namespace prefix */ /* stripped off. */ /************************************************************************/ static const char *BareGMLElement( const char *pszInput ) { const char *pszReturn = strchr( pszInput, ':' ); if( pszReturn == NULL ) pszReturn = pszInput; else pszReturn++; return pszReturn; } /************************************************************************/ /* FindBareXMLChild() */ /* */ /* Find a child node with the indicated "bare" name, that is */ /* after any namespace qualifiers have been stripped off. */ /************************************************************************/ static const CPLXMLNode *FindBareXMLChild( const CPLXMLNode *psParent, const char *pszBareName ) { const CPLXMLNode *psCandidate = psParent->psChild; while( psCandidate != NULL ) { if( psCandidate->eType == CXT_Element && EQUAL(BareGMLElement(psCandidate->pszValue), pszBareName) ) return psCandidate; psCandidate = psCandidate->psNext; } return NULL; } /************************************************************************/ /* GetElementText() */ /************************************************************************/ static const char *GetElementText( const CPLXMLNode *psElement ) { if( psElement == NULL ) return NULL; const CPLXMLNode *psChild = psElement->psChild; while( psChild != NULL ) { if( psChild->eType == CXT_Text ) return psChild->pszValue; psChild = psChild->psNext; } return NULL; } /************************************************************************/ /* GetChildElement() */ /************************************************************************/ static const CPLXMLNode *GetChildElement( const CPLXMLNode *psElement ) { if( psElement == NULL ) return NULL; const CPLXMLNode *psChild = psElement->psChild; while( psChild != NULL ) { if( psChild->eType == CXT_Element ) return psChild; psChild = psChild->psNext; } return NULL; } /************************************************************************/ /* GetElementOrientation() */ /* Returns true for positive orientation. */ /************************************************************************/ static bool GetElementOrientation( const CPLXMLNode *psElement ) { if( psElement == NULL ) return true; const CPLXMLNode *psChild = psElement->psChild; while( psChild != NULL ) { if( psChild->eType == CXT_Attribute && EQUAL(psChild->pszValue, "orientation") ) return EQUAL(psChild->psChild->pszValue, "+"); psChild = psChild->psNext; } return true; } /************************************************************************/ /* AddPoint() */ /* */ /* Add a point to the passed geometry. */ /************************************************************************/ static bool AddPoint( OGRGeometry *poGeometry, double dfX, double dfY, double dfZ, int nDimension ) { const OGRwkbGeometryType eType = wkbFlatten(poGeometry->getGeometryType()); if( eType == wkbPoint ) { OGRPoint *poPoint = dynamic_cast<OGRPoint *>(poGeometry); if( poPoint == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPoint."); return false; } if( !poPoint->IsEmpty() ) { CPLError(CE_Failure, CPLE_AppDefined, "More than one coordinate for <Point> element."); return false; } poPoint->setX( dfX ); poPoint->setY( dfY ); if( nDimension == 3 ) poPoint->setZ( dfZ ); return true; } else if( eType == wkbLineString || eType == wkbCircularString ) { OGRSimpleCurve *poCurve = dynamic_cast<OGRSimpleCurve *>(poGeometry); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRSimpleCurve."); return false; } if( nDimension == 3 ) poCurve->addPoint(dfX, dfY, dfZ); else poCurve->addPoint(dfX, dfY); return true; } CPLAssert( false ); return false; } /************************************************************************/ /* ParseGMLCoordinates() */ /************************************************************************/ static bool ParseGMLCoordinates( const CPLXMLNode *psGeomNode, OGRGeometry *poGeometry, int nSRSDimension ) { const CPLXMLNode *psCoordinates = FindBareXMLChild( psGeomNode, "coordinates" ); int iCoord = 0; /* -------------------------------------------------------------------- */ /* Handle <coordinates> case. */ /* Note that we don't do a strict validation, so we accept and */ /* sometimes generate output whereas we should just reject it. */ /* -------------------------------------------------------------------- */ if( psCoordinates != NULL ) { const char *pszCoordString = GetElementText( psCoordinates ); const char *pszDecimal = CPLGetXMLValue(const_cast<CPLXMLNode *>(psCoordinates), "decimal", NULL); char chDecimal = '.'; if( pszDecimal != NULL ) { if( strlen(pszDecimal) != 1 || (pszDecimal[0] >= '0' && pszDecimal[0] <= '9') ) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong value for decimal attribute"); return false; } chDecimal = pszDecimal[0]; } const char *pszCS = CPLGetXMLValue(const_cast<CPLXMLNode *>(psCoordinates), "cs", NULL); char chCS = ','; if( pszCS != NULL ) { if( strlen(pszCS) != 1 || (pszCS[0] >= '0' && pszCS[0] <= '9') ) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong value for cs attribute"); return false; } chCS = pszCS[0]; } const char *pszTS = CPLGetXMLValue(const_cast<CPLXMLNode *>(psCoordinates), "ts", NULL); char chTS = ' '; if( pszTS != NULL ) { if( strlen(pszTS) != 1 || (pszTS[0] >= '0' && pszTS[0] <= '9') ) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong value for tes attribute"); return false; } chTS = pszTS[0]; } if( pszCoordString == NULL ) { poGeometry->empty(); return true; } while( *pszCoordString != '\0' ) { double dfX = 0.0; int nDimension = 2; // parse out 2 or 3 tuple. if( chDecimal == '.' ) dfX = OGRFastAtof( pszCoordString ); else dfX = CPLAtofDelim( pszCoordString, chDecimal); while( *pszCoordString != '\0' && *pszCoordString != chCS && !isspace((unsigned char)*pszCoordString) ) pszCoordString++; if( *pszCoordString == '\0' ) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupt <coordinates> value."); return false; } else if( chCS == ',' && pszCS == NULL && isspace((unsigned char)*pszCoordString) ) { // In theory, the coordinates inside a coordinate tuple should // be separated by a comma. However it has been found in the // wild that the coordinates are in rare cases separated by a // space, and the tuples by a comma. // See: // https://52north.org/twiki/bin/view/Processing/WPS-IDWExtension-ObservationCollectionExample // or // http://agisdemo.faa.gov/aixmServices/getAllFeaturesByLocatorId?locatorId=DFW chCS = ' '; chTS = ','; } pszCoordString++; double dfY = 0.0; if( chDecimal == '.' ) dfY = OGRFastAtof( pszCoordString ); else dfY = CPLAtofDelim( pszCoordString, chDecimal); while( *pszCoordString != '\0' && *pszCoordString != chCS && *pszCoordString != chTS && !isspace(static_cast<unsigned char>(*pszCoordString)) ) pszCoordString++; double dfZ = 0.0; if( *pszCoordString == chCS ) { pszCoordString++; if( chDecimal == '.' ) dfZ = OGRFastAtof( pszCoordString ); else dfZ = CPLAtofDelim( pszCoordString, chDecimal); nDimension = 3; while( *pszCoordString != '\0' && *pszCoordString != chCS && *pszCoordString != chTS && !isspace((unsigned char)*pszCoordString) ) pszCoordString++; } if( *pszCoordString == chTS ) { pszCoordString++; } while( isspace(static_cast<unsigned char>(*pszCoordString)) ) pszCoordString++; if( !AddPoint( poGeometry, dfX, dfY, dfZ, nDimension ) ) return false; iCoord++; } return iCoord > 0; } /* -------------------------------------------------------------------- */ /* Is this a "pos"? GML 3 construct. */ /* Parse if it exist a series of pos elements (this would allow */ /* the correct parsing of gml3.1.1 geometries such as linestring */ /* defined with pos elements. */ /* -------------------------------------------------------------------- */ bool bHasFoundPosElement = false; for( const CPLXMLNode *psPos = psGeomNode->psChild; psPos != NULL; psPos = psPos->psNext ) { if( psPos->eType != CXT_Element ) continue; const char* pszSubElement = BareGMLElement(psPos->pszValue); if( EQUAL(pszSubElement, "pointProperty") ) { for( const CPLXMLNode *psPointPropertyIter = psPos->psChild; psPointPropertyIter != NULL; psPointPropertyIter = psPointPropertyIter->psNext ) { if( psPointPropertyIter->eType != CXT_Element ) continue; const char* pszBareElement = BareGMLElement(psPointPropertyIter->pszValue); if( EQUAL(pszBareElement, "Point") || EQUAL(pszBareElement, "ElevatedPoint") ) { OGRPoint oPoint; if( ParseGMLCoordinates( psPointPropertyIter, &oPoint, nSRSDimension ) ) { const bool bSuccess = AddPoint( poGeometry, oPoint.getX(), oPoint.getY(), oPoint.getZ(), oPoint.getCoordinateDimension() ); if( bSuccess ) bHasFoundPosElement = true; else return false; } } } if( psPos->psChild && psPos->psChild->eType == CXT_Attribute && psPos->psChild->psNext == NULL && strcmp(psPos->psChild->pszValue, "xlink:href") == 0 ) { CPLError(CE_Warning, CPLE_AppDefined, "Cannot resolve xlink:href='%s'. " "Try setting GML_SKIP_RESOLVE_ELEMS=NONE", psPos->psChild->psChild->pszValue); } continue; } if( !EQUAL(pszSubElement, "pos") ) continue; const char* pszPos = GetElementText( psPos ); if( pszPos == NULL ) { poGeometry->empty(); return true; } const char* pszCur = pszPos; const char* pszX = GMLGetCoordTokenPos(pszCur, &pszCur); const char* pszY = (pszCur != NULL) ? GMLGetCoordTokenPos(pszCur, &pszCur) : NULL; const char* pszZ = (pszCur != NULL) ? GMLGetCoordTokenPos(pszCur, &pszCur) : NULL; if( pszY == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Did not get 2+ values in <gml:pos>%s</gml:pos> tuple.", pszPos ); return false; } const double dfX = OGRFastAtof(pszX); const double dfY = OGRFastAtof(pszY); const double dfZ = (pszZ != NULL) ? OGRFastAtof(pszZ) : 0.0; const bool bSuccess = AddPoint( poGeometry, dfX, dfY, dfZ, (pszZ != NULL) ? 3 : 2 ); if( bSuccess ) bHasFoundPosElement = true; else return false; } if( bHasFoundPosElement ) return true; /* -------------------------------------------------------------------- */ /* Is this a "posList"? GML 3 construct (SF profile). */ /* -------------------------------------------------------------------- */ const CPLXMLNode *psPosList = FindBareXMLChild( psGeomNode, "posList" ); if( psPosList != NULL ) { int nDimension = 2; // Try to detect the presence of an srsDimension attribute // This attribute is only available for gml3.1.1 but not // available for gml3.1 SF. const char* pszSRSDimension = CPLGetXMLValue(const_cast<CPLXMLNode *>(psPosList), "srsDimension", NULL); // If not found at the posList level, try on the enclosing element. if( pszSRSDimension == NULL ) pszSRSDimension = CPLGetXMLValue(const_cast<CPLXMLNode *>(psGeomNode), "srsDimension", NULL); if( pszSRSDimension != NULL ) nDimension = atoi(pszSRSDimension); else if( nSRSDimension != 0 ) // Or use one coming from a still higher level element (#5606). nDimension = nSRSDimension; if( nDimension != 2 && nDimension != 3 ) { CPLError( CE_Failure, CPLE_AppDefined, "srsDimension = %d not supported", nDimension); return false; } const char* pszPosList = GetElementText( psPosList ); if( pszPosList == NULL ) { poGeometry->empty(); return true; } bool bSuccess = false; const char* pszCur = pszPosList; while( true ) { const char* pszX = GMLGetCoordTokenPos(pszCur, &pszCur); if( pszX == NULL && bSuccess ) break; const char* pszY = (pszCur != NULL) ? GMLGetCoordTokenPos(pszCur, &pszCur) : NULL; const char* pszZ = (nDimension == 3 && pszCur != NULL) ? GMLGetCoordTokenPos(pszCur, &pszCur) : NULL; if( pszY == NULL || (nDimension == 3 && pszZ == NULL) ) { CPLError( CE_Failure, CPLE_AppDefined, "Did not get at least %d values or invalid number of " "set of coordinates <gml:posList>%s</gml:posList>", nDimension, pszPosList); return false; } double dfX = OGRFastAtof(pszX); double dfY = OGRFastAtof(pszY); double dfZ = (pszZ != NULL) ? OGRFastAtof(pszZ) : 0.0; bSuccess = AddPoint( poGeometry, dfX, dfY, dfZ, nDimension ); if( !bSuccess || pszCur == NULL ) break; } return bSuccess; } /* -------------------------------------------------------------------- */ /* Handle form with a list of <coord> items each with an <X>, */ /* and <Y> element. */ /* -------------------------------------------------------------------- */ for( const CPLXMLNode *psCoordNode = psGeomNode->psChild; psCoordNode != NULL; psCoordNode = psCoordNode->psNext ) { if( psCoordNode->eType != CXT_Element || !EQUAL(BareGMLElement(psCoordNode->pszValue), "coord") ) continue; const CPLXMLNode *psXNode = FindBareXMLChild( psCoordNode, "X" ); const CPLXMLNode *psYNode = FindBareXMLChild( psCoordNode, "Y" ); const CPLXMLNode *psZNode = FindBareXMLChild( psCoordNode, "Z" ); if( psXNode == NULL || psYNode == NULL || GetElementText(psXNode) == NULL || GetElementText(psYNode) == NULL || (psZNode != NULL && GetElementText(psZNode) == NULL) ) { CPLError( CE_Failure, CPLE_AppDefined, "Corrupt <coord> element, missing <X> or <Y> element?" ); return false; } double dfX = OGRFastAtof( GetElementText(psXNode) ); double dfY = OGRFastAtof( GetElementText(psYNode) ); int nDimension = 2; double dfZ = 0.0; if( psZNode != NULL && GetElementText(psZNode) != NULL ) { dfZ = OGRFastAtof( GetElementText(psZNode) ); nDimension = 3; } if( !AddPoint( poGeometry, dfX, dfY, dfZ, nDimension ) ) return false; iCoord++; } return iCoord > 0; } #ifdef HAVE_GEOS /************************************************************************/ /* GML2FaceExtRing() */ /* */ /* Identifies the "good" Polygon whithin the collection returned */ /* by GEOSPolygonize() */ /* short rationale: GEOSPolygonize() will possibly return a */ /* collection of many Polygons; only one is the "good" one, */ /* (including both exterior- and interior-rings) */ /* any other simply represents a single "hole", and should be */ /* consequently ignored at all. */ /************************************************************************/ static OGRPolygon *GML2FaceExtRing( OGRGeometry *poGeom ) { OGRGeometryCollection *poColl = dynamic_cast<OGRGeometryCollection *>(poGeom); if( poColl == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRGeometryCollection."); return NULL; } OGRPolygon *poPolygon = NULL; bool bError = false; int iCount = poColl->getNumGeometries(); int iExterior = 0; int iInterior = 0; for( int ig = 0; ig < iCount; ig++) { // A collection of Polygons is expected to be found. OGRGeometry *poChild = poColl->getGeometryRef(ig); if( poChild == NULL) { bError = true; continue; } if( wkbFlatten( poChild->getGeometryType()) == wkbPolygon ) { OGRPolygon *poPg = dynamic_cast<OGRPolygon *>(poChild); if( poPg == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPolygon."); return NULL; } if( poPg->getNumInteriorRings() > 0 ) iExterior++; else iInterior++; } else { bError = true; } } if( !bError && iCount > 0 ) { if( iCount == 1 && iExterior == 0 && iInterior == 1) { // There is a single Polygon within the collection. OGRPolygon *poPg = dynamic_cast<OGRPolygon *>(poColl->getGeometryRef(0)); if( poPg == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPolygon."); return NULL; } poPolygon = dynamic_cast<OGRPolygon *>(poPg->clone()); if( poPolygon == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPolygon."); return NULL; } } else { if( iExterior == 1 && iInterior == iCount - 1 ) { // Searching the unique Polygon containing holes. for( int ig = 0; ig < iCount; ig++ ) { OGRPolygon *poPg = dynamic_cast<OGRPolygon *>(poColl->getGeometryRef(ig)); if( poPg == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPolygon."); return NULL; } if( poPg->getNumInteriorRings() > 0 ) { poPolygon = dynamic_cast<OGRPolygon *>(poPg->clone()); if( poPolygon == NULL ) { CPLError( CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPolygon."); return NULL; } } } } } } return poPolygon; } #endif /************************************************************************/ /* GML2OGRGeometry_AddToCompositeCurve() */ /************************************************************************/ static bool GML2OGRGeometry_AddToCompositeCurve( OGRCompoundCurve* poCC, OGRGeometry* poGeom, bool& bChildrenAreAllLineString ) { if( poGeom == NULL || !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError(CE_Failure, CPLE_AppDefined, "CompositeCurve: Got %.500s geometry as Member instead of a " "curve.", poGeom ? poGeom->getGeometryName() : "NULL" ); return false; } // Crazy but allowed by GML: composite in composite. if( wkbFlatten(poGeom->getGeometryType()) == wkbCompoundCurve ) { OGRCompoundCurve* poCCChild = dynamic_cast<OGRCompoundCurve *>(poGeom); if( poCCChild == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCompoundCurve."); return false; } while( poCCChild->getNumCurves() != 0 ) { OGRCurve* poCurve = poCCChild->stealCurve(0); if( wkbFlatten(poCurve->getGeometryType()) != wkbLineString ) bChildrenAreAllLineString = false; if( poCC->addCurveDirectly(poCurve) != OGRERR_NONE ) { delete poCurve; return false; } } delete poCCChild; } else { if( wkbFlatten(poGeom->getGeometryType()) != wkbLineString ) bChildrenAreAllLineString = false; OGRCurve *poCurve = dynamic_cast<OGRCurve *>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCurve."); return false; } if( poCC->addCurveDirectly( poCurve ) != OGRERR_NONE ) { return false; } } return true; } /************************************************************************/ /* GML2OGRGeometry_AddToCompositeCurve() */ /************************************************************************/ static bool GML2OGRGeometry_AddToMultiSurface( OGRMultiSurface* poMS, OGRGeometry*& poGeom, const char* pszMemberElement, bool& bChildrenAreAllPolygons ) { if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid %s", pszMemberElement ); return false; } OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType()); if( eType == wkbPolygon || eType == wkbCurvePolygon ) { if( eType != wkbPolygon ) bChildrenAreAllPolygons = false; if( poMS->addGeometryDirectly( poGeom ) != OGRERR_NONE ) { return false; } } else if( eType == wkbMultiPolygon || eType == wkbMultiSurface ) { OGRMultiSurface* poMS2 = dynamic_cast<OGRMultiSurface *>(poGeom); if( poMS2 == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRMultiSurface."); return false; } for( int i = 0; i < poMS2->getNumGeometries(); i++ ) { if( wkbFlatten(poMS2->getGeometryRef(i)->getGeometryType()) != wkbPolygon ) bChildrenAreAllPolygons = false; if( poMS->addGeometry(poMS2->getGeometryRef(i)) != OGRERR_NONE ) { return false; } } delete poGeom; poGeom = NULL; } else { CPLError( CE_Failure, CPLE_AppDefined, "Got %.500s geometry as %s.", poGeom->getGeometryName(), pszMemberElement ); return false; } return true; } /************************************************************************/ /* GML2OGRGeometry_XMLNode() */ /* */ /* Translates the passed XMLnode and it's children into an */ /* OGRGeometry. This is used recursively for geometry */ /* collections. */ /************************************************************************/ static OGRGeometry *GML2OGRGeometry_XMLNode_Internal( const CPLXMLNode *psNode, int nPseudoBoolGetSecondaryGeometryOption, int nRecLevel, int nSRSDimension, const char* pszSRSName, bool bIgnoreGSG = false, bool bOrientation = true, bool bFaceHoleNegative = false ); OGRGeometry *GML2OGRGeometry_XMLNode( const CPLXMLNode *psNode, int nPseudoBoolGetSecondaryGeometryOption, int nRecLevel, int nSRSDimension, bool bIgnoreGSG, bool bOrientation, bool bFaceHoleNegative ) { return GML2OGRGeometry_XMLNode_Internal( psNode, nPseudoBoolGetSecondaryGeometryOption, nRecLevel, nSRSDimension, NULL, bIgnoreGSG, bOrientation, bFaceHoleNegative); } static OGRGeometry *GML2OGRGeometry_XMLNode_Internal( const CPLXMLNode *psNode, int nPseudoBoolGetSecondaryGeometryOption, int nRecLevel, int nSRSDimension, const char* pszSRSName, bool bIgnoreGSG, bool bOrientation, bool bFaceHoleNegative ) { const bool bCastToLinearTypeIfPossible = true; // Hard-coded for now. if( psNode != NULL && strcmp(psNode->pszValue, "?xml") == 0 ) psNode = psNode->psNext; while( psNode != NULL && psNode->eType == CXT_Comment ) psNode = psNode->psNext; if( psNode == NULL ) return NULL; const char* pszSRSDimension = CPLGetXMLValue(const_cast<CPLXMLNode *>(psNode), "srsDimension", NULL); if( pszSRSDimension != NULL ) nSRSDimension = atoi(pszSRSDimension); if( pszSRSName == NULL ) pszSRSName = CPLGetXMLValue(const_cast<CPLXMLNode *>(psNode), "srsName", NULL); const char *pszBaseGeometry = BareGMLElement( psNode->pszValue ); if( nPseudoBoolGetSecondaryGeometryOption < 0 ) nPseudoBoolGetSecondaryGeometryOption = CPLTestBool(CPLGetConfigOption("GML_GET_SECONDARY_GEOM", "NO")); bool bGetSecondaryGeometry = bIgnoreGSG ? false : CPL_TO_BOOL(nPseudoBoolGetSecondaryGeometryOption); // Arbitrary value, but certainly large enough for reasonable usages. if( nRecLevel == 32 ) { CPLError( CE_Failure, CPLE_AppDefined, "Too many recursion levels (%d) while parsing GML geometry.", nRecLevel ); return NULL; } if( bGetSecondaryGeometry ) if( !( EQUAL(pszBaseGeometry, "directedEdge") || EQUAL(pszBaseGeometry, "TopoCurve") ) ) return NULL; /* -------------------------------------------------------------------- */ /* Polygon / PolygonPatch / Rectangle */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Polygon") || EQUAL(pszBaseGeometry, "PolygonPatch") || EQUAL(pszBaseGeometry, "Rectangle")) { // Find outer ring. const CPLXMLNode *psChild = FindBareXMLChild( psNode, "outerBoundaryIs" ); if( psChild == NULL ) psChild = FindBareXMLChild( psNode, "exterior"); psChild = GetChildElement(psChild); if( psChild == NULL ) { // <gml:Polygon/> is invalid GML2, but valid GML3, so be tolerant. return new OGRPolygon(); } // Translate outer ring and add to polygon. OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid exterior ring"); return NULL; } if( !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError( CE_Failure, CPLE_AppDefined, "%s: Got %.500s geometry as outerBoundaryIs.", pszBaseGeometry, poGeom->getGeometryName() ); delete poGeom; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) == wkbLineString && !EQUAL(poGeom->getGeometryName(), "LINEARRING") ) { OGRCurve *poCurve = dynamic_cast<OGRCurve *>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCurve."); } poGeom = OGRCurve::CastToLinearRing(poCurve); } OGRCurvePolygon *poCP = NULL; bool bIsPolygon = false; if( EQUAL(poGeom->getGeometryName(), "LINEARRING") ) { poCP = new OGRPolygon(); bIsPolygon = true; } else { poCP = new OGRCurvePolygon(); bIsPolygon = false; } { OGRCurve *poCurve = dynamic_cast<OGRCurve *>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCurve."); } if( poCP->addRingDirectly(poCurve) != OGRERR_NONE ) { delete poCP; delete poGeom; return NULL; } } // Find all inner rings for( psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && (EQUAL(BareGMLElement(psChild->pszValue), "innerBoundaryIs") || EQUAL(BareGMLElement(psChild->pszValue), "interior"))) { const CPLXMLNode* psInteriorChild = GetChildElement(psChild); if( psInteriorChild != NULL ) poGeom = GML2OGRGeometry_XMLNode_Internal( psInteriorChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); else poGeom = NULL; if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid interior ring"); delete poCP; return NULL; } if( !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError( CE_Failure, CPLE_AppDefined, "%s: Got %.500s geometry as innerBoundaryIs.", pszBaseGeometry, poGeom->getGeometryName() ); delete poCP; delete poGeom; return NULL; } if( bIsPolygon ) { if( !EQUAL(poGeom->getGeometryName(), "LINEARRING") ) { if( wkbFlatten(poGeom->getGeometryType()) == wkbLineString ) { OGRLineString* poLS = dynamic_cast<OGRLineString *>(poGeom); if( poLS == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRLineString."); } poGeom = OGRCurve::CastToLinearRing(poLS); } else { OGRPolygon *poPolygon = dynamic_cast<OGRPolygon *>(poCP); if( poPolygon == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRPolygon."); } // Might fail if some rings are not closed. // We used to be tolerant about that with Polygon. // but we have become stricter with CurvePolygon. poCP = OGRSurface::CastToCurvePolygon(poPolygon); if( poCP == NULL ) { delete poGeom; return NULL; } bIsPolygon = false; } } } else { if( EQUAL(poGeom->getGeometryName(), "LINEARRING") ) { OGRCurve *poCurve = dynamic_cast<OGRCurve*>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRCurve."); } poGeom = OGRCurve::CastToLineString(poCurve); } } OGRCurve *poCurve = dynamic_cast<OGRCurve*>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRCurve."); } if( poCP->addRingDirectly(poCurve) != OGRERR_NONE ) { delete poCP; delete poGeom; return NULL; } } } return poCP; } /* -------------------------------------------------------------------- */ /* Triangle */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Triangle")) { // Find outer ring. const CPLXMLNode *psChild = FindBareXMLChild( psNode, "outerBoundaryIs" ); if( psChild == NULL ) psChild = FindBareXMLChild( psNode, "exterior"); psChild = GetChildElement(psChild); if( psChild == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Empty Triangle"); return new OGRTriangle(); } // Translate outer ring and add to Triangle. OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName); if( poGeom == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid exterior ring"); return NULL; } if( !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError( CE_Failure, CPLE_AppDefined, "%s: Got %.500s geometry as outerBoundaryIs.", pszBaseGeometry, poGeom->getGeometryName() ); delete poGeom; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) == wkbLineString && !EQUAL(poGeom->getGeometryName(), "LINEARRING") ) { poGeom = OGRCurve::CastToLinearRing((OGRCurve*)poGeom); } OGRTriangle *poTriangle; if( EQUAL(poGeom->getGeometryName(), "LINEARRING") ) { poTriangle = new OGRTriangle(); } else { delete poGeom; return NULL; } if( poTriangle->addRingDirectly( (OGRCurve*)poGeom ) != OGRERR_NONE ) { delete poTriangle; delete poGeom; return NULL; } return poTriangle; } /* -------------------------------------------------------------------- */ /* LinearRing */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "LinearRing") ) { OGRLinearRing *poLinearRing = new OGRLinearRing(); if( !ParseGMLCoordinates( psNode, poLinearRing, nSRSDimension ) ) { delete poLinearRing; return NULL; } return poLinearRing; } /* -------------------------------------------------------------------- */ /* Ring GML3 */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Ring") ) { OGRCurve* poRing = NULL; OGRCompoundCurve *poCC = NULL; bool bChildrenAreAllLineString = true; bool bLastCurveWasApproximateArc = false; bool bLastCurveWasApproximateArcInvertedAxisOrder = false; double dfLastCurveApproximateArcRadius = 0.0; for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "curveMember") ) { const CPLXMLNode* psCurveChild = GetChildElement(psChild); OGRGeometry* poGeom = NULL; if( psCurveChild != NULL ) { poGeom = GML2OGRGeometry_XMLNode_Internal( psCurveChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); } else { if( psChild->psChild && psChild->psChild->eType == CXT_Attribute && psChild->psChild->psNext == NULL && strcmp(psChild->psChild->pszValue, "xlink:href") == 0 ) { CPLError(CE_Warning, CPLE_AppDefined, "Cannot resolve xlink:href='%s'. " "Try setting GML_SKIP_RESOLVE_ELEMS=NONE", psChild->psChild->psChild->pszValue); } delete poRing; delete poCC; delete poGeom; return NULL; } // Try to join multiline string to one linestring. if( poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbMultiLineString ) { poGeom = OGRGeometryFactory::forceToLineString(poGeom, false); } if( poGeom == NULL || !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { delete poGeom; delete poRing; delete poCC; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) != wkbLineString ) bChildrenAreAllLineString = false; // Ad-hoc logic to handle nicely connecting ArcByCenterPoint // with consecutive curves, as found in some AIXM files. bool bIsApproximateArc = false; const CPLXMLNode* psChild2, *psChild3; if( strcmp(psCurveChild->pszValue, "Curve") == 0 && (psChild2 = GetChildElement(psCurveChild)) != NULL && strcmp(psChild2->pszValue, "segments") == 0 && (psChild3 = GetChildElement(psChild2)) != NULL && strcmp(psChild3->pszValue, "ArcByCenterPoint") == 0 ) { const CPLXMLNode* psRadius = FindBareXMLChild(psChild3, "radius"); if( psRadius && psRadius->eType == CXT_Element ) { double dfRadius = CPLAtof(CPLGetXMLValue( const_cast<CPLXMLNode *>(psRadius), NULL, "0")); const char* pszUnits = CPLGetXMLValue( const_cast<CPLXMLNode *>(psRadius), "uom", NULL); bool bSRSUnitIsDegree = false; bool bInvertedAxisOrder = false; if( pszSRSName != NULL ) { OGRSpatialReference oSRS; if( oSRS.SetFromUserInput(pszSRSName) == OGRERR_NONE ) { if( oSRS.IsGeographic() ) { bInvertedAxisOrder = CPL_TO_BOOL(oSRS.EPSGTreatsAsLatLong()); bSRSUnitIsDegree = fabs(oSRS.GetAngularUnits(NULL) - CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-8; } } } if( bSRSUnitIsDegree && pszUnits != NULL && (EQUAL(pszUnits, "m") || EQUAL(pszUnits, "nm") || EQUAL(pszUnits, "mi") || EQUAL(pszUnits, "ft")) ) { bIsApproximateArc = true; if( EQUAL(pszUnits, "nm") ) dfRadius *= CPLAtof(SRS_UL_INTL_NAUT_MILE_CONV); else if( EQUAL(pszUnits, "mi") ) dfRadius *= CPLAtof(SRS_UL_INTL_STAT_MILE_CONV); else if( EQUAL(pszUnits, "ft") ) dfRadius *= CPLAtof(SRS_UL_INTL_FOOT_CONV); dfLastCurveApproximateArcRadius = dfRadius; bLastCurveWasApproximateArcInvertedAxisOrder = bInvertedAxisOrder; } } } if( poCC == NULL && poRing == NULL ) { poRing = dynamic_cast<OGRCurve *>(poGeom); if( poRing == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRCurve."); } } else { if( poCC == NULL ) { poCC = new OGRCompoundCurve(); bool bIgnored = false; if( !GML2OGRGeometry_AddToCompositeCurve(poCC, poRing, bIgnored) ) { delete poGeom; delete poRing; delete poCC; return NULL; } poRing = NULL; } if( bIsApproximateArc ) { if( poGeom->getGeometryType() == wkbLineString ) { OGRCurve* poPreviousCurve = poCC->getCurve(poCC->getNumCurves()-1); OGRLineString* poLS = dynamic_cast<OGRLineString *>(poGeom); if( poLS == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRLineString."); } if( poPreviousCurve->getNumPoints() >= 2 && poLS->getNumPoints() >= 2 ) { OGRPoint p; OGRPoint p2; poPreviousCurve->EndPoint(&p); poLS->StartPoint(&p2); double dfDistance = 0.0; if( bLastCurveWasApproximateArcInvertedAxisOrder ) dfDistance = OGRXPlane_Distance( p.getX(), p.getY(), p2.getX(), p2.getY()); else dfDistance = OGRXPlane_Distance( p.getY(), p.getX(), p2.getY(), p2.getX()); // CPLDebug("OGR", "%f %f", // dfDistance, // dfLastCurveApproximateArcRadius // / 10.0 ); if( dfDistance < dfLastCurveApproximateArcRadius / 5.0 ) { CPLDebug("OGR", "Moving approximate start of " "ArcByCenterPoint to end of " "previous curve"); poLS->setPoint(0, &p); } } } } else if( bLastCurveWasApproximateArc ) { OGRCurve* poPreviousCurve = poCC->getCurve(poCC->getNumCurves()-1); if( poPreviousCurve->getGeometryType() == wkbLineString ) { OGRLineString* poLS = dynamic_cast<OGRLineString *>(poPreviousCurve); if( poLS == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRLineString."); } OGRCurve *poCurve = dynamic_cast<OGRCurve *>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRCurve."); } if( poLS->getNumPoints() >= 2 && poCurve->getNumPoints() >= 2 ) { OGRPoint p; OGRPoint p2; poCurve->StartPoint(&p); poLS->EndPoint(&p2); double dfDistance = 0.0; if( bLastCurveWasApproximateArcInvertedAxisOrder ) dfDistance = OGRXPlane_Distance( p.getX(), p.getY(), p2.getX(), p2.getY()); else dfDistance = OGRXPlane_Distance( p.getY(), p.getX(), p2.getY(), p2.getX()); // CPLDebug( // "OGR", "%f %f", // dfDistance, // dfLastCurveApproximateArcRadius / 10.0 ); // "A-311 WHEELER AFB OAHU, HI.xml" needs more // than 10%. if( dfDistance < dfLastCurveApproximateArcRadius / 5.0 ) { CPLDebug( "OGR", "Moving approximate end of last " "ArcByCenterPoint to start of the " "current curve"); poLS->setPoint(poLS->getNumPoints() - 1, &p); } } } } OGRCurve *poCurve = dynamic_cast<OGRCurve *>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCurve."); } bool bIgnored = false; if( !GML2OGRGeometry_AddToCompositeCurve( poCC, poCurve, bIgnored ) ) { delete poGeom; delete poCC; delete poRing; return NULL; } } bLastCurveWasApproximateArc = bIsApproximateArc; } } if( poRing ) { if( poRing->getNumPoints() < 2 || !poRing->get_IsClosed() ) { CPLError(CE_Failure, CPLE_AppDefined, "Non-closed ring"); delete poRing; return NULL; } return poRing; } if( poCC == NULL ) return NULL; else if( bCastToLinearTypeIfPossible && bChildrenAreAllLineString ) { return OGRCurve::CastToLinearRing(poCC); } else { if( poCC->getNumPoints() < 2 || !poCC->get_IsClosed() ) { CPLError(CE_Failure, CPLE_AppDefined, "Non-closed ring"); delete poCC; return NULL; } return poCC; } } /* -------------------------------------------------------------------- */ /* LineString */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "LineString") || EQUAL(pszBaseGeometry, "LineStringSegment") || EQUAL(pszBaseGeometry, "GeodesicString") ) { OGRLineString *poLine = new OGRLineString(); if( !ParseGMLCoordinates( psNode, poLine, nSRSDimension ) ) { delete poLine; return NULL; } return poLine; } /* -------------------------------------------------------------------- */ /* Arc */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Arc") ) { OGRCircularString *poCC = new OGRCircularString(); if( !ParseGMLCoordinates( psNode, poCC, nSRSDimension ) ) { delete poCC; return NULL; } if( poCC->getNumPoints() != 3 ) { CPLError(CE_Failure, CPLE_AppDefined, "Bad number of points in Arc"); delete poCC; return NULL; } return poCC; } /* -------------------------------------------------------------------- */ /* ArcString */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "ArcString") ) { OGRCircularString *poCC = new OGRCircularString(); if( !ParseGMLCoordinates( psNode, poCC, nSRSDimension ) ) { delete poCC; return NULL; } if( poCC->getNumPoints() < 3 || (poCC->getNumPoints() % 2) != 1 ) { CPLError(CE_Failure, CPLE_AppDefined, "Bad number of points in ArcString"); delete poCC; return NULL; } return poCC; } /* -------------------------------------------------------------------- */ /* Circle */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Circle") ) { OGRLineString *poLine = new OGRLineString(); if( !ParseGMLCoordinates( psNode, poLine, nSRSDimension ) ) { delete poLine; return NULL; } if( poLine->getNumPoints() != 3 ) { CPLError(CE_Failure, CPLE_AppDefined, "Bad number of points in Circle"); delete poLine; return NULL; } double R = 0.0; double cx = 0.0; double cy = 0.0; double alpha0 = 0.0; double alpha1 = 0.0; double alpha2 = 0.0; if( !OGRGeometryFactory::GetCurveParmeters( poLine->getX(0), poLine->getY(0), poLine->getX(1), poLine->getY(1), poLine->getX(2), poLine->getY(2), R, cx, cy, alpha0, alpha1, alpha2 ) ) { delete poLine; return NULL; } OGRCircularString *poCC = new OGRCircularString(); OGRPoint p; poLine->getPoint(0, &p); poCC->addPoint(&p); poLine->getPoint(1, &p); poCC->addPoint(&p); poLine->getPoint(2, &p); poCC->addPoint(&p); const double alpha4 = alpha2 > alpha0 ? alpha0 + kdf2PI : alpha0 - kdf2PI; const double alpha3 = (alpha2 + alpha4) / 2.0; const double x = cx + R * cos(alpha3); const double y = cy + R * sin(alpha3); if( poCC->getCoordinateDimension() == 3 ) poCC->addPoint( x, y, p.getZ() ); else poCC->addPoint( x, y ); poLine->getPoint(0, &p); poCC->addPoint(&p); delete poLine; return poCC; } /* -------------------------------------------------------------------- */ /* ArcByBulge */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "ArcByBulge") ) { const CPLXMLNode *psChild = FindBareXMLChild( psNode, "bulge"); if( psChild == NULL || psChild->eType != CXT_Element ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing bulge element." ); return NULL; } const double dfBulge = CPLAtof(psChild->psChild->pszValue); psChild = FindBareXMLChild( psNode, "normal"); if( psChild == NULL || psChild->eType != CXT_Element ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing normal element." ); return NULL; } double dfNormal = CPLAtof(psChild->psChild->pszValue); OGRLineString* poLS = new OGRLineString(); if( !ParseGMLCoordinates( psNode, poLS, nSRSDimension ) ) { delete poLS; return NULL; } if( poLS->getNumPoints() != 2 ) { CPLError(CE_Failure, CPLE_AppDefined, "Bad number of points in ArcByBulge"); delete poLS; return NULL; } OGRCircularString *poCC = new OGRCircularString(); OGRPoint p; poLS->getPoint(0, &p); poCC->addPoint(&p); const double dfMidX = (poLS->getX(0) + poLS->getX(1)) / 2.0; const double dfMidY = (poLS->getY(0) + poLS->getY(1)) / 2.0; const double dfDirX = (poLS->getX(1) - poLS->getX(0)) / 2.0; const double dfDirY = (poLS->getY(1) - poLS->getY(0)) / 2.0; double dfNormX = -dfDirY; double dfNormY = dfDirX; const double dfNorm = sqrt(dfNormX * dfNormX + dfNormY * dfNormY); if( dfNorm != 0.0 ) { dfNormX /= dfNorm; dfNormY /= dfNorm; } const double dfNewX = dfMidX + dfNormX * dfBulge * dfNormal; const double dfNewY = dfMidY + dfNormY * dfBulge * dfNormal; if( poCC->getCoordinateDimension() == 3 ) poCC->addPoint( dfNewX, dfNewY, p.getZ() ); else poCC->addPoint( dfNewX, dfNewY ); poLS->getPoint(1, &p); poCC->addPoint(&p); delete poLS; return poCC; } /* -------------------------------------------------------------------- */ /* ArcByCenterPoint */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "ArcByCenterPoint") ) { const CPLXMLNode *psChild = FindBareXMLChild( psNode, "radius"); if( psChild == NULL || psChild->eType != CXT_Element ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing radius element." ); return NULL; } const double dfRadius = CPLAtof(CPLGetXMLValue(const_cast<CPLXMLNode *>(psChild), NULL, "0")); const char* pszUnits = CPLGetXMLValue(const_cast<CPLXMLNode *>(psChild), "uom", NULL); psChild = FindBareXMLChild( psNode, "startAngle"); if( psChild == NULL || psChild->eType != CXT_Element ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing startAngle element." ); return NULL; } const double dfStartAngle = CPLAtof(CPLGetXMLValue(const_cast<CPLXMLNode *>(psChild), NULL, "0")); psChild = FindBareXMLChild( psNode, "endAngle"); if( psChild == NULL || psChild->eType != CXT_Element ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing endAngle element." ); return NULL; } const double dfEndAngle = CPLAtof(CPLGetXMLValue(const_cast<CPLXMLNode *>(psChild), NULL, "0")); OGRPoint p; if( !ParseGMLCoordinates( psNode, &p, nSRSDimension ) ) { return NULL; } bool bSRSUnitIsDegree = false; bool bInvertedAxisOrder = false; if( pszSRSName != NULL ) { OGRSpatialReference oSRS; if( oSRS.SetFromUserInput(pszSRSName) == OGRERR_NONE ) { if( oSRS.IsGeographic() ) { bInvertedAxisOrder = CPL_TO_BOOL(oSRS.EPSGTreatsAsLatLong()); bSRSUnitIsDegree = fabs(oSRS.GetAngularUnits(NULL) - CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-8; } } } const double dfCenterX = p.getX(); const double dfCenterY = p.getY(); if( bSRSUnitIsDegree && pszUnits != NULL && (EQUAL(pszUnits, "m") || EQUAL(pszUnits, "nm") || EQUAL(pszUnits, "mi") || EQUAL(pszUnits, "ft")) ) { OGRLineString* poLS = new OGRLineString(); const double dfStep = CPLAtof(CPLGetConfigOption("OGR_ARC_STEPSIZE", "4")); double dfDistance = dfRadius; if( EQUAL(pszUnits, "nm") ) dfDistance *= CPLAtof(SRS_UL_INTL_NAUT_MILE_CONV); else if( EQUAL(pszUnits, "mi") ) dfDistance *= CPLAtof(SRS_UL_INTL_STAT_MILE_CONV); else if( EQUAL(pszUnits, "ft") ) dfDistance *= CPLAtof(SRS_UL_INTL_FOOT_CONV); const double dfSign = dfStartAngle < dfEndAngle ? 1 : -1; for( double dfAngle = dfStartAngle; (dfAngle - dfEndAngle) * dfSign < 0; dfAngle += dfSign * dfStep) { double dfLong = 0.0; double dfLat = 0.0; if( bInvertedAxisOrder ) { OGRXPlane_ExtendPosition( dfCenterX, dfCenterY, dfDistance, // Not sure of angle conversion here. 90.0 - dfAngle, &dfLat, &dfLong); p.setY( dfLat ); p.setX( dfLong ); } else { OGRXPlane_ExtendPosition(dfCenterY, dfCenterX, dfDistance, 90-dfAngle, &dfLat, &dfLong); p.setX( dfLong ); p.setY( dfLat ); } poLS->addPoint(&p); } double dfLong = 0.0; double dfLat = 0.0; if( bInvertedAxisOrder ) { OGRXPlane_ExtendPosition(dfCenterX, dfCenterY, dfDistance, // Not sure of angle conversion here. 90.0 - dfEndAngle, &dfLat, &dfLong); p.setY( dfLat ); p.setX( dfLong ); } else { OGRXPlane_ExtendPosition(dfCenterY, dfCenterX, dfDistance, 90-dfEndAngle, &dfLat, &dfLong); p.setX( dfLong ); p.setY( dfLat ); } poLS->addPoint(&p); return poLS; } OGRCircularString *poCC = new OGRCircularString(); p.setX(dfCenterX + dfRadius * cos(dfStartAngle * kdfD2R)); p.setY(dfCenterY + dfRadius * sin(dfStartAngle * kdfD2R)); poCC->addPoint(&p); const double dfAverageAngle = (dfStartAngle + dfEndAngle) / 2.0; p.setX(dfCenterX + dfRadius * cos(dfAverageAngle * kdfD2R)); p.setY(dfCenterY + dfRadius * sin(dfAverageAngle * kdfD2R)); poCC->addPoint(&p); p.setX(dfCenterX + dfRadius * cos(dfEndAngle * kdfD2R)); p.setY(dfCenterY + dfRadius * sin(dfEndAngle * kdfD2R)); poCC->addPoint(&p); return poCC; } /* -------------------------------------------------------------------- */ /* CircleByCenterPoint */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "CircleByCenterPoint") ) { const CPLXMLNode *psChild = FindBareXMLChild( psNode, "radius"); if( psChild == NULL || psChild->eType != CXT_Element ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing radius element." ); return NULL; } const double dfRadius = CPLAtof(CPLGetXMLValue(const_cast<CPLXMLNode *>(psChild), NULL, "0")); const char* pszUnits = CPLGetXMLValue(const_cast<CPLXMLNode *>(psChild), "uom", NULL); OGRPoint p; if( !ParseGMLCoordinates( psNode, &p, nSRSDimension ) ) { return NULL; } bool bSRSUnitIsDegree = false; bool bInvertedAxisOrder = false; if( pszSRSName != NULL ) { OGRSpatialReference oSRS; if( oSRS.SetFromUserInput(pszSRSName) == OGRERR_NONE ) { if( oSRS.IsGeographic() ) { bInvertedAxisOrder = CPL_TO_BOOL(oSRS.EPSGTreatsAsLatLong()); bSRSUnitIsDegree = fabs(oSRS.GetAngularUnits(NULL) - CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-8; } } } const double dfCenterX = p.getX(); const double dfCenterY = p.getY(); if( bSRSUnitIsDegree && pszUnits != NULL && (EQUAL(pszUnits, "m") || EQUAL(pszUnits, "nm") || EQUAL(pszUnits, "mi") || EQUAL(pszUnits, "ft")) ) { OGRLineString* poLS = new OGRLineString(); const double dfStep = CPLAtof(CPLGetConfigOption("OGR_ARC_STEPSIZE", "4")); double dfDistance = dfRadius; if( EQUAL(pszUnits, "nm") ) dfDistance *= CPLAtof(SRS_UL_INTL_NAUT_MILE_CONV); else if( EQUAL(pszUnits, "mi") ) dfDistance *= CPLAtof(SRS_UL_INTL_STAT_MILE_CONV); else if( EQUAL(pszUnits, "ft") ) dfDistance *= CPLAtof(SRS_UL_INTL_FOOT_CONV); for( double dfAngle = 0; dfAngle < 360; dfAngle += dfStep ) { double dfLong = 0.0; double dfLat = 0.0; if( bInvertedAxisOrder ) { OGRXPlane_ExtendPosition(dfCenterX, dfCenterY, dfDistance, dfAngle, &dfLat, &dfLong); p.setY( dfLat ); p.setX( dfLong ); } else { OGRXPlane_ExtendPosition(dfCenterY, dfCenterX, dfDistance, dfAngle, &dfLat, &dfLong); p.setX( dfLong ); p.setY( dfLat ); } poLS->addPoint(&p); } poLS->getPoint(0, &p); poLS->addPoint(&p); return poLS; } OGRCircularString *poCC = new OGRCircularString(); p.setX( dfCenterX - dfRadius ); p.setY( dfCenterY ); poCC->addPoint(&p); p.setX( dfCenterX + dfRadius); p.setY( dfCenterY ); poCC->addPoint(&p); p.setX( dfCenterX - dfRadius ); p.setY( dfCenterY ); poCC->addPoint(&p); return poCC; } /* -------------------------------------------------------------------- */ /* PointType */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "PointType") || EQUAL(pszBaseGeometry, "Point") || EQUAL(pszBaseGeometry, "ConnectionPoint") ) { OGRPoint *poPoint = new OGRPoint(); if( !ParseGMLCoordinates( psNode, poPoint, nSRSDimension ) ) { delete poPoint; return NULL; } return poPoint; } /* -------------------------------------------------------------------- */ /* Box */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "BoxType") || EQUAL(pszBaseGeometry, "Box") ) { OGRLineString oPoints; if( !ParseGMLCoordinates( psNode, &oPoints, nSRSDimension ) ) return NULL; if( oPoints.getNumPoints() < 2 ) return NULL; OGRLinearRing *poBoxRing = new OGRLinearRing(); OGRPolygon *poBoxPoly = new OGRPolygon(); poBoxRing->setNumPoints( 5 ); poBoxRing->setPoint( 0, oPoints.getX(0), oPoints.getY(0), oPoints.getZ(0) ); poBoxRing->setPoint( 1, oPoints.getX(1), oPoints.getY(0), oPoints.getZ(0) ); poBoxRing->setPoint( 2, oPoints.getX(1), oPoints.getY(1), oPoints.getZ(1) ); poBoxRing->setPoint( 3, oPoints.getX(0), oPoints.getY(1), oPoints.getZ(0) ); poBoxRing->setPoint( 4, oPoints.getX(0), oPoints.getY(0), oPoints.getZ(0) ); poBoxPoly->addRingDirectly( poBoxRing ); return poBoxPoly; } /* -------------------------------------------------------------------- */ /* Envelope */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Envelope") ) { const CPLXMLNode* psLowerCorner = FindBareXMLChild( psNode, "lowerCorner"); const CPLXMLNode* psUpperCorner = FindBareXMLChild( psNode, "upperCorner"); if( psLowerCorner == NULL || psUpperCorner == NULL ) return NULL; const char* pszLowerCorner = GetElementText(psLowerCorner); const char* pszUpperCorner = GetElementText(psUpperCorner); if( pszLowerCorner == NULL || pszUpperCorner == NULL ) return NULL; char** papszLowerCorner = CSLTokenizeString(pszLowerCorner); char** papszUpperCorner = CSLTokenizeString(pszUpperCorner); const int nTokenCountLC = CSLCount(papszLowerCorner); const int nTokenCountUC = CSLCount(papszUpperCorner); if( nTokenCountLC < 2 || nTokenCountUC < 2 ) { CSLDestroy(papszLowerCorner); CSLDestroy(papszUpperCorner); return NULL; } const double dfLLX = CPLAtof(papszLowerCorner[0]); const double dfLLY = CPLAtof(papszLowerCorner[1]); const double dfURX = CPLAtof(papszUpperCorner[0]); const double dfURY = CPLAtof(papszUpperCorner[1]); CSLDestroy(papszLowerCorner); CSLDestroy(papszUpperCorner); OGRLinearRing *poEnvelopeRing = new OGRLinearRing(); OGRPolygon *poPoly = new OGRPolygon(); poEnvelopeRing->setNumPoints( 5 ); poEnvelopeRing->setPoint(0, dfLLX, dfLLY); poEnvelopeRing->setPoint(1, dfURX, dfLLY); poEnvelopeRing->setPoint(2, dfURX, dfURY); poEnvelopeRing->setPoint(3, dfLLX, dfURY); poEnvelopeRing->setPoint(4, dfLLX, dfLLY); poPoly->addRingDirectly(poEnvelopeRing ); return poPoly; } /* --------------------------------------------------------------------- */ /* MultiPolygon / MultiSurface / CompositeSurface */ /* */ /* For CompositeSurface, this is a very rough approximation to deal with */ /* it as a MultiPolygon, because it can several faces of a 3D volume. */ /* --------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "MultiPolygon") || EQUAL(pszBaseGeometry, "MultiSurface") || EQUAL(pszBaseGeometry, "CompositeSurface") ) { OGRMultiSurface* poMS = EQUAL(pszBaseGeometry, "MultiPolygon") ? new OGRMultiPolygon() : new OGRMultiSurface(); bool bReconstructTopology = false; bool bChildrenAreAllPolygons = true; // Iterate over children. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { const char* pszMemberElement = BareGMLElement(psChild->pszValue); if( psChild->eType == CXT_Element && (EQUAL(pszMemberElement, "polygonMember") || EQUAL(pszMemberElement, "surfaceMember")) ) { const CPLXMLNode* psSurfaceChild = GetChildElement(psChild); if( psSurfaceChild != NULL ) { // Cf #5421 where there are PolygonPatch with only inner // rings. const CPLXMLNode* psPolygonPatch = GetChildElement(GetChildElement(psSurfaceChild)); const CPLXMLNode* psPolygonPatchChild = NULL; if( psPolygonPatch != NULL && psPolygonPatch->eType == CXT_Element && EQUAL(BareGMLElement(psPolygonPatch->pszValue), "PolygonPatch") && (psPolygonPatchChild = GetChildElement(psPolygonPatch)) != NULL && EQUAL(BareGMLElement(psPolygonPatchChild->pszValue), "interior") ) { // Find all inner rings for( const CPLXMLNode* psChild2 = psPolygonPatch->psChild; psChild2 != NULL; psChild2 = psChild2->psNext ) { if( psChild2->eType == CXT_Element && (EQUAL(BareGMLElement(psChild2->pszValue), "interior"))) { const CPLXMLNode* psInteriorChild = GetChildElement(psChild2); OGRGeometry* poRing = psInteriorChild == NULL ? NULL : GML2OGRGeometry_XMLNode_Internal( psInteriorChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poRing == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid interior ring"); delete poMS; return NULL; } if( !EQUAL(poRing->getGeometryName(), "LINEARRING") ) { CPLError( CE_Failure, CPLE_AppDefined, "%s: Got %.500s geometry as " "innerBoundaryIs instead of " "LINEARRING.", pszBaseGeometry, poRing->getGeometryName()); delete poRing; delete poMS; return NULL; } bReconstructTopology = true; OGRPolygon *poPolygon = new OGRPolygon(); OGRLinearRing *poLinearRing = dynamic_cast<OGRLinearRing *>(poRing); if( poLinearRing == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRLinearRing."); } poPolygon->addRingDirectly(poLinearRing); poMS->addGeometryDirectly( poPolygon ); } } } else { OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psSurfaceChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( !GML2OGRGeometry_AddToMultiSurface( poMS, poGeom, pszMemberElement, bChildrenAreAllPolygons) ) { delete poGeom; delete poMS; return NULL; } } } } else if( psChild->eType == CXT_Element && EQUAL(pszMemberElement, "surfaceMembers") ) { for( const CPLXMLNode *psChild2 = psChild->psChild; psChild2 != NULL; psChild2 = psChild2->psNext ) { pszMemberElement = BareGMLElement(psChild2->pszValue); if( psChild2->eType == CXT_Element && (EQUAL(pszMemberElement, "Surface") || EQUAL(pszMemberElement, "Polygon") || EQUAL(pszMemberElement, "PolygonPatch") || EQUAL(pszMemberElement, "CompositeSurface")) ) { OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild2, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( !GML2OGRGeometry_AddToMultiSurface( poMS, poGeom, pszMemberElement, bChildrenAreAllPolygons) ) { delete poGeom; delete poMS; return NULL; } } } } } if( bReconstructTopology && bChildrenAreAllPolygons ) { OGRMultiPolygon* poMPoly = wkbFlatten(poMS->getGeometryType()) == wkbMultiSurface ? OGRMultiSurface::CastToMultiPolygon(poMS) : dynamic_cast<OGRMultiPolygon *>(poMS); CPLAssert(poMPoly); // Should not fail. const int nPolygonCount = poMPoly->getNumGeometries(); OGRGeometry** papoPolygons = new OGRGeometry*[ nPolygonCount ]; for( int i = 0; i < nPolygonCount; i++ ) { papoPolygons[i] = poMPoly->getGeometryRef(0); poMPoly->removeGeometry(0, FALSE); } delete poMPoly; int bResultValidGeometry = FALSE; OGRGeometry* poRet = OGRGeometryFactory::organizePolygons( papoPolygons, nPolygonCount, &bResultValidGeometry ); delete[] papoPolygons; return poRet; } else { if( bCastToLinearTypeIfPossible && wkbFlatten(poMS->getGeometryType()) == wkbMultiSurface && bChildrenAreAllPolygons ) { return OGRMultiSurface::CastToMultiPolygon(poMS); } return poMS; } } /* -------------------------------------------------------------------- */ /* MultiPoint */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "MultiPoint") ) { OGRMultiPoint *poMP = new OGRMultiPoint(); // Collect points. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "pointMember") ) { const CPLXMLNode* psPointChild = GetChildElement(psChild); if( psPointChild != NULL ) { OGRGeometry *poPointMember = GML2OGRGeometry_XMLNode_Internal( psPointChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poPointMember == NULL || wkbFlatten(poPointMember->getGeometryType()) != wkbPoint ) { CPLError( CE_Failure, CPLE_AppDefined, "MultiPoint: Got %.500s geometry as " "pointMember instead of POINT", poPointMember ? poPointMember->getGeometryName() : "NULL" ); delete poPointMember; delete poMP; return NULL; } poMP->addGeometryDirectly( poPointMember ); } } else if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "pointMembers") ) { for( const CPLXMLNode *psChild2 = psChild->psChild; psChild2 != NULL; psChild2 = psChild2->psNext ) { if( psChild2->eType == CXT_Element && (EQUAL(BareGMLElement(psChild2->pszValue), "Point")) ) { OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild2, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid %s", BareGMLElement(psChild2->pszValue)); delete poMP; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) == wkbPoint ) { OGRPoint *poPoint = dynamic_cast<OGRPoint *>(poGeom); if( poPoint == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRCPoint."); } poMP->addGeometryDirectly( poPoint ); } else { CPLError( CE_Failure, CPLE_AppDefined, "Got %.500s geometry as pointMember " "instead of POINT.", poGeom->getGeometryName() ); delete poGeom; delete poMP; return NULL; } } } } } return poMP; } /* -------------------------------------------------------------------- */ /* MultiLineString */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "MultiLineString") ) { OGRMultiLineString *poMLS = new OGRMultiLineString(); // Collect lines. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "lineStringMember") ) { const CPLXMLNode* psLineStringChild = GetChildElement(psChild); OGRGeometry *poGeom = psLineStringChild == NULL ? NULL : GML2OGRGeometry_XMLNode_Internal( psLineStringChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL || wkbFlatten(poGeom->getGeometryType()) != wkbLineString ) { CPLError(CE_Failure, CPLE_AppDefined, "MultiLineString: Got %.500s geometry as Member " "instead of LINESTRING.", poGeom ? poGeom->getGeometryName() : "NULL" ); delete poGeom; delete poMLS; return NULL; } poMLS->addGeometryDirectly( poGeom ); } } return poMLS; } /* -------------------------------------------------------------------- */ /* MultiCurve */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "MultiCurve") ) { OGRMultiCurve *poMC = new OGRMultiCurve(); bool bChildrenAreAllLineString = true; // Collect curveMembers. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "curveMember") ) { const CPLXMLNode *psChild2 = GetChildElement(psChild); if( psChild2 != NULL ) // Empty curveMember is valid. { OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild2, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL || !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError(CE_Failure, CPLE_AppDefined, "MultiCurve: Got %.500s geometry as Member " "instead of a curve.", poGeom ? poGeom->getGeometryName() : "NULL" ); if( poGeom != NULL ) delete poGeom; delete poMC; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) != wkbLineString ) bChildrenAreAllLineString = false; if( poMC->addGeometryDirectly( poGeom ) != OGRERR_NONE ) { delete poGeom; } } } else if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "curveMembers") ) { for( const CPLXMLNode *psChild2 = psChild->psChild; psChild2 != NULL; psChild2 = psChild2->psNext ) { if( psChild2->eType == CXT_Element ) { OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild2, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL || !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError( CE_Failure, CPLE_AppDefined, "MultiCurve: Got %.500s geometry as " "Member instead of a curve.", poGeom ? poGeom->getGeometryName() : "NULL" ); if( poGeom != NULL ) delete poGeom; delete poMC; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) != wkbLineString ) bChildrenAreAllLineString = false; if( poMC->addGeometryDirectly( poGeom ) != OGRERR_NONE ) { delete poGeom; } } } } } if( bCastToLinearTypeIfPossible && bChildrenAreAllLineString ) { return OGRMultiCurve::CastToMultiLineString(poMC); } return poMC; } /* -------------------------------------------------------------------- */ /* CompositeCurve */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "CompositeCurve") ) { OGRCompoundCurve *poCC = new OGRCompoundCurve(); bool bChildrenAreAllLineString = true; // Collect curveMembers. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "curveMember") ) { const CPLXMLNode *psChild2 = GetChildElement(psChild); if( psChild2 != NULL ) // Empty curveMember is valid. { OGRGeometry*poGeom = GML2OGRGeometry_XMLNode_Internal( psChild2, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( !GML2OGRGeometry_AddToCompositeCurve( poCC, poGeom, bChildrenAreAllLineString) ) { delete poGeom; delete poCC; return NULL; } } } else if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "curveMembers") ) { for( const CPLXMLNode *psChild2 = psChild->psChild; psChild2 != NULL; psChild2 = psChild2->psNext ) { if( psChild2->eType == CXT_Element ) { OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild2, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( !GML2OGRGeometry_AddToCompositeCurve( poCC, poGeom, bChildrenAreAllLineString) ) { delete poGeom; delete poCC; return NULL; } } } } } if( bCastToLinearTypeIfPossible && bChildrenAreAllLineString ) { return OGRCurve::CastToLineString(poCC); } return poCC; } /* -------------------------------------------------------------------- */ /* Curve */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Curve") ) { const CPLXMLNode *psChild = FindBareXMLChild( psNode, "segments"); if( psChild == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "GML3 Curve geometry lacks segments element." ); return NULL; } OGRGeometry *poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL || !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError( CE_Failure, CPLE_AppDefined, "Curve: Got %.500s geometry as Member instead of segments.", poGeom ? poGeom->getGeometryName() : "NULL" ); if( poGeom != NULL ) delete poGeom; return NULL; } return poGeom; } /* -------------------------------------------------------------------- */ /* segments */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "segments") ) { OGRCurve* poCurve = NULL; OGRCompoundCurve *poCC = NULL; bool bChildrenAreAllLineString = true; for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element // && (EQUAL(BareGMLElement(psChild->pszValue), // "LineStringSegment") || // EQUAL(BareGMLElement(psChild->pszValue), // "GeodesicString") || // EQUAL(BareGMLElement(psChild->pszValue), "Arc") || // EQUAL(BareGMLElement(psChild->pszValue), "Circle")) ) { OGRGeometry *poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL || !OGR_GT_IsCurve(poGeom->getGeometryType()) ) { CPLError(CE_Failure, CPLE_AppDefined, "segments: Got %.500s geometry as Member " "instead of curve.", poGeom ? poGeom->getGeometryName() : "NULL"); delete poGeom; delete poCurve; delete poCC; return NULL; } if( wkbFlatten(poGeom->getGeometryType()) != wkbLineString ) bChildrenAreAllLineString = false; if( poCC == NULL && poCurve == NULL ) { poCurve = dynamic_cast<OGRCurve *>(poGeom); if( poCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCurve."); } } else { if( poCC == NULL ) { poCC = new OGRCompoundCurve(); if( poCC->addCurveDirectly(poCurve) != OGRERR_NONE ) { delete poGeom; delete poCurve; delete poCC; return NULL; } poCurve = NULL; } OGRCurve *poAsCurve = dynamic_cast<OGRCurve *>(poGeom); if( poAsCurve == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRCurve."); } if( poCC->addCurveDirectly(poAsCurve) != OGRERR_NONE ) { delete poGeom; delete poCC; return NULL; } } } } if( poCurve != NULL ) return poCurve; if( poCC == NULL ) return NULL; if( bCastToLinearTypeIfPossible && bChildrenAreAllLineString ) { return OGRCurve::CastToLineString(poCC); } return poCC; } /* -------------------------------------------------------------------- */ /* MultiGeometry */ /* CAUTION: OGR < 1.8.0 produced GML with GeometryCollection, which is */ /* not a valid GML 2 keyword! The right name is MultiGeometry. Let's be */ /* tolerant with the non compliant files we produced. */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "MultiGeometry") || EQUAL(pszBaseGeometry, "GeometryCollection") ) { OGRGeometryCollection *poGC = new OGRGeometryCollection(); // Collect geoms. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "geometryMember") ) { const CPLXMLNode* psGeometryChild = GetChildElement(psChild); if( psGeometryChild != NULL ) { OGRGeometry *poGeom = GML2OGRGeometry_XMLNode_Internal( psGeometryChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "GeometryCollection: Failed to get geometry " "in geometryMember" ); delete poGeom; delete poGC; return NULL; } poGC->addGeometryDirectly( poGeom ); } } } return poGC; } /* -------------------------------------------------------------------- */ /* Directed Edge */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "directedEdge") ) { // Collect edge. const CPLXMLNode *psEdge = FindBareXMLChild(psNode, "Edge"); if( psEdge == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to get Edge element in directedEdge" ); return NULL; } // TODO(schwehr): Localize vars after removing gotos. OGRGeometry *poGeom = NULL; const CPLXMLNode *psNodeElement = NULL; const CPLXMLNode *psPointProperty = NULL; const CPLXMLNode *psPoint = NULL; bool bNodeOrientation = true; OGRPoint *poPositiveNode = NULL; OGRPoint *poNegativeNode = NULL; const bool bEdgeOrientation = GetElementOrientation(psNode); if( bGetSecondaryGeometry ) { const CPLXMLNode *psdirectedNode = FindBareXMLChild(psEdge, "directedNode"); if( psdirectedNode == NULL ) goto nonode; bNodeOrientation = GetElementOrientation( psdirectedNode ); psNodeElement = FindBareXMLChild(psdirectedNode, "Node"); if( psNodeElement == NULL ) goto nonode; psPointProperty = FindBareXMLChild(psNodeElement, "pointProperty"); if( psPointProperty == NULL ) psPointProperty = FindBareXMLChild(psNodeElement, "connectionPointProperty"); if( psPointProperty == NULL ) goto nonode; psPoint = FindBareXMLChild(psPointProperty, "Point"); if( psPoint == NULL ) psPoint = FindBareXMLChild(psPointProperty, "ConnectionPoint"); if( psPoint == NULL ) goto nonode; poGeom = GML2OGRGeometry_XMLNode_Internal( psPoint, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName, true ); if( poGeom == NULL || wkbFlatten(poGeom->getGeometryType()) != wkbPoint ) { // CPLError( CE_Failure, CPLE_AppDefined, // "Got %.500s geometry as Member instead of POINT.", // poGeom ? poGeom->getGeometryName() : "NULL" ); if( poGeom != NULL) delete poGeom; goto nonode; } { OGRPoint *poPoint = dynamic_cast<OGRPoint *>(poGeom); if( poPoint == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPoint."); } if( ( bNodeOrientation == bEdgeOrientation ) != bOrientation ) poPositiveNode = poPoint; else poNegativeNode = poPoint; } // Look for the other node. psdirectedNode = psdirectedNode->psNext; while( psdirectedNode != NULL && !EQUAL( psdirectedNode->pszValue, "directedNode" ) ) psdirectedNode = psdirectedNode->psNext; if( psdirectedNode == NULL ) goto nonode; if( GetElementOrientation( psdirectedNode ) == bNodeOrientation ) goto nonode; psNodeElement = FindBareXMLChild(psEdge, "Node"); if( psNodeElement == NULL ) goto nonode; psPointProperty = FindBareXMLChild(psNodeElement, "pointProperty"); if( psPointProperty == NULL ) psPointProperty = FindBareXMLChild(psNodeElement, "connectionPointProperty"); if( psPointProperty == NULL ) goto nonode; psPoint = FindBareXMLChild(psPointProperty, "Point"); if( psPoint == NULL ) psPoint = FindBareXMLChild(psPointProperty, "ConnectionPoint"); if( psPoint == NULL ) goto nonode; poGeom = GML2OGRGeometry_XMLNode_Internal( psPoint, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName, true ); if( poGeom == NULL || wkbFlatten(poGeom->getGeometryType()) != wkbPoint ) { // CPLError( CE_Failure, CPLE_AppDefined, // "Got %.500s geometry as Member instead of POINT.", // poGeom ? poGeom->getGeometryName() : "NULL" ); if( poGeom != NULL) delete poGeom; goto nonode; } { OGRPoint *poPoint = dynamic_cast<OGRPoint *>(poGeom); if( poPoint == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRPoint."); } if( ( bNodeOrientation == bEdgeOrientation ) != bOrientation ) poNegativeNode = poPoint; else poPositiveNode = poPoint; } { // Create a scope so that poMP can be initialized with goto // above and label below. OGRMultiPoint *poMP = new OGRMultiPoint(); poMP->addGeometryDirectly( poNegativeNode ); poMP->addGeometryDirectly( poPositiveNode ); return poMP; } nonode:; } // Collect curveproperty. const CPLXMLNode *psCurveProperty = FindBareXMLChild(psEdge, "curveProperty"); if( psCurveProperty == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "directedEdge: Failed to get curveProperty in Edge" ); return NULL; } const CPLXMLNode *psCurve = FindBareXMLChild(psCurveProperty, "LineString"); if( psCurve == NULL ) psCurve = FindBareXMLChild(psCurveProperty, "Curve"); if( psCurve == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "directedEdge: Failed to get LineString or " "Curve tag in curveProperty"); return NULL; } OGRGeometry* poLineStringBeforeCast = GML2OGRGeometry_XMLNode_Internal( psCurve, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName, true ); if( poLineStringBeforeCast == NULL || wkbFlatten(poLineStringBeforeCast->getGeometryType()) != wkbLineString ) { CPLError(CE_Failure, CPLE_AppDefined, "Got %.500s geometry as Member instead of LINESTRING.", poLineStringBeforeCast ? poLineStringBeforeCast->getGeometryName() : "NULL" ); delete poLineStringBeforeCast; return NULL; } OGRLineString *poLineString = dynamic_cast<OGRLineString *>(poLineStringBeforeCast); if( poLineString == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. Expected OGRLineString."); } if( bGetSecondaryGeometry ) { // Choose a point based on the orientation. poNegativeNode = new OGRPoint(); poPositiveNode = new OGRPoint(); if( bEdgeOrientation == bOrientation ) { poLineString->StartPoint( poNegativeNode ); poLineString->EndPoint( poPositiveNode ); } else { poLineString->StartPoint( poPositiveNode ); poLineString->EndPoint( poNegativeNode ); } delete poLineString; OGRMultiPoint *poMP = new OGRMultiPoint(); poMP->addGeometryDirectly( poNegativeNode ); poMP->addGeometryDirectly( poPositiveNode ); return poMP; } // correct orientation of the line string if( bEdgeOrientation != bOrientation ) { int iStartCoord = 0; int iEndCoord = poLineString->getNumPoints() - 1; OGRPoint *poTempStartPoint = new OGRPoint(); OGRPoint *poTempEndPoint = new OGRPoint(); while( iStartCoord < iEndCoord ) { poLineString->getPoint( iStartCoord, poTempStartPoint ); poLineString->getPoint( iEndCoord, poTempEndPoint ); poLineString->setPoint( iStartCoord, poTempEndPoint ); poLineString->setPoint( iEndCoord, poTempStartPoint ); iStartCoord++; iEndCoord--; } delete poTempStartPoint; delete poTempEndPoint; } return poLineString; } /* -------------------------------------------------------------------- */ /* TopoCurve */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "TopoCurve") ) { OGRMultiLineString *poMLS = NULL; OGRMultiPoint *poMP = NULL; if( bGetSecondaryGeometry ) poMP = new OGRMultiPoint(); else poMLS = new OGRMultiLineString(); // Collect directedEdges. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "directedEdge")) { OGRGeometry *poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to get geometry in directedEdge" ); delete poGeom; if( bGetSecondaryGeometry ) delete poMP; else delete poMLS; return NULL; } // Add the two points corresponding to the two nodes to poMP. if( bGetSecondaryGeometry && wkbFlatten(poGeom->getGeometryType()) == wkbMultiPoint ) { OGRMultiPoint *poMultiPoint = dynamic_cast<OGRMultiPoint *>(poGeom); if( poMultiPoint == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRMultiPoint."); } //TODO: TopoCurve geometries with more than one // directedEdge elements were not tested. if( poMP->getNumGeometries() <= 0 || !(poMP->getGeometryRef( poMP->getNumGeometries() - 1 )-> Equals(poMultiPoint->getGeometryRef(0))) ) { poMP->addGeometry(poMultiPoint->getGeometryRef(0) ); } poMP->addGeometry(poMultiPoint->getGeometryRef(1) ); delete poGeom; } else if( !bGetSecondaryGeometry && wkbFlatten(poGeom->getGeometryType()) == wkbLineString ) { poMLS->addGeometryDirectly( poGeom ); } else { CPLError( CE_Failure, CPLE_AppDefined, "Got %.500s geometry as Member instead of %s.", poGeom ? poGeom->getGeometryName() : "NULL", bGetSecondaryGeometry?"MULTIPOINT":"LINESTRING"); delete poGeom; if( bGetSecondaryGeometry ) delete poMP; else delete poMLS; return NULL; } } } if( bGetSecondaryGeometry ) return poMP; return poMLS; } /* -------------------------------------------------------------------- */ /* TopoSurface */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "TopoSurface") ) { /****************************************************************/ /* applying the FaceHoleNegative = false rules */ /* */ /* - each <TopoSurface> is expected to represent a MultiPolygon */ /* - each <Face> is expected to represent a distinct Polygon, */ /* this including any possible Interior Ring (holes); */ /* orientation="+/-" plays no role at all to identify "holes" */ /* - each <Edge> within a <Face> may indifferently represent */ /* an element of the Exterior or Interior Boundary; relative */ /* order of <Edges> is absolutely irrelevant. */ /****************************************************************/ /* Contributor: Alessandro Furieri, a.furieri@lqt.it */ /* Developed for Faunalia (http://www.faunalia.it) */ /* with funding from Regione Toscana - */ /* Settore SISTEMA INFORMATIVO TERRITORIALE ED AMBIENTALE */ /****************************************************************/ if( !bFaceHoleNegative ) { if( bGetSecondaryGeometry ) return NULL; #ifndef HAVE_GEOS static bool bWarningAlreadyEmitted = false; if( !bWarningAlreadyEmitted ) { CPLError( CE_Failure, CPLE_AppDefined, "Interpreating that GML TopoSurface geometry requires GDAL " "to be built with GEOS support. As a workaround, you can " "try defining the GML_FACE_HOLE_NEGATIVE configuration " "option to YES, so that the 'old' interpretation algorithm " "is used. But be warned that the result might be " "incorrect."); bWarningAlreadyEmitted = true; } return NULL; #else OGRMultiPolygon *poTS = new OGRMultiPolygon(); // Collect directed faces. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "directedFace") ) { // Collect next face (psChild->psChild). const CPLXMLNode *psFaceChild = GetChildElement(psChild); while( psFaceChild != NULL && !(psFaceChild->eType == CXT_Element && EQUAL(BareGMLElement(psFaceChild->pszValue), "Face")) ) psFaceChild = psFaceChild->psNext; if( psFaceChild == NULL ) continue; OGRMultiLineString *poCollectedGeom = new OGRMultiLineString(); // Collect directed edges of the face. for( const CPLXMLNode *psDirectedEdgeChild = psFaceChild->psChild; psDirectedEdgeChild != NULL; psDirectedEdgeChild = psDirectedEdgeChild->psNext ) { if( psDirectedEdgeChild->eType == CXT_Element && EQUAL(BareGMLElement(psDirectedEdgeChild->pszValue), "directedEdge") ) { OGRGeometry *poEdgeGeom = GML2OGRGeometry_XMLNode_Internal( psDirectedEdgeChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName, true); if( poEdgeGeom == NULL || wkbFlatten(poEdgeGeom->getGeometryType()) != wkbLineString ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to get geometry in directedEdge" ); delete poEdgeGeom; delete poCollectedGeom; delete poTS; return NULL; } poCollectedGeom->addGeometryDirectly( poEdgeGeom ); } } OGRGeometry *poFaceCollectionGeom = poCollectedGeom->Polygonize(); if( poFaceCollectionGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to assemble Edges in Face" ); delete poCollectedGeom; delete poTS; return NULL; } OGRPolygon *poFaceGeom = GML2FaceExtRing(poFaceCollectionGeom); if( poFaceGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to build Polygon for Face" ); delete poCollectedGeom; delete poTS; return NULL; } else { int iCount = poTS->getNumGeometries(); if( iCount == 0) { // Inserting the first Polygon. poTS->addGeometryDirectly( poFaceGeom ); } else { // Using Union to add the current Polygon. OGRGeometry *poUnion = poTS->Union( poFaceGeom ); delete poFaceGeom; delete poTS; if( poUnion == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed Union for TopoSurface" ); return NULL; } if( wkbFlatten(poUnion->getGeometryType()) == wkbPolygon ) { // Forcing to be a MultiPolygon. poTS = new OGRMultiPolygon(); poTS->addGeometryDirectly(poUnion); } else if( wkbFlatten(poUnion->getGeometryType()) == wkbMultiPolygon ) { poTS = dynamic_cast<OGRMultiPolygon *>(poUnion); if( poTS == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRMultiPolygon."); } } else { CPLError( CE_Failure, CPLE_AppDefined, "Unexpected geometry type resulting " "from Union for TopoSurface" ); delete poUnion; return NULL; } } } delete poFaceCollectionGeom; delete poCollectedGeom; } } return poTS; #endif // HAVE_GEOS } /****************************************************************/ /* applying the FaceHoleNegative = true rules */ /* */ /* - each <TopoSurface> is expected to represent a MultiPolygon */ /* - any <Face> declaring orientation="+" is expected to */ /* represent an Exterior Ring (no holes are allowed) */ /* - any <Face> declaring orientation="-" is expected to */ /* represent an Interior Ring (hole) belonging to the latest */ /* Exterior Ring. */ /* - <Edges> within the same <Face> are expected to be */ /* arranged in geometrically adjacent and consecutive */ /* sequence. */ /****************************************************************/ if( bGetSecondaryGeometry ) return NULL; bool bFaceOrientation = true; OGRPolygon *poTS = new OGRPolygon(); // Collect directed faces. for( const CPLXMLNode *psChild = psNode->psChild; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "directedFace") ) { bFaceOrientation = GetElementOrientation(psChild); // Collect next face (psChild->psChild). const CPLXMLNode *psFaceChild = GetChildElement(psChild); while( psFaceChild != NULL && !EQUAL(BareGMLElement(psFaceChild->pszValue), "Face") ) psFaceChild = psFaceChild->psNext; if( psFaceChild == NULL ) continue; OGRLinearRing *poFaceGeom = new OGRLinearRing(); // Collect directed edges of the face. for( const CPLXMLNode *psDirectedEdgeChild = psFaceChild->psChild; psDirectedEdgeChild != NULL; psDirectedEdgeChild = psDirectedEdgeChild->psNext ) { if( psDirectedEdgeChild->eType == CXT_Element && EQUAL(BareGMLElement(psDirectedEdgeChild->pszValue), "directedEdge") ) { OGRGeometry *poEdgeGeom = GML2OGRGeometry_XMLNode_Internal( psDirectedEdgeChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName, true, bFaceOrientation ); if( poEdgeGeom == NULL || wkbFlatten(poEdgeGeom->getGeometryType()) != wkbLineString ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to get geometry in directedEdge" ); delete poEdgeGeom; delete poFaceGeom; delete poTS; return NULL; } OGRLineString *poEdgeGeomLS = dynamic_cast<OGRLineString *>(poEdgeGeom); if( poEdgeGeomLS == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRLineString."); delete poEdgeGeom; delete poFaceGeom; delete poTS; return NULL; } if( !bFaceOrientation ) { OGRLineString *poLS = poEdgeGeomLS; OGRLineString *poAddLS = poFaceGeom; // TODO(schwehr): Use AlmostEqual. const double epsilon = 1.0e-14; if( poAddLS->getNumPoints() < 2 ) { // Skip it. } else if( poLS->getNumPoints() > 0 && fabs(poLS->getX(poLS->getNumPoints() - 1) - poAddLS->getX(0)) < epsilon && fabs(poLS->getY(poLS->getNumPoints() - 1) - poAddLS->getY(0)) < epsilon && fabs(poLS->getZ(poLS->getNumPoints() - 1) - poAddLS->getZ(0)) < epsilon ) { // Skip the first point of the new linestring to avoid // invalidate duplicate points. poLS->addSubLineString( poAddLS, 1 ); } else { // Add the whole new line string. poLS->addSubLineString( poAddLS ); } poFaceGeom->empty(); } // TODO(schwehr): Suspicious that poLS overwritten without else. OGRLineString *poLS = poFaceGeom; OGRLineString *poAddLS = poEdgeGeomLS; if( poAddLS->getNumPoints() < 2 ) { // Skip it. } else if( poLS->getNumPoints() > 0 && fabs(poLS->getX(poLS->getNumPoints()-1) - poAddLS->getX(0)) < 1e-14 && fabs(poLS->getY(poLS->getNumPoints()-1) - poAddLS->getY(0)) < 1e-14 && fabs(poLS->getZ(poLS->getNumPoints()-1) - poAddLS->getZ(0)) < 1e-14) { // Skip the first point of the new linestring to avoid // invalidate duplicate points. poLS->addSubLineString( poAddLS, 1 ); } else { // Add the whole new line string. poLS->addSubLineString( poAddLS ); } delete poEdgeGeom; } } // if( poFaceGeom == NULL ) // { // CPLError( CE_Failure, CPLE_AppDefined, // "Failed to get Face geometry in directedFace" ); // delete poFaceGeom; // return NULL; // } poTS->addRingDirectly( poFaceGeom ); } } // if( poTS == NULL ) // { // CPLError( CE_Failure, CPLE_AppDefined, // "Failed to get TopoSurface geometry" ); // delete poTS; // return NULL; // } return poTS; } /* -------------------------------------------------------------------- */ /* Surface */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Surface") ) { // Find outer ring. const CPLXMLNode *psChild = FindBareXMLChild( psNode, "patches" ); if( psChild == NULL ) psChild = FindBareXMLChild( psNode, "polygonPatches" ); if( psChild == NULL ) psChild = FindBareXMLChild( psNode, "trianglePatches" ); psChild = GetChildElement(psChild); if( psChild == NULL ) { // <gml:Surface/> and <gml:Surface><gml:patches/></gml:Surface> are // valid GML. return new OGRPolygon(); } OGRMultiSurface* poMS = NULL; OGRGeometry* poResultPoly = NULL; OGRGeometry* poResultTri = NULL; OGRTriangulatedSurface *poTIN = NULL; OGRGeometryCollection *poGC = NULL; for( ; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && (EQUAL(BareGMLElement(psChild->pszValue), "PolygonPatch") || EQUAL(BareGMLElement(psChild->pszValue), "Rectangle"))) { OGRGeometry *poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { delete poResultPoly; return NULL; } const OGRwkbGeometryType eGeomType = wkbFlatten(poGeom->getGeometryType()); if( poResultPoly == NULL ) poResultPoly = poGeom; else { if( poMS == NULL ) { if( wkbFlatten(poResultPoly->getGeometryType()) == wkbPolygon && eGeomType == wkbPolygon ) poMS = new OGRMultiPolygon(); else poMS = new OGRMultiSurface(); #ifdef DEBUG OGRErr eErr = #endif poMS->addGeometryDirectly( poResultPoly ); CPLAssert(eErr == OGRERR_NONE); poResultPoly = poMS; } else if( eGeomType != wkbPolygon && wkbFlatten(poMS->getGeometryType()) == wkbMultiPolygon ) { OGRMultiPolygon *poMultiPoly = dynamic_cast<OGRMultiPolygon *>(poMS); if( poMultiPoly == NULL ) { CPLError(CE_Fatal, CPLE_AppDefined, "dynamic_cast failed. " "Expected OGRMultiPolygon."); } poMS = OGRMultiPolygon::CastToMultiSurface(poMultiPoly); poResultPoly = poMS; } #ifdef DEBUG OGRErr eErr = #endif poMS->addGeometryDirectly( poGeom ); CPLAssert(eErr == OGRERR_NONE); } } else if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "Triangle")) { OGRGeometry *poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { delete poResultTri; return NULL; } if( poResultTri == NULL ) poResultTri = poGeom; else { if( poTIN == NULL ) { poTIN = new OGRTriangulatedSurface(); #ifdef DEBUG OGRErr eErr = #endif poTIN->addGeometryDirectly( poResultTri ); CPLAssert(eErr == OGRERR_NONE); poResultTri = poTIN; } #ifdef DEBUG OGRErr eErr = #endif poTIN->addGeometryDirectly( poGeom ); CPLAssert(eErr == OGRERR_NONE); } } } if( poResultTri == NULL && poResultPoly == NULL ) return NULL; if( poResultTri == NULL ) return poResultPoly; else if( poResultPoly == NULL ) return poResultTri; else if( poResultTri != NULL && poResultPoly != NULL ) { poGC = new OGRGeometryCollection(); poGC->addGeometryDirectly(poResultTri); poGC->addGeometryDirectly(poResultPoly); return poGC; } } /* -------------------------------------------------------------------- */ /* TriangulatedSurface */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "TriangulatedSurface") || EQUAL(pszBaseGeometry, "Tin") ) { // Find trianglePatches. const CPLXMLNode *psChild = FindBareXMLChild( psNode, "trianglePatches" ); if( psChild == NULL ) psChild = FindBareXMLChild( psNode, "patches" ); psChild = GetChildElement(psChild); if( psChild == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing <trianglePatches> for %s.", pszBaseGeometry ); return NULL; } OGRTriangulatedSurface *poTIN = new OGRTriangulatedSurface(); for( ; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "Triangle") ) { OGRGeometry *poTriangle = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poTriangle == NULL ) { delete poTIN; return NULL; } else { poTIN->addGeometryDirectly( poTriangle ); } } } return poTIN; } /* -------------------------------------------------------------------- */ /* PolyhedralSurface */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "PolyhedralSurface") ) { // Find polygonPatches. const CPLXMLNode *psParent = FindBareXMLChild( psNode, "polygonPatches" ); if( psParent == NULL ) { if( GetChildElement(psNode) == NULL ) { // This is empty PolyhedralSurface. return new OGRPolyhedralSurface(); } else { CPLError( CE_Failure, CPLE_AppDefined, "Missing <polygonPatches> for %s.", pszBaseGeometry ); return NULL; } } const CPLXMLNode *psChild = GetChildElement(psParent); if( psChild == NULL ) { // This is empty PolyhedralSurface. return new OGRPolyhedralSurface(); } else if( psChild != NULL && !EQUAL(BareGMLElement(psChild->pszValue), "PolygonPatch") ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing <PolygonPatch> for %s.", pszBaseGeometry ); return NULL; } // Each psParent has the tags corresponding to <gml:polygonPatches> // Each psChild has the tags corresponding to <gml:PolygonPatch> // Each PolygonPatch has a set of polygons enclosed in a // OGRPolyhedralSurface. OGRPolyhedralSurface *poPS = NULL; OGRGeometryCollection *poGC = new OGRGeometryCollection(); OGRGeometry *poResult = NULL; for( ; psParent != NULL; psParent = psParent->psNext ) { poPS = new OGRPolyhedralSurface(); for( ; psChild != NULL; psChild = psChild->psNext ) { if( psChild->eType == CXT_Element && EQUAL(BareGMLElement(psChild->pszValue), "PolygonPatch") ) { OGRGeometry *poPolygon = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poPolygon == NULL ) { delete poPS; delete poGC; CPLError( CE_Failure, CPLE_AppDefined, "Wrong geometry type for %s.", pszBaseGeometry ); return NULL; } else if( wkbFlatten(poPolygon->getGeometryType()) == wkbPolygon ) { poPS->addGeometryDirectly( poPolygon ); } else { delete poPS; delete poGC; CPLError( CE_Failure, CPLE_AppDefined, "Wrong geometry type for %s.", pszBaseGeometry ); return NULL; } } } poGC->addGeometryDirectly(poPS); } if( poGC->getNumGeometries() == 0 ) { delete poGC; return NULL; } else if( poPS != NULL && poGC->getNumGeometries() == 1 ) { poResult = poPS->clone(); delete poGC; return poResult; } else { poResult = poGC; return poResult; } } /* -------------------------------------------------------------------- */ /* Solid */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "Solid") ) { // Find exterior element. const CPLXMLNode *psChild = FindBareXMLChild( psNode, "exterior"); psChild = GetChildElement(psChild); if( psChild == NULL ) { // <gml:Solid/> and <gml:Solid><gml:exterior/></gml:Solid> are valid // GML. return new OGRPolygon(); } // Get the geometry inside <exterior>. OGRGeometry* poGeom = GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); if( poGeom == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid exterior element"); delete poGeom; return NULL; } psChild = FindBareXMLChild( psNode, "interior"); if( psChild != NULL ) { static bool bWarnedOnce = false; if( !bWarnedOnce ) { CPLError( CE_Warning, CPLE_AppDefined, "<interior> elements of <Solid> are ignored"); bWarnedOnce = true; } } return poGeom; } /* -------------------------------------------------------------------- */ /* OrientableSurface */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "OrientableSurface") ) { // Find baseSurface. const CPLXMLNode *psChild = FindBareXMLChild( psNode, "baseSurface" ); psChild = GetChildElement(psChild); if( psChild == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing <baseSurface> for OrientableSurface." ); return NULL; } return GML2OGRGeometry_XMLNode_Internal( psChild, nPseudoBoolGetSecondaryGeometryOption, nRecLevel + 1, nSRSDimension, pszSRSName ); } /* -------------------------------------------------------------------- */ /* SimplePolygon, SimpleRectangle, SimpleTriangle */ /* (GML 3.3 compact encoding) */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "SimplePolygon") || EQUAL(pszBaseGeometry, "SimpleRectangle") ) { OGRLinearRing *poRing = new OGRLinearRing(); if( !ParseGMLCoordinates( psNode, poRing, nSRSDimension ) ) { delete poRing; return NULL; } poRing->closeRings(); OGRPolygon* poPolygon = new OGRPolygon(); poPolygon->addRingDirectly(poRing); return poPolygon; } if( EQUAL(pszBaseGeometry, "SimpleTriangle") ) { OGRLinearRing *poRing = new OGRLinearRing(); if( !ParseGMLCoordinates( psNode, poRing, nSRSDimension ) ) { delete poRing; return NULL; } poRing->closeRings(); OGRTriangle* poTriangle = new OGRTriangle(); poTriangle->addRingDirectly(poRing); return poTriangle; } /* -------------------------------------------------------------------- */ /* SimpleMultiPoint (GML 3.3 compact encoding) */ /* -------------------------------------------------------------------- */ if( EQUAL(pszBaseGeometry, "SimpleMultiPoint") ) { OGRLineString *poLS = new OGRLineString(); if( !ParseGMLCoordinates( psNode, poLS, nSRSDimension ) ) { delete poLS; return NULL; } OGRMultiPoint* poMP = new OGRMultiPoint(); int nPoints = poLS->getNumPoints(); for( int i = 0; i < nPoints; i++ ) { OGRPoint* poPoint = new OGRPoint(); poLS->getPoint(i, poPoint); poMP->addGeometryDirectly(poPoint); } delete poLS; return poMP; } CPLError( CE_Failure, CPLE_AppDefined, "Unrecognized geometry type <%.500s>.", pszBaseGeometry ); return NULL; } /************************************************************************/ /* OGR_G_CreateFromGMLTree() */ /************************************************************************/ /** Create geometry from GML */ OGRGeometryH OGR_G_CreateFromGMLTree( const CPLXMLNode *psTree ) { return reinterpret_cast<OGRGeometryH>(GML2OGRGeometry_XMLNode(psTree, -1)); } /************************************************************************/ /* OGR_G_CreateFromGML() */ /************************************************************************/ /** * \brief Create geometry from GML. * * This method translates a fragment of GML containing only the geometry * portion into a corresponding OGRGeometry. There are many limitations * on the forms of GML geometries supported by this parser, but they are * too numerous to list here. * * The following GML2 elements are parsed : Point, LineString, Polygon, * MultiPoint, MultiLineString, MultiPolygon, MultiGeometry. * * (OGR >= 1.8.0) The following GML3 elements are parsed : Surface, * MultiSurface, PolygonPatch, Triangle, Rectangle, Curve, MultiCurve, * CompositeCurve, LineStringSegment, Arc, Circle, CompositeSurface, * OrientableSurface, Solid, Tin, TriangulatedSurface. * * Arc and Circle elements are stroked to linestring, by using a * 4 degrees step, unless the user has overridden the value with the * OGR_ARC_STEPSIZE configuration variable. * * The C++ method OGRGeometryFactory::createFromGML() is the same as * this function. * * @param pszGML The GML fragment for the geometry. * * @return a geometry on success, or NULL on error. */ OGRGeometryH OGR_G_CreateFromGML( const char *pszGML ) { if( pszGML == NULL || strlen(pszGML) == 0 ) { CPLError( CE_Failure, CPLE_AppDefined, "GML Geometry is empty in OGR_G_CreateFromGML()." ); return NULL; } /* -------------------------------------------------------------------- */ /* Try to parse the XML snippet using the MiniXML API. If this */ /* fails, we assume the minixml api has already posted a CPL */ /* error, and just return NULL. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psGML = CPLParseXMLString( pszGML ); if( psGML == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Convert geometry recursively. */ /* -------------------------------------------------------------------- */ // Must be in synced in OGR_G_CreateFromGML(), OGRGMLLayer::OGRGMLLayer() // and GMLReader::GMLReader(). const bool bFaceHoleNegative = CPLTestBool(CPLGetConfigOption("GML_FACE_HOLE_NEGATIVE", "NO")); OGRGeometry *poGeometry = GML2OGRGeometry_XMLNode( psGML, -1, 0, 0, false, true, bFaceHoleNegative ); CPLDestroyXMLNode( psGML ); return reinterpret_cast<OGRGeometryH>(poGeometry); }
; A291582: Maximum number of 6 sphinx tile shapes in a sphinx tiled hexagon of order n. ; 30,132,306,552,870,1260,1722,2256,2862,3540,4290,5112,6006,6972,8010,9120,10302,11556,12882,14280,15750,17292,18906,20592,22350,24180,26082,28056,30102,32220,34410,36672,39006,41412,43890,46440,49062,51756,54522,57360,60270,63252,66306,69432,72630,75900,79242,82656,86142,89700,93330,97032,100806,104652,108570,112560,116622,120756,124962,129240,133590,138012,142506,147072,151710,156420,161202,166056,170982,175980,181050,186192,191406,196692,202050,207480,212982,218556,224202,229920,235710,241572,247506,253512,259590,265740,271962,278256,284622,291060,297570,304152,310806,317532,324330,331200,338142,345156,352242,359400 add $0,1 mul $0,6 bin $0,2 mul $0,2
; void b_vector_empty_fastcall(b_vector_t *v) SECTION code_clib SECTION code_adt_b_vector PUBLIC _b_vector_empty_fastcall EXTERN _b_array_empty_fastcall defc _b_vector_empty_fastcall = _b_array_empty_fastcall
#ifndef OCCA_PARSER_MAGIC_HEADER #define OCCA_PARSER_MAGIC_HEADER #include "occaParser.hpp" namespace occa { namespace parserNS { class parserBase; class viInfo_t; class infoDB_t; typedef std::map<statement*, int> smntInfoMap_t; typedef smntInfoMap_t::iterator smntInfoIterator; typedef std::map<varInfo*, viInfo_t*> viInfoMap_t_; typedef viInfoMap_t_::iterator viInfoIterator; namespace viType { static const int isUseless = (1 << 0); static const int isAVariable = (1 << 1); static const int isAnIterator = (1 << 2); static const int isConstant = (1 << 3); static const int isComplex = (1 << 4); std::string infoToStr(const int info); }; namespace analyzeInfo { // Statement Info static const int isExecuted = (1 << 0); static const int isIgnored = (1 << 1); static const int schrodinger = (isExecuted | isIgnored); // hehe static const int hasLCD = (1 << 2); // Return Info static const int didntChange = 0; static const int changed = 1; // Bounds Info static const int LB = 0; static const int UB = 1; static const int S = 2; }; class atomInfo_t { public: infoDB_t *db; int info; typeHolder constValue; expNode *exp; varInfo *var; atomInfo_t(infoDB_t *db_ = NULL); atomInfo_t(const atomInfo_t &ai); atomInfo_t& operator = (const atomInfo_t &ai); bool operator == (const std::string &str); bool operator == (expNode &e); bool operator == (atomInfo_t &ai); bool operator != (atomInfo_t &ai); void setDB(infoDB_t *db_); void load(expNode &e); void load(varInfo &var_); void load(const std::string &s); bool expandValue(); bool expandValue(expNode &e); bool expandValue(expNode *&expRoot, varInfo &v); void saveTo(expNode &e, const int leafPos = 0); bool isComplex(); std::string getInfoStr(); friend std::ostream& operator << (std::ostream &out, atomInfo_t &info); }; class valueInfo_t { public: infoDB_t *db; int info; int indices; atomInfo_t value; atomInfo_t *vars, *strides; valueInfo_t(infoDB_t *db_ = NULL); valueInfo_t(expNode &e, infoDB_t *db_ = NULL); valueInfo_t(const valueInfo_t &vi); valueInfo_t& operator = (const valueInfo_t &vi); bool operator == (valueInfo_t &vi); bool operator != (valueInfo_t &vi); void setDB(infoDB_t *db_); void allocVS(const int count); bool isConstant(); typeHolder constValue(); bool isUseless(); bool isComplex(); void load(expNode &e); void load(varInfo &var); void load(const std::string &s); void loadVS(expNode &e, const int pos); int iteratorsIn(expNode &e); bool hasAnIterator(expNode &e); bool isAnIteratorExp(expNode &e); int iteratorExpsIn(expNode &e); bool hasAnIteratorExp(expNode &e); bool expandValues(); void reEvaluateStrides(); void sortIndices(); static int qSortIndices(const void *a, const void *b); void mergeIndices(); void saveTo(expNode &e, const int leafPos = 0); void saveIndexTo(const int index, expNode &e, const int leafPos = 0); void update(expNode &op, expNode &e); int hasStride(expNode &e); int hasStride(const std::string &str); int hasStride(atomInfo_t &stride); bool hasComplexStride(); bool stridesConflict(); // Assumption that (this and v) are not complex // nor have conflicting strides bool conflictsWith(valueInfo_t &v); void setBoundInfo(typeHolder *&bounds, bool *&hasBounds); void insertOp(const std::string &op, expNode &value); void insertOp(const std::string &op, const std::string &value); varInfo& varValue(); varInfo& var(const int pos); atomInfo_t& stride(const int pos); friend std::ostream& operator << (std::ostream &out, valueInfo_t &info); }; class accessInfo_t { public: infoDB_t *db; statement *s; int dim; valueInfo_t value; valueInfo_t *dimIndices; accessInfo_t(infoDB_t *db_ = NULL); accessInfo_t(const accessInfo_t &ai); accessInfo_t& operator = (const accessInfo_t &ai); void setDB(infoDB_t *db_); void load(expNode &varNode); void load(const int brackets, expNode &bracketNode); bool hasComplexAccess(); bool stridesConflict(); bool conflictsWith(accessInfo_t &ai); friend std::ostream& operator << (std::ostream &out, accessInfo_t &info); }; class iteratorInfo_t { public: infoDB_t *db; statement *s; valueInfo_t start, end, stride; iteratorInfo_t(infoDB_t *db_ = NULL); bool operator == (iteratorInfo_t &iter); bool operator != (iteratorInfo_t &iter); void setDB(infoDB_t *db_); friend std::ostream& operator << (std::ostream &out, iteratorInfo_t &info); }; class viInfo_t { public: infoDB_t *db; varInfo *var; int info; valueInfo_t valueInfo; iteratorInfo_t iteratorInfo; std::vector<accessInfo_t> reads, writes; std::vector<bool> writeSetsValue; static const int writeValue = (1 << 0); static const int readValue = (1 << 1); viInfo_t(infoDB_t *db_ = NULL, varInfo *var_ = NULL); void setDB(infoDB_t *db_); bool hasBeenInitialized(); void addWrite(const bool isUpdated, expNode &varNode); void addWrite(const bool isUpdated, const int brackets, expNode &bracketNode); void addRead(expNode &varNode); void addRead(const int brackets, expNode &bracketNode); void updateValue(expNode &opNode, expNode &setNode); void statementHasLCD(statement *sEnd); void sharedStatementHaveLCD(statement *a, statement *b); statement* lastSetStatement(); void checkComplexity(); void checkLastInput(accessInfo_t &ai, const int inputType); friend std::ostream& operator << (std::ostream &out, viInfo_t &info); }; class viInfoMap_t { public: infoDB_t *db; viInfoMap_t_ viMap; viInfo_t *anonVar; // Stores non-restrict variables viInfoMap_t(infoDB_t *db_); void setDB(infoDB_t *db_); void free(); void add(varInfo &var); viInfo_t* has(varInfo &var); viInfo_t& operator [] (varInfo &var); }; class infoDB_t { public: bool locked; viInfoMap_t viInfoMap; smntInfoMap_t smntInfoMap; std::stack<int> smntInfoStack; infoDB_t(); void lock(); void unlock(); bool isLocked(); int& getSmntInfo(); void add(varInfo &var); viInfo_t* has(varInfo &var); void enteringStatement(statement &s); void leavingStatement(); viInfo_t& operator [] (varInfo &var); bool varIsAnIterator(varInfo &var); void statementsHaveLCD(statement *s); bool statementHasLCD(statement &s); }; class magician { public: parserBase &parser; statement &globalScope; varUsedMap_t &varUpdateMap; varUsedMap_t &varUsedMap; intVector_t testedTileSizes; infoDB_t db; magician(parserBase &parser_); viInfoMap_t* currentViInfoMap(); void pushMapStack(); void popMapStack(); static void castMagicOn(parserBase &parser_); void castMagic(); statementNode* analyzeFunction(statement &fs); void analyzeStatement(statement &s); void analyzeEmbeddedStatements(statement &s); void analyzeDeclareStatement(expNode &e); void analyzeDeclareExpression(expNode &e, const int pos); void analyzeUpdateStatement(expNode &e); void analyzeUpdateExpression(expNode &e, const int pos); void analyzeForStatement(statement &s); void analyzeFortranForStatement(statement &s); void analyzeWhileStatement(statement &s); void analyzeIfStatement(statementNode *snStart, statementNode *snEnd); void analyzeSwitchStatement(statement &s); bool statementGuaranteesBreak(statement &s); statementNode* generatePossibleKernels(statement &kernel); void storeInnerLoopCandidates(statementVector_t &loopsVec, intVector_t &depthVec, int outerLoopIdx, int innerLoopIdx, intVector_t &innerLoopVec); void storeNextDepthLoops(statementVector_t &loopsVec, intVector_t &depthVec, int loopIdx, intVector_t &ndLoopsVec); bool nestedLoopHasSameBounds(statementVector_t &loopsVec, intVector_t &depthVec, int ndLoopIdx, iteratorInfo_t &iteratorInfo, intVector_t &innerLoopVec, const bool isFirstCall = true); statementNode* generateKernelsAndLabelLoops(statementVector_t &loopsVec, intVector_t &depthVec, intVector_t &outerLoopVec, intVecVector_t &innerLoopVec); void storeLoopsAndDepths(statement &s, statementVector_t &loopsVec, intVector_t &depthVec, int depth); iteratorInfo_t iteratorLoopBounds(statement &s); void updateLoopBounds(statement &s); void printIfLoopsHaveLCD(statement &s); void addVariableWrite(expNode &varNode, expNode &opNode, expNode &setNode); void addVariableWrite(expNode &varNode, expNode &opNode, expNode &setNode, const int brackets, expNode &bracketNode); void addVariableRead(expNode &varNode); void addVariableRead(expNode &varNode, const int brackets, expNode &bracketNode); void addExpressionRead(expNode &e); //---[ Helper Functions ]--------- static void placeAddedExps(infoDB_t &db, expNode &e, expVec_t &sumNodes); static void placeMultExps(infoDB_t &db, expNode &e, expVec_t &sumNodes); static void placeExps(infoDB_t &db, expNode &e, expVec_t &sumNodes, const std::string &delimiters); static bool expHasOp(expNode &e, const std::string &delimiters); static void simplify(infoDB_t &db, expNode &e); static void removePermutations(infoDB_t &db, expNode &e); static void turnMinusIntoNegatives(infoDB_t &db, expNode &e); static void mergeConstants(infoDB_t &db, expNode &e); static void mergeConstantsIn(infoDB_t &db, expNode &e); static void applyConstantsIn(infoDB_t &db, expNode &e); static void mergeVariables(infoDB_t &db, expNode &e); static void expandExp(infoDB_t &db, expNode &e); static void expandMult(infoDB_t &db, expNode &e); static void removeParentheses(infoDB_t &db, expNode &e); static expVec_t iteratorsIn(infoDB_t &db, expVec_t &v); static bool iteratorsMatch(expVec_t &a, expVec_t &b); static expVec_t removeItersFromExpVec(expVec_t &a, expVec_t &b); static void multiplyExpVec(expVec_t &v, expNode &e); static void sumExpVec(expVec_t &v, expNode &e); static void applyOpToExpVec(expVec_t &v, expNode &e, const std::string &op); }; }; }; #endif
/* MIT License Copyright (c) 2021 Attila Kiss 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 (CONFIG.INC) NAME BIT_VARIABLES $IF (ASSEMBLE_VARIABLES = 1) $IF (ASSEMBLE_BIT_VARIABLES = 1) ;VARIABLES FOR BIT MEMORY SPACE. SAME SPACE AS BITADDRESSABLE BIT_SEG SEGMENT BIT RSEG BIT_SEG PUBLIC B_VAR PUBLIC B_T0_OVF_SEC_EXTEND_BIT B_VAR: DBIT 1 B_T0_OVF_SEC_EXTEND_BIT: DBIT 1 $ENDIF $ENDIF END
#include "geometry/GeometryIO.h" #include "geometry/GeometryObject.h" #include "quickhull/QuickHull.hpp" #include <fstream> #include <set> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> namespace fast { FAST_EXPORT TriangleMesh loadParticleMesh(const std::string & path) { using Edge = TriangleMesh::Edge; using Face = TriangleMesh::Face; TriangleMesh m; std::ifstream f(path); if (!f.good()) throw "loadParticleMesh invalid file"; int nv, nf; f >> nv; if (nv <= 0) throw "loadParticleMesh invalid number of vertices"; m.vertices.resize(nv); for (auto i = 0; i < nv; i++) { f >> m.vertices[i].x >> m.vertices[i].y >> m.vertices[i].z; } f >> nf; if (nf <= 0) throw "loadParticleMesh invalid number of faces"; m.faces.resize(nf); auto cmpEdge = [](const Edge & a, const Edge & b) { Edge as = a; if (as.x > as.y) std::swap(as.x, as.y); Edge bs = b; if (bs.x > bs.y) std::swap(bs.x, bs.y); if (as.x < bs.x) return true; if (as.x > bs.x) return false; return (as.y < bs.y); }; std::set<Edge, decltype(cmpEdge)> edgeSet(cmpEdge); for (auto i = 0; i < nf; i++) { Face & face = m.faces[i]; //Read number of vertices in this face int nfv; f >> nfv; assert(nfv >= 3); //Load vertex indices face.vertices.resize(nfv); for (auto k = 0; k < nfv; k++) { f >> face.vertices[k]; } //Save edges for (auto k = 0; k < nfv; k++) { Edge e = { face.vertices[k], face.vertices[(k + 1) % nfv] }; edgeSet.insert(e); } } m.edges.resize(edgeSet.size()); std::copy(edgeSet.begin(), edgeSet.end(), m.edges.begin()); m.recomputeNormals(); return m; } TriangleMesh halfEdgeMeshToTriangleMesh(const quickhull::HalfEdgeMesh<float, size_t> & hemesh) { using namespace quickhull; TriangleMesh tm; tm.vertices.resize(hemesh.m_vertices.size()); std::memcpy(tm.vertices.data(), hemesh.m_vertices.data(), hemesh.m_vertices.size() * sizeof(vec3)); auto cmpEdge = [](const TriangleMesh::Edge & a, const TriangleMesh::Edge & b) { TriangleMesh::Edge as = a; if (as.x > as.y) std::swap(as.x, as.y); TriangleMesh::Edge bs = b; if (bs.x > bs.y) std::swap(bs.x, bs.y); if (as.x < bs.x) return true; if (as.x > bs.x) return false; return (as.y < bs.y); }; std::set<TriangleMesh::Edge, decltype(cmpEdge)> edgeSet(cmpEdge); for(auto i=0; i < hemesh.m_faces.size(); i++){ auto heIndexStart = hemesh.m_faces[i].m_halfEdgeIndex; auto he = hemesh.m_halfEdges[heIndexStart]; auto heIndexNext = he.m_next; TriangleMesh::Face newF; newF.vertices.push_back(int(he.m_endVertex)); while (heIndexNext != heIndexStart) { he = hemesh.m_halfEdges[heIndexNext]; newF.vertices.push_back(int(he.m_endVertex)); heIndexNext = he.m_next; } tm.faces.push_back(newF); for (auto k = 0; k < newF.vertices.size(); k++) { TriangleMesh::Edge e = { newF.vertices[k], newF.vertices[(k + 1) % newF.vertices.size()] }; edgeSet.insert(e); } } tm.edges.resize(edgeSet.size()); std::copy(edgeSet.begin(), edgeSet.end(), tm.edges.begin()); tm.recomputeNormals(); return tm; } TriangleMesh hullCoordsToMesh(const std::vector<vec3> & pts) { using namespace quickhull; QuickHull<float> qh; HalfEdgeMesh<float, size_t> hullMesh = qh.getConvexHullAsMesh( reinterpret_cast<const float*>(pts.data()), pts.size(), false ); return halfEdgeMeshToTriangleMesh(hullMesh); } FAST_EXPORT std::vector<std::shared_ptr<GeometryObject>> readPosFile( std::ifstream & stream, size_t index, AABB trim ) { std::vector<std::shared_ptr<GeometryObject>> res; #define CMP_MATCH 0 enum ShapeType { SHAPE_SPHERE, SHAPE_POLY }; const std::string boxS = "boxMatrix"; const std::string defS = "def"; const std::string eofS = "eof"; std::string defName = ""; char line[4096]; ShapeType shapeType; AABB bb; vec3 scale; vec3 trimRange = trim.range(); std::vector<vec3> coords; std::shared_ptr<Geometry> templateParticle; size_t curCount = 0; //Seek to index while (stream.good()) { size_t pos = stream.tellg(); stream.getline(line, 4096); if (boxS.compare(0, boxS.length(), line, 0, boxS.length()) == CMP_MATCH) { if (curCount == index) { std::stringstream ss; ss << (line + boxS.length()); bb.min = vec3(0); vec3 v[3]; ss >> v[0].x >> v[0].y >> v[0].z; ss >> v[1].x >> v[1].y >> v[1].z; ss >> v[2].x >> v[2].y >> v[2].z; bb.max = vec3(v[0].x, v[1].y, v[2].z); scale = vec3(1.0f / bb.range().x, 1.0f / bb.range().y, 1.0f / bb.range().z); std::cout << line << std::endl; std::cout << bb.max.x << ", " << bb.max.y << ", " << bb.max.z << std::endl; break; } curCount++; } } while (stream.good()) { size_t pos = stream.tellg(); stream.getline(line, 4096); //auto s = std::string(line); /*if (boxS.compare(0, boxS.length(), line, 0, boxS.length()) == CMP_MATCH) { }*/ if (eofS.compare(0, eofS.length(), line, 0, eofS.length()) == CMP_MATCH) { break; } if (defS.compare(0, defS.length(), line, 0, defS.length()) == CMP_MATCH) { std::stringstream ss; ss << (line + defS.length() + 1); getline(ss, defName, ' '); std::string tmp; getline(ss, tmp, '"'); getline(ss, tmp, ' '); if (tmp == "poly3d") shapeType = SHAPE_POLY; else shapeType = SHAPE_SPHERE; int n; ss >> n; coords.resize(n); for (int i = 0; i < n; i++) { ss >> coords[i].x >> coords[i].y >> coords[i].z; } Transform t; t.scale = scale; templateParticle = std::move(hullCoordsToMesh(coords).transformed(t)); } //Instances if (defName.length() > 0 && defName.compare(0, defName.length(), line, 0, defName.length()) == CMP_MATCH) { std::stringstream ss; ss << (line + defName.length() + 1); if (shapeType == SHAPE_POLY) { int tmp; ss >> tmp; Transform t; vec3 pos; ss >> pos.x >> pos.y >> pos.z; ss >> t.rotation[0] >> t.rotation[1] >> t.rotation[2] >> t.rotation[3]; t.translation = pos * scale + vec3(0.5f); auto instance = std::make_shared<GeometryObject>(templateParticle); instance->setTransform(t); if (trim.testIntersection(instance->bounds())) { vec3 trimScale = vec3(1.0 / trimRange.x, 1.0 / trimRange.y, 1.0 / trimRange.z); t.translation = pos * scale * trimScale + trimScale * vec3(0.5f); t.scale = trimScale; instance->setTransform(t); res.push_back(instance); } } } } return res; } FAST_EXPORT size_t getPosFileCount(std::ifstream & stream) { size_t count = 0; size_t pos = stream.tellg(); const std::string boxS = "boxMatrix"; char line[4096]; while (stream.good()) { stream.getline(line, 4096); if (boxS.compare(0, boxS.length(), line, 0, boxS.length()) == CMP_MATCH) { count++; } } //Reset stream to where it was stream.clear(); stream.seekg(pos); return count; } }
; A204439: Symmetric matrix: f(i,j)=((i+j+2)^2 mod 3), by (constant) antidiagonals. ; 1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 add $0,1 lpb $0 add $0,1 mov $1,1 add $2,2 sub $0,$2 trn $0,$2 trn $1,$0 add $2,1 trn $0,$2 lpe
; A162214: a(n) = the largest positive multiple of n with exactly n digits when written in binary. ; 1,2,6,12,30,60,126,248,504,1020,2046,4092,8190,16380,32760,65520,131070,262134,524286,1048560,2097144,4194300,8388606,16777200,33554425,67108860,134217702,268435440,536870910,1073741820,2147483646,4294967264,8589934584,17179869180,34359738350,68719476708,137438953470,274877906940,549755813880,1099511627760,2199023255550,4398046511082,8796093022206,17592186044400,35184372088815,70368744177660,140737488355326,281474976710640,562949953421282,1125899906842600,2251799813685240,4503599627370480,9007199254740990 add $0,1 mov $1,$0 mov $2,2 pow $2,$0 sub $2,1 div $2,$0 mul $1,$2 add $1,3 lpb $0 mov $0,0 add $1,4 lpe sub $1,7
; A093141: Expansion of (1-6x)/(1-10x). ; 1,4,40,400,4000,40000,400000,4000000,40000000,400000000,4000000000,40000000000,400000000000,4000000000000,40000000000000,400000000000000,4000000000000000,40000000000000000,400000000000000000 mov $1,10 pow $1,$0 mul $1,2 sub $1,1 div $1,5 add $1,1 mov $0,$1
; A178305: a(0)=1, a(1)=a(2)=1 and a(3k)=a(k), a(3k+1) = a(3k+2) = 2a(k) for k >= 1. ; 0,1,1,1,2,2,1,2,2,1,2,2,2,4,4,2,4,4,1,2,2,2,4,4,2,4,4,1,2,2,2,4,4,2,4,4,2,4,4,4,8,8,4,8,8,2,4,4,4,8,8,4,8,8,1,2,2,2,4,4,2,4,4,2,4,4,4,8,8,4,8,8,2,4,4,4,8,8,4,8,8,1,2,2,2,4,4,2,4,4,2,4,4,4,8,8,4,8,8,2,4,4,4,8,8 mov $1,2 cal $0,160384 ; Number of nonzero digits in the base-3 representation of n. pow $1,$0 div $1,2
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r15 push %r8 push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x5293, %rsi lea addresses_A_ht+0x4e93, %rdi nop nop nop nop nop and %r15, %r15 mov $58, %rcx rep movsq nop and %r14, %r14 lea addresses_WT_ht+0x12093, %r15 sub %r14, %r14 movl $0x61626364, (%r15) nop nop and $52086, %rdi lea addresses_A_ht+0x1d893, %rcx nop and $26936, %rdx movl $0x61626364, (%rcx) sub $14087, %rdi lea addresses_normal_ht+0xc493, %rsi lea addresses_UC_ht+0x10893, %rdi cmp $7463, %r15 mov $93, %rcx rep movsb nop nop nop xor %rcx, %rcx lea addresses_WC_ht+0xe293, %rsi clflush (%rsi) nop nop nop nop cmp $59211, %r10 vmovups (%rsi), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %rcx nop nop nop nop nop inc %r15 lea addresses_WC_ht+0x19793, %rsi lea addresses_WT_ht+0x1a4f3, %rdi nop nop nop nop cmp %rdx, %rdx mov $107, %rcx rep movsq nop nop nop nop nop add $17779, %r14 lea addresses_D_ht+0xf093, %rsi lea addresses_D_ht+0xa093, %rdi nop sub %r8, %r8 mov $76, %rcx rep movsb nop nop nop nop nop cmp $4317, %r15 lea addresses_UC_ht+0xaf53, %rdx nop nop nop nop cmp %r8, %r8 movb $0x61, (%rdx) cmp %rsi, %rsi lea addresses_UC_ht+0x6567, %rsi lea addresses_WC_ht+0x17933, %rdi clflush (%rdi) sub $49935, %r14 mov $113, %rcx rep movsq nop nop nop nop nop inc %rcx lea addresses_UC_ht+0x4809, %r14 nop nop nop nop cmp %rcx, %rcx mov $0x6162636465666768, %r15 movq %r15, %xmm7 vmovups %ymm7, (%r14) sub %rdx, %rdx lea addresses_A_ht+0x8293, %rsi lea addresses_A_ht+0x14b17, %rdi clflush (%rsi) nop nop add $60168, %r8 mov $57, %rcx rep movsq nop dec %rcx lea addresses_A_ht+0x7893, %rsi lea addresses_D_ht+0x1a813, %rdi nop nop nop dec %r8 mov $109, %rcx rep movsl nop nop nop nop nop sub $53960, %r15 lea addresses_A_ht+0xc413, %r8 nop nop dec %rcx movups (%r8), %xmm7 vpextrq $0, %xmm7, %r14 nop sub %r15, %r15 pop %rsi pop %rdx pop %rdi pop %rcx pop %r8 pop %r15 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %rbp push %rcx push %rdi push %rsi // REPMOV lea addresses_WC+0x9753, %rsi lea addresses_US+0x10893, %rdi nop nop dec %rbp mov $33, %rcx rep movsb add $52366, %rcx // Store lea addresses_UC+0x18b, %r14 nop dec %r10 movb $0x51, (%r14) sub %rcx, %rcx // Store lea addresses_US+0x1da53, %r14 nop nop nop inc %rdi mov $0x5152535455565758, %r15 movq %r15, %xmm0 vmovups %ymm0, (%r14) nop nop nop nop nop xor $58993, %rcx // Store mov $0x4a7ef80000000d0f, %r14 nop nop and %r15, %r15 movb $0x51, (%r14) nop nop nop cmp %r15, %r15 // Faulty Load lea addresses_US+0x10893, %rdi nop nop nop nop cmp $65066, %rbp movups (%rdi), %xmm5 vpextrq $1, %xmm5, %rcx lea oracles, %rdi and $0xff, %rcx shlq $12, %rcx mov (%rdi,%rcx,1), %rcx pop %rsi pop %rdi pop %rcx pop %rbp pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_US', 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': True, 'congruent': 3, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 1, 'size': 1, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 11, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 8, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 7, 'size': 16, 'same': False, 'NT': False}} {'00': 1} 00 */
[bits 16] vpcomltb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 00 vpcomleb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 01 vpcomgtb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 02 vpcomgeb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 03 vpcomeqb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 04 vpcomneqb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 05 vpcomneb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 05 vpcomfalseb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 06 vpcomtrueb xmm1, xmm2, xmm3 ; out: 8F E8 68 CC 313 07 vpcomltuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 00 vpcomleuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 01 vpcomgtuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 02 vpcomgeuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 03 vpcomequw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 04 vpcomnequw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 05 vpcomneuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 05 vpcomfalseuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 06 vpcomtrueuw xmm1, xmm2, xmm3 ; out: 8F E8 68 ED 313 07
; char *gets_unlocked_fastcall(char *s) SECTION code_stdio PUBLIC _gets_unlocked_fastcall EXTERN asm_gets_unlocked _gets_unlocked_fastcall: push ix call asm_gets_unlocked pop ix ret
Route21Mons: db $19 db 21,RATTATA db 23,PIDGEY db 30,RATICATE db 23,RATTATA db 21,PIDGEY db 30,PIDGEOTTO db 32,PIDGEOTTO db 28,MR_MIME db 30,MR_MIME db 32,MR_MIME db $05 db 15,TENTACOOL db 10,TENTACOOL db 15,TENTACOOL db 10,TENTACOOL db 15,TENTACOOL db 20,TENTACOOL db 25,TENTACOOL db 30,TENTACRUEL db 35,TENTACRUEL db 40,TENTACRUEL
#include <iostream> #include <string> #include <pcl/common/common_headers.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/features/normal_3d.h> #include <pcl/features/pfh.h> #include <pcl/features/fpfh.h> #include <pcl/visualization/pcl_plotter.h> #include <pcl/visualization/histogram_visualizer.h> /*---------------------read from txt file--------------------*/ void createCloudFromTxt(const std::string file_path, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { //std::ifstream file(file_path.c_str()); std::cout<<"current file path is: "<<file_path<<std::endl; std::ifstream file(file_path); std::string line; pcl::PointXYZ point; while(getline(file,line)){ //std::cout<<"current line is: "<<line<<std::endl; std::stringstream ss(line); std::string x; std::getline(ss, x, ','); point.x = std::stof(x); std::string y; std::getline(ss, y, ','); point.y = std::stof(y); std::string z; std::getline(ss, z, ','); point.z = std::stof(z); //std::cout<<"current point is: "<<point.x<<" "<<point.y<<" "<<point.z<<std::endl; cloud->push_back(point); } file.close(); } /*-----------------------pcl visualization-------------------*/ void visualCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { pcl::visualization::CloudViewer viewer ("simple cloud viewer"); viewer.showCloud(cloud); while(!viewer.wasStopped()) { } } void visualCloudNormals(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, pcl::PointCloud<pcl::Normal>::Ptr normals) { pcl::visualization::PCLVisualizer viewer ("cloud and normal estimation viewer"); viewer.setBackgroundColor(0.0,0.0,0.0); viewer.addPointCloudNormals<pcl::PointXYZ,pcl::Normal>(cloud,normals); while (!viewer.wasStopped()) { viewer.spinOnce(); } } int main(int argc, char **argv) { std::cout << "Test PCL reading and visualization" << std::endl; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); createCloudFromTxt("/home/swarm/developments/point_cloud/modelnet40_normal_resampled/airplane/airplane_0001.txt",cloud); pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne; PCL_INFO ("Normal Estimation - Source\n"); ne.setInputCloud (cloud); //create an empty kdtree representation pcl::search::KdTree<pcl::PointXYZ>::Ptr tree_src(new pcl::search::KdTree<pcl::PointXYZ> ()); //ne.setSearchSurface (cloud_src); ne.setSearchMethod (tree_src); ne.setRadiusSearch (0.05); ne.compute (*normals); // Create the FPFH estimation class, and pass the input dataset+normals to it pcl::FPFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fpfh; fpfh.setInputCloud (cloud); fpfh.setInputNormals (normals); // alternatively, if cloud is of tpe PointNormal, do fpfh.setInputNormals (cloud); // Create an empty kdtree representation, and pass it to the FPFH estimation object. // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given). pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); fpfh.setSearchMethod (tree); // Output datasets pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs (new pcl::PointCloud<pcl::FPFHSignature33> ()); // Use all neighbors in a sphere of radius 5cm // IMPORTANT: the radius used here has to be larger than the radius used to estimate the surface normals!!! fpfh.setRadiusSearch (0.05); // Compute the features fpfh.compute (*fpfhs); // pfhs->size () should have the same size as the input cloud->size ()* //visualize cloud with normals //visualCloudNormals(cloud,normals); //define plotter pcl::visualization::PCLPlotter *plotter = new pcl::visualization::PCLPlotter ("My Plotter"); //attFr plotter->setShowLegend (true); std::cout<<pcl::getFieldsList<pcl::FPFHSignature33>(*fpfhs); //visualize, pfhs->size: number of cloud points, 125->5*5*5, 5 bins for each dimension //it prints out histogram of each cloud point for each one of 125 bins for (int m=0; m<fpfhs->size();m++) { std::cout<<"current dimension index is: "<<m<<" "<<fpfhs->size()<<std::endl; //check output of each query point pcl::FPFHSignature33 descriptor = fpfhs->points[m]; std::cout<<descriptor<<std::endl; plotter->addFeatureHistogram<pcl::FPFHSignature33>(*fpfhs, "fpfh", m, std::to_string(m)/*"one_fpfh"*/); plotter->setWindowSize(800, 600); plotter->spinOnce(10000); } while(!plotter->wasStopped()) { } plotter->clearPlots(); return 0; }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r9 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x107cc, %rbx nop nop nop inc %rsi mov $0x6162636465666768, %r12 movq %r12, %xmm2 movups %xmm2, (%rbx) nop nop nop nop xor %rbp, %rbp lea addresses_WC_ht+0x1a30c, %r9 sub %rax, %rax mov $0x6162636465666768, %r10 movq %r10, %xmm0 movups %xmm0, (%r9) nop nop nop sub %rax, %rax lea addresses_UC_ht+0x7c2b, %rax nop nop nop nop xor %r9, %r9 movups (%rax), %xmm4 vpextrq $1, %xmm4, %rbp nop cmp $33909, %r9 lea addresses_WC_ht+0x5c7e, %rsi nop nop nop and %r9, %r9 mov (%rsi), %rax nop nop nop nop nop xor %rbp, %rbp lea addresses_WC_ht+0x30d8, %rsi lea addresses_WC_ht+0x11456, %rdi clflush (%rsi) nop nop nop nop nop cmp $1088, %r12 mov $30, %rcx rep movsw nop sub $62820, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r9 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %rbx push %rcx push %rdi push %rsi // REPMOV lea addresses_PSE+0x15a3c, %rsi lea addresses_normal+0x1aabc, %rdi nop cmp %r11, %r11 mov $21, %rcx rep movsb nop add %rsi, %rsi // Store lea addresses_WC+0x6d3c, %r15 nop and $17725, %r13 mov $0x5152535455565758, %rcx movq %rcx, %xmm7 movups %xmm7, (%r15) nop nop nop sub %rdi, %rdi // Store lea addresses_WT+0xd48c, %rdi nop nop nop inc %r11 mov $0x5152535455565758, %rcx movq %rcx, (%rdi) sub %rbx, %rbx // Load mov $0x219459000000047c, %rbx nop nop nop nop nop cmp %rsi, %rsi vmovups (%rbx), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $0, %xmm0, %rcx dec %r13 // Faulty Load lea addresses_D+0x3e3c, %rbx add %rcx, %rcx movups (%rbx), %xmm4 vpextrq $1, %xmm4, %r13 lea oracles, %r15 and $0xff, %r13 shlq $12, %r13 mov (%r15,%r13,1), %r13 pop %rsi pop %rdi pop %rcx pop %rbx pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_PSE', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_NC', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 4}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}} {'36': 1} 36 */
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r14 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x11bac, %r14 nop nop nop nop nop add $49505, %rbx mov $0x6162636465666768, %rsi movq %rsi, %xmm6 movups %xmm6, (%r14) xor $62371, %rsi lea addresses_A_ht+0xcafc, %rsi nop nop nop nop cmp $54332, %rbp and $0xffffffffffffffc0, %rsi movaps (%rsi), %xmm5 vpextrq $0, %xmm5, %r11 nop nop nop inc %r11 lea addresses_A_ht+0x1a51c, %rcx nop nop nop nop xor %r12, %r12 movb $0x61, (%rcx) nop cmp $9977, %rbp lea addresses_WC_ht+0xbd1c, %rsi lea addresses_normal_ht+0x792c, %rdi nop nop add %rbp, %rbp mov $93, %rcx rep movsl nop nop inc %r14 lea addresses_UC_ht+0x8122, %rcx nop nop nop nop nop inc %r12 mov (%rcx), %r14 nop nop nop nop nop sub %rbx, %rbx lea addresses_A_ht+0x1769c, %rsi lea addresses_WT_ht+0x491c, %rdi nop nop nop nop dec %r12 mov $52, %rcx rep movsl sub %r11, %r11 lea addresses_D_ht+0x1dd1c, %rcx nop nop nop xor $52119, %r12 movups (%rcx), %xmm4 vpextrq $1, %xmm4, %r14 inc %rbp lea addresses_WT_ht+0xa41c, %r12 nop nop and %rbp, %rbp mov $0x6162636465666768, %rbx movq %rbx, (%r12) nop nop nop nop nop inc %rbx lea addresses_D_ht+0x543c, %rdi nop nop add $47924, %r11 movb $0x61, (%rdi) nop nop nop dec %rbp lea addresses_A_ht+0xe170, %r12 nop nop inc %rbx mov $0x6162636465666768, %rcx movq %rcx, %xmm4 movups %xmm4, (%r12) nop nop nop nop nop cmp %rbx, %rbx lea addresses_A_ht+0x169dc, %rcx add $50098, %rbp mov $0x6162636465666768, %rbx movq %rbx, %xmm5 movups %xmm5, (%rcx) nop nop sub %r12, %r12 lea addresses_normal_ht+0x9f9c, %rdi nop sub %rcx, %rcx mov (%rdi), %r11d nop nop nop add %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r14 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r9 push %rax push %rbx push %rcx push %rdi // Store mov $0x755a380000000f1c, %rbx clflush (%rbx) nop nop add %r12, %r12 movb $0x51, (%rbx) // Exception!!! nop nop nop nop nop mov (0), %r12 nop nop nop nop xor %rax, %rax // Faulty Load lea addresses_UC+0x451c, %rcx nop nop nop nop nop sub $257, %rdi vmovups (%rcx), %ymm4 vextracti128 $1, %ymm4, %xmm4 vpextrq $0, %xmm4, %r12 lea oracles, %rdi and $0xff, %r12 shlq $12, %r12 mov (%rdi,%r12,1), %r12 pop %rdi pop %rcx pop %rbx pop %rax pop %r9 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_NC', 'AVXalign': False, 'size': 1}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16}} {'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_A_ht', 'AVXalign': True, 'size': 16}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1}} {'src': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16}} {'src': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'45': 21821, '47': 1, '00': 4, '48': 3} 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 */
; this is especially thanks to: ; http://blog.markloiseau.com/2012/05/tiny-64-bit-elf-executables/ BITS 64 org 0x00400000 ; Program load offset ; 64-bit ELF header ehdr: ; 1), 0 (ABI ver.) db 0x7F, "ELF", 2, 1, 1, 0 ; e_ident times 8 db 0 ; reserved (zeroes) dw 2 ; e_type: Executable file dw 0x3e ; e_machine: AMD64 dd 1 ; e_version: current version dq _start ; e_entry: program entry address (0x78) dq phdr - $$ ; e_phoff program header offset (0x40) dq 0 ; e_shoff no section headers dd 0 ; e_flags no flags dw ehdrsize ; e_ehsize: ELF header size (0x40) dw phdrsize ; e_phentsize: program header size (0x38) dw 1 ; e_phnum: one program header dw 0 ; e_shentsize dw 0 ; e_shnum dw 0 ; e_shstrndx ehdrsize equ $ - ehdr ; 64-bit ELF program header phdr: dd 1 ; p_type: loadable segment dd 5 ; p_flags read and execute dq 0 ; p_offset dq $$ ; p_vaddr: start of the current section dq $$ ; p_paddr: " " dq filesize ; p_filesz dq filesize ; p_memsz dq 0x200000 ; p_align: 2^11=200000 = section alignment ; program header size phdrsize equ $ - phdr ; Hello World!/your program here _start: ; sys_write(stdout, message, length) mov rax, 1 ; sys_write mov rdi, 1 ; stdout mov rsi, message ; message address mov rdx, length ; message string length syscall ; sys_exit(return_code) mov rax, 60 ; sys_exit mov rdi, 0 ; return 0 (success) syscall message: db 0x0A db 'Hello World!', 0x0A db 0x0A length: equ $-message ; message length calculation ; File size calculation filesize equ $ - $$
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r15 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x2e96, %rsi lea addresses_UC_ht+0x532d, %rdi nop nop nop nop nop and $57265, %r12 mov $111, %rcx rep movsw nop nop nop nop add $52307, %rax lea addresses_WT_ht+0x12a6a, %rsi lea addresses_UC_ht+0x1a696, %rdi nop nop sub $57206, %r15 mov $71, %rcx rep movsq nop nop inc %rdi lea addresses_normal_ht+0x12796, %rsi lea addresses_normal_ht+0xe7ae, %rdi sub $24970, %r12 mov $53, %rcx rep movsl nop nop nop nop nop inc %rax lea addresses_WT_ht+0x372b, %rsi lea addresses_UC_ht+0x996, %rdi nop nop nop sub $50259, %rdx mov $26, %rcx rep movsl xor %rdi, %rdi lea addresses_normal_ht+0x1e996, %rdi nop nop inc %rcx movl $0x61626364, (%rdi) nop nop nop nop cmp $23647, %r15 lea addresses_normal_ht+0x1550e, %rsi nop nop nop nop and $26747, %rcx and $0xffffffffffffffc0, %rsi movaps (%rsi), %xmm3 vpextrq $0, %xmm3, %rax nop nop add $35309, %r12 lea addresses_WT_ht+0x17bb6, %rdi nop nop sub $12951, %rax movl $0x61626364, (%rdi) nop nop nop nop add $38393, %r15 pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r15 push %r8 push %r9 push %rbx push %rcx push %rsi // Store lea addresses_WC+0x4196, %rbx nop and %rsi, %rsi mov $0x5152535455565758, %rcx movq %rcx, %xmm5 vmovups %ymm5, (%rbx) nop nop nop nop xor $14058, %rcx // Store lea addresses_UC+0x8d96, %r8 nop nop nop inc %rcx movw $0x5152, (%r8) dec %rcx // Store lea addresses_UC+0x4d96, %rbx nop dec %r8 mov $0x5152535455565758, %r15 movq %r15, %xmm4 movups %xmm4, (%rbx) sub %r8, %r8 // Faulty Load lea addresses_UC+0x4d96, %rsi nop nop nop add %rcx, %rcx vmovaps (%rsi), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $1, %xmm2, %r8 lea oracles, %rsi and $0xff, %r8 shlq $12, %r8 mov (%rsi,%r8,1), %r8 pop %rsi pop %rcx pop %rbx pop %r9 pop %r8 pop %r15 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WC', 'congruent': 9}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC', 'congruent': 11}, 'OP': 'STOR'} {'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC', 'congruent': 0}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': True, 'AVXalign': True, 'size': 32, 'type': 'addresses_UC', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 7, 'type': 'addresses_WC_ht'}} {'dst': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 2, 'type': 'addresses_WT_ht'}} {'dst': {'same': False, 'congruent': 2, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 8, 'type': 'addresses_normal_ht'}} {'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 10}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT_ht', 'congruent': 5}, 'OP': 'STOR'} {'44': 1476, '49': 264, '00': 20089} 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 44 44 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 49 00 00 00 00 00 00 00 00 44 00 00 00 00 00 44 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 44 49 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 44 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 44 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 44 00 00 00 00 44 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 44 00 00 44 00 00 44 00 00 00 44 00 00 00 00 00 00 00 49 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 44 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 49 44 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 44 00 00 00 00 00 00 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 44 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 49 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 44 00 00 00 00 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 44 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 00 00 00 00 00 00 00 00 00 00 44 00 */
#include "CharacterDemo.h" #include "GlutStuff.h" #include "GLDebugDrawer.h" #include "btBulletDynamicsCommon.h" GLDebugDrawer gDebugDrawer; int main(int argc,char** argv) { CharacterDemo* characterDemo = new CharacterDemo; characterDemo->initPhysics(); characterDemo->getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); return glutmain(argc, argv,640,480,"Bullet Character Demo. http://www.continuousphysics.com/Bullet/phpBB2/", characterDemo); }
dnl MIPS32 mpn_addmul_1 -- Multiply a limb vector with a single limb and add dnl the product to a second limb vector. dnl Copyright 1992, 1994, 1996, 2000, 2002 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C INPUT PARAMETERS C res_ptr $4 C s1_ptr $5 C size $6 C s2_limb $7 ASM_START() PROLOGUE(mpn_addmul_1) C feed-in phase 0 lw $8,0($5) C feed-in phase 1 addiu $5,$5,4 multu $8,$7 addiu $6,$6,-1 beq $6,$0,$LC0 move $2,$0 C zero cy2 addiu $6,$6,-1 beq $6,$0,$LC1 lw $8,0($5) C load new s1 limb as early as possible Loop: lw $10,0($4) mflo $3 mfhi $9 addiu $5,$5,4 addu $3,$3,$2 C add old carry limb to low product limb multu $8,$7 lw $8,0($5) C load new s1 limb as early as possible addiu $6,$6,-1 C decrement loop counter sltu $2,$3,$2 C carry from previous addition -> $2 addu $3,$10,$3 sltu $10,$3,$10 addu $2,$2,$10 sw $3,0($4) addiu $4,$4,4 bne $6,$0,Loop addu $2,$9,$2 C add high product limb and carry from addition C wind-down phase 1 $LC1: lw $10,0($4) mflo $3 mfhi $9 addu $3,$3,$2 sltu $2,$3,$2 multu $8,$7 addu $3,$10,$3 sltu $10,$3,$10 addu $2,$2,$10 sw $3,0($4) addiu $4,$4,4 addu $2,$9,$2 C add high product limb and carry from addition C wind-down phase 0 $LC0: lw $10,0($4) mflo $3 mfhi $9 addu $3,$3,$2 sltu $2,$3,$2 addu $3,$10,$3 sltu $10,$3,$10 addu $2,$2,$10 sw $3,0($4) j $31 addu $2,$9,$2 C add high product limb and carry from addition EPILOGUE(mpn_addmul_1)
.code /* "<stdin>":0:109 contract x { constructor() public {} function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } } */ 0x80 0x40 mstore /* "<stdin>":13:36 constructor() public {} */ callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_1 jumpi /* "--CODEGEN--":30:31 */ 0x00 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_1: /* "<stdin>":13:36 constructor() public {} */ pop /* "<stdin>":0:109 contract x { constructor() public {} function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } } */ sub_0_length dup1 sub_0 0x00 codecopy 0x00 return stop sub_0 { .code /* "<stdin>":0:109 contract x { constructor() public {} function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } } */ 0x80 0x40 mstore callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_1 jumpi /* "--CODEGEN--":30:31 */ 0x00 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_1: /* "<stdin>":0:109 contract x { constructor() public {} function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } } */ pop 0x04 calldatasize lt tag_2 jumpi 0x00 calldataload 0xe0 shr dup1 0x6438a68d eq tag_3 jumpi tag_2: 0x00 dup1 revert /* "<stdin>":37:107 function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } */ tag_3: tag_4 0x04 dup1 calldatasize sub /* "--CODEGEN--":13:15 */ 0x20 /* "--CODEGEN--":8:11 */ dup2 /* "--CODEGEN--":5:16 */ lt /* "--CODEGEN--":2:4 */ iszero tag_5 jumpi /* "--CODEGEN--":29:30 */ 0x00 /* "--CODEGEN--":26:27 */ dup1 /* "--CODEGEN--":19:31 */ revert /* "--CODEGEN--":2:4 */ tag_5: /* "<stdin>":37:107 function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } */ dup2 add swap1 dup1 dup1 calldataload 0xffffffff and swap1 0x20 add swap1 swap3 swap2 swap1 pop pop pop tag_6 jump // in tag_4: 0x40 mload dup1 dup3 0xffffffff and 0xffffffff and dup2 mstore 0x20 add swap2 pop pop 0x40 mload dup1 swap2 sub swap1 return tag_6: /* "<stdin>":78:88 uint32 ret */ 0x00 /* "<stdin>":102:104 23 */ 0x17 /* "<stdin>":98:99 a */ dup3 /* "<stdin>":98:104 a + 23 */ add /* "<stdin>":92:104 ret = a + 23 */ swap1 pop /* "<stdin>":37:107 function g(uint32 a) public pure returns(uint32 ret) { ret = a + 23; } */ swap2 swap1 pop jump // out .data 0xa165627a7a723058207da7f0f721bbd655182ffcd973e77115f0edd9ee0d07fb2557c66193cfe8a1f30029 }
# PowerPC-64 mpn_rshift -- Shift a number right. # Copyright (C) 1999, 2000 Free Software Foundation, Inc. # This file is part of the GNU MP Library. # The GNU MP Library is free software; you can redistribute it and/or modify # it under the terms of the GNU Library General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # The GNU MP Library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public # License for more details. # You should have received a copy of the GNU Library General Public License # along with the GNU MP Library; see the file COPYING.LIB. If not, write to # the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, # MA 02111-1307, USA. # INPUT PARAMETERS # res_ptr r3 # s1_ptr r4 # size r5 # cnt r6 include(`../config.m4') ASM_START() PROLOGUE(mpn_rshift) mtctr r5 # copy size into CTR addi r7,r3,-8 # move adjusted res_ptr to free return reg subfic r8,r6,64 ld r11,0(r4) # load first s1 limb sld r3,r11,r8 # compute function return value bdz .Lend1 .Loop: ldu r10,8(r4) srd r9,r11,r6 sld r12,r10,r8 or r9,r9,r12 stdu r9,8(r7) bdz .Lend2 ldu r11,8(r4) srd r9,r10,r6 sld r12,r11,r8 or r9,r9,r12 stdu r9,8(r7) bdnz .Loop .Lend1: srd r0,r11,r6 std r0,8(r7) blr .Lend2: srd r0,r10,r6 std r0,8(r7) blr EPILOGUE(mpn_rshift)
; ; ZX81 libraries - Stefano ; ;---------------------------------------------------------------- ; Internal use code portion to update the actual ptr to d-file ; Can't be used from the external, it expect adjusted ; values for ROW and COLUMN ;---------------------------------------------------------------- ; ; $Id: zx_dfile_addr.asm,v 1.6 2016-06-26 20:32:08 dom Exp $ ; ;---------------------------------------------------------------- SECTION code_clib PUBLIC zx_dfile_addr IF FORzx80 DEFC COLUMN=$4024 ; S_POSN_x DEFC ROW=$4025 ; S_POSN_y ELSE DEFC COLUMN=$4039 ; S_POSN_x DEFC ROW=$403A ; S_POSN_y ENDIF zx_dfile_addr: push af IF FORlambda ld hl,16510 ELSE ld hl,(16396) ; D_FILE inc hl ENDIF ld a,(ROW) and a jr z,r_zero ld b,a ld de,33 ; 32+1. Every text line ends with an HALT .r_loop add hl,de djnz r_loop .r_zero ld a,(COLUMN) ld d,0 ld e,a add hl,de IF !FORzx80 ld ($400E),hl ; DF_CC ..current ZX81 cursor position on display file ENDIF pop af ret
db LAPRAS ; pokedex id db 130 ; base hp db 85 ; base attack db 80 ; base defense db 60 ; base speed db 95 ; base special db WATER ; species type 1 db ICE ; species type 2 db 45 ; catch rate db 219 ; base exp yield INCBIN "pic/gsmon/lapras.pic",0,1 ; 77, sprite dimensions dw LaprasPicFront dw LaprasPicBack ; attacks known at lvl 0 db WATER_GUN db 0 db 0 db 0 db 5 ; growth rate ; learnset tmlearn 6,7,8 tmlearn 9,10,11,13,14,15 tmlearn 20,23,24 tmlearn 25,29,30,31,32 tmlearn 33,34,40 tmlearn 44,46 tmlearn 50,53,54 db BANK(LaprasPicFront)
Music_SafariZone_Ch1:: tempo 132 volume 7, 7 vibrato 6, 3, 4 toggle_perfect_pitch duty_cycle 2 note_type 12, 9, 2 octave 3 pitch_slide 1, 4, A_ note C_, 1 pitch_slide 1, 4, A_ note G_, 1 pitch_slide 1, 4, A_ note C_, 1 pitch_slide 1, 4, A_ note G_, 1 rest 4 duty_cycle 3 Music_SafariZone_branch_bc4f:: sound_call Music_SafariZone_branch_bc5f note_type 12, 10, 4 note F#, 4 sound_call Music_SafariZone_branch_bc5f note_type 12, 10, 4 note F#, 4 sound_loop 0, Music_SafariZone_branch_bc4f Music_SafariZone_branch_bc5f:: note_type 12, 10, 2 octave 3 note C_, 4 note G_, 4 note C_, 4 note G_, 4 note C_, 4 note G_, 4 note C_, 4 sound_ret Music_SafariZone_Ch2:: duty_cycle 2 vibrato 8, 2, 5 note_type 12, 10, 2 octave 4 note G_, 1 note D_, 1 note G_, 1 note D_, 1 rest 4 duty_cycle 3 Music_SafariZone_branch_bc79:: sound_call Music_SafariZone_branch_bc89 note_type 12, 11, 5 note A_, 4 sound_call Music_SafariZone_branch_bc89 note_type 12, 11, 5 note B_, 4 sound_loop 0, Music_SafariZone_branch_bc79 Music_SafariZone_branch_bc89:: note_type 12, 11, 2 octave 3 note G_, 4 note D_, 4 note G_, 4 note D_, 4 note G_, 4 note D_, 4 note G_, 4 sound_ret Music_SafariZone_Ch3:: note_type 12, 1, 0 rest 8 Music_SafariZone_branch_bc97:: sound_call Music_SafariZone_branch_bca5 octave 4 note A_, 4 sound_call Music_SafariZone_branch_bca5 octave 4 note B_, 4 sound_loop 0, Music_SafariZone_branch_bc97 Music_SafariZone_branch_bca5:: octave 3 note A_, 2 rest 2 octave 4 note D_, 2 rest 2 octave 3 note A_, 2 rest 2 octave 4 note D_, 2 rest 2 octave 3 note A_, 2 rest 2 octave 4 note D_, 2 rest 2 octave 3 note A_, 2 rest 2 sound_ret
; ; Copyright (c) 2016-2017 László Heim ; ; Source file for image loading functions ; %include 'third-party/util.inc' ; Memory allocation and file heandling %include 'third-party/io.inc' %include 'third-party/mio.inc' ; Print memory contents global spr_create global spr_load_gimp_ppm global spr_dump_memory global spr_delete section .text ; Local functions: fio_read_char: ; Read one character from the file handle specified in eax to edx register ; In case of error, carry flag is set push ebx push ecx mov ecx, 1 mov ebx, read_buffer call fio_read cmp edx, ecx ; No more bytes to read jne .noread ; Save character in edx xor edx, edx mov dl, [ebx] clc jmp .exit .noread: stc .exit: pop ecx pop ebx ret read_until_eol: ; Read characters (and discard them) until end-of-file is found .read_loop: call fio_read_char jc .nomore cmp edx, 10 je .eol jmp .read_loop .eol: ; End-of-line found clc ret .nomore: ; No more bytes in file stc ret mul_ebx_10: ; Multiply ebx by 10 push eax push edx mov eax, ebx mov ebx, 10 mul ebx mov ebx, eax pop edx pop eax ret read_num: ; Read the width or height of the image from eax file handle and return ; it in edx push ebx xor ebx, ebx .read_loop: call fio_read_char jc .format_error cmp edx, ' ' clc je .read_end cmp edx, 10 clc je .read_end cmp edx, '0' jb .format_error cmp edx, '9' ja .format_error ; Valid character call mul_ebx_10 sub edx, '0' add ebx, edx jmp .read_loop .format_error: stc .read_end: mov edx, ebx pop ebx ret ; Global functions: spr_create: ; Create a texture map with width (eax higher part) and height (eax lower ; part) push ebx ; Save width and height push eax xor ebx, ebx test eax, 0x80008000 ; The width or the height is too big ; (We can't multiply width with height and 3, because it becomes bigger ; than 2^32 - 1) ; (We checked the first bits of the two numbers) jnz .toobig_error ; Get the width and the height mov bx, ax shr eax, 16 ; Calculate width * height mul ebx ; Calculate width * height * 3 mov ebx, 3 mul ebx ; Calculate width * height * 3 + 4 add eax, 4 ; call io_writeint ; Do memory allocation call mem_alloc ; Check for allocation error test eax, eax jz .alloc_error ; Everything went fine... let's save width and height pop ebx mov [eax+2], bx shr ebx, 16 mov [eax], bx ; Restore register pop ebx ; Successful return ret ; Unsuccessful returns .toobig_error: ; TODO: Handle them differently! .alloc_error: xor eax, eax ; Restore ebx pop ebx ret spr_delete: ; Delete a sprite test eax, eax jnz .delete ret .delete: call mem_free xor eax, eax ret spr_load_gimp_ppm: ; Create a texture map and load pixelmap from ppm as content push ebx push edx push edi push ecx ; Open file for read xor ebx, ebx call fio_open test eax, eax jz .cantopen_error ; Start reading header information call fio_read_char jc .format_error ; First byte = 'P' = 80 cmp edx, 80 jne .format_error ; Second byte = '6' = 54 call fio_read_char jc .format_error cmp edx, 54 jne .format_error ; Read unneccesary new line call fio_read_char jc .format_error ; Read comment call read_until_eol jc .format_error ; Read width call read_num jc .format_error test edx, 0xffff8000 jne .format_error ; Save width in ebx or ebx, edx ; Read height call read_num jc .format_error test edx, 0xffff8000 jne .format_error ; Save height in ebx shl ebx, 16 or ebx, edx ; Read color depth (not interesting, gimp filters to 255 max value) call read_num jc .format_error ; Create sprite, before starting to save it mov edi, eax mov eax, ebx call spr_create test eax, eax je .alloc_error ; Start saving pixel data xchg eax, edi push edi ; Write start position add edi, 4 ; Start writing data to sprite xor ecx, ecx mov cx, bx ; Move height in ecx shr ebx, 16 ; Will contain width loop count .column_loop: ; Read columns - works on height push ecx mov ecx, ebx ; Move inner loop .row_loop: ; Read rows push ecx mov ecx, 3 .pixel_loop: ; Read pixel components call fio_read_char jc .format_error_inner mov [edi], dl inc edi loop .pixel_loop pop ecx loop .row_loop pop ecx loop .column_loop ; Close file call fio_close ; Pixels saved in sprite memory pop eax ; pop sprite address to eax (pushed with edx) ; Restore registers pop ecx pop edi pop edx pop ebx ret ;;; ret #1 .format_error_inner: call fio_close pop eax call spr_delete ; Delete sprite .cantopen_error: ; TODO: handle these differently... .format_error: .alloc_error: xor eax, eax pop ecx pop edi pop edx pop ebx ret ;;; ret #2 spr_dump_memory: ; Print out memory content to the console: push eax push ebx push ecx push edx xor ebx, ebx xor ecx, ecx mov ebx, eax mov eax, size_msg call io_writestr xor eax, eax mov ax, [ebx] mov ecx, eax call io_writeint mov al, ',' call mio_writechar mov ax, [ebx+2] call io_writeint call io_writeln imul ecx, eax imul ecx, 3 add ebx, 4 xor edx, edx .write_loop: mov al, '#' call mio_writechar mov eax, edx call io_writeint xor eax, eax mov al, ':' call mio_writechar mov al, ' ' call mio_writechar inc edx mov al, [ebx] call io_writeint mov al, ' ' call mio_writechar inc ebx dec ecx mov al, [ebx] call io_writeint mov al, ' ' call mio_writechar inc ebx dec ecx mov al, [ebx] call io_writeint inc ebx call io_writeln loop .write_loop ; Restore registers pop edx pop ecx pop ebx pop eax ret section .bss read_buffer resb 1 section .data size_msg db 'Size of image: ', 0
; A024537: a(n) = floor( a(n-1)/(sqrt(2) - 1) ), with a(0) = 1. ; 1,2,4,9,21,50,120,289,697,1682,4060,9801,23661,57122,137904,332929,803761,1940450,4684660,11309769,27304197,65918162,159140520,384199201,927538921,2239277042,5406093004,13051463049,31509019101,76069501250,183648021600,443365544449,1070379110497,2584123765442,6238626641380,15061377048201,36361380737781,87784138523762,211929657785304,511643454094369,1235216565974041,2982076586042450,7199369738058940,17380816062160329,41961001862379597,101302819786919522,244566641436218640,590436102659356801,1425438846754932241,3441313796169221282,8308066439093374804,20057446674355970889,48422959787805316581,116903366249966604050,282229692287738524680,681362750825443653409,1644955193938625831497,3971273138702695316402,9587501471344016464300,23146276081390728245001,55880053634125472954301,134906383349641674153602,325692820333408821261504,786292024016459316676609,1898276868366327454614721,4582845760749114225906050,11063968389864555906426820,26710782540478226038759689,64485533470821007983946197,155681849482120242006652082,375849232435061491997250360,907380314352243226001152801,2190609861139547943999555961,5288600036631339114000264722,12767809934402226172000085404,30824219905435791458000435529,74416249745273809088000956461,179656719395983409634002348450,433729688537240628356005653360,1047116096470464666346013655169,2527961881478169961048032963697,6103039859426804588442079582562,14734041600331779137932192128820,35571123060090362864306463840201,85876287720512504866545119809221,207323698501115372597396703458642,500523684722743250061338526726504,1208371067946601872720073756911649,2917265820615946995501486040549801,7042902709178495863723045838011250,17003071238972938722947577716572300,41049045187124373309618201271155849,99101161613221685342183980258883997,239251368413567743993986161788923842,577603898440357173330156303836731680 seq $0,78057 ; Expansion of (1+x)/(1-2*x-x^2). add $0,2 div $0,2
; ; VGM YM2610 chip ; YM2610: MACRO super: Chip YM2610_ym2610Name, Header.ym2610BClock, YM2610_Connect ; hl' = time remaining ; ix = player ; iy = reader ProcessPort0Command: PROC call Reader_ReadWord_IY jp System_Return writeRegister: equ $ - 2 ENDP ; hl' = time remaining ; ix = player ; iy = reader ProcessPort1Command: PROC call Reader_ReadWord_IY jp System_Return writeRegister: equ $ - 2 ENDP ; b = bit 7: dual chip number ; dehl = size ; ix = player ; iy = reader ProcessDataBlockA: PROC bit 7,b jp z,Player_SkipDataBlock process: equ $ - 2 jp Player_SkipDataBlock processDual: equ $ - 2 ENDP ; b = bit 7: dual chip number ; dehl = size ; ix = player ; iy = reader ProcessDataBlockB: PROC bit 7,b jp z,Player_SkipDataBlock process: equ $ - 2 jp Player_SkipDataBlock processDual: equ $ - 2 ENDP ENDM ; ix = this ; iy = header YM2610_Construct: call Chip_Construct call YM2610_GetName jp Chip_SetName ; ix = this YM2610_Destruct: equ Chip_Destruct ; jp Chip_Destruct ; ix = this ; f <- nz: YM2610B YM2610_IsYM2610B: equ Device_GetFlagBit7 ; jp Device_GetFlagBit7 ; iy = drivers ; ix = this YM2610_Connect: call YM2610_TryCreate ret nc call Chip_SetDriver ld bc,YM2610.ProcessPort0Command.writeRegister call Device_ConnectInterface ld bc,YM2610.ProcessPort1Command.writeRegister call Device_ConnectInterface ld bc,YM2610.ProcessDataBlockA.process call Device_ConnectInterface ld bc,YM2610.ProcessDataBlockB.process jp Device_ConnectInterface ; ix = this ; hl <- name YM2610_GetName: call YM2610_IsYM2610B ld hl,YM2610_ym2610Name ret z ld hl,YM2610_ym2610bName ret ; iy = drivers ; ix = this ; de <- driver ; hl <- device interface ; f <- c: succeeded YM2610_TryCreate: PROC call YM2610_IsYM2610B jr z,NoYM2610B call Drivers_TryCreateOPNBBOnNeotronOPNA_IY ld hl,OPNBBOnNeotronOPNA_interface ret c NoYM2610B: call Drivers_TryCreateNeotron_IY ld hl,Neotron_interface ret ENDP ; SECTION RAM YM2610_instance: YM2610 ENDS YM2610_ym2610Name: db "YM2610 (OPNB)",0 YM2610_ym2610bName: db "YM2610B (OPNB)",0
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r8 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x5420, %r12 nop nop nop add %r8, %r8 movl $0x61626364, (%r12) sub $57762, %rdx lea addresses_D_ht+0x5cb8, %rsi lea addresses_A_ht+0x136de, %rdi nop sub $10994, %rax mov $65, %rcx rep movsl nop nop nop nop add %rsi, %rsi lea addresses_WC_ht+0xf9d8, %r8 nop nop nop add $50414, %rcx mov (%r8), %rdx nop nop nop nop cmp %rax, %rax lea addresses_A_ht+0x1e9d8, %rsi nop nop nop nop nop and $17362, %rcx mov (%rsi), %edi nop nop nop nop nop add $21169, %rax lea addresses_normal_ht+0x1a908, %rcx nop dec %rdi movb $0x61, (%rcx) nop nop nop sub %rdi, %rdi pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r15 push %rax push %rbp push %rbx push %rsi // Faulty Load lea addresses_D+0x75d8, %rsi nop nop nop nop nop cmp %rax, %rax movaps (%rsi), %xmm5 vpextrq $0, %xmm5, %rbx lea oracles, %rsi and $0xff, %rbx shlq $12, %rbx mov (%rsi,%rbx,1), %rbx pop %rsi pop %rbx pop %rbp pop %rax pop %r15 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 16, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'00': 20985} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A082305: G.f.: (1 - 6*x - sqrt(36*x^2 - 16*x + 1))/(2*x). ; Submitted by Jon Maiga ; 1,7,56,497,4760,48174,507696,5516133,61363736,695540258,8004487568,93283238986,1098653880688,13056472392796,156371970692448,1885491757551213,22870028390806296,278862330338622618,3416227165353152976,42026974738864811934,518985757875094199760,6430948993711243916292,79938117746373916668576,996496872893704566665442,12454873398116191002587760,156046575434829211223669844,1959481191164367746408202656,24656360970083772656277680948,310852566617483164073244894176,3926092917155029859849925528760 mov $1,1 mov $2,1 mov $3,$0 mov $4,2 lpb $3 mul $1,$3 mul $2,7 sub $3,1 mul $1,$3 add $5,$4 div $1,$5 add $2,$1 add $4,2 lpe mov $0,$2
; A262734: Period 16: repeat (1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2). ; 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,8 add $0,1 lpb $0,1 sub $0,16 pow $1,$1 lpe mul $0,2 mul $1,2 trn $1,$0 add $1,4 mul $1,2 add $1,$0 sub $1,10 div $1,2 add $1,1
#Mergesort for benchmarking #Optimized for 512 bit I$ 1024 bit D$ #Author Adam Hendrickson ahendri@purdue.edu #CORE 0 org 0x0000 ori $fp, $zero, 0xFFFC ori $sp, $zero, 0xFFFC ori $a0, $zero, data lw $s0, size($zero) srl $a1, $s0, 1 or $s1, $zero, $a0 or $s2, $zero, $a1 jal insertion_sort srl $t0, $s0, 1 subu $a1, $s0, $t0 sll $t0, $t0, 2 ori $a0, $zero, data addu $a0, $a0, $t0 or $s3, $zero, $a0 or $s4, $zero, $a1 or $a0, $zero, $s1 or $a1, $zero, $s2 or $a2, $zero, $s3 or $a3, $zero, $s4 ori $t0, $zero, sorted push $t0 ori $t1, $zero, flag wait1: lw $t2, 0($t1) beq $t2, $zero, wait1 jal merge addiu $sp, $sp, 4 halt #CORE 1 org 0x0200 ori $fp, $zero, 0x3FFC ori $sp, $zero, 0x3FFC ori $a0, $zero, data lw $s0, size($zero) srl $a1, $s0, 1 sll $t0, $a1, 2 addu $a0, $a0, $t0 subu $a1, $s0, $a1 jal insertion_sort ori $t0, $zero, flag ori $t1, $zero, 1 sw $t1, 0($t0) halt #void insertion_sort(int* $a0, int $a1) # $a0 : pointer to data start # $a1 : size of array #-------------------------------------- insertion_sort: ori $t0, $zero, 4 sll $t1, $a1, 2 is_outer: sltu $at, $t0, $t1 beq $at, $zero, is_end addu $t9, $a0, $t0 lw $t8, 0($t9) is_inner: beq $t9, $a0, is_inner_end lw $t7, -4($t9) slt $at, $t8, $t7 beq $at, $zero, is_inner_end sw $t7, 0($t9) addiu $t9, $t9, -4 j is_inner is_inner_end: sw $t8, 0($t9) addiu $t0, $t0, 4 j is_outer is_end: jr $ra #-------------------------------------- #void merge(int* $a0, int $a1, int* $a2, int $a3, int* dst) # $a0 : pointer to list 1 # $a1 : size of list 1 # $a2 : pointer to list 2 # $a3 : size of list 2 # dst [$sp+4] : pointer to merged list location #-------------------------------------- merge: lw $t0, 0($sp) m_1: bne $a1, $zero, m_3 m_2: bne $a3, $zero, m_3 j m_end m_3: beq $a3, $zero, m_4 beq $a1, $zero, m_5 lw $t1, 0($a0) lw $t2, 0($a2) slt $at, $t1, $t2 beq $at, $zero, m_3a sw $t1, 0($t0) addiu $t0, $t0, 4 addiu $a0, $a0, 4 addiu $a1, $a1, -1 j m_1 m_3a: sw $t2, 0($t0) addiu $t0, $t0, 4 addiu $a2, $a2, 4 addiu $a3, $a3, -1 j m_1 m_4: #left copy lw $t1, 0($a0) sw $t1, 0($t0) addiu $t0, $t0, 4 addiu $a1, $a1, -1 addiu $a0, $a0, 4 beq $a1, $zero, m_end j m_4 m_5: # right copy lw $t2, 0($a2) sw $t2, 0($t0) addiu $t0, $t0, 4 addiu $a3, $a3, -1 addiu $a2, $a2, 4 beq $a3, $zero, m_end j m_5 m_end: jr $ra #-------------------------------------- org 0x400 flag: cfw 0 size: cfw 18 data: cfw 90 cfw 81 cfw 51 cfw 25 cfw 80 cfw 41 cfw 22 cfw 21 cfw 12 cfw 62 cfw 75 cfw 71 cfw 83 cfw 81 cfw 26 cfw 8 cfw 11 cfw 91 org 0x600 sorted:
;FINAL .include "m2560def.inc" .def temp =r21 .def row =r17 .def col =r18 .def mask =r19 .def temp2 =r20 .def count_letter =r22 ;multiple times .def push_flag=r23 ;whether any button has pushed .def letter_num = r24 ;maximum number .def finish_input_flag =r25 ;0 is pushed, input finish .def temp_count_for_question =r2 .def keypad_version = r3 ;char - 0 num - 1 .def input10 = r4 .equ PORTLDIR = 0xF0 .equ INITCOLMASK = 0xEF .equ INITROWMASK = 0x01 .equ ROWMASK = 0x0F .equ second_line = 0b10101000 .macro do_lcd_command ldi r16, @0 rcall lcd_command rcall lcd_wait .endmacro .macro do_lcd_command_imme mov r16, @0 rcall lcd_command rcall lcd_wait .endmacro .macro do_lcd_data ldi r16, @0 rcall lcd_data rcall lcd_wait .endmacro .macro do_lcd_data_imme mov r16, @0 rcall lcd_data rcall lcd_wait .endmacro .macro stop_time_head do_lcd_data 'T' do_lcd_data 'i' do_lcd_data 'm' do_lcd_data 'e' do_lcd_data ' ' do_lcd_data_imme @0 do_lcd_data ' ' do_lcd_data 't' do_lcd_data 'o' do_lcd_data ' ' do_lcd_data '1' do_lcd_data ':' do_lcd_command 0b11000000 .endmacro .macro train_stop do_lcd_data 'T' do_lcd_data 'r' do_lcd_data 'a' do_lcd_data 'i' do_lcd_data 'n' do_lcd_data ' ' do_lcd_data 's' do_lcd_data 't' do_lcd_data 'o' do_lcd_data 'p' do_lcd_data ' ' do_lcd_data 'f' do_lcd_data 'o' do_lcd_data 'r' do_lcd_data ':' .endmacro // .macro station_name do_lcd_data 'T' do_lcd_data 'y' do_lcd_data 'p' do_lcd_data 'e' do_lcd_data ' ' do_lcd_data 's' do_lcd_data 't' do_lcd_data 'o' do_lcd_data 'p' do_lcd_data_imme @0 do_lcd_data ' ' do_lcd_data 'n' do_lcd_data 'a' do_lcd_data 'm' do_lcd_data 'e' do_lcd_data ':' .endmacro .macro stop_maximum do_lcd_data 'M' do_lcd_data 'a' do_lcd_data 'x' do_lcd_data ' ' do_lcd_data 's' do_lcd_data 't' do_lcd_data 'o' do_lcd_data 'p' do_lcd_data ' ' do_lcd_data 'n' do_lcd_data 'u' do_lcd_data 'm' do_lcd_data ':' do_lcd_command 0b11000000 .endmacro .macro stop_time do_lcd_data 'T' do_lcd_data 'i' do_lcd_data 'm' do_lcd_data 'e' do_lcd_data ' ' do_lcd_data_imme @0 inc @0 do_lcd_data ' ' do_lcd_data 't' do_lcd_data 'o' do_lcd_data ' ' do_lcd_data_imme @0 do_lcd_data ':' do_lcd_command 0b11000000 .endmacro .macro finish_info do_lcd_data 'A' do_lcd_data 'l' do_lcd_data 'l' do_lcd_data ' ' do_lcd_data 'd' do_lcd_data 'o' do_lcd_data 'n' do_lcd_data 'e' do_lcd_command 0b11000000 do_lcd_data 'W' do_lcd_data 'a' do_lcd_data 'i' do_lcd_data 't' do_lcd_data ' ' do_lcd_data 'f' do_lcd_data 'o' do_lcd_data 'r' do_lcd_data ' ' do_lcd_data '5' do_lcd_data 's' .endmacro .macro wrong do_lcd_data 'E' do_lcd_data 'r' do_lcd_data 'r' do_lcd_data '!' .endmacro .macro clear ldi YL, low(@0) ldi YH, high(@0) clr temp st Y+,temp st Y,temp .endmacro .macro clearonebyte ldi YL, low(@0) ldi YH, high(@0) clr temp st Y,temp .endmacro .macro timeten lsl @0 mov r16, @0 lsl @0 lsl @0 add @0, r16 .endmacro .dseg ////////////////////////////// ;++++++ variable +++++++++ ////////////////////////////// SecondCounter: .byte 2 TempCounter: .byte 2 Status: .byte 1 Position: .byte 1 count_question:.byte 1 Maximum: .byte 1 TempNumInfo: .byte 1 current_name_pointer: .byte 2 station_stop_time: .byte 1 current_time_pointer: .byte 2 pb_flag: .byte 1 led: .byte 1 stop_flag: .byte 1 hash_flag: .byte 1 //////////////////////////// ;station storage //////////////////////////// station1: .byte 10 station2: .byte 10 station3: .byte 10 station4: .byte 10 station5: .byte 10 station6: .byte 10 station7: .byte 10 station8: .byte 10 station9: .byte 10 station10: .byte 10 time_data: .byte 10 .cseg .org 0x0 jmp RESET .org INT0addr ; INT0addr is the address of EXT_INT0 jmp EXT_INT0 .org INT1addr ; INT1addr is the address of EXT_INT1 jmp EXT_INT1 jmp DEFAULT .org OVF0addr jmp Timer0OVF DEFAULT:reti RESET: ldi temp, low(RAMEND) out SPL, temp ldi temp, high(RAMEND) out SPH, temp ldi temp, PORTLDIR ; columns are outputs, rows are inputs STS DDRL, temp ; cannot use out ser temp out DDRC, temp ; Make PORTC all outputs clr temp out PORTC, temp ser temp out DDRF, temp out DDRA, temp clr temp out PORTF, temp out PORTA, temp ;clr station ldi yl,low(station1) ldi yh,high(station2) ldi temp,99 clr r16 clear_stations: cpi temp,0 breq time_setup st y+,r16 dec temp rjmp clear_stations ;clear time time_setup: ;timer0 setup clear TempCounter clear SecondCounter ldi temp,0b00000000 out TCCR0A,temp ;set mode 000- normal mode ldi temp,0b00000010 out TCCR0B,temp ;set prescaler - 8 ldi temp, 1<<TOIE0 ;time overflow from 3 kinds of overflow cmpA,cmpB,time overflow sts TIMSK0,temp ;apply to mask sei ;every timer overflow trigger an interrupt, when the times of interrupt is equal ;to 7812(that is the times should happen in a second) add 1s //////////////////////////// //set lcd start position//// //////////////////////////// ldi r24, second_line sts Position, r24 //////////////////////////// //set letter counter//////// //////////////////////////// ldi push_flag,1 clr letter_num ldi count_letter, 0b00000000 clearonebyte count_question do_lcd_command 0b00111000 ; 2x5x7 rcall sleep_5ms do_lcd_command 0b00111000 ; 2x5x7 rcall sleep_1ms do_lcd_command 0b00111000 ; 2x5x7 do_lcd_command 0b00111000 ; 2x5x7 do_lcd_command 0b00001000 ; display off? do_lcd_command 0b00000001 ; clear display do_lcd_command 0b00000110 ; increment, no display shift do_lcd_command 0b00001110 ; Cursor on, bar, no blink ;clr line // jmp main EXT_INT0: ;(PB0) push temp in temp, SREG push temp ldi temp,1 sts pb_flag,temp pop temp out SREG, temp pop temp reti EXT_INT1: ;(PB1) push temp in temp, SREG push temp ldi temp,1 sts pb_flag,temp pop temp out SREG, temp pop temp reti /* EXT_INT1: ; PB1 rcall sleep_350ms push temp in temp, SREG push temp lds temp,hash_flag cpi temp,1 breq close_motor cpi temp,0 breq open_motor close_motor: ldi temp,1 sts stop_flag,temp ldi temp,0 sts hash_flag,temp sei close_motor_loop: lds temp2,hash_flag cpi temp2,1 breq hash_end rjmp close_motor_loop open_motor: ldi temp2,1 sts hash_flag,temp2 ldi temp, 0b00111100 out DDRE, temp ldi temp, 0xff sts OCR3BL,temp clr temp sts OCR3BH, temp ldi temp, (1 << CS30) ; CS31=1: no prescaling sts TCCR3B, temp ldi temp, (1<< WGM30)|(1<<COM3B1) ; WGM30=1: phase correct PWM, 8 bits ; COM3B1=1: make OC3B override the normal port functionality of the I/O pin PL3 sts TCCR3A, temp */ hash_end: cli clearonebyte stop_flag pop temp out SREG, temp pop temp reti Timer0OVF: in temp, SREG push temp push YH push YL push r25 push r24 lds r24,TempCounter lds r25,TempCounter+1 adiw r25:r24,1 cpi r24,low(7812) ldi temp,high(7812) cpc r25,temp brne NotSecond clear TempCounter lds r24,SecondCounter lds r25,SecondCounter+1 adiw r25:r24,1 sts SecondCounter, r24 sts SecondCounter+1,r25 lds r24, Status ;? cpi r24,0 breq input_wait rcall partc_timer rjmp EndIF NotSecond: sts TempCounter, r24 sts TempCounter+1,r25 lds r24, Status ;? cpi r24,0 breq EndIF rcall partc_timer EndIF: pop r24 pop r25 pop YL pop YH pop temp out SREG,temp reti input_wait: lds r24,SecondCounter cpi r24, 1 brsh restart go_EndIF: rjmp EndIF restart: cli clear TempCounter clear SecondCounter sbrc push_flag,0 ;if 0, then there is a char pressed rjmp noAction lds r24,Position inc r24 sts Position,r24 ldi push_flag,1 inc letter_num lds yl,current_name_pointer lds yh,current_name_pointer+1 st y+,row sts current_name_pointer,yl sts current_name_pointer+1,yh do_lcd_data_imme row noAction: sei ldi count_letter,0b00000000 rjmp go_EndIF /////////////////////////// //do motor and led at here partc_timer: push temp push temp2 push r24 push r25 //dont use r17 lds temp,stop_flag cpi temp,1 breq rail_stop partc_timer_end: pop r25 pop r24 pop temp2 pop temp ret rail_stop: //test lds r24,TempCounter lds r25,TempCounter+1 cpi r24,low(2604) ldi temp,high(2604) cpc r25,temp brsh change_led do_motor: ldi temp, 0b00111100 out DDRE, temp ; set PL3 (OC5A) as output. ldi temp, 0x00 ; this value and the operation mode determine the PWM duty cycle sts OCR5AL, temp sts OCR3BL,temp clr temp sts OCR3BH, temp ldi temp, (1 << CS30) sts TCCR3B, temp ldi temp, (1<< WGM30)|(1<<COM3B1) sts TCCR3A, temp rjmp partc_timer_end //havenot done this part let it stop change_led: lds temp2,led cpi temp2,0 breq light cpi temp2,1 breq dark light: ldi temp2,0b11111111 out PORTC,temp2 ldi temp2,1 sts led,temp2 rjmp change_end dark: ldi temp2,0b00000000 out PORTC,temp2 ldi temp2,0 sts led,temp2 rjmp change_end change_end: clear TempCounter rjmp do_motor main: /////////////////////////////////// ; part a ;get and store information /////////////////////////////////// stop_maximum ldi temp,1 ;1 is for num pad mov keypad_version , temp rcall keypad_part lds temp, TempNumInfo cpi temp, 11 brsh wrong_info_max sts Maximum,temp rjmp ask_stop_name wrong_info_max: do_lcd_command 0b00000001 wrong clearonebyte TempNumInfo rjmp main ask_stop_name: do_lcd_command 0b00000001 ; clear display clr keypad_version lds temp, count_question ;start from 0 lds r16, Maximum cp temp, r16 brsh stop_time_start ldi r16, 0b00110000 mov temp_count_for_question, temp add r16, temp mov r1, r16 inc r1 rcall store_name ;store name store station_name r1 rcall keypad_part mov r1, temp_count_for_question inc r1 sts count_question, r1 rjmp ask_stop_name stop_time_start: clearonebyte count_question clearonebyte tempNumInfo ask_stop_time: lds r1, count_question mov temp_count_for_question, r1 lds r16, Maximum dec r16 cp r1, r16 brsh back_to_head inc r1 ldi r16, 0b00110000 add r1,r16 stop_time r1 ldi temp,1 ;1 is for num pad mov keypad_version , temp rcall keypad_part rjmp back_to_time ;check overflow for station time back_to_head: lds r1, count_question mov r16, r1 cpi r16, 1 breq ask_for_waiting_time ldi r16, 0b00110000 add r1,r16 inc r1 stop_time_head r1 rcall keypad_part // rjmp time_head ask_for_waiting_time: ;new block train_stop rcall keypad_part lds temp, TempNumInfo cpi temp, 6 brsh wrong_stop cpi temp, 2 brlo wrong_stop sts station_stop_time,temp rjmp finish wrong_stop: do_lcd_command 0b00000001 wrong do_lcd_command 0b11000000 clearonebyte TempNumInfo rjmp ask_for_waiting_time //wrong handler finish: do_lcd_command 0b00000001 finish_info rcall sleep_350ms rjmp partc back_to_time: lds temp, TempNumInfo cpi temp, 11 brsh wrong_station_info rcall store_time lds temp,tempNumInfo lds xl,current_time_pointer lds xh,current_time_pointer+1 st x+,temp inc temp_count_for_question mov r1, temp_count_for_question sts count_question,r1 clearonebyte tempNumInfo do_lcd_command 0b00000001 rjmp ask_stop_time time_head: lds temp, TempNumInfo cpi temp, 11 brsh wrong_station_info rcall store_time lds temp,tempNumInfo lds xl,current_time_pointer lds xh,current_time_pointer+1 st x+,temp inc temp_count_for_question mov r1, temp_count_for_question sts count_question,r1 clearonebyte tempNumInfo // do_lcd_command 0b00000001 rjmp ask_for_waiting_time wrong_station_info: do_lcd_command 0b00000001 wrong clearonebyte TempNumInfo rjmp ask_stop_time ////////////////////////////////// ;part c ;show stored information ///////////////////////////////////// // partc: ldi temp, (2 << ISC10) | (2 << ISC00) ;enable external interrupt sts EICRA, temp in temp, EIMSK ori temp, (1<<INT0) | (1<<INT1) out EIMSK, temp sei ldi temp, 0b00111100 out DDRE, temp ldi temp, 0x00 sts OCR3BL,temp clr temp sts OCR3BH, temp ldi temp, (1 << CS30) sts TCCR3B, temp ldi temp, (1<< WGM30)|(1<<COM3B1) sts TCCR3A, temp rcall sleep_1000ms rcall sleep_1000ms rcall sleep_1000ms rcall sleep_1000ms rcall sleep_1000ms do_lcd_command 0b00000001 clearonebyte count_question ldi temp, 1 sts Status, temp ldi temp,2 mov keypad_version, temp ldi temp, 1 sts hash_flag, temp clr temp sts pb_flag,temp clearonebyte led clearonebyte stop_flag print_data: ldi temp, 0b00111100 out DDRE, temp ldi temp, 0xff sts OCR3BL,temp clr temp sts OCR3BH, temp ldi temp, (1 << CS30) sts TCCR3B, temp ldi temp, (1<< WGM30)|(1<<COM3B1) sts TCCR3A, temp rcall store_time /////////////////////////// // check if overflow /////////////////////////// lds r18,Maximum lds r19,count_question sub r18,r19 cpi r18,0 breq time_back_to_1 rjmp print_go_on time_back_to_1: ldi yl,low(time_data) ldi yh,high(time_data) sts current_time_pointer,yl sts current_time_pointer+1,yh print_go_on: lds yl,current_time_pointer lds yh,current_time_pointer+1 ld r18,y // do_lcd_command 0b00000001 do_lcd_data 'n' do_lcd_data 'e' do_lcd_data 'x' do_lcd_data 't' do_lcd_data ':' do_lcd_command 0b11000000 rcall sleep_5ms rcall print_all on_way_loop: cpi r18,0 breq check_stop do_lcd_data '>' rcall sleep_1000ms dec r18 rjmp on_way_loop check_stop: lds temp,pb_flag cpi temp,1 breq Station_stop rjmp print_data_end Station_stop: ldi r17,1 sts stop_flag,r17 clear TempCounter do_lcd_command 0b00000001 do_lcd_data 'w' do_lcd_data 'a' do_lcd_data 'i' do_lcd_data 't' do_lcd_data ' ' do_lcd_data 'f' do_lcd_data 'o' do_lcd_data 'r' do_lcd_data ':' do_lcd_command 0b11000000 lds r17,count_question dec r17 sts count_question,r17 rcall print_all inc r17 sts count_question,r17 lds r17,station_stop_time ;out PORTC,r17 Station_stop_loop: do_lcd_data '>' rcall sleep_1000ms cpi r17,0 breq print_data_end dec r17 rjmp Station_stop_loop print_data_end: clearonebyte stop_flag clearonebyte pb_flag ldi temp2,0b00000000 out PORTC,temp2 rjmp print_data print_all: //cli push temp push temp2 push r16 push yl push yh ldi yl,low(station1) ldi yh,high(station1) sts current_name_pointer, yl sts current_name_pointer+1,yh show_station: lds temp2,Maximum lds temp,count_question sub temp2,temp cpi temp2,0 breq back_to_one /////////////////////// //get next station lds r16,count_question lds temp,count_question lds temp2,Maximum inc temp sub temp2,temp cpi temp2,0 breq next_first sts count_question,temp rjmp print_first // back_to_one: clr temp sts count_question,temp ldi yl,low(station1) ldi yh,high(station1) rjmp show_station next_first: clr temp sts count_question,temp // print_first: rcall store_name sts count_question,r16 lds yl,current_name_pointer lds yh,current_name_pointer+1 ldi temp2,9 //print next name print_name: ld temp,y+ cpi temp,0 breq show_station_end cpi temp2,0 breq show_station_end do_lcd_data_imme temp dec temp2 rjmp print_name show_station_end: lds temp,count_question inc temp sts count_question,temp ldi temp2,0b00000000 out PORTC,temp2 pop yh pop yl pop r16 pop temp2 pop temp //sei ret loop: rjmp loop //// ; keypad input //// keypad_part: ldi mask, INITCOLMASK ; initial column mask clr col ; initial column colloop: STS PORTL, mask ; set column to mask value ; (sets column 0 off) ldi temp, 0xFF ; implement a delay so the ; hardware can stabilize delay: dec temp brne delay LDS temp, PINL ; read PORTL. Cannot use in andi temp, ROWMASK ; read only the row bits cpi temp, 0xF ; check if any rows are grounded breq nextcol ; if not go to the next column ldi mask, INITROWMASK ; initialise row check clr row ; initial row rowloop: mov temp2, temp and temp2, mask ; check masked bit brne skipconv mov temp, keypad_version cpi temp, 1 breq call_num cpi temp, 2 breq call_working rcall convert_char ; if bit is clear, convert the bitcode back: cpi finish_input_flag, 1 breq question jmp keypad_part ; and start again skipconv: inc row ; else move to the next row lsl mask ; shift the mask to the next bit jmp rowloop nextcol: cpi col, 3 ; check if we^re on the last column breq keypad_part ; if so, no buttons were pushed, ; so start again. sec ; else shift the column mask: ; We must set the carry bit rol mask ; and then rotate left by a bit, inc col ; increment column value jmp colloop ; and check the next column call_num: rcall convert_num rjmp back call_working: rjmp keypad_part question: ldi r16, second_line ;restart all things for keypad sts Position, r16 ldi push_flag,1 clr letter_num clr finish_input_flag clr count_letter sei ret //////////////////////////////// ////convert result to character /////////////////////////////// convert_char: rcall sleep_350ms ;add a debouncing here, at first it's not stable,when we detect a key pushed ;wait until disturbing signal disappear then convert cpi col, 3 breq letters cpi col, 2 mov temp, row lsl temp add temp, row add temp, col mov r16, temp lsl temp add temp, r16 ldi r16,0b01000000 add temp,r16 inc temp jmp convert_end letters: cpi row, 0 breq delete cpi row, 2 breq c_for_finish ;C for confirm jmp ending c_for_finish: ldi finish_input_flag,1 rjmp ending convert_end: add temp, count_letter inc count_letter cpi count_letter,0b00000011 breq remain final: cpi letter_num, 11 brsh no_num clr push_flag cpi temp,0b01011011 brne go_on ldi temp, 0b10100000 normal: mov row,temp ;row is useless now ,so treat it as another temp lds r16, Position do_lcd_command_imme r16 do_lcd_data_imme row clear TempCounter clear SecondCounter ending: ret ; return to caller go_on: rjmp normal remain: ldi count_letter,0b00000000 rjmp final delete: lds r16, Position cpi r16, 1 dec r16 sts Position,r16 do_lcd_data ' ' rcall sleep_350ms rjmp ending no_num: rjmp ending ;normal convert_num: cli rcall sleep_350ms ;add a debouncing here, at first it's not stable,when we detect a key pushed cpi col, 3 ;wait until disturbing signal disappear then convert breq num_letter mov temp, row lsl temp add temp, row add temp, col inc temp cpi push_flag,0 breq time10 update_tempnum: lds temp2,TempNumInfo add temp2, temp ;push = 0, has pressed sts TempNumInfo, temp2 ldi r16,48 add temp,r16 clr push_flag jmp convert_num_end num_letter: cpi row, 1 breq zero_num cpi row, 2 breq c_for_finish_num jmp ending c_for_finish_num: ldi finish_input_flag,1 rjmp num_end zero_num: ldi temp, 0b00110000 lds temp2,TempNumInfo timeten temp2 sts TempNumInfo, temp2 convert_num_end: do_lcd_data_imme temp num_end: ret ; return to caller time10: lds temp2,TempNumInfo timeten temp2 sts TempNumInfo, temp2 rjmp update_tempnum /// ;store operation /// store_name: cli push temp push temp2 lds temp,count_question ldi temp2,10 //move y to current station point_station: load1: cpi temp,0 brne load2 ldi yl,low(station1) ldi yh,high(station1) rjmp clear_10 load2: cpi temp,1 brne load3 ldi yl,low(station2) ldi yh,high(station2) rjmp clear_10 load3: cpi temp,2 brne load4 ldi yl,low(station3) ldi yh,high(station3) rjmp clear_10 load4: cpi temp,3 brne load5 ldi yl,low(station4) ldi yh,high(station4) rjmp clear_10 load5: cpi temp,4 brne load6 ldi yl,low(station5) ldi yh,high(station5) rjmp clear_10 load6: cpi temp,5 brne load7 ldi yl,low(station6) ldi yh,high(station6) rjmp clear_10 load7: cpi temp,6 brne load8 ldi yl,low(station7) ldi yh,high(station7) rjmp clear_10 load8: cpi temp,7 brne load9 ldi yl,low(station8) ldi yh,high(station8) rjmp clear_10 load9: cpi temp,8 brne load10 ldi yl,low(station9) ldi yh,high(station9) rjmp clear_10 load10: ldi yl,low(station10) ldi yh,high(station10) rjmp clear_10 //clear 10 byte clear_10: sts current_name_pointer, yl sts current_name_pointer+1,yh clr r6 clear_10_loop: cpi temp2,10 breq store_name_end st y+,r6 st y+,r6 st y+,r6 st y+,r6 st y+,r6 st y+,r6 st y+,r6 st y+,r6 st y+,r6 st y+,r6 dec temp2 rjmp clear_10_loop store_name_end: pop temp2 pop temp sei ret //storetime store_time: cli push temp push yl push yh lds temp,count_question ldi yl,low(time_data) ldi yh,high(time_data) store_time_loop: cpi temp,0 breq store_time_end ld r7,y+ dec temp rjmp store_time_loop store_time_end: sts current_time_pointer,yl sts current_time_pointer+1,yh pop yh pop yl pop temp sei ret //// ;lcd operation //// .equ LCD_RS = 7 .equ LCD_E = 6 .equ LCD_RW = 5 .equ LCD_BE = 4 .macro lcd_set sbi PORTA, @0 .endmacro .macro lcd_clr cbi PORTA, @0 .endmacro ; ; Send a command to the LCD (r16) ; lcd_command: out PORTF, r16 nop lcd_set LCD_E nop nop nop lcd_clr LCD_E nop nop nop ret lcd_data: out PORTF, r16 lcd_set LCD_RS nop nop nop lcd_set LCD_E nop nop nop lcd_clr LCD_E nop nop nop lcd_clr LCD_RS ret lcd_wait: push r16 clr r16 out DDRF, r16 out PORTF, r16 lcd_set LCD_RW lcd_wait_loop: nop lcd_set LCD_E nop nop nop in r16, PINF lcd_clr LCD_E sbrc r16, 7 rjmp lcd_wait_loop lcd_clr LCD_RW ser r16 out DDRF, r16 pop r16 ret .equ F_CPU = 16000000 .equ DELAY_1MS = F_CPU / 4 / 1000 - 4 ; 4 cycles per iteration - setup/call-return overhead sleep_1ms: push r24 push r25 ldi r25, high(DELAY_1MS) ldi r24, low(DELAY_1MS) delayloop_1ms: sbiw r25:r24, 1 brne delayloop_1ms pop r25 pop r24 ret sleep_5ms: rcall sleep_1ms rcall sleep_1ms rcall sleep_1ms rcall sleep_1ms rcall sleep_1ms ret sleep_1000ms: clr r16 d_loop: cpi r16, 200 brne increase ret increase: inc r16 rcall sleep_5ms rjmp d_loop sleep_350ms: clr r16 d_loop1: cpi r16, 70 brne increase1 ret increase1: inc r16 rcall sleep_5ms rjmp d_loop1
; A033415: [ 95/n ]. ; 95,47,31,23,19,15,13,11,10,9,8,7,7,6,6,5,5,5,5,4,4,4,4,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 add $0,1 mov $1,95 div $1,$0
TITLE Assignment 4 (Project04.asm) ; Name: Brandon Lee ; Email: leebran@onid.oregonstate.edu ; Class: CS271 Section 400 ; Assignment: #4 ; Due Date: 4/10/15 ; Description: The fourth homework assignment - procedures, loops, nested loops, data validation INCLUDE Irvine32.inc LOWER = 1 UPPER = 400 .data introMsg BYTE "TITLE: Assignment 4 - Brandon Lee",0 byeMsg BYTE "Goodbye",0 instruct0 BYTE "Enter the number of composite numbers you would like to see.",0 instruct1 BYTE "Please enter numbers in [1 .. 400]: ",0 errMsg BYTE "Your input is not valid",0 spaces BYTE " ",0 userInput DWORD ? compositeNum DWORD ? lineCounter DWORD 0 .code main PROC call intro call getUserData call showComposites call farewell ; exit to operating system exit main ENDP ;----- Display Intro messages ----- intro PROC mov edx, OFFSET introMsg call WriteString call CrLf mov edx, OFFSET instruct0 call WriteString call CrLf ret intro ENDP ;----- Gets the user's input ----- getUserData PROC ;Prompt user to input data mov edx, OFFSET instruct1 call WriteString call ReadInt ;Move input into global and call validate procedure mov userInput, eax call validate call CrLf ret getUserData ENDP ;----- Validates the user's input givent by the getUserInfo procedure ----- validate PROC ;Validate if input is within bounds of 1 and 400, if not move to error handling cmp userInput, LOWER jl ErrorLabel cmp userInput, UPPER jg ErrorLabel ret ErrorLabel: ;If data is not valid, display error message and jump back to input prompt procedure mov edx, OFFSET errMsg call WriteString call CrLf jmp getUserData validate ENDP ;----- Displays a composite number for n (userinput) number of times. Uses calls isComposite to get the next composite number ----- showComposites PROC ;Move user input to loop counter register. ;Initilize eax as 4 (lowest composite number) and ebx as 2 (lowest divider for composite numbers). mov ecx, userInput mov eax, 4 mov compositeNum, eax mov ebx, 2 ;Initilize outerloop to the userInput counter OuterLoop: ;Call isComposite procedure to find the next composite number call isComposite ;Once composite number is found, print it out to user, and increment the number mov eax, compositeNum call WriteDec inc compositeNum ;Count the number of integers for each line inc lineCounter mov eax, lineCounter mov ebx, 10 cdq div ebx ;Check if there are 10 in a line, if so, jump and add new line, if not, jump and add spaces cmp edx, 0 je NewLine jne AddSpaces NewLine: call CrLf jmp ResumeLoop AddSpaces: mov edx, OFFSET spaces call WriteString ;Loop the outer loop again! ResumeLoop: mov ebx, 2 mov eax, compositeNum loop OuterLoop ;Done with looping ret showComposites ENDP ;----- Finds the next composite number and returns it to showComposite procedure ----- isComposite PROC ;Initilize inner loop InnerLoop: ;Check if the number still can possibably be composite cmp ebx, eax ;If not, jump to incrementing the number of restarting je NoCompositeAtAll ;Check if number is composite by dividing and comparing modulus to 0 cdq div ebx cmp edx, 0 je YesComposite jne NoComposite ;If number composite, we're done with inner loop! YesComposite: ret ;If number not composite with divisor, increment divisor, reset number, and restart inner loop NoComposite: mov eax, compositeNum inc ebx jmp InnerLoop ;If number is just not composite, increment the composite number, reset divisor, and restart inner loop NoCompositeAtAll: inc compositeNum mov eax, compositeNum mov ebx, 2 jmp InnerLoop isComposite ENDP ;----- Display goodbye message ----- farewell PROC mov edx, OFFSET byeMsg call CrLf call CrLf call WriteString call CrLf ret farewell ENDP END main
#include "mission_raw_impl.h" #include "system.h" #include "global_include.h" #include <fstream> // for `std::ifstream` #include <sstream> // for `std::stringstream` #include <cmath> namespace dronecode_sdk { using namespace std::placeholders; // for `_1` MissionRawImpl::MissionRawImpl(System &system) : PluginImplBase(system) { _parent->register_plugin(this); } MissionRawImpl::~MissionRawImpl() { _parent->unregister_plugin(this); } void MissionRawImpl::init() { _parent->register_mavlink_message_handler( MAVLINK_MSG_ID_MISSION_ACK, std::bind(&MissionRawImpl::process_mission_ack, this, _1), this); _parent->register_mavlink_message_handler( MAVLINK_MSG_ID_MISSION_COUNT, std::bind(&MissionRawImpl::process_mission_count, this, _1), this); _parent->register_mavlink_message_handler( MAVLINK_MSG_ID_MISSION_ITEM_INT, std::bind(&MissionRawImpl::process_mission_item_int, this, _1), this); } void MissionRawImpl::deinit() { _parent->unregister_all_mavlink_message_handlers(this); } void MissionRawImpl::enable() {} void MissionRawImpl::disable() {} void MissionRawImpl::process_mission_ack(const mavlink_message_t &message) { mavlink_mission_ack_t mission_ack; mavlink_msg_mission_ack_decode(&message, &mission_ack); if (mission_ack.type != MAV_MISSION_ACCEPTED) { return; } // We assume that if the vehicle sends an ACCEPTED ack might have received // a new mission. In that case we need to notify our user. std::lock_guard<std::mutex> lock(_mission_changed.mutex); if (_mission_changed.callback) { // Local copy because we can't make a copy of member variable. auto callback = _mission_changed.callback; _parent->call_user_callback([callback]() { callback(); }); } } void MissionRawImpl::download_mission_async( const MissionRaw::mission_items_and_result_callback_t &callback) { { std::lock_guard<std::mutex> lock(_mission_download.mutex); if (_mission_download.state != MissionDownload::State::NONE) { if (callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> empty_vec{}; _parent->call_user_callback( [callback, empty_vec]() { callback(MissionRaw::Result::BUSY, empty_vec); }); } return; } _mission_download.state = MissionDownload::State::REQUEST_LIST; _mission_download.retries = 0; _mission_download.mavlink_mission_items_downloaded.clear(); _mission_download.callback = callback; } _parent->register_timeout_handler( std::bind(&MissionRawImpl::do_download_step, this), 0.0, nullptr); } void MissionRawImpl::do_download_step() { std::lock_guard<std::mutex> lock(_mission_download.mutex); switch (_mission_download.state) { case MissionDownload::State::NONE: LogWarn() << "Invalid state: do_download_step and State::NONE"; break; case MissionDownload::State::REQUEST_LIST: request_list(); break; case MissionDownload::State::REQUEST_ITEM: request_item(); break; case MissionDownload::State::SHOULD_ACK: send_ack(); break; } } void MissionRawImpl::request_list() { // Requires _mission_download.mutex. if (_mission_download.retries++ >= 3) { // We tried multiple times without success, let's give up. _mission_download.state = MissionDownload::State::NONE; if (_mission_download.callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> empty_vec{}; auto callback = _mission_download.callback; _parent->call_user_callback( [callback, empty_vec]() { callback(MissionRaw::Result::TIMEOUT, empty_vec); }); } return; } // LogDebug() << "Requesting mission list (" << _mission_download.retries << ")"; mavlink_message_t message; mavlink_msg_mission_request_list_pack(_parent->get_own_system_id(), _parent->get_own_component_id(), &message, _parent->get_system_id(), _parent->get_autopilot_id(), MAV_MISSION_TYPE_MISSION); if (!_parent->send_message(message)) { // This is a terrible and unexpected error. Therefore we don't even // retry but just give up. _mission_download.state = MissionDownload::State::NONE; if (_mission_download.callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> empty_vec{}; auto callback = _mission_download.callback; _parent->call_user_callback( [callback, empty_vec]() { callback(MissionRaw::Result::ERROR, empty_vec); }); } return; } // We retry the list request and mission item request, so we use the lower timeout. _parent->register_timeout_handler( std::bind(&MissionRawImpl::do_download_step, this), RETRY_TIMEOUT_S, &_timeout_cookie); } void MissionRawImpl::process_mission_count(const mavlink_message_t &message) { // LogDebug() << "Received mission count"; std::lock_guard<std::mutex> lock(_mission_download.mutex); if (_mission_download.state != MissionDownload::State::REQUEST_LIST) { return; } mavlink_mission_count_t mission_count; mavlink_msg_mission_count_decode(&message, &mission_count); _mission_download.num_mission_items_to_download = mission_count.count; _mission_download.next_mission_item_to_download = 0; _mission_download.retries = 0; // We can get rid of the timeout and schedule and do the next step straightaway. _parent->unregister_timeout_handler(_timeout_cookie); _mission_download.state = MissionDownload::State::REQUEST_ITEM; if (mission_count.count == 0) { _mission_download.state = MissionDownload::State::SHOULD_ACK; } // Let's just add this to the queue, this way we don't block the receive thread // and let go of the mutex as well. _parent->register_timeout_handler( std::bind(&MissionRawImpl::do_download_step, this), 0.0, nullptr); } void MissionRawImpl::request_item() { // Requires _mission_download.mutex. if (_mission_download.retries++ >= 3) { // We tried multiple times without success, let's give up. _mission_download.state = MissionDownload::State::NONE; if (_mission_download.callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> empty_vec{}; auto callback = _mission_download.callback; _parent->call_user_callback( [callback, empty_vec]() { callback(MissionRaw::Result::TIMEOUT, empty_vec); }); } return; } // LogDebug() << "Requesting mission item " << _mission_download.next_mission_item_to_download // << " (" << _mission_download.retries << ")"; mavlink_message_t message; mavlink_msg_mission_request_int_pack(_parent->get_own_system_id(), _parent->get_own_component_id(), &message, _parent->get_system_id(), _parent->get_autopilot_id(), _mission_download.next_mission_item_to_download, MAV_MISSION_TYPE_MISSION); if (!_parent->send_message(message)) { // This is a terrible and unexpected error. Therefore we don't even // retry but just give up. _mission_download.state = MissionDownload::State::NONE; if (_mission_download.callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> empty_vec{}; auto callback = _mission_download.callback; _parent->call_user_callback( [callback, empty_vec]() { callback(MissionRaw::Result::ERROR, empty_vec); }); } return; } // We retry the list request and mission item request, so we use the lower timeout. _parent->register_timeout_handler( std::bind(&MissionRawImpl::do_download_step, this), RETRY_TIMEOUT_S, &_timeout_cookie); } void MissionRawImpl::process_mission_item_int(const mavlink_message_t &message) { // LogDebug() << "Received mission item int"; std::lock_guard<std::mutex> lock(_mission_download.mutex); if (_mission_download.state != MissionDownload::State::REQUEST_ITEM) { return; } mavlink_mission_item_int_t mission_item_int; mavlink_msg_mission_item_int_decode(&message, &mission_item_int); if (mission_item_int.seq != _mission_download.next_mission_item_to_download) { LogWarn() << "Received mission item " << int(mission_item_int.seq) << " instead of " << _mission_download.next_mission_item_to_download << " (ignored)"; // The timeout will happen anyway and retry for this case. return; } auto new_item = std::make_shared<MissionRaw::MavlinkMissionItemInt>(); new_item->target_system = mission_item_int.target_system; new_item->target_component = mission_item_int.target_component; new_item->seq = mission_item_int.seq; new_item->frame = mission_item_int.frame; new_item->command = mission_item_int.command; new_item->current = mission_item_int.current; new_item->autocontinue = mission_item_int.autocontinue; new_item->param1 = mission_item_int.param1; new_item->param2 = mission_item_int.param2; new_item->param3 = mission_item_int.param3; new_item->param4 = mission_item_int.param4; new_item->x = mission_item_int.x; new_item->y = mission_item_int.y; new_item->z = mission_item_int.z; new_item->mission_type = mission_item_int.mission_type; _mission_download.mavlink_mission_items_downloaded.push_back(new_item); ++_mission_download.next_mission_item_to_download; _mission_download.retries = 0; if (_mission_download.next_mission_item_to_download == _mission_download.num_mission_items_to_download) { _mission_download.state = MissionDownload::State::SHOULD_ACK; } // We can remove timeout. _parent->unregister_timeout_handler(_timeout_cookie); // And schedule the next request. _parent->register_timeout_handler( std::bind(&MissionRawImpl::do_download_step, this), 0.0, nullptr); } void MissionRawImpl::send_ack() { // Requires _mission_download.mutex. // LogDebug() << "Sending ack"; mavlink_message_t message; mavlink_msg_mission_ack_pack(_parent->get_own_system_id(), _parent->get_own_component_id(), &message, _parent->get_system_id(), _parent->get_autopilot_id(), MAV_MISSION_ACCEPTED, MAV_MISSION_TYPE_MISSION); if (!_parent->send_message(message)) { // This is a terrible and unexpected error. Therefore we don't even // retry but just give up. _mission_download.state = MissionDownload::State::NONE; if (_mission_download.callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> empty_vec{}; auto callback = _mission_download.callback; _parent->call_user_callback( [callback, empty_vec]() { callback(MissionRaw::Result::ERROR, empty_vec); }); } return; } // We did it, we are done. _mission_download.state = MissionDownload::State::NONE; if (_mission_download.callback) { std::vector<std::shared_ptr<MissionRaw::MavlinkMissionItemInt>> vec_copy = _mission_download.mavlink_mission_items_downloaded; auto callback = _mission_download.callback; _parent->call_user_callback( [callback, vec_copy]() { callback(MissionRaw::Result::SUCCESS, vec_copy); }); } } void MissionRawImpl::download_mission_cancel() {} void MissionRawImpl::subscribe_mission_changed(MissionRaw::mission_changed_callback_t callback) { std::lock_guard<std::mutex> lock(_mission_changed.mutex); _mission_changed.callback = callback; } } // namespace dronecode_sdk
#include <helper.h> unsigned int Helper::getLedSpeed(DistanceSensor sensor) { // TODO use percent values to release dependency to fixed warn distance if (sensor.getDistance() <= 50) { return 3; } if (sensor.getDistance() <= 100) { return 2; } return 1; }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r8 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_normal_ht+0x1b835, %rcx nop sub $18820, %r13 mov (%rcx), %eax sub $30841, %rax lea addresses_D_ht+0x73d5, %r8 nop dec %r9 mov $0x6162636465666768, %r10 movq %r10, %xmm4 and $0xffffffffffffffc0, %r8 vmovaps %ymm4, (%r8) nop nop nop sub $41871, %rcx lea addresses_A_ht+0xca45, %rsi lea addresses_A_ht+0x1d715, %rdi nop nop nop add %r8, %r8 mov $20, %rcx rep movsl nop sub $24163, %rax lea addresses_UC_ht+0x1df15, %rsi lea addresses_WT_ht+0x9315, %rdi and %r8, %r8 mov $45, %rcx rep movsw nop dec %rax lea addresses_D_ht+0x13f15, %rsi lea addresses_WC_ht+0x4f15, %rdi nop dec %rax mov $49, %rcx rep movsw nop xor $2562, %rcx lea addresses_WT_ht+0x315, %rsi nop nop nop and %r13, %r13 movups (%rsi), %xmm6 vpextrq $0, %xmm6, %r8 nop nop nop dec %rcx lea addresses_D_ht+0x1af25, %rdi cmp %r10, %r10 movb (%rdi), %r13b nop sub $1606, %rsi lea addresses_UC_ht+0xdf15, %rcx nop nop nop nop add $36151, %rdi mov $0x6162636465666768, %r8 movq %r8, %xmm7 and $0xffffffffffffffc0, %rcx vmovntdq %ymm7, (%rcx) nop nop xor %rcx, %rcx lea addresses_WC_ht+0x15d0e, %rax nop nop nop nop nop sub $30470, %rcx movb $0x61, (%rax) nop nop nop xor $40963, %rdi lea addresses_UC_ht+0x7915, %r9 nop nop nop add $62986, %rax movups (%r9), %xmm4 vpextrq $1, %xmm4, %r10 cmp $60080, %rsi lea addresses_A_ht+0x15f27, %rcx nop nop nop nop and $43057, %r13 movups (%rcx), %xmm4 vpextrq $1, %xmm4, %r10 nop nop nop nop and $1487, %rdi lea addresses_normal_ht+0x6895, %rsi lea addresses_UC_ht+0x1b915, %rdi nop sub %r9, %r9 mov $57, %rcx rep movsq nop nop nop nop sub $45209, %rax lea addresses_D_ht+0x11115, %r8 nop cmp $38990, %rax movb $0x61, (%r8) nop nop nop nop nop add %rcx, %rcx lea addresses_A_ht+0x4835, %rax xor $18086, %rdi mov (%rax), %r8w nop sub %rcx, %rcx lea addresses_WT_ht+0x4315, %r9 clflush (%r9) nop xor %rdi, %rdi mov $0x6162636465666768, %rax movq %rax, %xmm2 and $0xffffffffffffffc0, %r9 vmovaps %ymm2, (%r9) nop nop nop sub %r9, %r9 pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r8 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %r9 push %rcx push %rdi push %rsi // Load lea addresses_RW+0x19495, %rdi nop nop nop sub %r13, %r13 mov (%rdi), %esi nop nop nop nop and $15550, %r9 // Store lea addresses_RW+0xad15, %r9 nop nop sub %r12, %r12 mov $0x5152535455565758, %rdi movq %rdi, (%r9) nop nop nop nop nop xor %rsi, %rsi // Store lea addresses_A+0xc8eb, %r9 nop nop add %r13, %r13 movl $0x51525354, (%r9) nop nop and $6940, %r12 // Store lea addresses_UC+0x1f7c5, %rcx nop nop sub %r14, %r14 mov $0x5152535455565758, %r9 movq %r9, %xmm3 movups %xmm3, (%rcx) nop nop nop nop dec %r12 // Store lea addresses_PSE+0x1b515, %r12 and %r9, %r9 movl $0x51525354, (%r12) nop nop nop nop xor %r9, %r9 // Store lea addresses_UC+0xa595, %r9 nop nop nop xor %rdi, %rdi mov $0x5152535455565758, %r12 movq %r12, (%r9) nop nop inc %r12 // Store lea addresses_normal+0x18f15, %rdi nop cmp $1980, %r9 movw $0x5152, (%rdi) nop nop nop nop nop xor $36709, %r9 // Store lea addresses_normal+0xb4f5, %rdi clflush (%rdi) nop add %r14, %r14 mov $0x5152535455565758, %r9 movq %r9, %xmm3 movups %xmm3, (%rdi) cmp %rsi, %rsi // Store lea addresses_A+0x12315, %r12 add %r9, %r9 mov $0x5152535455565758, %rsi movq %rsi, %xmm1 movaps %xmm1, (%r12) nop dec %r12 // Faulty Load lea addresses_normal+0x2f15, %rsi nop nop nop cmp %r9, %r9 vmovups (%rsi), %ymm5 vextracti128 $0, %ymm5, %xmm5 vpextrq $0, %xmm5, %r12 lea oracles, %rdi and $0xff, %r12 shlq $12, %r12 mov (%rdi,%r12,1), %r12 pop %rsi pop %rdi pop %rcx pop %r9 pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6, 'same': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'} {'dst': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 1, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4, 'same': False, 'type': 'addresses_UC'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'STOR'} {'dst': {'NT': True, 'AVXalign': True, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_UC'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 9, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_normal'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'congruent': 4, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'congruent': 11, 'same': True, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'dst': {'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 2, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'34': 881} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
; ----- bool multipoint(int hv, int length, int x, int y) ;Usage: ;pick a vertical or horizontal bit bar, up to 16 bits long IF !__CPU_INTEL__ && !__CPU_GBZ80__ SECTION code_graphics PUBLIC multipoint_callee PUBLIC _multipoint_callee PUBLIC asm_multipoint EXTERN w_pointxy EXTERN swapgfxbk EXTERN swapgfxbk1 INCLUDE "graphics/grafix.inc" .multipoint_callee ._multipoint_callee pop af ; ret addr pop de ; y pop hl ; x pop bc ex af,af ld a,c ; length pop bc ; h/v ld b,a ex af,af push af ; ret addr .asm_multipoint push ix IF NEED_swapgfxbk = 1 call swapgfxbk ENDIF ld a,b rr c ld bc,0 jr nc,horizontal .vertical sla c rl b push af push hl push de push bc call w_pointxy pop bc pop de pop hl jr z,jv inc bc .jv pop af inc de dec a jr nz,vertical jr exit .horizontal sla c rl b push af push hl push de push bc call w_pointxy pop bc pop de pop hl jr z,jh inc bc .jh pop af inc hl dec a jr nz,horizontal .exit IF NEED_swapgfxbk = 1 call swapgfxbk1 ENDIF pop ix ld h,b ld l,c ret ENDIF
; A274536: a(n) = 6 * sigma(n). ; 6,18,24,42,36,72,48,90,78,108,72,168,84,144,144,186,108,234,120,252,192,216,144,360,186,252,240,336,180,432,192,378,288,324,288,546,228,360,336,540,252,576,264,504,468,432,288,744,342,558,432,588,324,720,432,720,480,540,360,1008,372,576,624,762,504,864,408,756,576,864,432,1170,444,684,744,840,576,1008,480,1116,726,756,504,1344,648,792,720,1080,540,1404,672,1008,768,864,720,1512,588,1026,936,1302,612,1296,624,1260,1152,972,648,1680,660,1296,912,1488,684,1440,864,1260,1092,1080,864,2160,798,1116,1008,1344,936,1872,768,1530,1056,1512,792,2016,960,1224,1440,1620,828,1728,840,2016,1152,1296,1008,2418,1080,1332,1368,1596,900,2232,912,1800,1404,1728,1152,2352,948,1440,1296,2268,1152,2178,984,1764,1728,1512,1008,2880,1098,1944,1560,1848,1044,2160,1488,2232,1440,1620,1080,3276,1092,2016,1488,2160,1368,2304,1296,2016,1920,2160,1152,3048,1164,1764,2016,2394,1188,2808,1200,2790,1632,1836,1440,3024,1512,1872,1872,2604,1440,3456,1272,2268,1728,1944,1584,3600,1536,1980,1776,3024,1512,2736,1344,3024,2418,2052,1368,3360,1380,2592,2304,2700,1404,3276,1728,2520,1920,2592,1440,4464,1452,2394,2184,2604,2052,3024,1680,2880,2016,2808 cal $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n). mov $1,$0 mul $1,6
; Define some selectors. SCodeSelector equ 0x08 ; System Code Selector SDataSelector equ 0x10 ; System Data Selector VideoSelector equ 0x18 ; Video Selector TSS1Selector equ 0x20 TSS2Selector equ 0x28 ; Define the location of read sectors num ReadSectors equ 0x0ff0 ; Define the location of keyboard LED status information location KeyboardLEDs equ 0x0ff1 ; Define the location of video mode information VideoMode equ 0x0ff2 ScreenX equ 0x0ff4 ScreenY equ 0x0ff6 VRAMOrigin equ 0x0ff8
;***************************************************************************** ;* Copyright (C) 2005-2010 x264 project ;* ;* Authors: Loren Merritt <lorenm@u.washington.edu> ;* Fiona Glaser <fiona@x264.com> ;* ;* This file is part of Libav. ;* ;* Libav 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. ;* ;* Libav 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 Libav; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "x86util.asm" SECTION .text ;----------------------------------------------------------------------------- ; void ff_cpu_cpuid(int index, int *eax, int *ebx, int *ecx, int *edx) ;----------------------------------------------------------------------------- cglobal cpu_cpuid, 5,7 push rbx push r4 push r3 push r2 push r1 mov eax, r0d xor ecx, ecx cpuid pop r4 mov [r4], eax pop r4 mov [r4], ebx pop r4 mov [r4], ecx pop r4 mov [r4], edx pop rbx RET ;----------------------------------------------------------------------------- ; void ff_cpu_xgetbv(int op, int *eax, int *edx) ;----------------------------------------------------------------------------- cglobal cpu_xgetbv, 3,7 push r2 push r1 mov ecx, r0d xgetbv pop r4 mov [r4], eax pop r4 mov [r4], edx RET %if ARCH_X86_64 == 0 ;----------------------------------------------------------------------------- ; int ff_cpu_cpuid_test(void) ; return 0 if unsupported ;----------------------------------------------------------------------------- cglobal cpu_cpuid_test pushfd push ebx push ebp push esi push edi pushfd pop eax mov ebx, eax xor eax, 0x200000 push eax popfd pushfd pop eax xor eax, ebx pop edi pop esi pop ebp pop ebx popfd ret %endif
// // Created by nunol on 12/31/2021. // #include "Engine/Graphics/Renderer.hpp" #include <stdexcept> #include <array> using namespace nl::gfx; Renderer::Renderer(Window &window, Device &device) : _window{window}, _device{device} { recreateSwapChain(); createCommandBuffers(); } Renderer::~Renderer() { freeCommandBuffers(); } void Renderer::recreateSwapChain() { auto extent = _window.getExtent(); while (extent.width == 0 || extent.height == 0) { extent = _window.getExtent(); glfwWaitEvents(); } vkDeviceWaitIdle(_device.device()); if (_swapChain == nullptr) { _swapChain = std::make_unique<SwapChain>(_device, extent); } else { std::shared_ptr<SwapChain> oldSwapChain = std::move(_swapChain); _swapChain = std::make_unique<SwapChain>(_device, extent, oldSwapChain); if (!oldSwapChain->compareSwapFormats(*_swapChain.get())) { throw std::runtime_error("SwapChain image(or depth) format has changed"); } } } void Renderer::createCommandBuffers() { _commandBuffers.resize(SwapChain::MAX_FRAMES_IN_FLIGHT); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = _device.getCommandPool(); allocInfo.commandBufferCount = static_cast<U32>(_commandBuffers.size()); if (vkAllocateCommandBuffers(_device.device(), &allocInfo, _commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers"); } } void Renderer::freeCommandBuffers() { vkFreeCommandBuffers( _device.device(), _device.getCommandPool(), static_cast<U32>(_commandBuffers.size()), _commandBuffers.data() ); _commandBuffers.clear(); } VkCommandBuffer Renderer::beginFrame() { assert(!_frameStarted); auto result = _swapChain->acquireNextImage(&_currentImageIndex); if (result == VK_ERROR_OUT_OF_DATE_KHR) { recreateSwapChain(); return nullptr; } if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire swap chain image"); } _frameStarted = true; auto commandBuffer = getCurrentcommandBuffer(); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers"); } return commandBuffer; } void Renderer::endFrame() { assert(_frameStarted); auto commandBuffer = getCurrentcommandBuffer(); if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) { throw std::runtime_error("Failed to record command buffers"); } auto result = _swapChain->submitCommandBuffers(&commandBuffer, &_currentImageIndex); if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || _window.wasWindowResized()) { _window.resetWindowResized(); recreateSwapChain(); } else if (result != VK_SUCCESS) { throw std::runtime_error("Failed to present swap chain image"); } _frameStarted = false; _currentFrameIndex = (_currentFrameIndex + 1) % SwapChain::MAX_FRAMES_IN_FLIGHT; } void Renderer::beginSwapChainRenderPass(VkCommandBuffer commandBuffer) { assert(_frameStarted); assert(commandBuffer == getCurrentcommandBuffer()); VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = _swapChain->getRenderPass(); renderPassInfo.framebuffer = _swapChain->getFrameBuffer(_currentImageIndex); renderPassInfo.renderArea.offset = {0, 0}; renderPassInfo.renderArea.extent = _swapChain->getSwapChainExtent(); std::array<VkClearValue, 2> clearValues{}; clearValues[0].color = {0.01f, 0.01f, 0.01f, 1.0f}; clearValues[1].depthStencil = {1.0f, 0}; renderPassInfo.clearValueCount = static_cast<U32>(clearValues.size()); renderPassInfo.pClearValues = clearValues.data(); vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<R32>(_swapChain->getSwapChainExtent().width); viewport.height = static_cast<R32>(_swapChain->getSwapChainExtent().height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{{0,0}, _swapChain->getSwapChainExtent()}; vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); } void Renderer::endSwapChainRenderPass(VkCommandBuffer commandBuffer) { assert(_frameStarted); assert(commandBuffer == getCurrentcommandBuffer()); vkCmdEndRenderPass(commandBuffer); }
; A220492: Number of primes p between quarter-squares, Q(n) < p <= Q(n+1), where Q(n) = A002620(n). ; 0,0,1,1,1,1,1,1,2,1,1,1,2,2,1,2,2,2,2,1,4,1,2,2,2,3,3,2,2,2,4,2,4,3,1,4,2,4,3,3,3,4,4,3,4,3,2,4,4,5,4,4,4,3,4,4,4,5,4,4,4,4,5,5,5,4,6,4,4,5,5,5,7,2,3,6,6,6,6,5,8,4,5,6,5,4,7 mov $3,2 mov $5,$0 lpb $3,1 mov $0,$5 sub $3,1 add $0,$3 pow $0,2 div $0,4 cal $0,230980 ; Number of primes <= n, starting at n=0. mov $2,$3 mov $4,$0 lpb $2,1 mov $1,$4 sub $2,1 lpe lpe lpb $5,1 sub $1,$4 mov $5,0 lpe