Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
5
1.04M
/* Copyright (c) 2020 UATC, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "neuropod/internal/memory_utils.hh" #include "neuropod/internal/tensor_types.hh" #include <memory> #include <string> #include <unordered_map> #include <vector> namespace neuropod { // Device types that are supported in the Neuropod configuration typedef int NeuropodDeviceType; namespace DeviceType { constexpr int CPU = 0; constexpr int GPU = 1; }; // namespace DeviceType // A struct that stores the value of a dimension struct Dimension { Dimension(int64_t value); Dimension(std::string symbol); ~Dimension(); bool operator==(const Dimension &other) const; // The value // -1 == Any value is allowed (None/null) // -2 == Symbol int64_t value; // The name of this symbol (if it is a symbol) std::string symbol; }; // A struct that stores a specification for a tensor struct TensorSpec { TensorSpec(const std::string &name, const std::vector<Dimension> dims, const TensorType type); ~TensorSpec(); const std::string name; const std::vector<Dimension> dims; const TensorType type; }; // A struct that stores the expected inputs and outputs of a model struct ModelConfig { const std::string name; const std::string platform; // The requested versions of the platform specified as a semver range // e.g. `1.13.1` or `> 1.13.1` // See the following URLs for examples and more info: // - https://semver.org/ // - https://docs.npmjs.com/misc/semver#ranges // - https://docs.npmjs.com/misc/semver#advanced-range-syntax const std::string platform_version_semver; const std::vector<TensorSpec> inputs; const std::vector<TensorSpec> outputs; const std::vector<std::string> custom_ops; // A map from an input tensor name to a device type const std::unordered_map<std::string, NeuropodDeviceType> input_tensor_device; }; std::unique_ptr<ModelConfig> load_model_config(const std::string &neuropod_path); std::unique_ptr<ModelConfig> load_model_config(std::istream &input_stream); } // namespace neuropod
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcComplexPropertyTemplate.h" #include "ifcpp/IFC4/include/IfcComplexPropertyTemplateTypeEnum.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/IfcPropertySetTemplate.h" #include "ifcpp/IFC4/include/IfcPropertyTemplate.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcComplexPropertyTemplate IfcComplexPropertyTemplate::IfcComplexPropertyTemplate() {} IfcComplexPropertyTemplate::IfcComplexPropertyTemplate( int id ) { m_entity_id = id; } IfcComplexPropertyTemplate::~IfcComplexPropertyTemplate() {} shared_ptr<BuildingObject> IfcComplexPropertyTemplate::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcComplexPropertyTemplate> copy_self( new IfcComplexPropertyTemplate() ); if( m_GlobalId ) { if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createBase64Uuid<wchar_t>().data() ) ); } else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_UsageName ) { copy_self->m_UsageName = dynamic_pointer_cast<IfcLabel>( m_UsageName->getDeepCopy(options) ); } if( m_TemplateType ) { copy_self->m_TemplateType = dynamic_pointer_cast<IfcComplexPropertyTemplateTypeEnum>( m_TemplateType->getDeepCopy(options) ); } for( size_t ii=0; ii<m_HasPropertyTemplates.size(); ++ii ) { auto item_ii = m_HasPropertyTemplates[ii]; if( item_ii ) { copy_self->m_HasPropertyTemplates.push_back( dynamic_pointer_cast<IfcPropertyTemplate>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcComplexPropertyTemplate::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCCOMPLEXPROPERTYTEMPLATE" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "*"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; } stream << ","; if( m_UsageName ) { m_UsageName->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_TemplateType ) { m_TemplateType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeEntityList( stream, m_HasPropertyTemplates ); stream << ");"; } void IfcComplexPropertyTemplate::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcComplexPropertyTemplate::toString() const { return L"IfcComplexPropertyTemplate"; } void IfcComplexPropertyTemplate::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 7 ){ std::stringstream err; err << "Wrong parameter count for entity IfcComplexPropertyTemplate, expecting 7, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::createObjectFromSTEP( args[2], map ); m_Description = IfcText::createObjectFromSTEP( args[3], map ); m_UsageName = IfcLabel::createObjectFromSTEP( args[4], map ); m_TemplateType = IfcComplexPropertyTemplateTypeEnum::createObjectFromSTEP( args[5], map ); readEntityReferenceList( args[6], m_HasPropertyTemplates, map ); } void IfcComplexPropertyTemplate::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) { IfcPropertyTemplate::getAttributes( vec_attributes ); vec_attributes.push_back( std::make_pair( "UsageName", m_UsageName ) ); vec_attributes.push_back( std::make_pair( "TemplateType", m_TemplateType ) ); if( m_HasPropertyTemplates.size() > 0 ) { shared_ptr<AttributeObjectVector> HasPropertyTemplates_vec_object( new AttributeObjectVector() ); std::copy( m_HasPropertyTemplates.begin(), m_HasPropertyTemplates.end(), std::back_inserter( HasPropertyTemplates_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "HasPropertyTemplates", HasPropertyTemplates_vec_object ) ); } } void IfcComplexPropertyTemplate::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) { IfcPropertyTemplate::getAttributesInverse( vec_attributes_inverse ); } void IfcComplexPropertyTemplate::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcPropertyTemplate::setInverseCounterparts( ptr_self_entity ); shared_ptr<IfcComplexPropertyTemplate> ptr_self = dynamic_pointer_cast<IfcComplexPropertyTemplate>( ptr_self_entity ); if( !ptr_self ) { throw BuildingException( "IfcComplexPropertyTemplate::setInverseCounterparts: type mismatch" ); } for( size_t i=0; i<m_HasPropertyTemplates.size(); ++i ) { if( m_HasPropertyTemplates[i] ) { m_HasPropertyTemplates[i]->m_PartOfComplexTemplate_inverse.push_back( ptr_self ); } } } void IfcComplexPropertyTemplate::unlinkFromInverseCounterparts() { IfcPropertyTemplate::unlinkFromInverseCounterparts(); for( size_t i=0; i<m_HasPropertyTemplates.size(); ++i ) { if( m_HasPropertyTemplates[i] ) { std::vector<weak_ptr<IfcComplexPropertyTemplate> >& PartOfComplexTemplate_inverse = m_HasPropertyTemplates[i]->m_PartOfComplexTemplate_inverse; for( auto it_PartOfComplexTemplate_inverse = PartOfComplexTemplate_inverse.begin(); it_PartOfComplexTemplate_inverse != PartOfComplexTemplate_inverse.end(); ) { weak_ptr<IfcComplexPropertyTemplate> self_candidate_weak = *it_PartOfComplexTemplate_inverse; if( self_candidate_weak.expired() ) { ++it_PartOfComplexTemplate_inverse; continue; } shared_ptr<IfcComplexPropertyTemplate> self_candidate( *it_PartOfComplexTemplate_inverse ); if( self_candidate.get() == this ) { it_PartOfComplexTemplate_inverse= PartOfComplexTemplate_inverse.erase( it_PartOfComplexTemplate_inverse ); } else { ++it_PartOfComplexTemplate_inverse; } } } } }
//---------------------------------------------------------------------- // Copyright 2004-2011 Synopsys, Inc. // Copyright 2010 Mentor Graphics Corporation // Copyright 2010-2011 Cadence Design Systems, Inc. // Copyright 2013-2014 NXP B.V. // All Rights Reserved Worldwide // // Licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in // compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in // writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See // the License for the specific language governing // permissions and limitations under the License. //---------------------------------------------------------------------- #include <systemc> #include <uvm> #include "tb_env.h" #include "tb_test.h" //---------------------------------------------------------------------- // This example demonstrates how to model a register containing // read-only fields and a register containing write-only fields // at the same physical address. //---------------------------------------------------------------------- int sc_main(int, char*[]) { tb_env* env; tb_test* test; env = new tb_env("env"); test = new tb_test("test"); uvm::uvm_root::get()->set_report_verbosity_level(uvm::UVM_FULL); test->set_report_verbosity_level(uvm::UVM_FULL); env->set_report_verbosity_level(uvm::UVM_FULL); uvm::uvm_report_server::get_server()->set_max_quit_count(10); uvm::run_test(); delete env; delete test; return 0; }
#include <bits/stdc++.h> using namespace std; #define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); typedef long long ll;typedef long double ld;typedef pair<int,int> pii; #define F first #define S second #define PB push_back #define MP make_pair const ll mod = 1e9+7, N = 2e6+7, M = 2e6+7, INF = INT_MAX/10; ll powe(ll x, ll y){ x = x%mod, y=y%(mod-1);ll ans = 1;while(y>0){if (y&1){ans = (1ll * x * ans)%mod;}y>>=1;x = (1ll * x * x)%mod;}return ans;} //Sum Of the elements of an array void input_of_array(int arr[],int n) { for (int i =0;i<n;i++) { cin>>arr[i]; } } void rotating_the_array(int arr[], int n) { int m; cin>>m; for(int i=0;i<m;i++) { int temp =arr[0]; for(int j=0;j<n;j++) { if(j==n-1) { arr[j]=temp; } else { arr[j]=arr[j+1]; } } } for(int i=0;i<n;i++) cout<<arr[i]<<" "; cout<<endl; } void solve(){ int arr[100]; int n; cin>>n; input_of_array(arr,n); rotating_the_array(arr,n); } signed main(){ fast; int t = 1; while(t--){ solve(); } return 0; }
// Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/recentrequeststablemodel.h> #include <qt/bitcoinunits.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <algorithm> #include <clientversion.h> #include <streams.h> RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) : QAbstractTableModel(parent), walletModel(parent) { nReceiveRequestsMaxId = 0; // Load entries from wallet std::vector<std::string> vReceiveRequests; parent->loadReceiveRequests(vReceiveRequests); for (const std::string& request : vReceiveRequests) addNewRequest(request); /* These columns must match the indices in the ColumnIndex enumeration */ columns << tr("Date") << tr("Label") << tr("Message") << getAmountTitle(); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } RecentRequestsTableModel::~RecentRequestsTableModel() { /* Intentionally left empty */ } int RecentRequestsTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return list.length(); } int RecentRequestsTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant RecentRequestsTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid() || index.row() >= list.length()) return QVariant(); if(role == Qt::DisplayRole || role == Qt::EditRole) { const RecentRequestEntry *rec = &list[index.row()]; switch(index.column()) { case Date: return GUIUtil::dateTimeStr(rec->date); case Label: if(rec->recipient.label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->recipient.label; } case Message: if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole) { return tr("(no message)"); } else { return rec->recipient.message; } case Amount: if (rec->recipient.amount == 0 && role == Qt::DisplayRole) return tr("(no amount requested)"); else if (role == Qt::EditRole) return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount, false, BitcoinUnits::separatorNever); else return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount); } } else if (role == Qt::TextAlignmentRole) { if (index.column() == Amount) return (int)(Qt::AlignRight|Qt::AlignVCenter); } return QVariant(); } bool RecentRequestsTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { return true; } QVariant RecentRequestsTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void RecentRequestsTableModel::updateAmountColumnTitle() { columns[Amount] = getAmountTitle(); Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } /** Gets title for amount column including current display unit if optionsModel reference available. */ QString RecentRequestsTableModel::getAmountTitle() { return (this->walletModel->getOptionsModel() != nullptr) ? tr("Requested") + " ("+BitcoinUnits::shortName(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : ""; } QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); return createIndex(row, column); } bool RecentRequestsTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); if(count > 0 && row >= 0 && (row+count) <= list.size()) { for (int i = 0; i < count; ++i) { const RecentRequestEntry* rec = &list[row+i]; if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, "")) return false; } beginRemoveRows(parent, row, row + count - 1); list.erase(list.begin() + row, list.begin() + row + count); endRemoveRows(); return true; } else { return false; } } Qt::ItemFlags RecentRequestsTableModel::flags(const QModelIndex &index) const { return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } // called when adding a request from the GUI void RecentRequestsTableModel::addNewRequest(const SendCoinsRecipient &recipient) { RecentRequestEntry newEntry; newEntry.id = ++nReceiveRequestsMaxId; newEntry.date = QDateTime::currentDateTime(); newEntry.recipient = recipient; CDataStream ss(SER_DISK, CLIENT_VERSION); ss << newEntry; if (!walletModel->saveReceiveRequest(recipient.address.toStdString(), newEntry.id, ss.str())) return; addNewRequest(newEntry); } // called from ctor when loading from wallet void RecentRequestsTableModel::addNewRequest(const std::string &recipient) { std::vector<char> data(recipient.begin(), recipient.end()); CDataStream ss(data, SER_DISK, CLIENT_VERSION); RecentRequestEntry entry; ss >> entry; if (entry.id == 0) // should not happen return; if (entry.id > nReceiveRequestsMaxId) nReceiveRequestsMaxId = entry.id; addNewRequest(entry); } // actually add to table in GUI void RecentRequestsTableModel::addNewRequest(RecentRequestEntry &recipient) { beginInsertRows(QModelIndex(), 0, 0); list.prepend(recipient); endInsertRows(); } void RecentRequestsTableModel::sort(int column, Qt::SortOrder order) { std::sort(list.begin(), list.end(), RecentRequestEntryLessThan(column, order)); Q_EMIT dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex())); } void RecentRequestsTableModel::updateDisplayUnit() { updateAmountColumnTitle(); } bool RecentRequestEntryLessThan::operator()(RecentRequestEntry &left, RecentRequestEntry &right) const { RecentRequestEntry *pLeft = &left; RecentRequestEntry *pRight = &right; if (order == Qt::DescendingOrder) std::swap(pLeft, pRight); switch(column) { case RecentRequestsTableModel::Date: return pLeft->date.toTime_t() < pRight->date.toTime_t(); case RecentRequestsTableModel::Label: return pLeft->recipient.label < pRight->recipient.label; case RecentRequestsTableModel::Message: return pLeft->recipient.message < pRight->recipient.message; case RecentRequestsTableModel::Amount: return pLeft->recipient.amount < pRight->recipient.amount; default: return pLeft->id < pRight->id; } }
//HEADER_GOES_HERE #include "../types.h" int invflag; void *pInvCels; int drawsbarflag; // idb int sgdwLastTime; // check name const InvXY InvRect[73] = { { 452, 31 }, // helmet { 480, 31 }, // helmet { 452, 59 }, // helmet { 480, 59 }, // helmet { 365, 205 }, // left ring { 567, 205 }, // right ring { 524, 59 }, // amulet { 337, 104 }, // left hand { 366, 104 }, // left hand { 337, 132 }, // left hand { 366, 132 }, // left hand { 337, 160 }, // left hand { 366, 160 }, // left hand { 567, 104 }, // right hand { 596, 104 }, // right hand { 567, 132 }, // right hand { 596, 132 }, // right hand { 567, 160 }, // right hand { 596, 160 }, // right hand { 452, 104 }, // chest { 480, 104 }, // chest { 452, 132 }, // chest { 480, 132 }, // chest { 452, 160 }, // chest { 480, 160 }, // chest { 337, 250 }, // inv row 1 { 366, 250 }, // inv row 1 { 394, 250 }, // inv row 1 { 423, 250 }, // inv row 1 { 451, 250 }, // inv row 1 { 480, 250 }, // inv row 1 { 509, 250 }, // inv row 1 { 538, 250 }, // inv row 1 { 567, 250 }, // inv row 1 { 596, 250 }, // inv row 1 { 337, 279 }, // inv row 2 { 366, 279 }, // inv row 2 { 394, 279 }, // inv row 2 { 423, 279 }, // inv row 2 { 451, 279 }, // inv row 2 { 480, 279 }, // inv row 2 { 509, 279 }, // inv row 2 { 538, 279 }, // inv row 2 { 567, 279 }, // inv row 2 { 596, 279 }, // inv row 2 { 337, 308 }, // inv row 3 { 366, 308 }, // inv row 3 { 394, 308 }, // inv row 3 { 423, 308 }, // inv row 3 { 451, 308 }, // inv row 3 { 480, 308 }, // inv row 3 { 509, 308 }, // inv row 3 { 538, 308 }, // inv row 3 { 567, 308 }, // inv row 3 { 596, 308 }, // inv row 3 { 337, 336 }, // inv row 4 { 366, 336 }, // inv row 4 { 394, 336 }, // inv row 4 { 423, 336 }, // inv row 4 { 451, 336 }, // inv row 4 { 480, 336 }, // inv row 4 { 509, 336 }, // inv row 4 { 538, 336 }, // inv row 4 { 567, 336 }, // inv row 4 { 596, 336 }, // inv row 4 { 205, 385 }, // belt { 234, 385 }, // belt { 263, 385 }, // belt { 292, 385 }, // belt { 321, 385 }, // belt { 350, 385 }, // belt { 379, 385 }, // belt { 408, 385 } // belt }; /* data */ int AP2x2Tbl[10] = { 8, 28, 6, 26, 4, 24, 2, 22, 0, 20 }; // weak void __cdecl FreeInvGFX() { void *invCels = pInvCels; pInvCels = NULL; mem_free_dbg(invCels); } void __cdecl InitInv() { if ( plr[myplr]._pClass == PC_WARRIOR ) { pInvCels = LoadFileInMem("Data\\Inv\\Inv.CEL", 0); } else if ( plr[myplr]._pClass == PC_ROGUE ) { pInvCels = LoadFileInMem("Data\\Inv\\Inv_rog.CEL", 0); } else if ( plr[myplr]._pClass == PC_SORCERER ) { pInvCels = LoadFileInMem("Data\\Inv\\Inv_Sor.CEL", 0); } invflag = 0; drawsbarflag = 0; } void __fastcall InvDrawSlotBack(int X, int Y, int W, int H) { unsigned char *v4; // edi int v5; // edx int v6; // ecx unsigned char v7; // al unsigned char v8; // al v4 = (unsigned char *)gpBuffer + screen_y_times_768[Y] + X; v5 = (unsigned short)H; do { v6 = (unsigned short)W; do { v7 = *v4; if ( *v4 < 0xB0u ) goto LABEL_9; if ( v7 > 0xBFu ) { if ( v7 < 0xF0u ) goto LABEL_9; v8 = v7 - 80; } else { v8 = v7 - 16; } *v4 = v8; LABEL_9: ++v4; --v6; } while ( v6 ); v4 = &v4[-(unsigned short)W - 768]; --v5; } while ( v5 ); } void __cdecl DrawInv() { BOOL invtest[40]; CelDecodeOnly(384, 511, pInvCels, 1, 320); if ( plr[myplr].InvBody[INVLOC_HEAD]._itype != ITYPE_NONE ) { InvDrawSlotBack(517, 219, 2 * INV_SLOT_SIZE_PX, 2 * INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_HEAD]._iCurs + 12; int frame_width = InvItemWidth[frame]; if ( pcursinvitem == INVITEM_HEAD ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_HEAD]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_HEAD]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, 517, 219, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_HEAD]._iStatFlag ) { CelDrawHdrOnly(517, 219, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(517, 219, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._itype != ITYPE_NONE ) { InvDrawSlotBack(432, 365, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_RING_LEFT]._iCurs + 12; int frame_width = InvItemWidth[frame]; if ( pcursinvitem == INVITEM_RING_LEFT ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_RING_LEFT]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, 432, 365, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._iStatFlag ) { CelDrawHdrOnly(432, 365, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(432, 365, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._itype != ITYPE_NONE ) { InvDrawSlotBack(633, 365, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_RING_RIGHT]._iCurs + 12; int frame_width = InvItemWidth[frame]; if ( pcursinvitem == INVITEM_RING_RIGHT ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_RING_RIGHT]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, 633, 365, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._iStatFlag ) { CelDrawHdrOnly(633, 365, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(633, 365, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } if ( plr[myplr].InvBody[INVLOC_AMULET]._itype != ITYPE_NONE ) { InvDrawSlotBack(589, 220, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_AMULET]._iCurs + 12; int frame_width = InvItemWidth[frame]; if ( pcursinvitem == INVITEM_AMULET ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_AMULET]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_AMULET]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, 589, 220, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_AMULET]._iStatFlag ) { CelDrawHdrOnly(589, 220, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(589, 220, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._itype != ITYPE_NONE ) { InvDrawSlotBack(401, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_HAND_LEFT]._iCurs + 12; int frame_width = InvItemWidth[frame]; // calc item offsets for weapons smaller than 2x3 slots int screen_x = frame_width == INV_SLOT_SIZE_PX ? 415 : 401; int screen_y = InvItemHeight[frame] == (3 * INV_SLOT_SIZE_PX) ? 320 : 306; if ( pcursinvitem == INVITEM_HAND_LEFT ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_HAND_LEFT]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iStatFlag ) { CelDrawHdrOnly(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8, 1); } if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iLoc == ILOC_TWOHAND ) { InvDrawSlotBack(631, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX); light_table_index = 0; cel_transparency_active = 1; CelDecodeHdrLightTrans( frame_width == INV_SLOT_SIZE_PX ? &gpBuffer->row[160].pixels[581] : &gpBuffer->row[160].pixels[567], (char *)pCursCels, frame, frame_width, 0, 8); cel_transparency_active = 0; } } if ( plr[myplr].InvBody[INVLOC_HAND_RIGHT]._itype != ITYPE_NONE ) { InvDrawSlotBack(631, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iCurs + 12; int frame_width = InvItemWidth[frame]; // calc item offsets for weapons smaller than 2x3 slots int screen_x = frame_width == INV_SLOT_SIZE_PX ? 645 : 633; int screen_y = InvItemHeight[frame] == 3 * INV_SLOT_SIZE_PX ? 320 : 306; if ( pcursinvitem == INVITEM_HAND_RIGHT ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iStatFlag ) { CelDrawHdrOnly(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } if ( plr[myplr].InvBody[INVLOC_CHEST]._itype != ITYPE_NONE ) { InvDrawSlotBack(517, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX); int frame = plr[myplr].InvBody[INVLOC_CHEST]._iCurs + 12; int frame_width = InvItemWidth[frame]; if ( pcursinvitem == INVITEM_CHEST ) { int colour = 197; if ( plr[myplr].InvBody[INVLOC_CHEST]._iMagical ) { colour = 181; } if ( !plr[myplr].InvBody[INVLOC_CHEST]._iStatFlag ) { colour = 229; } CelDecodeClr(colour, 517, 320, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvBody[INVLOC_CHEST]._iStatFlag ) { CelDrawHdrOnly(517, 320, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed(517, 320, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } for ( int i = 0; i < NUM_INV_GRID_ELEM; i++ ) { if ( plr[myplr].InvGrid[i] != 0 ) { InvDrawSlotBack( InvRect[i + SLOTXY_INV_FIRST].X + 64, InvRect[i + SLOTXY_INV_FIRST].Y + 159, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX); } } for ( int j = 0; j < NUM_INV_GRID_ELEM; j++ ) { if ( plr[myplr].InvGrid[j] > 0 ) // first slot of an item { int ii = plr[myplr].InvGrid[j] - 1; invtest[j] = TRUE; int frame = plr[myplr].InvList[ii]._iCurs + 12; int frame_width = InvItemWidth[frame]; if ( pcursinvitem == ii + INVITEM_INV_FIRST ) { int colour = 197; if ( plr[myplr].InvList[ii]._iMagical ) { colour = 181; } if ( !plr[myplr].InvList[ii]._iStatFlag ) { colour = 229; } CelDecodeClr( colour, InvRect[j + SLOTXY_INV_FIRST].X + 64, InvRect[j + SLOTXY_INV_FIRST].Y + 159, (char *)pCursCels, frame, frame_width, 0, 8); } if ( plr[myplr].InvList[ii]._iStatFlag ) { CelDrawHdrOnly( InvRect[j + SLOTXY_INV_FIRST].X + 64, InvRect[j + SLOTXY_INV_FIRST].Y + 159, (char *)pCursCels, frame, frame_width, 0, 8); } else { CelDrawHdrLightRed( InvRect[j + SLOTXY_INV_FIRST].X + 64, InvRect[j + SLOTXY_INV_FIRST].Y + 159, (char *)pCursCels, frame, frame_width, 0, 8, 1); } } } } // 4B8CB8: using guessed type char pcursinvitem; // 69BEF8: using guessed type int light_table_index; // 69CF94: using guessed type int cel_transparency_active; // 41B8C4: using guessed type int var_A0[40]; void __cdecl DrawInvBelt() { int v0; // ebx signed int v1; // esi int v2; // ecx int v3; // eax int v4; // edi char v5; // cl int v6; // edx bool v7; // zf int v8; // ecx int v9; // eax unsigned char v10; // edx signed int v11; // [esp+4h] [ebp-Ch] int frame_width; // [esp+8h] [ebp-8h] int v13; // [esp+Ch] [ebp-4h] v0 = 0; if ( !talkflag ) { DrawPanelBox(205, 21, 0xE8u, 0x1Cu, 269, 517); v11 = 0; v13 = 0; do { if ( *(int *)((char *)&plr[myplr].SpdList[0]._itype + v0) != -1 ) { v1 = v11; InvDrawSlotBack(InvRect[v11 + 65].X + 64, InvRect[v11 + 65].Y + 159, 28, 28); v2 = myplr; v3 = v0 + 21720 * myplr; v4 = *(int *)((char *)&plr[0].SpdList[0]._iCurs + v3) + 12; frame_width = InvItemWidth[v4]; if ( pcursinvitem == v11 + 47 ) { v5 = -59; if ( *(&plr[0].SpdList[0]._iMagical + v3) ) v5 = -75; if ( !*(int *)((char *)&plr[0].SpdList[0]._iStatFlag + v3) ) v5 = -27; CelDecodeClr( v5, InvRect[v1 + 65].X + 64, InvRect[v1 + 65].Y + 159, (char *)pCursCels, v4, frame_width, 0, 8); v2 = myplr; } v0 = v13; v6 = InvRect[v1 + 65].Y + 159; v7 = *(int *)((char *)&plr[v2].SpdList[0]._iStatFlag + v13) == 0; v8 = InvRect[v1 + 65].X; if ( v7 ) CelDrawHdrLightRed(v8 + 64, v6, (char *)pCursCels, v4, frame_width, 0, 8, 1); else CelDrawHdrOnly(v8 + 64, v6, (char *)pCursCels, v4, frame_width, 0, 8); v9 = v13 + 21720 * myplr; if ( AllItemsList[*(int *)((char *)&plr[0].SpdList[0].IDidx + v9)].iUsable && *(int *)((char *)&plr[0].SpdList[0]._iStatFlag + v9) && *(int *)((char *)&plr[0].SpdList[0]._itype + v9) != 11 ) { v10 = fontframe[fontidx[(unsigned char)(v11 + 49)]]; CPrintString( screen_y_times_768[InvRect[v1 + 65].Y + 159] - fontkern[v10] + InvRect[v1 + 65].X + 92, v10, 0); } } ++v11; v0 += 368; v13 = v0; } while ( v11 < 8 ); } } // 4B8960: using guessed type int talkflag; // 4B8CB8: using guessed type char pcursinvitem; int __fastcall AutoPlace(int pnum, int ii, int sx, int sy, int saveflag) { __int64 v5; // rax int v6; // ebx signed int v7; // edx signed int v8; // eax signed int v9; // esi int j; // edi int v11; // eax signed int v12; // esi signed int v13; // ecx int v14; // edi char *v15; // ecx char v16; // dl signed int v18; // [esp+Ch] [ebp-Ch] int p; // [esp+10h] [ebp-8h] int v20; // [esp+14h] [ebp-4h] int i; // [esp+14h] [ebp-4h] p = pnum; v5 = ii; v6 = 1; v18 = v5 % 10; v7 = 10 * (unsigned __int64)(v5 / 10); v8 = v7; if ( v7 < 0 ) v8 = 0; v20 = 0; if ( sy <= 0 ) { LABEL_16: if ( saveflag ) { v11 = pnum; qmemcpy( &plr[pnum].InvList[plr[pnum]._pNumInv], &plr[pnum].HoldItem, sizeof(plr[pnum].InvList[plr[pnum]._pNumInv])); ++plr[v11]._pNumInv; v12 = v7; if ( v7 < 0 ) v12 = 0; for ( i = 0; i < sy; ++i ) { v13 = v18; if ( v18 < 0 ) v13 = 0; v14 = 0; if ( sx > 0 ) { v15 = &plr[v11].InvGrid[v13 + v12]; do { if ( v14 || i != sy - 1 ) v16 = -_LOBYTE(plr[v11]._pNumInv); else v16 = plr[v11]._pNumInv; *v15++ = v16; ++v14; } while ( v14 < sx ); } v12 += 10; } CalcPlrScrolls(p); } } else { while ( v6 ) { if ( v8 >= 40 ) v6 = 0; v9 = v18; if ( v18 < 0 ) v9 = 0; for ( j = 0; j < sx; ++j ) { if ( !v6 ) break; v6 = 0; if ( v9 < 10 ) _LOBYTE(v6) = plr[pnum].InvGrid[v9 + v8] == 0; ++v9; } v8 += 10; if ( ++v20 >= sy ) { if ( !v6 ) return v6; goto LABEL_16; } } } return v6; } int __fastcall SpecialAutoPlace(int pnum, int ii, int sx, int sy, int saveflag) { __int64 v5; // rax int v6; // ebx signed int v7; // edx signed int v8; // eax signed int v9; // esi int j; // edi signed int v11; // ecx int *v12; // eax int v13; // eax signed int v14; // esi signed int v15; // ecx int v16; // edi char *v17; // ecx char v18; // dl signed int v20; // [esp+Ch] [ebp-Ch] int p; // [esp+10h] [ebp-8h] int v22; // [esp+14h] [ebp-4h] int i; // [esp+14h] [ebp-4h] p = pnum; v5 = ii; v6 = 1; v20 = v5 % 10; v7 = 10 * (unsigned __int64)(v5 / 10); v8 = v7; if ( v7 < 0 ) v8 = 0; v22 = 0; if ( sy <= 0 ) { LABEL_25: if ( saveflag ) { v13 = p; qmemcpy(&plr[p].InvList[plr[p]._pNumInv], &plr[p].HoldItem, sizeof(plr[p].InvList[plr[p]._pNumInv])); ++plr[v13]._pNumInv; v14 = v7; if ( v7 < 0 ) v14 = 0; for ( i = 0; i < sy; ++i ) { v15 = v20; if ( v20 < 0 ) v15 = 0; v16 = 0; if ( sx > 0 ) { v17 = &plr[v13].InvGrid[v15 + v14]; do { if ( v16 || i != sy - 1 ) v18 = -_LOBYTE(plr[v13]._pNumInv); else v18 = plr[v13]._pNumInv; *v17++ = v18; ++v16; } while ( v16 < sx ); } v14 += 10; } CalcPlrScrolls(p); } return v6; } while ( v6 ) { if ( v8 >= 40 ) v6 = 0; v9 = v20; if ( v20 < 0 ) v9 = 0; for ( j = 0; j < sx; ++j ) { if ( !v6 ) break; v6 = 0; if ( v9 < 10 ) _LOBYTE(v6) = plr[pnum].InvGrid[v9 + v8] == 0; ++v9; } v8 += 10; if ( ++v22 >= sy ) { if ( v6 ) goto LABEL_25; break; } } if ( sx <= 1 && sy <= 1 ) { v11 = 0; v12 = &plr[p].SpdList[0]._itype; while ( *v12 != -1 ) { ++v11; v12 += 92; if ( v11 >= 8 ) goto LABEL_24; } v6 = 1; goto LABEL_25; } v6 = 0; LABEL_24: if ( v6 ) goto LABEL_25; return v6; } int __fastcall GoldAutoPlace(int pnum) { int v1; // ebp int v2; // edi int v3; // ecx int *v4; // esi int v5; // eax int v6; // edi int *v7; // esi int v8; // eax signed int v9; // ebx char *v10; // edx int v11; // eax int v12; // ecx int pnuma; // [esp+10h] [ebp-4h] pnuma = pnum; v1 = pnum; v2 = 0; v3 = 0; if ( plr[v1]._pNumInv <= 0 ) { LABEL_14: v6 = 0; if ( plr[v1]._pNumInv <= 0 ) { LABEL_28: v9 = 39; do { if ( v3 ) break; v10 = &plr[0].InvGrid[10 * (v9 / 10) + v1 * 21720 + v9 % 10]; if ( !*v10 ) { v11 = v1 * 21720 + 368 * plr[v1]._pNumInv; qmemcpy((char *)plr[0].InvList + v11, &plr[v1].HoldItem, 0x170u); ++plr[v1]._pNumInv; *v10 = plr[v1]._pNumInv; v12 = plr[v1].HoldItem._ivalue; if ( v12 < 2500 ) { if ( v12 > 1000 ) *(int *)((char *)&plr[0].InvList[0]._iCurs + v11) = 5; else *(int *)((char *)&plr[0].InvList[0]._iCurs + v11) = 4; } else { *(int *)((char *)&plr[0].InvList[0]._iCurs + v11) = 6; } plr[v1]._pGold = CalculateGold(pnuma); v3 = 1; } --v9; } while ( v9 >= 0 ); } else { v7 = &plr[v1].InvList[0]._ivalue; while ( !v3 ) { if ( *(v7 - 47) == 11 && *v7 < 5000 ) { v8 = plr[v1].HoldItem._ivalue + *v7; if ( v8 <= 5000 ) { *v7 = v8; if ( v8 < 2500 ) { if ( v8 > 1000 ) *(v7 - 1) = 5; else *(v7 - 1) = 4; } else { *(v7 - 1) = 6; } plr[v1]._pGold = CalculateGold(pnuma); v3 = 1; } } ++v6; v7 += 92; if ( v6 >= plr[v1]._pNumInv ) { if ( v3 ) return v3; goto LABEL_28; } } } } else { v4 = &plr[v1].InvList[0]._ivalue; while ( !v3 ) { if ( *(v4 - 47) == 11 ) { v5 = *v4 + plr[v1].HoldItem._ivalue; if ( v5 <= 5000 ) { *v4 = v5; if ( v5 < 2500 ) { if ( v5 > 1000 ) *(v4 - 1) = 5; else *(v4 - 1) = 4; } else { *(v4 - 1) = 6; } plr[v1]._pGold = CalculateGold(pnuma); v3 = 1; } } ++v2; v4 += 92; if ( v2 >= plr[v1]._pNumInv ) { if ( v3 ) return v3; goto LABEL_14; } } } return v3; } int __fastcall WeaponAutoPlace(int pnum) { int v1; // edi int v2; // eax int v3; // ecx ItemStruct *v4; // esi ItemStruct *v5; // edi int result; // eax v1 = pnum; if ( plr[pnum].HoldItem._iLoc == ILOC_TWOHAND ) { if ( plr[v1].InvBody[4]._itype != -1 || plr[v1].InvBody[5]._itype != -1 ) return 0; LABEL_12: NetSendCmdChItem(1u, 4u); v4 = &plr[v1].HoldItem; v5 = &plr[v1].InvBody[4]; goto LABEL_13; } v2 = plr[v1].InvBody[4]._itype; if ( v2 != -1 && plr[v1].InvBody[4]._iClass == 1 ) return 0; v3 = plr[v1].InvBody[5]._itype; if ( v3 != -1 && plr[v1].InvBody[5]._iClass == 1 ) return 0; if ( v2 == -1 ) goto LABEL_12; if ( v3 == -1 && plr[v1].InvBody[4]._iLoc != ILOC_TWOHAND ) { NetSendCmdChItem(1u, 5u); v4 = &plr[v1].HoldItem; v5 = &plr[v1].InvBody[5]; LABEL_13: result = 1; qmemcpy(v5, v4, sizeof(ItemStruct)); return result; } return 0; } int __fastcall SwapItem(ItemStruct *a, ItemStruct *b) { int v2; // eax ItemStruct h; // [esp+8h] [ebp-170h] qmemcpy(&h, a, sizeof(h)); v2 = h._iCurs; qmemcpy(a, b, sizeof(ItemStruct)); qmemcpy(b, &h, sizeof(ItemStruct)); return v2 + 12; } void __fastcall CheckInvPaste(int pnum, int mx, int my) { int v3; // ebx int v4; // edi int v5; // eax int v6; // esi signed int v7; // edi int v8; // edx int v9; // edx signed int v10; // edi char v11; // al signed int v12; // ecx int v13; // eax int v14; // eax char *v15; // edi int v16; // esi int v17; // ecx int v18; // edx char v19; // al int v20; // ecx int v21; // esi ItemStruct *v22; // edi ItemStruct *v23; // ecx int v24; // eax int v25; // eax int v26; // edx ItemStruct *v27; // esi int v28; // eax int v29; // ecx int v30; // esi int v31; // eax int v32; // eax int v33; // ecx int v34; // eax int v35; // ecx char *v36; // eax int v37; // edx int v38; // ecx int v39; // edi int v40; // esi int v41; // ebx int v42; // edx int v43; // eax int v44; // eax signed int v45; // ecx int v46; // edx char *v47; // eax int v48; // edi int v49; // eax int v50; // ecx char *v51; // esi char v52; // cl int v53; // ecx int v54; // eax int v55; // edi int v56; // edx int v57; // esi int v58; // ebx int v59; // eax int v60; // esi ItemStruct tempitem; // [esp+Ch] [ebp-190h] int v62; // [esp+17Ch] [ebp-20h] int p; // [esp+180h] [ebp-1Ch] int v64; // [esp+184h] [ebp-18h] int v65; // [esp+188h] [ebp-14h] int v66; // [esp+18Ch] [ebp-10h] int v67; // [esp+190h] [ebp-Ch] int v68; // [esp+194h] [ebp-8h] int v69; // [esp+198h] [ebp-4h] int cursor_id; // [esp+1A4h] [ebp+8h] int cursor_ida; // [esp+1A4h] [ebp+8h] p = pnum; v3 = pnum; v4 = mx; SetICursor(plr[pnum].HoldItem._iCurs + 12); v5 = my + (icursH >> 1); v6 = v4 + (icursW >> 1); v64 = icursW28; v7 = 0; v67 = icursH28; v68 = 0; do { if ( v7 ) goto LABEL_18; v8 = InvRect[v68].X; if ( v6 >= v8 && v6 < v8 + 28 ) { v9 = InvRect[v68].Y; if ( v5 >= v9 - 29 && v5 < v9 ) { v7 = 1; --v68; } } if ( v68 != 24 ) goto LABEL_13; if ( !(v64 & 1) ) v6 -= 14; if ( !(v67 & 1) ) { v5 -= 14; LABEL_13: if ( v68 == 64 && !(v67 & 1) ) v5 += 14; } ++v68; } while ( (unsigned int)v68 < 0x49 ); if ( !v7 ) return; LABEL_18: v10 = v68; v69 = ILOC_UNEQUIPABLE; if ( v68 >= 0 && v68 <= ILOC_ARMOR ) v69 = ILOC_HELM; if ( v68 >= ILOC_HELM && v68 <= ILOC_RING ) v69 = ILOC_RING; if ( v68 == ILOC_AMULET ) v69 = ILOC_AMULET; if ( v68 >= ILOC_UNEQUIPABLE && v68 <= 18 ) v69 = ILOC_ONEHAND; if ( v68 >= 19 && v68 <= 24 ) v69 = ILOC_ARMOR; if ( v68 >= 65 && v68 <= 72 ) v69 = ILOC_BELT; v11 = plr[v3].HoldItem._iLoc; v12 = 0; if ( (char)v11 == v69 ) v12 = 1; if ( v69 == 1 && v11 == ILOC_TWOHAND ) { v69 = ILOC_TWOHAND; v12 = 1; } if ( v11 != 7 || v69 != ILOC_BELT ) { LABEL_50: if ( v69 != ILOC_UNEQUIPABLE ) goto LABEL_81; v66 = 0; cursor_id = 1; v13 = (v68 - 25) / 10; if ( plr[v3].HoldItem._itype == ITYPE_GOLD ) { _LOBYTE(v13) = plr[0].InvGrid[10 * v13 + v3 * 21720 + (v68 - 25) % 10]; if ( !(_BYTE)v13 ) goto LABEL_93; v13 = (char)v13; if ( (char)v13 <= 0 ) { v13 = -v13; } else if ( *(int *)((char *)&plr[0].InvBody[v13 + 6]._itype + v3 * 21720) == ITYPE_GOLD ) { goto LABEL_93; } v66 = v13; LABEL_93: v21 = p; if ( p == myplr ) { PlaySFX(ItemInvSnds[ItemCAnimTbl[plr[v3].HoldItem._iCurs]]); v10 = v68; } cursor_ida = 1; switch ( v69 ) { case ILOC_ONEHAND: if ( v10 > 12 ) { if ( plr[v3].InvBody[5]._itype == ITYPE_NONE ) { v25 = plr[v3].InvBody[4]._itype; if ( v25 == ITYPE_NONE ) goto LABEL_232; if ( plr[v3].InvBody[4]._iLoc == ILOC_TWOHAND ) { NetSendCmdDelItem(0, 4u); NetSendCmdChItem(0, 5u); SwapItem(&plr[v3].InvBody[5], &plr[v3].InvBody[4]); v23 = &plr[v3].InvBody[5]; LABEL_99: v24 = SwapItem(v23, &plr[v3].HoldItem); LABEL_172: cursor_ida = v24; goto LABEL_226; } if ( v25 == ITYPE_NONE || plr[v3].InvBody[4]._iClass != plr[v3].HoldItem._iClass ) { LABEL_232: NetSendCmdChItem(0, 5u); v22 = &plr[v3].InvBody[5]; LABEL_158: qmemcpy(v22, &plr[v3].HoldItem, sizeof(ItemStruct)); goto LABEL_226; } } else if ( plr[v3].InvBody[4]._itype == ITYPE_NONE || plr[v3].InvBody[4]._iClass != plr[v3].HoldItem._iClass ) { goto LABEL_114; } } else { if ( plr[v3].InvBody[4]._itype == ITYPE_NONE ) { if ( plr[v3].InvBody[5]._itype != ITYPE_NONE && plr[v3].InvBody[5]._iClass == plr[v3].HoldItem._iClass ) { LABEL_114: NetSendCmdChItem(0, 5u); v23 = &plr[v3].InvBody[5]; goto LABEL_99; } NetSendCmdChItem(0, 4u); v22 = &plr[v3].InvBody[4]; goto LABEL_158; } if ( plr[v3].InvBody[5]._itype != ITYPE_NONE && plr[v3].InvBody[5]._iClass == plr[v3].HoldItem._iClass ) { goto LABEL_114; } } NetSendCmdChItem(0, 4u); v23 = &plr[v3].InvBody[4]; goto LABEL_99; case ILOC_TWOHAND: NetSendCmdDelItem(0, 5u); if ( plr[v3].InvBody[4]._itype == ITYPE_NONE ) goto LABEL_147; v26 = plr[v3].InvBody[5]._itype; if ( v26 == -1 ) goto LABEL_146; qmemcpy(&tempitem, &plr[v3].HoldItem, sizeof(tempitem)); v27 = &plr[v3].InvBody[5]; if ( v26 != 5 ) v27 = &plr[v3].InvBody[4]; v28 = p; qmemcpy(&plr[v3].HoldItem, v27, sizeof(plr[v3].HoldItem)); v29 = plr[v3].HoldItem._iCurs + 12; if ( v28 == myplr ) SetCursor(v29); else SetICursor(v29); v67 = 0; v30 = 0; do { if ( v67 ) break; v31 = AutoPlace(p, v30++, icursW28, icursH28, 1); v67 = v31; } while ( v30 < 40 ); v32 = p; qmemcpy(&plr[v3].HoldItem, &tempitem, sizeof(plr[v3].HoldItem)); v33 = plr[v3].HoldItem._iCurs + 12; if ( v32 == myplr ) SetCursor(v33); else SetICursor(v33); if ( !v67 ) return; if ( plr[v3].InvBody[5]._itype == ITYPE_SHIELD ) plr[v3].InvBody[5]._itype = ITYPE_NONE; else plr[v3].InvBody[4]._itype = ITYPE_NONE; LABEL_146: if ( plr[v3].InvBody[4]._itype != ITYPE_NONE ) goto LABEL_149; LABEL_147: if ( plr[v3].InvBody[5]._itype == ITYPE_NONE ) { NetSendCmdChItem(0, 4u); qmemcpy(&plr[v3].InvBody[4], &plr[v3].HoldItem, sizeof(plr[v3].InvBody[4])); } else { LABEL_149: NetSendCmdChItem(0, 4u); if ( plr[v3].InvBody[4]._itype == ITYPE_NONE ) SwapItem(&plr[v3].InvBody[4], &plr[v3].InvBody[5]); cursor_ida = SwapItem(&plr[v3].InvBody[4], &plr[v3].HoldItem); } if ( plr[v3].InvBody[4]._itype == ITYPE_STAFF ) { v34 = plr[v3].InvBody[4]._iSpell; if ( v34 ) { if ( plr[v3].InvBody[4]._iCharges > 0 ) { plr[v3]._pRSpell = v34; _LOBYTE(plr[v3]._pRSplType) = 3; drawpanflag = 255; } } } goto LABEL_226; case ILOC_ARMOR: NetSendCmdChItem(0, 6u); if ( plr[v3].InvBody[6]._itype == ITYPE_NONE ) { v22 = &plr[v3].InvBody[6]; goto LABEL_158; } v23 = &plr[v3].InvBody[6]; goto LABEL_99; case ILOC_HELM: NetSendCmdChItem(0, 0); if ( plr[v3].InvBody[0]._itype == ITYPE_NONE ) { v22 = plr[v3].InvBody; goto LABEL_158; } v23 = plr[v3].InvBody; goto LABEL_99; case ILOC_RING: if ( v10 == 4 ) { NetSendCmdChItem(0, 1u); if ( plr[v3].InvBody[1]._itype == ITYPE_NONE ) { v22 = &plr[v3].InvBody[1]; goto LABEL_158; } v23 = &plr[v3].InvBody[1]; } else { NetSendCmdChItem(0, 2u); if ( plr[v3].InvBody[2]._itype == ITYPE_NONE ) { v22 = &plr[v3].InvBody[2]; goto LABEL_158; } v23 = &plr[v3].InvBody[2]; } goto LABEL_99; case ILOC_AMULET: NetSendCmdChItem(0, 3u); if ( plr[v3].InvBody[3]._itype == ITYPE_NONE ) { v22 = &plr[v3].InvBody[3]; goto LABEL_158; } v23 = &plr[v3].InvBody[3]; goto LABEL_99; case ILOC_UNEQUIPABLE: v35 = plr[v3].HoldItem._itype; if ( v35 == 11 ) { if ( !v66 ) { v36 = &plr[0].InvGrid[10 * ((v68 - 25) / 10) + v3 * 21720 + (v68 - 25) % 10]; if ( *v36 <= 0 ) { v42 = 368 * plr[v3]._pNumInv + v3 * 21720; qmemcpy((char *)plr[0].InvList + v42, &plr[v3].HoldItem, 0x170u); ++plr[v3]._pNumInv; *v36 = plr[v3]._pNumInv; v43 = plr[v3].HoldItem._ivalue; plr[v3]._pGold += v43; if ( v43 <= 5000 ) { if ( v43 < 2500 ) { if ( v43 > 1000 ) *(int *)((char *)&plr[0].InvList[0]._iCurs + v42) = 5; else *(int *)((char *)&plr[0].InvList[0]._iCurs + v42) = 4; } else { *(int *)((char *)&plr[0].InvList[0]._iCurs + v42) = 6; } } goto LABEL_226; } v37 = plr[v3].HoldItem._ivalue; v38 = 368 * (*v36 - 1) + v3 * 21720; v39 = *(int *)((char *)&plr[0].InvList[0]._ivalue + v38); v40 = v37 + v39; if ( v37 + v39 <= 5000 ) { *(int *)((char *)&plr[0].InvList[0]._ivalue + v38) = v40; plr[v3]._pGold += plr[v3].HoldItem._ivalue; if ( v40 < 2500 ) { if ( v40 > 1000 ) *(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 5; else *(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 4; } else { *(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 6; } goto LABEL_226; } plr[v3]._pGold += 5000 - v39; plr[v3].HoldItem._ivalue = v37 - (5000 - v39); *(int *)((char *)&plr[0].InvList[0]._ivalue + v38) = 5000; *(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 6; v41 = plr[v3].HoldItem._ivalue; if ( v41 >= 2500 ) { cursor_ida = 18; goto LABEL_226; } v24 = (v41 > 1000) + 16; goto LABEL_172; } } else if ( !v66 ) { qmemcpy((char *)&plr[0].InvList[plr[v3]._pNumInv++] + v3 * 21720, &plr[v3].HoldItem, 0x170u); v66 = plr[v3]._pNumInv; LABEL_191: v48 = v67; v49 = 10 * ((v68 - 25) / 10 - ((v67 - 1) >> 1)); if ( v49 < 0 ) v49 = 0; v65 = 0; if ( v67 > 0 ) { v69 = (v68 - 25) % 10 - ((v64 - 1) >> 1); do { v50 = v69; if ( v69 < 0 ) v50 = 0; v67 = 0; if ( v64 > 0 ) { v51 = &plr[v3].InvGrid[v50 + v49]; do { if ( v67 || v65 != v48 - 1 ) v52 = -(char)v66; else v52 = v66; *v51++ = v52; ++v67; } while ( v67 < v64 ); } v49 += 10; ++v65; } while ( v65 < v48 ); } goto LABEL_226; } v44 = v66 - 1; if ( v35 == 11 ) plr[v3]._pGold += plr[v3].HoldItem._ivalue; cursor_ida = SwapItem((ItemStruct *)((char *)&plr[0].InvList[v44] + v3 * 21720), &plr[v3].HoldItem); if ( plr[v3].HoldItem._itype == ITYPE_GOLD ) plr[v3]._pGold = CalculateGold(v21); v45 = 0; v46 = -v66; do { v47 = &plr[v3].InvGrid[v45]; if ( *v47 == v66 ) *v47 = 0; if ( *v47 == v46 ) *v47 = 0; ++v45; } while ( v45 < 40 ); goto LABEL_191; case ILOC_BELT: v53 = v3 * 21720 + 368 * (v68 - 65); if ( plr[v3].HoldItem._itype != ITYPE_GOLD ) { if ( *(int *)((char *)&plr[0].SpdList[0]._itype + v53) == ITYPE_NONE ) { qmemcpy((char *)plr[0].SpdList + v53, &plr[v3].HoldItem, 0x170u); } else { cursor_ida = SwapItem((ItemStruct *)((char *)plr[0].SpdList + v53), &plr[v3].HoldItem); if ( plr[v3].HoldItem._itype == ITYPE_GOLD ) plr[v3]._pGold = CalculateGold(p); } goto LABEL_225; } v54 = *(int *)((char *)&plr[0].SpdList[0]._itype + v53); if ( v54 != -1 ) { if ( v54 == 11 ) { v55 = *(int *)((char *)&plr[0].SpdList[0]._ivalue + v53); v56 = plr[v3].HoldItem._ivalue; v57 = v55 + v56; if ( v55 + v56 <= 5000 ) { *(int *)((char *)&plr[0].SpdList[0]._ivalue + v53) = v57; plr[v3]._pGold += plr[v3].HoldItem._ivalue; if ( v57 < 2500 ) { if ( v57 > 1000 ) *(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 5; else *(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 4; } else { *(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 6; } goto LABEL_225; } plr[v3]._pGold += 5000 - v55; plr[v3].HoldItem._ivalue = v56 - (5000 - v55); *(int *)((char *)&plr[0].SpdList[0]._ivalue + v53) = 5000; *(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 6; v58 = plr[v3].HoldItem._ivalue; if ( v58 >= 2500 ) { cursor_ida = 18; goto LABEL_225; } v59 = (v58 > 1000) + 16; } else { plr[v3]._pGold += plr[v3].HoldItem._ivalue; v59 = SwapItem((ItemStruct *)((char *)plr[0].SpdList + v53), &plr[v3].HoldItem); } cursor_ida = v59; goto LABEL_225; } qmemcpy((char *)plr[0].SpdList + v53, &plr[v3].HoldItem, 0x170u); plr[v3]._pGold += plr[v3].HoldItem._ivalue; LABEL_225: drawsbarflag = 1; LABEL_226: v60 = p; CalcPlrInv(p, 1u); if ( v60 == myplr ) { if ( cursor_ida == 1 ) SetCursorPos(MouseX + (cursW >> 1), MouseY + (cursH >> 1)); SetCursor(cursor_ida); } return; default: goto LABEL_226; } } v62 = (v68 - 25) % 10; v14 = 10 * (v13 - ((v67 - 1) >> 1)); if ( v14 < 0 ) v14 = 0; v65 = 0; if ( v67 <= 0 ) goto LABEL_93; v15 = &plr[v3].InvGrid[v14]; while ( 1 ) { if ( cursor_id == CURSOR_NONE ) return; if ( v14 >= 40 ) cursor_id = 0; v16 = v62 - ((v64 - 1) >> 1); if ( v16 < 0 ) v16 = 0; v17 = 0; if ( v64 > 0 ) break; LABEL_79: v14 += 10; v15 += 10; if ( ++v65 >= v67 ) { v12 = cursor_id; v10 = v68; goto LABEL_81; } } while ( 1 ) { if ( cursor_id == CURSOR_NONE ) goto LABEL_79; if ( v16 >= 10 ) goto LABEL_233; _LOBYTE(v18) = v15[v16]; if ( (_BYTE)v18 ) { v18 = (char)v18; if ( (v18 & 0x80u) != 0 ) v18 = -v18; if ( !v66 ) { v66 = v18; goto LABEL_78; } if ( v66 != v18 ) LABEL_233: cursor_id = 0; } LABEL_78: ++v16; if ( ++v17 >= v64 ) goto LABEL_79; } } if ( v64 == 1 && v67 == 1 ) { v12 = 1; if ( !AllItemsList[plr[v3].HoldItem.IDidx].iUsable ) v12 = 0; if ( !plr[v3].HoldItem._iStatFlag ) v12 = 0; if ( plr[v3].HoldItem._itype == ITYPE_GOLD ) { v12 = 0; goto LABEL_50; } } LABEL_81: if ( !v12 ) return; if ( v69 == ILOC_UNEQUIPABLE || v69 == ILOC_BELT || plr[v3].HoldItem._iStatFlag ) goto LABEL_92; v19 = plr[v3]._pClass; if ( !v19 ) { v20 = PS_WARR13; goto LABEL_89; } if ( v19 != 1 ) { if ( v19 != 2 ) return; PlaySFX(PS_MAGE13); v12 = 0; v10 = v68; LABEL_92: if ( !v12 ) return; goto LABEL_93; } v20 = PS_ROGUE13; LABEL_89: PlaySFX(v20); } // 4B8C9C: using guessed type int cursH; // 4B8CB4: using guessed type int icursH; // 4B8CBC: using guessed type int icursW; // 52571C: using guessed type int drawpanflag; void __fastcall CheckInvSwap(int pnum, BYTE bLoc, int idx, WORD wCI, int seed, BOOL bId) { RecreateItem(MAXITEMS, idx, wCI, seed, 0); PlayerStruct *p = &plr[pnum]; p->HoldItem = item[MAXITEMS]; if ( bId ) { p->HoldItem._iIdentified = TRUE; } if ( bLoc < NUM_INVLOC ) { p->InvBody[bLoc] = p->HoldItem; if ( bLoc == INVLOC_HAND_LEFT && p->HoldItem._iLoc == ILOC_TWOHAND ) { p->InvBody[INVLOC_HAND_RIGHT]._itype = ITYPE_NONE; } else if ( bLoc == INVLOC_HAND_RIGHT && p->HoldItem._iLoc == ILOC_TWOHAND ) { p->InvBody[INVLOC_HAND_LEFT]._itype = ITYPE_NONE; } } CalcPlrInv(pnum, TRUE); } void __fastcall CheckInvCut(int pnum, int mx, int my) { if ( plr[pnum]._pmode > PM_WALK3 ) { return; } if ( dropGoldFlag ) { dropGoldFlag = 0; dropGoldValue = 0; } int r; BOOL done = FALSE; // TODO: this loop is compiled differently (via InvRect pointers) for ( r = 0; (DWORD)r < NUM_XY_SLOTS && !done; r++ ) { // check which inventory rectangle the mouse is in, if any if ( mx >= InvRect[r].X && mx < InvRect[r].X + (INV_SLOT_SIZE_PX + 1) && my >= InvRect[r].Y - (INV_SLOT_SIZE_PX + 1) && my < InvRect[r].Y ) { done = TRUE; r--; } } if ( !done ) { // not on an inventory slot rectangle return; } plr[pnum].HoldItem._itype = ITYPE_NONE; if ( r >= SLOTXY_HEAD_FIRST && r <= SLOTXY_HEAD_LAST && plr[pnum].InvBody[INVLOC_HEAD]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_HEAD); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_HEAD]; plr[pnum].InvBody[INVLOC_HEAD]._itype = ITYPE_NONE; } if ( r == SLOTXY_RING_LEFT && plr[pnum].InvBody[INVLOC_RING_LEFT]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_RING_LEFT); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_RING_LEFT]; plr[pnum].InvBody[INVLOC_RING_LEFT]._itype = ITYPE_NONE; } if ( r == SLOTXY_RING_RIGHT && plr[pnum].InvBody[INVLOC_RING_RIGHT]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_RING_RIGHT); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_RING_RIGHT]; plr[pnum].InvBody[INVLOC_RING_RIGHT]._itype = ITYPE_NONE; } if ( r == SLOTXY_AMULET && plr[pnum].InvBody[INVLOC_AMULET]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_AMULET); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_AMULET]; plr[pnum].InvBody[INVLOC_AMULET]._itype = ITYPE_NONE; } if ( r >= SLOTXY_HAND_LEFT_FIRST && r <= SLOTXY_HAND_LEFT_LAST && plr[pnum].InvBody[INVLOC_HAND_LEFT]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_HAND_LEFT); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_HAND_LEFT]; plr[pnum].InvBody[INVLOC_HAND_LEFT]._itype = ITYPE_NONE; } if ( r >= SLOTXY_HAND_RIGHT_FIRST && r <= SLOTXY_HAND_RIGHT_LAST && plr[pnum].InvBody[INVLOC_HAND_RIGHT]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_HAND_RIGHT); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_HAND_RIGHT]; plr[pnum].InvBody[INVLOC_HAND_RIGHT]._itype = ITYPE_NONE; } if ( r >= SLOTXY_CHEST_FIRST && r <= SLOTXY_CHEST_LAST && plr[pnum].InvBody[INVLOC_CHEST]._itype != ITYPE_NONE ) { NetSendCmdDelItem(FALSE, INVLOC_CHEST); plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_CHEST]; plr[pnum].InvBody[INVLOC_CHEST]._itype = ITYPE_NONE; } if ( r >= SLOTXY_INV_FIRST && r <= SLOTXY_INV_LAST ) { char ii = plr[pnum].InvGrid[r - SLOTXY_INV_FIRST]; if ( ii ) { int iv = ii; if ( ii <= 0 ) { iv = -ii; } for ( int i = 0; i < NUM_INV_GRID_ELEM; i++ ) { if ( plr[pnum].InvGrid[i] == iv || plr[pnum].InvGrid[i] == -iv ) { plr[pnum].InvGrid[i] = 0; } } iv--; plr[pnum].HoldItem = plr[pnum].InvList[iv]; plr[pnum]._pNumInv--; if ( plr[pnum]._pNumInv > 0 && plr[pnum]._pNumInv != iv ) { plr[pnum].InvList[iv] = plr[pnum].InvList[plr[pnum]._pNumInv]; for ( int j = 0; j < NUM_INV_GRID_ELEM; j++ ) { if ( plr[pnum].InvGrid[j] == plr[pnum]._pNumInv + 1 ) { plr[pnum].InvGrid[j] = iv + 1; } if ( plr[pnum].InvGrid[j] == -(plr[pnum]._pNumInv + 1) ) { plr[pnum].InvGrid[j] = -iv - 1; } } } } } if ( r >= SLOTXY_BELT_FIRST ) { int offs = r - SLOTXY_BELT_FIRST; if ( plr[pnum].SpdList[offs]._itype != ITYPE_NONE ) { plr[pnum].HoldItem = plr[pnum].SpdList[offs]; plr[pnum].SpdList[offs]._itype = ITYPE_NONE; drawsbarflag = 1; } } if ( plr[pnum].HoldItem._itype != ITYPE_NONE ) { if ( plr[pnum].HoldItem._itype == ITYPE_GOLD ) { plr[pnum]._pGold = CalculateGold(pnum); } CalcPlrInv(pnum, TRUE); CheckItemStats(pnum); if ( pnum == myplr ) { PlaySFX(IS_IGRAB); SetCursor(plr[pnum].HoldItem._iCurs + CURSOR_FIRSTITEM); SetCursorPos(mx - (cursW >> 1), MouseY - (cursH >> 1)); } } } void __fastcall inv_update_rem_item(int pnum, BYTE iv) { if ( iv < NUM_INVLOC ) { plr[pnum].InvBody[iv]._itype = ITYPE_NONE; } BOOL Loadgfx = FALSE; if ( plr[pnum]._pmode != PM_DEATH ) { Loadgfx = TRUE; } CalcPlrInv(pnum, Loadgfx); } void __fastcall RemoveInvItem(int pnum, int iv) { iv++; for ( int i = 0; i < NUM_INV_GRID_ELEM; i++ ) { if ( plr[pnum].InvGrid[i] == iv || plr[pnum].InvGrid[i] == -iv ) { plr[pnum].InvGrid[i] = 0; } } iv--; plr[pnum]._pNumInv--; if ( plr[pnum]._pNumInv > 0 && plr[pnum]._pNumInv != iv ) { plr[pnum].InvList[iv] = plr[pnum].InvList[plr[pnum]._pNumInv]; for ( int j = 0; j < NUM_INV_GRID_ELEM; j++ ) { if ( plr[pnum].InvGrid[j] == plr[pnum]._pNumInv + 1 ) { plr[pnum].InvGrid[j] = iv + 1; } if ( plr[pnum].InvGrid[j] == -(plr[pnum]._pNumInv + 1) ) { plr[pnum].InvGrid[j] = -(iv + 1); } } } CalcPlrScrolls(pnum); if ( plr[pnum]._pRSplType == RSPLTYPE_SCROLL ) { if ( plr[pnum]._pRSpell != SPL_INVALID ) { // BUGFIX: Cast the literal `1` to `UINT64` to make that bitshift 64bit // this causes the last 4 skills to not reset correctly after use if ( !( plr[pnum]._pScrlSpells64 & (1 << (plr[pnum]._pRSpell - 1))) ) { plr[pnum]._pRSpell = SPL_INVALID; } drawpanflag = 255; } } } void __fastcall RemoveSpdBarItem(int pnum, int iv) { plr[pnum].SpdList[iv]._itype = ITYPE_NONE; CalcPlrScrolls(pnum); if ( plr[pnum]._pRSplType == RSPLTYPE_SCROLL ) { if ( plr[pnum]._pRSpell != SPL_INVALID ) { // BUGFIX: Cast the literal `1` to `UINT64` to make that bitshift 64bit // this causes the last 4 skills to not reset correctly after use if ( !( plr[pnum]._pScrlSpells64 & (1 << (plr[pnum]._pRSpell - 1))) ) { plr[pnum]._pRSpell = SPL_INVALID; } } } drawpanflag = 255; } void __cdecl CheckInvItem() { if ( pcurs >= CURSOR_FIRSTITEM ) { CheckInvPaste(myplr, MouseX, MouseY); } else { CheckInvCut(myplr, MouseX, MouseY); } } void __cdecl CheckInvScrn() { if ( MouseX > 190 && MouseX < 437 && MouseY > 352 && MouseY < 385 ) { CheckInvItem(); } } void __fastcall CheckItemStats(int pnum) { PlayerStruct *p = &plr[pnum]; p->HoldItem._iStatFlag = FALSE; if ( p->_pStrength >= p->HoldItem._iMinStr && p->_pMagic >= p->HoldItem._iMinMag && p->_pDexterity >= p->HoldItem._iMinDex ) { p->HoldItem._iStatFlag = TRUE; } } void __fastcall CheckBookLevel(int pnum) { int v1; // ecx int v2; // eax unsigned char v3; // bl int v4; // edi v1 = pnum; if ( plr[v1].HoldItem._iMiscId == IMISC_BOOK ) { v2 = plr[v1].HoldItem._iSpell; v3 = spelldata[plr[v1].HoldItem._iSpell].sMinInt; plr[v1].HoldItem._iMinMag = v3; v4 = plr[0]._pSplLvl[v2 + v1 * 21720]; if ( plr[0]._pSplLvl[v2 + v1 * 21720] ) { do { v3 += 20 * v3 / 100; --v4; if ( v3 + 20 * v3 / 100 > 255 ) { v3 = -1; v4 = 0; } } while ( v4 ); plr[v1].HoldItem._iMinMag = v3; } } } void __fastcall CheckQuestItem(int pnum) { int v1; // ecx int v2; // esi char v3; // cl char v4; // cl char v5; // cl char v6; // cl char v7; // al v1 = pnum; v2 = plr[v1].HoldItem.IDidx; if ( v2 == IDI_OPTAMULET ) quests[8]._qactive = 3; if ( v2 == IDI_MUSHROOM && quests[1]._qactive == 2 && quests[1]._qvar1 == 3 ) { v3 = plr[v1]._pClass; sfxdelay = IDI_OPTAMULET; if ( v3 ) { if ( v3 == 1 ) { sfxdnum = PS_ROGUE95; } else if ( v3 == 2 ) { sfxdnum = PS_MAGE95; } } else { sfxdnum = PS_WARR95; } quests[1]._qvar1 = 4; } if ( v2 == IDI_ANVIL ) { if ( quests[10]._qactive == 1 ) { quests[10]._qactive = 2; quests[10]._qvar1 = 1; } if ( quests[10]._qlog == 1 ) { sfxdelay = IDI_OPTAMULET; v4 = plr[myplr]._pClass; if ( v4 ) { if ( v4 == 1 ) { sfxdnum = PS_ROGUE89; } else if ( v4 == 2 ) { sfxdnum = PS_MAGE89; } } else { sfxdnum = PS_WARR89; } } } if ( v2 == IDI_GLDNELIX ) { sfxdelay = 30; v5 = plr[myplr]._pClass; if ( v5 ) { if ( v5 == 1 ) { sfxdnum = PS_ROGUE88; } else if ( v5 == 2 ) { sfxdnum = PS_MAGE88; } } else { sfxdnum = PS_WARR88; } } if ( v2 == IDI_ROCK ) { if ( quests[0]._qactive == 1 ) { quests[0]._qactive = 2; quests[0]._qvar1 = 1; } if ( quests[0]._qlog == 1 ) { sfxdelay = IDI_OPTAMULET; v6 = plr[myplr]._pClass; if ( v6 ) { if ( v6 == 1 ) { sfxdnum = PS_ROGUE87; } else if ( v6 == 2 ) { sfxdnum = PS_MAGE87; } } else { sfxdnum = PS_WARR87; } } } if ( v2 == IDI_ARMOFVAL ) { quests[9]._qactive = 3; sfxdelay = 20; v7 = plr[myplr]._pClass; if ( v7 ) { if ( v7 == 1 ) { sfxdnum = PS_ROGUE91; } else if ( v7 == 2 ) { sfxdnum = PS_MAGE91; } } else { sfxdnum = PS_WARR91; } } } // 52A554: using guessed type int sfxdelay; void __fastcall InvGetItem(int pnum, int ii) { int v2; // ebp int v3; // edx int v4; // ecx int v5; // ecx int pnuma; // [esp+4h] [ebp-8h] int v7; // [esp+8h] [ebp-4h] v7 = ii; pnuma = pnum; if ( dropGoldFlag ) { dropGoldFlag = 0; dropGoldValue = 0; } v2 = ii; if ( dItem[item[ii]._ix][item[ii]._iy] ) { if ( myplr == pnum && pcurs >= CURSOR_FIRSTITEM ) NetSendCmdPItem(1u, CMD_SYNCPUTITEM, plr[myplr].WorldX, plr[myplr].WorldY); _HIBYTE(item[v2]._iCreateInfo) &= 0x7Fu; qmemcpy(&plr[pnuma].HoldItem, &item[v2], sizeof(plr[pnuma].HoldItem)); CheckQuestItem(pnuma); CheckBookLevel(pnuma); CheckItemStats(pnuma); v3 = 0; dItem[item[v2]._ix][item[v2]._iy] = 0; while ( v3 < numitems ) { v4 = itemactive[v3]; if ( v4 == v7 ) { DeleteItem(v4, v3); v3 = 0; } else { ++v3; } } v5 = plr[pnuma].HoldItem._iCurs; pcursitem = -1; SetCursor(v5 + 12); } } // 4B84DC: using guessed type int dropGoldFlag; // 4B8CC0: using guessed type char pcursitem; void __fastcall AutoGetItem(int pnum, int ii) { int v2; // ebx int v3; // ebp int v4; // eax int v5; // ecx int v6; // edi int v7; // edi int v8; // edi int v9; // edi int v10; // edx int v11; // ecx char v12; // al int v13; // ecx int iia; // [esp+10h] [ebp-18h] signed int iib; // [esp+10h] [ebp-18h] signed int iic; // [esp+10h] [ebp-18h] signed int iid; // [esp+10h] [ebp-18h] signed int iie; // [esp+10h] [ebp-18h] signed int iif; // [esp+10h] [ebp-18h] signed int iig; // [esp+10h] [ebp-18h] signed int iih; // [esp+10h] [ebp-18h] signed int iii; // [esp+10h] [ebp-18h] signed int iij; // [esp+10h] [ebp-18h] ItemStruct *v24; // [esp+14h] [ebp-14h] int *v25; // [esp+14h] [ebp-14h] int v26; // [esp+18h] [ebp-10h] int i; // [esp+1Ch] [ebp-Ch] int v28; // [esp+20h] [ebp-8h] int v29; // [esp+24h] [ebp-4h] v2 = pnum; i = ii; if ( dropGoldFlag ) { dropGoldFlag = 0; dropGoldValue = 0; } if ( ii == 127 || dItem[item[ii]._ix][item[ii]._iy] ) { v3 = pnum; _HIBYTE(item[ii]._iCreateInfo) &= 0x7Fu; v28 = ii; qmemcpy(&plr[pnum].HoldItem, &item[ii], sizeof(plr[pnum].HoldItem)); CheckQuestItem(pnum); CheckBookLevel(v2); CheckItemStats(v2); SetICursor(plr[v2].HoldItem._iCurs + 12); if ( plr[v2].HoldItem._itype == ITYPE_GOLD ) { v4 = GoldAutoPlace(v2); } else { v4 = 0; if ( (!(plr[v3]._pgfxnum & 0xF) || (plr[v3]._pgfxnum & 0xF) == 1) && plr[v3]._pmode <= PM_WALK3 ) { if ( plr[v3].HoldItem._iStatFlag ) { if ( plr[v3].HoldItem._iClass == 1 ) { v4 = WeaponAutoPlace(v2); if ( v4 ) { CalcPlrInv(v2, 1u); goto LABEL_71; } } } } v5 = icursW28; v29 = icursW28; v26 = icursH28; if ( icursW28 == 1 ) { if ( icursH28 == 1 ) { if ( plr[v3].HoldItem._iStatFlag && AllItemsList[plr[v3].HoldItem.IDidx].iUsable ) { iia = 0; v24 = plr[v3].SpdList; do { if ( v4 ) break; if ( v24->_itype == -1 ) { qmemcpy(v24, &plr[v3].HoldItem, sizeof(ItemStruct)); CalcPlrScrolls(v2); v4 = 1; drawsbarflag = 1; } ++iia; ++v24; } while ( iia < 8 ); } v6 = 30; do { if ( v4 ) break; v4 = AutoPlace(v2, v6++, 1, 1, 1); } while ( v6 <= 39 ); v7 = 20; do { if ( v4 ) break; v4 = AutoPlace(v2, v7++, 1, 1, 1); } while ( v7 <= 29 ); v8 = 10; do { if ( v4 ) break; v4 = AutoPlace(v2, v8++, 1, 1, 1); } while ( v8 <= 19 ); v9 = 0; while ( !v4 ) { v4 = AutoPlace(v2, v9++, 1, 1, 1); if ( v9 > 9 ) goto LABEL_35; } goto LABEL_71; } LABEL_35: if ( v26 == 2 ) { iib = 29; do { if ( v4 ) break; v4 = AutoPlace(v2, iib--, 1, 2, 1); } while ( iib >= 20 ); iic = 9; do { if ( v4 ) break; v4 = AutoPlace(v2, iic--, 1, 2, 1); } while ( iic >= 0 ); iid = 19; while ( !v4 ) { v4 = AutoPlace(v2, iid--, 1, 2, 1); if ( iid < 10 ) goto LABEL_45; } goto LABEL_71; } LABEL_45: if ( v26 == 3 ) { iie = 0; while ( !v4 ) { v4 = AutoPlace(v2, iie++, 1, 3, 1); if ( iie >= 20 ) goto LABEL_49; } goto LABEL_71; } } else { LABEL_49: if ( v29 == 2 ) { if ( v26 == 2 ) { v25 = AP2x2Tbl; do { if ( v4 ) break; v4 = AutoPlace(v2, *v25, 2, 2, 1); ++v25; } while ( (signed int)v25 < (signed int)&AP2x2Tbl[10] ); iif = 21; do { if ( v4 ) break; v4 = AutoPlace(v2, iif, 2, 2, 1); iif += 2; } while ( iif < 29 ); iig = 1; do { if ( v4 ) break; v4 = AutoPlace(v2, iig, 2, 2, 1); iig += 2; } while ( iig < 9 ); iih = 10; while ( !v4 ) { v4 = AutoPlace(v2, iih++, 2, 2, 1); if ( iih >= 19 ) goto LABEL_63; } goto LABEL_71; } LABEL_63: if ( v26 == 3 ) { iii = 0; do { if ( v4 ) break; v4 = AutoPlace(v2, iii++, 2, 3, 1); } while ( iii < 9 ); iij = 10; while ( !v4 ) { v4 = AutoPlace(v2, iij++, 2, 3, 1); if ( iij >= 19 ) goto LABEL_70; } goto LABEL_71; } } } } LABEL_70: if ( v4 ) { LABEL_71: v10 = 0; dItem[item[v28]._ix][item[v28]._iy] = 0; while ( v10 < numitems ) { v11 = itemactive[v10]; if ( v11 == i ) { DeleteItem(v11, v10); v10 = 0; } else { ++v10; } } return; } if ( v2 == myplr ) { v12 = plr[v3]._pClass; switch ( v12 ) { case UI_WARRIOR: v13 = random(0, 3) + PS_WARR14; LABEL_84: PlaySFX(v13); break; case UI_ROGUE: v13 = random(0, 3) + PS_ROGUE14; goto LABEL_84; case UI_SORCERER: v13 = random(0, 3) + PS_MAGE14; goto LABEL_84; } } qmemcpy(&plr[v3].HoldItem, &item[v28], sizeof(plr[v3].HoldItem)); RespawnItem(i, 1); NetSendCmdPItem(1u, CMD_RESPAWNITEM, item[v28]._ix, item[v28]._iy); plr[v3].HoldItem._itype = ITYPE_NONE; } } // 48E9A8: using guessed type int AP2x2Tbl[10]; // 4B84DC: using guessed type int dropGoldFlag; int __fastcall FindGetItem(int indx, unsigned short ci, int iseed) { int i; // ebx int ii; // esi i = 0; if ( numitems <= 0 ) return -1; while ( 1 ) { ii = itemactive[i]; if ( item[ii].IDidx == indx && item[ii]._iSeed == iseed && item[ii]._iCreateInfo == ci ) break; if ( ++i >= numitems ) return -1; } return ii; } void __fastcall SyncGetItem(int x, int y, int idx, unsigned short ci, int iseed) { char v5; // cl int v6; // esi int v7; // eax int v8; // edx int v9; // ecx //int v10; // ecx v5 = dItem[x][y]; if ( v5 && (v6 = v5 - 1, v7 = v6, item[v7].IDidx == idx) && item[v7]._iSeed == iseed && item[v7]._iCreateInfo == ci ) { FindGetItem(idx, ci, iseed); } else { v6 = FindGetItem(idx, ci, iseed); } if ( v6 != -1 ) { v8 = 0; dItem[item[v6]._ix][item[v6]._iy] = 0; while ( v8 < numitems ) { v9 = itemactive[v8]; if ( v9 == v6 ) { DeleteItem(v9, v8); FindGetItem(idx, ci, iseed); FindGetItem(idx, ci, iseed); /* check idx */ v8 = 0; } else { ++v8; } } FindGetItem(idx, ci, iseed); } } int __fastcall CanPut(int i, int j) { int v2; // ecx int v3; // esi char v4; // al int v5; // eax char v6; // al bool v7; // sf char v8; // al char v9; // cl v2 = i; if ( dItem[v2][j] ) return 0; v3 = v2 * 112 + j; if ( nSolidTable[dPiece[0][v3]] ) return 0; v4 = dObject[v2][j]; if ( v4 ) { v5 = v4 <= 0 ? -1 - v4 : v4 - 1; if ( object[v5]._oSolidFlag ) return 0; } v6 = dObject[v2 + 1][j + 1]; v7 = v6 < 0; if ( v6 > 0 ) { if ( object[v6 - 1]._oSelFlag ) /* check */ return 0; v7 = v6 < 0; } if ( v7 && object[-(v6 + 1)]._oSelFlag ) return 0; v8 = dObject[v2 + 1][j]; if ( v8 > 0 ) { v9 = dObject[v2][j + 1]; if ( v9 > 0 && object[v8 - 1]._oSelFlag && object[v9 - 1]._oSelFlag ) return 0; } if ( !currlevel && (dMonster[0][v3] || dMonster[1][v3 + 1]) ) return 0; return 1; } int __cdecl TryInvPut() { int result; // eax int v1; // eax char v2; // si int v3; // edi int v4; // ebx int v5; // esi if ( numitems >= 127 ) return 0; v1 = GetDirection(plr[myplr].WorldX, plr[myplr].WorldY, cursmx, cursmy); v2 = v1; v3 = plr[myplr].WorldY; v4 = plr[myplr].WorldX; if ( CanPut(v4 + offset_x[v1], v3 + offset_y[v1]) || (v5 = (v2 - 1) & 7, CanPut(v4 + offset_x[v5], v3 + offset_y[v5])) || CanPut(v4 + offset_x[((_BYTE)v5 + 2) & 7], v3 + offset_y[((_BYTE)v5 + 2) & 7]) ) { result = 1; } else { result = CanPut(v4, v3); } return result; } void __fastcall DrawInvMsg(char *msg) { char *v1; // esi int v2; // eax v1 = msg; v2 = GetTickCount(); if ( (unsigned int)(v2 - sgdwLastTime) >= 5000 ) { sgdwLastTime = v2; ErrorPlrMsg(v1); } } int __fastcall InvPutItem(int pnum, int x, int y) { int v3; // edi int *v4; // esi int v5; // ebx int v6; // esi int v7; // eax int v8; // edi int v9; // esi int v10; // esi int v11; // eax int v12; // edx int v13; // esi int v15; // eax int *v16; // edx int v17; // edx ItemStruct *v18; // [esp+Ch] [ebp-1Ch] int v19; // [esp+10h] [ebp-18h] signed int v20; // [esp+14h] [ebp-14h] int v21; // [esp+18h] [ebp-10h] int v22; // [esp+1Ch] [ebp-Ch] signed int v23; // [esp+20h] [ebp-8h] int xa; // [esp+24h] [ebp-4h] int ya; // [esp+30h] [ebp+8h] int yb; // [esp+30h] [ebp+8h] int yc; // [esp+30h] [ebp+8h] xa = x; if ( numitems >= 127 ) return -1; v3 = pnum; _LOWORD(x) = plr[pnum].HoldItem._iCreateInfo; v4 = &plr[pnum].HoldItem._iSeed; v18 = &plr[pnum].HoldItem; v5 = y; if ( FindGetItem(plr[pnum].HoldItem.IDidx, x, plr[pnum].HoldItem._iSeed) != -1 ) { DrawInvMsg("A duplicate item has been detected. Destroying duplicate..."); SyncGetItem(xa, y, plr[v3].HoldItem.IDidx, plr[v3].HoldItem._iCreateInfo, *v4); } ya = GetDirection(plr[v3].WorldX, plr[v3].WorldY, xa, y); v6 = v5 - plr[v3].WorldY; if ( abs(xa - plr[v3].WorldX) > 1 || abs(v6) > 1 ) { v5 = plr[v3].WorldY + offset_y[ya]; xa = plr[v3].WorldX + offset_x[ya]; } if ( !CanPut(xa, v5) ) { v7 = plr[v3].WorldX; v8 = plr[v3].WorldY; v9 = ((_BYTE)ya - 1) & 7; v19 = v7; v5 = v8 + offset_y[v9]; xa = v7 + offset_x[v9]; if ( !CanPut(xa, v8 + offset_y[v9]) ) { v10 = ((_BYTE)v9 + 2) & 7; v5 = v8 + offset_y[v10]; xa = v19 + offset_x[v10]; if ( !CanPut(xa, v8 + offset_y[v10]) ) { v23 = 0; v11 = -1; yb = 1; v20 = -1; while ( !v23 ) { v22 = v11; while ( v11 <= yb && !v23 ) { v21 = v20; v12 = v8 + v22; v13 = v19 + v20; do { if ( v23 ) break; if ( CanPut(v13, v12) ) { v23 = 1; xa = v13; v5 = v12; } ++v21; ++v13; } while ( v21 <= yb ); v11 = ++v22; } ++yb; v11 = v20-- - 1; if ( v20 <= -50 ) { if ( v23 ) break; return -1; } } } } } CanPut(xa, v5); v15 = itemavail[0]; dItem[xa][v5] = _LOBYTE(itemavail[0]) + 1; yc = v15; v16 = &itemavail[-numitems + 126]; itemactive[numitems] = v15; itemavail[0] = *v16; v17 = v15; qmemcpy(&item[v15], v18, sizeof(ItemStruct)); item[v17]._iy = v5; item[v17]._ix = xa; RespawnItem(v15, 1); ++numitems; SetCursor(CURSOR_HAND); return yc; } int __fastcall SyncPutItem(int pnum, int x, int y, int idx, int icreateinfo, int iseed, int Id, int dur, int mdur, int ch, int mch, int ivalue, unsigned int ibuff) { int v13; // ebx int v14; // edi int v15; // esi int v17; // edi int v18; // ecx int v19; // edi int v20; // eax int v21; // eax int v22; // eax int v23; // edx int v25; // ecx int *v26; // edx int v27; // eax int v28; // eax int v29; // [esp+Ch] [ebp-18h] int v30; // [esp+Ch] [ebp-18h] signed int v31; // [esp+10h] [ebp-14h] int v32; // [esp+14h] [ebp-10h] int v33; // [esp+18h] [ebp-Ch] int o1; // [esp+1Ch] [ebp-8h] signed int v35; // [esp+20h] [ebp-4h] int i; // [esp+2Ch] [ebp+8h] int ia; // [esp+2Ch] [ebp+8h] int ib; // [esp+2Ch] [ebp+8h] int ic; // [esp+2Ch] [ebp+8h] v13 = x; v14 = pnum; if ( numitems >= 127 ) return -1; v15 = y; if ( FindGetItem(idx, icreateinfo, iseed) != -1 ) { DrawInvMsg("A duplicate item has been detected from another player."); SyncGetItem(v13, y, idx, icreateinfo, iseed); } v17 = v14; i = GetDirection(plr[v17].WorldX, plr[v17].WorldY, v13, y); v29 = v15 - plr[v17].WorldY; if ( abs(v13 - plr[v17].WorldX) > 1 || abs(v29) > 1 ) { v13 = plr[v17].WorldX + offset_x[i]; v15 = plr[v17].WorldY + offset_y[i]; } if ( !CanPut(v13, v15) ) { v18 = plr[v17].WorldX; v19 = plr[v17].WorldY; v20 = ((_BYTE)i - 1) & 7; v30 = v18; ia = v20; v20 *= 4; v13 = v18 + *(int *)((char *)offset_x + v20); v15 = v19 + *(int *)((char *)offset_y + v20); if ( !CanPut(v18 + *(int *)((char *)offset_x + v20), v19 + *(int *)((char *)offset_y + v20)) ) { v21 = ((_BYTE)ia + 2) & 7; v13 = v30 + offset_x[v21]; v15 = v19 + offset_y[v21]; if ( !CanPut(v30 + offset_x[v21], v19 + offset_y[v21]) ) { v35 = 0; v22 = -1; ib = 1; v31 = -1; while ( !v35 ) { v33 = v22; while ( v22 <= ib && !v35 ) { v23 = v19 + v33; v32 = v31; o1 = v30 + v31; do { if ( v35 ) break; if ( CanPut(o1, v23) ) { v13 = o1; v35 = 1; v15 = v23; } ++v32; ++o1; } while ( v32 <= ib ); v22 = ++v33; } ++ib; v22 = v31-- - 1; if ( v31 <= -50 ) { if ( v35 ) break; return -1; } } } } } CanPut(v13, v15); v25 = itemavail[0]; ic = itemavail[0]; dItem[v13][v15] = _LOBYTE(itemavail[0]) + 1; v26 = &itemavail[-numitems + 126]; itemactive[numitems] = v25; itemavail[0] = *v26; if ( idx == IDI_EAR ) { RecreateEar(v25, icreateinfo, iseed, Id, dur, mdur, ch, mch, ivalue, ibuff); } else { RecreateItem(v25, idx, icreateinfo, iseed, ivalue); if ( Id ) item[ic]._iIdentified = 1; v27 = ic; item[v27]._iDurability = dur; item[v27]._iMaxDur = mdur; item[v27]._iCharges = ch; item[v27]._iMaxCharges = mch; } v28 = ic; item[v28]._ix = v13; item[v28]._iy = v15; RespawnItem(ic, 1); ++numitems; return ic; } int __cdecl CheckInvHLight() { signed int v0; // ebx int result; // eax ItemStruct *v2; // edi PlayerStruct *v3; // esi int v4; // eax int v5; // ebx int v6; // edi char *v7; // eax char v8; // al char v9; // [esp+Fh] [ebp-1h] v0 = 0; do { result = InvRect[v0].X; if ( MouseX >= result ) { result += 29; if ( MouseX < result ) { result = InvRect[v0].Y; if ( MouseY >= result - 29 && MouseY < result ) break; } } ++v0; } while ( (unsigned int)v0 < 0x49 ); if ( (unsigned int)v0 >= 0x49 ) goto LABEL_37; v9 = -1; _LOBYTE(infoclr) = 0; v2 = 0; v3 = &plr[myplr]; ClearPanel(); if ( v0 >= 0 && v0 <= 3 ) { v9 = 0; v2 = v3->InvBody; goto LABEL_36; } switch ( v0 ) { case 4: v9 = 1; v2 = &v3->InvBody[1]; goto LABEL_36; case 5: v9 = 2; v2 = &v3->InvBody[2]; goto LABEL_36; case 6: v9 = 3; v2 = &v3->InvBody[3]; goto LABEL_36; } if ( v0 >= 7 && v0 <= 12 ) { v9 = 4; v2 = &v3->InvBody[4]; goto LABEL_36; } if ( v0 < 13 || v0 > 18 ) { if ( v0 >= 19 && v0 <= 24 ) { v9 = 6; v2 = &v3->InvBody[6]; goto LABEL_36; } if ( v0 < 25 || v0 > 64 ) { if ( v0 < 65 ) goto LABEL_36; v5 = v0 - 65; drawsbarflag = 1; result = 368 * v5; v2 = &v3->SpdList[v5]; if ( v3->SpdList[v5]._itype != -1 ) { v9 = v5 + 47; goto LABEL_36; } } else { result = abs(v3->InvGrid[v0 - 25]); // abs(*((char *)&v3->InvList[39]._iVAdd2 + v0 + 3)); /* find right address */ if ( result ) { v4 = result - 1; v9 = v4 + 7; v2 = &v3->InvList[v4]; goto LABEL_36; } } LABEL_37: _LOBYTE(result) = -1; return result; } v2 = &v3->InvBody[4]; if ( v3->InvBody[4]._itype == -1 || v3->InvBody[4]._iLoc != 2 ) { v9 = 5; v2 = &v3->InvBody[5]; } else { v9 = 4; } LABEL_36: result = v2->_itype; if ( result == ITYPE_NONE ) goto LABEL_37; if ( result == ITYPE_GOLD ) { v6 = v2->_ivalue; v7 = get_pieces_str(v6); result = sprintf(infostr, "%i gold %s", v6, v7); } else { v8 = v2->_iMagical; if ( v8 == 1 ) { _LOBYTE(infoclr) = 1; } else if ( v8 == 2 ) { _LOBYTE(infoclr) = 3; } strcpy(infostr, v2->_iName); if ( v2->_iIdentified ) { strcpy(infostr, v2->_iIName); PrintItemDetails(v2); } else { PrintItemDur(v2); } } _LOBYTE(result) = v9; return result; } // 4B883C: using guessed type int infoclr; void __fastcall RemoveScroll(int pnum) { int v1; // eax int v2; // esi int v3; // edx int *v4; // ecx int v5; // edx int *v6; // ecx int p; // [esp+Ch] [ebp-4h] p = pnum; v1 = pnum; v2 = plr[pnum]._pNumInv; v3 = 0; if ( v2 <= 0 ) { LABEL_8: v5 = 0; v6 = &plr[v1].SpdList[0]._iMiscId; while ( *(v6 - 53) == -1 || *v6 != IMISC_SCROLL && *v6 != IMISC_SCROLLT || v6[1] != plr[v1]._pSpell ) { ++v5; v6 += 92; if ( v5 >= 8 ) return; } RemoveSpdBarItem(p, v5); } else { v4 = &plr[v1].InvList[0]._iMiscId; while ( *(v4 - 53) == -1 || *v4 != IMISC_SCROLL && *v4 != IMISC_SCROLLT || v4[1] != plr[v1]._pSpell ) { ++v3; v4 += 92; if ( v3 >= v2 ) goto LABEL_8; } RemoveInvItem(p, v3); } CalcPlrScrolls(p); } bool __cdecl UseScroll() { int v0; // eax int v1; // esi int v2; // ecx int *v3; // edx signed int v4; // esi int *v5; // ecx if ( pcurs != CURSOR_HAND || leveltype == DTYPE_TOWN && !*(_DWORD *)&spelldata[plr[myplr]._pRSpell].sTownSpell ) return 0; v0 = myplr; v1 = 0; v2 = plr[myplr]._pNumInv; if ( v2 <= 0 ) { LABEL_11: v4 = 0; v5 = &plr[v0].SpdList[0]._iMiscId; while ( *(v5 - 53) == -1 || *v5 != IMISC_SCROLL && *v5 != IMISC_SCROLLT || v5[1] != plr[v0]._pRSpell ) { ++v4; v5 += 92; if ( v4 >= 8 ) return 0; } } else { v3 = &plr[v0].InvList[0]._iMiscId; while ( *(v3 - 53) == -1 || *v3 != IMISC_SCROLL && *v3 != IMISC_SCROLLT || v3[1] != plr[v0]._pRSpell ) { ++v1; v3 += 92; if ( v1 >= v2 ) goto LABEL_11; } } return 1; } // 5BB1ED: using guessed type char leveltype; void __fastcall UseStaffCharge(int pnum) { int v1; // eax int *v2; // eax v1 = pnum; if ( plr[pnum].InvBody[4]._itype != ITYPE_NONE && plr[v1].InvBody[4]._iMiscId == IMISC_STAFF && plr[v1].InvBody[4]._iSpell == plr[v1]._pRSpell ) { v2 = &plr[v1].InvBody[4]._iCharges; if ( *v2 > 0 ) { --*v2; CalcPlrStaff(pnum); } } } bool __cdecl UseStaff() { int v0; // eax bool result; // al result = 0; if ( pcurs == CURSOR_HAND ) { v0 = myplr; if ( plr[myplr].InvBody[4]._itype != ITYPE_NONE && plr[v0].InvBody[4]._iMiscId == IMISC_STAFF && plr[v0].InvBody[4]._iSpell == plr[v0]._pRSpell && plr[v0].InvBody[4]._iCharges > 0 ) { result = 1; } } return result; } void __cdecl StartGoldDrop() { int v0; // eax initialDropGoldIndex = pcursinvitem; if ( pcursinvitem > 46 ) v0 = plr[myplr].InvBody[pcursinvitem]._iMaxDur; else v0 = plr[myplr].InvBody[pcursinvitem]._ivalue; dropGoldValue = 0; initialDropGoldValue = v0; dropGoldFlag = 1; if ( talkflag ) control_reset_talk(); } // 4B84DC: using guessed type int dropGoldFlag; // 4B8960: using guessed type int talkflag; // 4B8CB8: using guessed type char pcursinvitem; int __fastcall UseInvItem(int pnum, int cii) { int v2; // esi int result; // eax int v4; // ebx int v5; // ebp _DWORD *v6; // edi char v7; // al int v8; // ecx int v9; // eax int v10; // ecx char v11; // al char v12; // al int p; // [esp+10h] [ebp-8h] signed int v14; // [esp+14h] [ebp-4h] v2 = pnum; p = pnum; if ( plr[pnum]._pInvincible && !plr[v2]._pHitPoints && pnum == myplr ) return 1; result = 1; if ( pcurs == 1 && !stextflag ) { if ( cii <= 5 ) return 0; if ( cii > 46 ) { if ( talkflag ) return result; v4 = cii - 47; v14 = 1; v5 = 368 * (cii - 47) + v2 * 21720; v6 = (_DWORD *)((char *)plr[0].SpdList + v5); } else { v4 = cii - 7; v14 = 0; v5 = 368 * (cii - 7) + v2 * 21720; v6 = (_DWORD *)((char *)plr[0].InvList + v5); } if ( v6[90] == 17 ) { v12 = plr[v2]._pClass; sfxdelay = 10; if ( v12 ) { if ( v12 == 1 ) { sfxdnum = PS_ROGUE95; } else if ( v12 == 2 ) { sfxdnum = PS_MAGE95; } } else { sfxdnum = PS_WARR95; } return 1; } if ( v6[90] == 19 ) { PlaySFX(IS_IBOOK); v11 = plr[v2]._pClass; sfxdelay = 10; if ( v11 ) { if ( v11 == 1 ) { sfxdnum = PS_ROGUE29; } else if ( v11 == 2 ) { sfxdnum = PS_MAGE29; } } else { sfxdnum = PS_WARR29; } return 1; } if ( !AllItemsList[v6[90]].iUsable ) return 0; if ( !v6[89] ) { v7 = plr[v2]._pClass; if ( v7 ) { if ( v7 == 1 ) { v8 = PS_ROGUE13; } else { if ( v7 != 2 ) return 1; v8 = PS_MAGE13; } } else { v8 = PS_WARR13; } PlaySFX(v8); return 1; } v9 = v6[55]; if ( !v9 && v6[2] == 11 ) { StartGoldDrop(); return 1; } if ( dropGoldFlag ) { dropGoldFlag = 0; dropGoldValue = 0; } if ( v9 == 21 && !currlevel && !*(_DWORD *)&spelldata[v6[56]].sTownSpell || v9 == 22 && !currlevel && !*(_DWORD *)&spelldata[v6[56]].sTownSpell ) { return 1; } if ( v9 == 24 ) { v10 = 65; } else { if ( pnum != myplr ) goto LABEL_39; v10 = ItemInvSnds[ItemCAnimTbl[v6[48]]]; } PlaySFX(v10); LABEL_39: UseItem(p, v6[55], v6[56]); if ( v14 ) { RemoveSpdBarItem(p, v4); } else if ( *(int *)((char *)&plr[0].InvList[0]._iMiscId + v5) != IMISC_MAPOFDOOM ) { RemoveInvItem(p, v4); } return 1; } return result; } // 4B84DC: using guessed type int dropGoldFlag; // 4B8960: using guessed type int talkflag; // 52A554: using guessed type int sfxdelay; // 6AA705: using guessed type char stextflag; void __cdecl DoTelekinesis() { if ( pcursobj != -1 ) NetSendCmdParam1(1u, CMD_OPOBJT, pcursobj); if ( pcursitem != -1 ) NetSendCmdGItem(1u, CMD_REQUESTAGITEM, myplr, myplr, pcursitem); if ( pcursmonst != -1 && !M_Talker(pcursmonst) && !monster[pcursmonst].mtalkmsg ) NetSendCmdParam1(1u, CMD_KNOCKBACK, pcursmonst); SetCursor(CURSOR_HAND); } // 4B8CC0: using guessed type char pcursitem; // 4B8CC1: using guessed type char pcursobj; int __fastcall CalculateGold(int pnum) { int result; // eax int v2; // ecx int *v3; // edx signed int v4; // esi int v5; // edx int *v6; // ecx result = 0; v2 = pnum; v3 = &plr[v2].SpdList[0]._ivalue; v4 = 8; do { if ( *(v3 - 47) == 11 ) { result += *v3; drawpanflag = 255; } v3 += 92; --v4; } while ( v4 ); v5 = plr[v2]._pNumInv; if ( v5 > 0 ) { v6 = &plr[v2].InvList[0]._ivalue; do { if ( *(v6 - 47) == 11 ) result += *v6; v6 += 92; --v5; } while ( v5 ); } return result; } // 52571C: using guessed type int drawpanflag; int __cdecl DropItemBeforeTrig() { if ( !TryInvPut() ) return 0; NetSendCmdPItem(1u, CMD_PUTITEM, cursmx, cursmy); SetCursor(CURSOR_HAND); return 1; }
#include <boost/metaparse/one_of_c.hpp>
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The nativecoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinunits.h" #include "chainparams.h" #include "primitives/transaction.h" #include <QSettings> #include <QStringList> BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(N8V); unitlist.append(mN8V); unitlist.append(uN8V); return unitlist; } bool BitcoinUnits::valid(int unit) { switch (unit) { case N8V: case mN8V: case uN8V: return true; default: return false; } } QString BitcoinUnits::id(int unit) { switch (unit) { case N8V: return QString("NativeCoin"); case mN8V: return QString("mNativeCoin"); case uN8V: return QString::fromUtf8("uNativeCoin"); default: return QString("???"); } } QString BitcoinUnits::name(int unit) { if (Params().NetworkID() == CBaseChainParams::MAIN) { switch (unit) { case N8V: return QString("N8V"); case mN8V: return QString("mN8V"); case uN8V: return QString::fromUtf8("μN8V"); default: return QString("???"); } } else { switch (unit) { case N8V: return QString("tN8V"); case mN8V: return QString("mtN8V"); case uN8V: return QString::fromUtf8("μtN8V"); default: return QString("???"); } } } QString BitcoinUnits::description(int unit) { if (Params().NetworkID() == CBaseChainParams::MAIN) { switch (unit) { case N8V: return QString("N8V"); case mN8V: return QString("Milli-N8V (1 / 1" THIN_SP_UTF8 "000)"); case uN8V: return QString("Micro-N8V (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } else { switch (unit) { case N8V: return QString("TestN8Vs"); case mN8V: return QString("Milli-TestN8V (1 / 1" THIN_SP_UTF8 "000)"); case uN8V: return QString("Micro-TestN8V (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } } qint64 BitcoinUnits::factor(int unit) { switch (unit) { case N8V: return 100000000; case mN8V: return 100000; case uN8V: return 100; default: return 100000000; } } int BitcoinUnits::decimals(int unit) { switch (unit) { case N8V: return 8; case mN8V: return 5; case uN8V: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if (!valid(unit)) return QString(); // Refuse to format invalid unit qint64 n = (qint64)nIn; qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Use SI-style thin space separators as these are locale independent and can't be // confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == separatorAlways || (separators == separatorStandard && q_size > 4)) for (int i = 3; i < q_size; i += 3) quotient_str.insert(q_size - i, thin_sp); //-------------------------------------------------------------------------------// if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); if (num_decimals <= 0) return quotient_str; return quotient_str + QString(".") + remainder_str; } // TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to // TODO: determine whether the output is used in a plain text context // TODO: or an HTML context (and replace with // TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully // TODO: there aren't instances where the result could be used in // TODO: either context. // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + name(unit); } QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QSettings settings; int digits = settings.value("digits").toInt(); QString result = format(unit, amount, plussign, separators); if (decimals(unit) > digits) result.chop(decimals(unit) - digits); return result + QString(" ") + name(unit); } QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(floorWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out) { if (!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if (parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if (parts.size() > 1) { decimals = parts[1]; } if (decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if (str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if (val_out) { *val_out = retvalue; } return ok; } QString BitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (BitcoinUnits::valid(unit)) { amountTitle += " (" + BitcoinUnits::name(unit) + ")"; } return amountTitle; } int BitcoinUnits::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex& index, int role) const { int row = index.row(); if (row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch (role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } CAmount BitcoinUnits::maxMoney() { return Params().MaxMoneyOut(); }
/* * This file is part of Matrix. * * See the COPYRIGHT file at the top-level directory of this distribution * for details of code ownership. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <doctest/doctest.h> #include <Matrix/matrix.h> TEST_SUITE_BEGIN("test_associative_multiplication"); TEST_CASE("small_ones_matrix") { using namespace linalg; Matrix<int> A{5, 5, 1}; Matrix<int> B{5, 5, 1}; Matrix<int> C{5, 5, 1}; Matrix<int> D{5, 5, 25}; CHECK(isSame(D, A * B * C) == 1); } TEST_CASE("small_matrix") { using namespace linalg; Matrix<int> A{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}}; Matrix<int> B{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}}; Matrix<int> C{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}}; Matrix<int> D{{{468, 576, 684}, {1062, 1305, 1548}, {1656, 2034, 2412}}}; CHECK(isSame(D, A * B * C) == 1); } TEST_CASE("medium_matrix") { using namespace linalg; Matrix<int> A{100, 100, 6}; Matrix<int> B{100, 100, 2}; Matrix<int> C{100, 100, 8}; Matrix<int> D{100, 100, 960000}; CHECK(isSame(D, A * B * C) == 1); } TEST_CASE("huge_matrix") { using namespace linalg; Matrix<int> A{1000, 1000, 9}; Matrix<int> B{1000, 1000, 7}; Matrix<int> C{1000, 1000, 1}; Matrix<int> D{1000, 1000, 63000000}; CHECK(isSame(D, A * B * C) == 1); } TEST_SUITE_END();
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2017-2020 The Qtum Core developers // Copyright (c) 2020 The BCS Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/system.h> #include <chainparamsbase.h> #include <random.h> #include <serialize.h> #include <util/strencodings.h> #include <regex> #include <iomanip> #include <stdarg.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #define _POSIX_C_SOURCE 200112L #endif // __linux__ #include <algorithm> #include <fcntl.h> #include <sched.h> #include <sys/resource.h> #include <sys/stat.h> #else #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <codecvt> #include <io.h> /* for _commit */ #include <shellapi.h> #include <shlobj.h> #endif #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #ifdef HAVE_MALLOPT_ARENA_MAX #include <malloc.h> #endif #include <thread> // Application startup time (used for uptime calculation) const int64_t nStartupTime = GetTime(); const char * const BITCOIN_CONF_FILENAME = "bcs.conf"; ArgsManager gArgs; /** A map that contains all the currently held directory locks. After * successful locking, these will be held here until the global destructor * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks * is called. */ static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks; /** Mutex to protect dir_locks. */ static std::mutex cs_dir_locks; bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only, bool try_lock) { std::lock_guard<std::mutex> ulock(cs_dir_locks); fs::path pathLockFile = directory / lockfile_name; // If a lock for this directory already exists in the map, don't try to re-lock it if (dir_locks.count(pathLockFile.string())) { return true; } // Create empty lock file if it doesn't exist. FILE* file = fsbridge::fopen(pathLockFile, "a"); if (file) fclose(file); auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile); if (try_lock && !lock->TryLock()) { return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason()); } if (!probe_only) { // Lock successful and we're not just probing, put it into the map dir_locks.emplace(pathLockFile.string(), std::move(lock)); } return true; } void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name) { std::lock_guard<std::mutex> lock(cs_dir_locks); dir_locks.erase((directory / lockfile_name).string()); } void ReleaseDirectoryLocks() { std::lock_guard<std::mutex> ulock(cs_dir_locks); dir_locks.clear(); } bool DirIsWritable(const fs::path& directory) { fs::path tmpFile = directory / fs::unique_path(); FILE* file = fsbridge::fopen(tmpFile, "a"); if (!file) return false; fclose(file); remove(tmpFile); return true; } /** * Interpret a string argument as a boolean. * * The definition of atoi() requires that non-numeric string values like "foo", * return 0. This means that if a user unintentionally supplies a non-integer * argument here, the return value is always false. This means that -foo=false * does what the user probably expects, but -foo=true is well defined but does * not do what they probably expected. * * The return value of atoi() is undefined when given input not representable as * an int. On most systems this means string value between "-2147483648" and * "2147483647" are well defined (this method will return true). Setting * -txindex=2147483648 on most systems, however, is probably undefined. * * For a more extensive discussion of this topic (and a wide range of opinions * on the Right Way to change this code), see PR12713. */ static bool InterpretBool(const std::string& strValue) { if (strValue.empty()) return true; return (atoi(strValue) != 0); } /** Internal helper functions for ArgsManager */ class ArgsManagerHelper { public: typedef std::map<std::string, std::vector<std::string>> MapArgs; /** Determine whether to use config settings in the default section, * See also comments around ArgsManager::ArgsManager() below. */ static inline bool UseDefaultSection(const ArgsManager& am, const std::string& arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args) { return (am.m_network == CBaseChainParams::MAIN || am.m_network_only_args.count(arg) == 0); } /** Convert regular argument into the network-specific setting */ static inline std::string NetworkArg(const ArgsManager& am, const std::string& arg) { assert(arg.length() > 1 && arg[0] == '-'); return "-" + am.m_network + "." + arg.substr(1); } /** Find arguments in a map and add them to a vector */ static inline void AddArgs(std::vector<std::string>& res, const MapArgs& map_args, const std::string& arg) { auto it = map_args.find(arg); if (it != map_args.end()) { res.insert(res.end(), it->second.begin(), it->second.end()); } } /** Return true/false if an argument is set in a map, and also * return the first (or last) of the possibly multiple values it has */ static inline std::pair<bool,std::string> GetArgHelper(const MapArgs& map_args, const std::string& arg, bool getLast = false) { auto it = map_args.find(arg); if (it == map_args.end() || it->second.empty()) { return std::make_pair(false, std::string()); } if (getLast) { return std::make_pair(true, it->second.back()); } else { return std::make_pair(true, it->second.front()); } } /* Get the string value of an argument, returning a pair of a boolean * indicating the argument was found, and the value for the argument * if it was found (or the empty string if not found). */ static inline std::pair<bool,std::string> GetArg(const ArgsManager &am, const std::string& arg) { LOCK(am.cs_args); std::pair<bool,std::string> found_result(false, std::string()); // We pass "true" to GetArgHelper in order to return the last // argument value seen from the command line (so "bitcoind -foo=bar // -foo=baz" gives GetArg(am,"foo")=={true,"baz"} found_result = GetArgHelper(am.m_override_args, arg, true); if (found_result.first) { return found_result; } // But in contrast we return the first argument seen in a config file, // so "foo=bar \n foo=baz" in the config file gives // GetArg(am,"foo")={true,"bar"} if (!am.m_network.empty()) { found_result = GetArgHelper(am.m_config_args, NetworkArg(am, arg)); if (found_result.first) { return found_result; } } if (UseDefaultSection(am, arg)) { found_result = GetArgHelper(am.m_config_args, arg); if (found_result.first) { return found_result; } } return found_result; } /* Special test for -testnet and -regtest args, because we * don't want to be confused by craziness like "[regtest] testnet=1" */ static inline bool GetNetBoolArg(const ArgsManager &am, const std::string& net_arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args) { std::pair<bool,std::string> found_result(false,std::string()); found_result = GetArgHelper(am.m_override_args, net_arg, true); if (!found_result.first) { found_result = GetArgHelper(am.m_config_args, net_arg, true); if (!found_result.first) { return false; // not set } } return InterpretBool(found_result.second); // is set, so evaluate } }; /** * Interpret -nofoo as if the user supplied -foo=0. * * This method also tracks when the -no form was supplied, and if so, * checks whether there was a double-negative (-nofoo=0 -> -foo=1). * * If there was not a double negative, it removes the "no" from the key, * and returns true, indicating the caller should clear the args vector * to indicate a negated option. * * If there was a double negative, it removes "no" from the key, sets the * value to "1" and returns false. * * If there was no "no", it leaves key and value untouched and returns * false. * * Where an option was negated can be later checked using the * IsArgNegated() method. One use case for this is to have a way to disable * options that are not normally boolean (e.g. using -nodebuglogfile to request * that debug log output is not sent to any file at all). */ static bool InterpretNegatedOption(std::string& key, std::string& val) { assert(key[0] == '-'); size_t option_index = key.find('.'); if (option_index == std::string::npos) { option_index = 1; } else { ++option_index; } if (key.substr(option_index, 2) == "no") { bool bool_val = InterpretBool(val); key.erase(option_index, 2); if (!bool_val ) { // Double negatives like -nofoo=0 are supported (but discouraged) LogPrintf("Warning: parsed potentially confusing double-negative %s=%s\n", key, val); val = "1"; } else { return true; } } return false; } ArgsManager::ArgsManager() : /* These options would cause cross-contamination if values for * mainnet were used while running on regtest/testnet (or vice-versa). * Setting them as section_only_args ensures that sharing a config file * between mainnet and regtest/testnet won't cause problems due to these * parameters by accident. */ m_network_only_args{ "-addnode", "-connect", "-port", "-bind", "-rpcport", "-rpcbind", "-wallet", } { // nothing to do } const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const { std::set<std::string> unsuitables; LOCK(cs_args); // if there's no section selected, don't worry if (m_network.empty()) return std::set<std::string> {}; // if it's okay to use the default section for this network, don't worry if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {}; for (const auto& arg : m_network_only_args) { std::pair<bool, std::string> found_result; // if this option is overridden it's fine found_result = ArgsManagerHelper::GetArgHelper(m_override_args, arg); if (found_result.first) continue; // if there's a network-specific value for this option, it's fine found_result = ArgsManagerHelper::GetArgHelper(m_config_args, ArgsManagerHelper::NetworkArg(*this, arg)); if (found_result.first) continue; // if there isn't a default value for this option, it's fine found_result = ArgsManagerHelper::GetArgHelper(m_config_args, arg); if (!found_result.first) continue; // otherwise, issue a warning unsuitables.insert(arg); } return unsuitables; } const std::set<std::string> ArgsManager::GetUnrecognizedSections() const { // Section names to be recognized in the config file. static const std::set<std::string> available_sections{ CBaseChainParams::REGTEST, CBaseChainParams::TESTNET, CBaseChainParams::MAIN }; std::set<std::string> diff; LOCK(cs_args); std::set_difference( m_config_sections.begin(), m_config_sections.end(), available_sections.begin(), available_sections.end(), std::inserter(diff, diff.end())); return diff; } void ArgsManager::SelectConfigNetwork(const std::string& network) { LOCK(cs_args); m_network = network; } bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error) { LOCK(cs_args); m_override_args.clear(); for (int i = 1; i < argc; i++) { std::string key(argv[i]); std::string val; size_t is_index = key.find('='); if (is_index != std::string::npos) { val = key.substr(is_index + 1); key.erase(is_index); } #ifdef WIN32 std::transform(key.begin(), key.end(), key.begin(), ToLower); if (key[0] == '/') key[0] = '-'; #endif if (key[0] != '-') break; // Transform --foo to -foo if (key.length() > 1 && key[1] == '-') key.erase(0, 1); // Check for -nofoo if (InterpretNegatedOption(key, val)) { m_override_args[key].clear(); } else { m_override_args[key].push_back(val); } // Check that the arg is known if (!(IsSwitchChar(key[0]) && key.size() == 1)) { if (!IsArgKnown(key)) { error = strprintf("Invalid parameter %s", key.c_str()); return false; } } } // we do not allow -includeconf from command line, so we clear it here auto it = m_override_args.find("-includeconf"); if (it != m_override_args.end()) { if (it->second.size() > 0) { for (const auto& ic : it->second) { error += "-includeconf cannot be used from commandline; -includeconf=" + ic + "\n"; } return false; } } return true; } bool ArgsManager::IsArgKnown(const std::string& key) const { size_t option_index = key.find('.'); std::string arg_no_net; if (option_index == std::string::npos) { arg_no_net = key; } else { arg_no_net = std::string("-") + key.substr(option_index + 1, std::string::npos); } LOCK(cs_args); for (const auto& arg_map : m_available_args) { if (arg_map.second.count(arg_no_net)) return true; } return false; } std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const { std::vector<std::string> result = {}; if (IsArgNegated(strArg)) return result; // special case LOCK(cs_args); ArgsManagerHelper::AddArgs(result, m_override_args, strArg); if (!m_network.empty()) { ArgsManagerHelper::AddArgs(result, m_config_args, ArgsManagerHelper::NetworkArg(*this, strArg)); } if (ArgsManagerHelper::UseDefaultSection(*this, strArg)) { ArgsManagerHelper::AddArgs(result, m_config_args, strArg); } return result; } bool ArgsManager::IsArgSet(const std::string& strArg) const { if (IsArgNegated(strArg)) return true; // special case return ArgsManagerHelper::GetArg(*this, strArg).first; } bool ArgsManager::IsArgNegated(const std::string& strArg) const { LOCK(cs_args); const auto& ov = m_override_args.find(strArg); if (ov != m_override_args.end()) return ov->second.empty(); if (!m_network.empty()) { const auto& cfs = m_config_args.find(ArgsManagerHelper::NetworkArg(*this, strArg)); if (cfs != m_config_args.end()) return cfs->second.empty(); } const auto& cf = m_config_args.find(strArg); if (cf != m_config_args.end()) return cf->second.empty(); return false; } std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const { if (IsArgNegated(strArg)) return "0"; std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg); if (found_res.first) return found_res.second; return strDefault; } int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const { if (IsArgNegated(strArg)) return 0; std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg); if (found_res.first) return atoi64(found_res.second); return nDefault; } bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const { if (IsArgNegated(strArg)) return false; std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg); if (found_res.first) return InterpretBool(found_res.second); return fDefault; } bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue) { LOCK(cs_args); if (IsArgSet(strArg)) return false; ForceSetArg(strArg, strValue); return true; } bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue) { LOCK(cs_args); m_override_args[strArg] = {strValue}; } void ArgsManager::AddArg(const std::string& name, const std::string& help, const bool debug_only, const OptionsCategory& cat) { // Split arg name from its help param size_t eq_index = name.find('='); if (eq_index == std::string::npos) { eq_index = name.size(); } LOCK(cs_args); std::map<std::string, Arg>& arg_map = m_available_args[cat]; auto ret = arg_map.emplace(name.substr(0, eq_index), Arg(name.substr(eq_index, name.size() - eq_index), help, debug_only)); assert(ret.second); // Make sure an insertion actually happened } void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names) { for (const std::string& name : names) { AddArg(name, "", false, OptionsCategory::HIDDEN); } } std::string ArgsManager::GetHelpMessage() const { const bool show_debug = gArgs.GetBoolArg("-help-debug", false); std::string usage = ""; LOCK(cs_args); for (const auto& arg_map : m_available_args) { switch(arg_map.first) { case OptionsCategory::OPTIONS: usage += HelpMessageGroup("Options:"); break; case OptionsCategory::CONNECTION: usage += HelpMessageGroup("Connection options:"); break; case OptionsCategory::ZMQ: usage += HelpMessageGroup("ZeroMQ notification options:"); break; case OptionsCategory::DEBUG_TEST: usage += HelpMessageGroup("Debugging/Testing options:"); break; case OptionsCategory::NODE_RELAY: usage += HelpMessageGroup("Node relay options:"); break; case OptionsCategory::BLOCK_CREATION: usage += HelpMessageGroup("Block creation options:"); break; case OptionsCategory::RPC: usage += HelpMessageGroup("RPC server options:"); break; case OptionsCategory::WALLET: usage += HelpMessageGroup("Wallet options:"); break; case OptionsCategory::WALLET_DEBUG_TEST: if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:"); break; case OptionsCategory::CHAINPARAMS: usage += HelpMessageGroup("Chain selection options:"); break; case OptionsCategory::GUI: usage += HelpMessageGroup("UI Options:"); break; case OptionsCategory::COMMANDS: usage += HelpMessageGroup("Commands:"); break; case OptionsCategory::REGISTER_COMMANDS: usage += HelpMessageGroup("Register Commands:"); break; default: break; } // When we get to the hidden options, stop if (arg_map.first == OptionsCategory::HIDDEN) break; for (const auto& arg : arg_map.second) { if (show_debug || !arg.second.m_debug_only) { std::string name; if (arg.second.m_help_param.empty()) { name = arg.first; } else { name = arg.first + arg.second.m_help_param; } usage += HelpMessageOpt(name, arg.second.m_help_text); } } } return usage; } bool HelpRequested(const ArgsManager& args) { return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug"); } void SetupHelpOptions(ArgsManager& args) { args.AddArg("-?", "Print this help message and exit", false, OptionsCategory::OPTIONS); args.AddHiddenArgs({"-h", "-help"}); } static const int screenWidth = 79; static const int optIndent = 2; static const int msgIndent = 7; std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); } std::string HelpMessageOpt(const std::string &option, const std::string &message) { return std::string(optIndent,' ') + std::string(option) + std::string("\n") + std::string(msgIndent,' ') + FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n"); } static std::string FormatException(const std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule)); #else const char* pszModule = "bitcoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void PrintExceptionContinue(const std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); tfm::format(std::cerr, "\n\n************************\n%s\n", message.c_str()); } fs::path GetDefaultDataDir() { // Windows < Vista: C:\Documents and Settings\Username\Application Data\BCS // Windows >= Vista: C:\Users\Username\AppData\Roaming\BCS // Mac: ~/Library/Application Support/BCS // Unix: ~/.bcs #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "BCS"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == nullptr || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac return pathRet / "Library/Application Support/BCS"; #else // Unix return pathRet / ".bcs"; #endif #endif } static fs::path g_blocks_path_cache_net_specific; static fs::path pathCached; static fs::path pathCachedNetSpecific; static CCriticalSection csPathCached; const fs::path &GetBlocksDir() { LOCK(csPathCached); fs::path &path = g_blocks_path_cache_net_specific; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (gArgs.IsArgSet("-blocksdir")) { path = fs::system_complete(gArgs.GetArg("-blocksdir", "")); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDataDir(false); } path /= BaseParams().DataDir(); path /= "blocks"; fs::create_directories(path); return path; } const fs::path &GetDataDir(bool fNetSpecific) { LOCK(csPathCached); fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (gArgs.IsArgSet("-datadir")) { path = fs::system_complete(gArgs.GetArg("-datadir", "")); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= BaseParams().DataDir(); if (fs::create_directories(path)) { // This is the first run, create wallets subdirectory too fs::create_directories(path / "wallets"); } return path; } void ClearDatadirCache() { LOCK(csPathCached); pathCached = fs::path(); pathCachedNetSpecific = fs::path(); g_blocks_path_cache_net_specific = fs::path(); } fs::path GetConfigFile(const std::string& confPath) { return AbsPathForConfigVal(fs::path(confPath), false); } static std::string TrimString(const std::string& str, const std::string& pattern) { std::string::size_type front = str.find_first_not_of(pattern); if (front == std::string::npos) { return std::string(); } std::string::size_type end = str.find_last_not_of(pattern); return str.substr(front, end - front + 1); } static bool GetConfigOptions(std::istream& stream, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::set<std::string>& sections) { std::string str, prefix; std::string::size_type pos; int linenr = 1; while (std::getline(stream, str)) { bool used_hash = false; if ((pos = str.find('#')) != std::string::npos) { str = str.substr(0, pos); used_hash = true; } const static std::string pattern = " \t\r\n"; str = TrimString(str, pattern); if (!str.empty()) { if (*str.begin() == '[' && *str.rbegin() == ']') { const std::string section = str.substr(1, str.size() - 2); sections.insert(section); prefix = section + '.'; } else if (*str.begin() == '-') { error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str); return false; } else if ((pos = str.find('=')) != std::string::npos) { std::string name = prefix + TrimString(str.substr(0, pos), pattern); std::string value = TrimString(str.substr(pos + 1), pattern); if (used_hash && name.find("rpcpassword") != std::string::npos) { error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr); return false; } options.emplace_back(name, value); if ((pos = name.rfind('.')) != std::string::npos) { sections.insert(name.substr(0, pos)); } } else { error = strprintf("parse error on line %i: %s", linenr, str); if (str.size() >= 2 && str.substr(0, 2) == "no") { error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str); } return false; } } ++linenr; } return true; } bool ArgsManager::ReadConfigStream(std::istream& stream, std::string& error, bool ignore_invalid_keys) { LOCK(cs_args); std::vector<std::pair<std::string, std::string>> options; m_config_sections.clear(); if (!GetConfigOptions(stream, error, options, m_config_sections)) { return false; } for (const std::pair<std::string, std::string>& option : options) { std::string strKey = std::string("-") + option.first; std::string strValue = option.second; if (InterpretNegatedOption(strKey, strValue)) { m_config_args[strKey].clear(); } else { m_config_args[strKey].push_back(strValue); } // Check that the arg is known if (!IsArgKnown(strKey)) { if (!ignore_invalid_keys) { error = strprintf("Invalid configuration value %s", option.first.c_str()); return false; } else { LogPrintf("Ignoring unknown configuration value %s\n", option.first); } } } return true; } bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys) { { LOCK(cs_args); m_config_args.clear(); } const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME); fsbridge::ifstream stream(GetConfigFile(confPath)); // ok to not have a config file if (stream.good()) { if (!ReadConfigStream(stream, error, ignore_invalid_keys)) { return false; } // if there is an -includeconf in the override args, but it is empty, that means the user // passed '-noincludeconf' on the command line, in which case we should not include anything bool emptyIncludeConf; { LOCK(cs_args); emptyIncludeConf = m_override_args.count("-includeconf") == 0; } if (emptyIncludeConf) { std::string chain_id = GetChainName(); std::vector<std::string> includeconf(GetArgs("-includeconf")); { // We haven't set m_network yet (that happens in SelectParams()), so manually check // for network.includeconf args. std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf")); includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end()); } // Remove -includeconf from configuration, so we can warn about recursion // later { LOCK(cs_args); m_config_args.erase("-includeconf"); m_config_args.erase(std::string("-") + chain_id + ".includeconf"); } for (const std::string& to_include : includeconf) { fsbridge::ifstream include_config(GetConfigFile(to_include)); if (include_config.good()) { if (!ReadConfigStream(include_config, error, ignore_invalid_keys)) { return false; } LogPrintf("Included configuration file %s\n", to_include.c_str()); } else { error = "Failed to include configuration file " + to_include; return false; } } // Warn about recursive -includeconf includeconf = GetArgs("-includeconf"); { std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf")); includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end()); std::string chain_id_final = GetChainName(); if (chain_id_final != chain_id) { // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs includeconf_net = GetArgs(std::string("-") + chain_id_final + ".includeconf"); includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end()); } } for (const std::string& to_include : includeconf) { tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", to_include.c_str()); } } } // If datadir is changed in .conf file: ClearDatadirCache(); if (!fs::is_directory(GetDataDir(false))) { error = strprintf("specified data directory \"%s\" does not exist.", gArgs.GetArg("-datadir", "").c_str()); return false; } return true; } std::string ArgsManager::GetChainName() const { LOCK(cs_args); bool fRegTest = ArgsManagerHelper::GetNetBoolArg(*this, "-regtest"); bool fTestNet = ArgsManagerHelper::GetNetBoolArg(*this, "-testnet"); if (fTestNet && fRegTest) throw std::runtime_error("Invalid combination of -regtest and -testnet."); if (fRegTest) return CBaseChainParams::REGTEST; if (fTestNet) return CBaseChainParams::TESTNET; return CBaseChainParams::MAIN; } bool RenameOver(fs::path src, fs::path dest) { #ifdef WIN32 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(), MOVEFILE_REPLACE_EXISTING) != 0; #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } /** * Ignores exceptions thrown by Boost's create_directories if the requested directory exists. * Specifically handles case where path p exists, but it wasn't possible for the user to * write to the parent directory. */ bool TryCreateDirectories(const fs::path& p) { try { return fs::create_directories(p); } catch (const fs::filesystem_error&) { if (!fs::exists(p) || !fs::is_directory(p)) throw; } // create_directories didn't create the directory, it had to have existed already return false; } bool FileCommit(FILE *file) { if (fflush(file) != 0) { // harmless if redundantly called LogPrintf("%s: fflush failed: %d\n", __func__, errno); return false; } #ifdef WIN32 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); if (FlushFileBuffers(hFile) == 0) { LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError()); return false; } #else #if defined(__linux__) || defined(__NetBSD__) if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync LogPrintf("%s: fdatasync failed: %d\n", __func__, errno); return false; } #elif defined(MAC_OSX) && defined(F_FULLFSYNC) if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno); return false; } #else if (fsync(fileno(file)) != 0 && errno != EINVAL) { LogPrintf("%s: fsync failed: %d\n", __func__, errno); return false; } #endif #endif return true; } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } /** * this function tries to raise the file descriptor limit to the requested number. * It returns the actual file descriptor limit (which may be more or less than nMinFD) */ int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } /** * this function tries to make a particular range of a file allocated (corresponding to disk space) * it is advisory, and the range specified in the arguments will never contain live data */ void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64_t nEndPos = (int64_t)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = (off_t)offset + length; fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), fst.fst_length); #elif defined(__linux__) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; posix_fallocate(fileno(file), 0, nEndPos); #else // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; if (fseek(file, offset, SEEK_SET)) { return; } while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } #ifdef WIN32 fs::path GetSpecialFolderPath(int nFolder, bool fCreate) { WCHAR pszPath[MAX_PATH] = L""; if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n"); return fs::path(""); } #endif void runCommand(const std::string& strCommand) { if (strCommand.empty()) return; #ifndef WIN32 int nErr = ::system(strCommand.c_str()); #else int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str()); #endif if (nErr) LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) pthread_setname_np(name); #else // Prevent warnings for unused parameters... (void)name; #endif } void SetupEnvironment() { #ifdef HAVE_MALLOPT_ARENA_MAX // glibc-specific: On 32-bit systems set the number of arenas to 1. // By default, since glibc 2.10, the C library will create up to two heap // arenas per core. This is known to cause excessive virtual address space // usage in our usage. Work around it by setting the maximum number of // arenas to 1. if (sizeof(void*) == 4) { mallopt(M_ARENA_MAX, 1); } #endif // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale // may be invalid, in which case the "C" locale is used as fallback. #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) try { std::locale(""); // Raises a runtime error if current locale is invalid } catch (const std::runtime_error&) { setenv("LC_ALL", "C", 1); } #elif defined(WIN32) // Set the default input/output charset is utf-8 SetConsoleCP(CP_UTF8); SetConsoleOutputCP(CP_UTF8); #endif // The path locale is lazy initialized and to avoid deinitialization errors // in multithreading environments, it is set explicitly by the main thread. // A dummy locale is used to extract the internal default locale, used by // fs::path, which is then used to explicitly imbue the path. std::locale loc = fs::path::imbue(std::locale::classic()); #ifndef WIN32 fs::path::imbue(loc); #else fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>())); #endif } bool SetupNetworking() { #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) return false; #endif return true; } int GetNumCores() { return std::thread::hardware_concurrency(); } std::string CopyrightHolders(const std::string& strPrefix) { std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION)); // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("BCS Core") == std::string::npos) { strCopyrightHolders += "\n" + strPrefix + "The BCS Core Developers"; } return strCopyrightHolders; } bool CheckHex(const std::string& str) { size_t data=0; if(str.size() > 2 && (str.compare(0, 2, "0x") == 0 || str.compare(0, 2, "0X") == 0)){ data=2; } return str.size() > data && str.find_first_not_of("0123456789abcdefABCDEF", data) == std::string::npos; } // Obtain the application startup time (used for uptime calculation) int64_t GetStartupTime() { return nStartupTime; } fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific) { return fs::absolute(path, GetDataDir(net_specific)); } int ScheduleBatchPriority() { #ifdef SCHED_BATCH const static sched_param param{}; if (int ret = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param)) { LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(errno)); return ret; } return 0; #else return 1; #endif } std::string toHexString(int64_t intValue) { //Store big endian representation in a vector uint64_t num = (uint64_t)intValue; std::vector<unsigned char> bigEndian; for(int i=sizeof(num) -1; i>=0; i--){ bigEndian.push_back( (num>>(8*i)) & 0xff ); } //Convert the vector into hex string return "0x" + HexStr(bigEndian.begin(), bigEndian.end()); } void ReplaceInt(const int64_t& number, const std::string& key, std::string& str) { // Convert the number into hex string std::string num_hex = toHexString(number); // Search for key in str and replace it with the hex string std::string str_replaced = std::regex_replace(str, std::regex(key), num_hex); str = str_replaced; } namespace util { #ifdef WIN32 WinCmdLineArgs::WinCmdLineArgs() { wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt; argv = new char*[argc]; args.resize(argc); for (int i = 0; i < argc; i++) { args[i] = utf8_cvt.to_bytes(wargv[i]); argv[i] = &*args[i].begin(); } LocalFree(wargv); } WinCmdLineArgs::~WinCmdLineArgs() { delete[] argv; } std::pair<int, char**> WinCmdLineArgs::get() { return std::make_pair(argc, argv); } #endif } // namespace util
/* * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "gtest/gtest.h" #include "usm_linked_list/usm_linked_list.hpp" #include "test_harness/test_harness.hpp" TEST(UsmLinkedListSystemTests, ApplicationReturnsSkipStatusGivenHelpMessageIsRequested) { compute_samples::UsmLinkedListApplication application; std::vector<std::string> command_line = {"--help"}; EXPECT_EQ(compute_samples::Application::Status::SKIP, application.run(command_line)); } HWTEST(UsmLinkedListSystemTests, GivenHostUsmThenApplicationReturnsOKStatus) { compute_samples::UsmLinkedListApplication application; std::vector<std::string> command_line = {"host"}; EXPECT_EQ(compute_samples::Application::Status::OK, application.run(command_line)); } HWTEST(UsmLinkedListSystemTests, GivenDeviceUsmThenApplicationReturnsOKStatus) { compute_samples::UsmLinkedListApplication application; std::vector<std::string> command_line = {"device"}; EXPECT_EQ(compute_samples::Application::Status::OK, application.run(command_line)); } HWTEST(UsmLinkedListSystemTests, GivenSharedUsmThenApplicationReturnsOKStatus) { compute_samples::UsmLinkedListApplication application; std::vector<std::string> command_line = {"shared"}; EXPECT_EQ(compute_samples::Application::Status::OK, application.run(command_line)); } HWTEST(UsmLinkedListSystemTests, GivenCustomListSizeThenApplicationReturnsOKStatus) { compute_samples::UsmLinkedListApplication application; std::vector<std::string> command_line = {"host", "--size", "1024"}; EXPECT_EQ(compute_samples::Application::Status::OK, application.run(command_line)); }
// Copyright (C) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of 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: wan@google.com (Zhanyong Wan) // Google Test - The Google C++ Testing Framework // // This file implements a universal value printer that can print a // value of any type T: // // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); // // It uses the << operator when possible, and prints the bytes in the // object otherwise. A user can override its behavior for a class // type Foo by defining either operator<<(::std::ostream&, const Foo&) // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that // defines Foo. #include "gtest/gtest-printers.h" #include <ctype.h> #include <stdio.h> #include <ostream> // NOLINT #include <string> #include "gtest/internal/gtest-port.h" namespace testing { namespace { using ::std::ostream; // Prints a segment of bytes in the given object. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, size_t count, ostream* os) { char text[5] = ""; for (size_t i = 0; i != count; i++) { const size_t j = start + i; if (i != 0) { // Organizes the bytes into groups of 2 for easy parsing by // human. if ((j % 2) == 0) *os << ' '; else *os << '-'; } GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); *os << text; } } // Prints the bytes in the given value to the given ostream. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, ostream* os) { // Tells the user how big the object is. *os << count << "-byte object <"; const size_t kThreshold = 132; const size_t kChunkSize = 64; // If the object size is bigger than kThreshold, we'll have to omit // some details by printing only the first and the last kChunkSize // bytes. // TODO(wan): let the user control the threshold using a flag. if (count < kThreshold) { PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); } else { PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. const size_t resume_pos = (count - kChunkSize + 1)/2*2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; } } // namespace namespace internal2 { // Delegates to PrintBytesInObjectToImpl() to print the bytes in the // given object. The delegation simplifies the implementation, which // uses the << operator and thus is easier done outside of the // ::testing::internal namespace, which contains a << operator that // sometimes conflicts with the one in STL. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ostream* os) { PrintBytesInObjectToImpl(obj_bytes, count, os); } } // namespace internal2 namespace internal { // Depending on the value of a char (or wchar_t), we print it in one // of three formats: // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexidecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on // Windows Mobile. inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; } // Prints a wide or narrow char c as a character literal without the // quotes, escaping it when necessary; returns how c was formatted. // The template argument UnsignedChar is the unsigned version of Char, // which is the type of c. template <typename UnsignedChar, typename Char> static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { switch (static_cast<wchar_t>(c)) { case L'\0': *os << "\\0"; break; case L'\'': *os << "\\'"; break; case L'\\': *os << "\\\\"; break; case L'\a': *os << "\\a"; break; case L'\b': *os << "\\b"; break; case L'\f': *os << "\\f"; break; case L'\n': *os << "\\n"; break; case L'\r': *os << "\\r"; break; case L'\t': *os << "\\t"; break; case L'\v': *os << "\\v"; break; default: if (IsPrintableAscii(c)) { *os << static_cast<char>(c); return kAsIs; } else { *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c)); return kHexEscape; } } return kSpecialEscape; } // Prints a wchar_t c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { switch (c) { case L'\'': *os << "'"; return kAsIs; case L'"': *os << "\\\""; return kSpecialEscape; default: return PrintAsCharLiteralTo<wchar_t>(c, os); } } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { return PrintAsStringLiteralTo( static_cast<wchar_t>(static_cast<unsigned char>(c)), os); } // Prints a wide or narrow character c and its code. '\0' is printed // as "'\\0'", other unprintable characters are also properly escaped // using the standard C++ escape sequence. The template argument // UnsignedChar is the unsigned version of Char, which is the type of c. template <typename UnsignedChar, typename Char> void PrintCharAndCodeTo(Char c, ostream* os) { // First, print c as a literal in the most readable form we can find. *os << ((sizeof(c) > 1) ? "L'" : "'"); const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os); *os << "'"; // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). if (c == 0) return; *os << " (" << static_cast<int>(c); // For more convenience, we print c's code again in hexidecimal, // unless c was already printed in the form '\x##' or the code is in // [1, 9]. if (format == kHexEscape || (1 <= c && c <= 9)) { // Do nothing. } else { *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c)); } *os << ")"; } void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo<unsigned char>(c, os); } void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo<unsigned char>(c, os); } // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its code. L'\0' is printed as "L'\\0'". void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); } // Prints the given array of characters to the ostream. CharType must be either // char or wchar_t. // The array starts at begin, the length is len, it may include '\0' characters // and may not be NUL-terminated. template <typename CharType> static void PrintCharsAsStringTo( const CharType* begin, size_t len, ostream* os) { const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; *os << kQuoteBegin; bool is_previous_hex = false; for (size_t index = 0; index < len; ++index) { const CharType cur = begin[index]; if (is_previous_hex && IsXDigit(cur)) { // Previous character is of '\x..' form and this character can be // interpreted as another hexadecimal digit in its number. Break string to // disambiguate. *os << "\" " << kQuoteBegin; } is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; } *os << "\""; } // Prints a (const) char/wchar_t array of 'len' elements, starting at address // 'begin'. CharType must be either char or wchar_t. template <typename CharType> static void UniversalPrintCharArray( const CharType* begin, size_t len, ostream* os) { // The code // const char kFoo[] = "foo"; // generates an array of 4, not 3, elements, with the last one being '\0'. // // Therefore when printing a char array, we don't print the last element if // it's '\0', such that the output matches the string literal as it's // written in the source code. if (len > 0 && begin[len - 1] == '\0') { PrintCharsAsStringTo(begin, len - 1, os); return; } // If, however, the last element in the array is not '\0', e.g. // const char kFoo[] = { 'f', 'o', 'o' }; // we must print the entire array. We also print a message to indicate // that the array is not NUL-terminated. PrintCharsAsStringTo(begin, len, os); *os << " (no terminating NUL)"; } // Prints a (const) char array of 'len' elements, starting at address 'begin'. void UniversalPrintArray(const char* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints a (const) wchar_t array of 'len' elements, starting at address // 'begin'. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints the given C string to the ostream. void PrintTo(const char* s, ostream* os) { if (s == NULL) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; PrintCharsAsStringTo(s, strlen(s), os); } } // MSVC compiler can be configured to define whar_t as a typedef // of unsigned short. Defining an overload for const wchar_t* in that case // would cause pointers to unsigned shorts be printed as wide strings, // possibly accessing more memory than intended and causing invalid // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when // wchar_t is implemented as a native type. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Prints the given wide C string to the ostream. void PrintTo(const wchar_t* s, ostream* os) { if (s == NULL) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; PrintCharsAsStringTo(s, wcslen(s), os); } } #endif // wchar_t is native // Prints a ::string object. #if GTEST_HAS_GLOBAL_STRING void PrintStringTo(const ::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_STRING void PrintStringTo(const ::std::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } // Prints a ::wstring object. #if GTEST_HAS_GLOBAL_WSTRING void PrintWideStringTo(const ::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING void PrintWideStringTo(const ::std::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_STD_WSTRING } // namespace internal } // namespace testing
#ifndef CONNECT___SERVER__HPP #define CONNECT___SERVER__HPP /* $Id: server.hpp 364724 2012-05-30 14:57:38Z ivanovp $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Aaron Ucko, Victor Joukov, Denis Vakatov * */ /// @file server.hpp /// Framework to create multithreaded network servers with thread-per-request /// scheduling. #include <connect/impl/thread_pool_for_server.hpp> #include <connect/ncbi_conn_stream.hpp> #include <connect/ncbi_conn_exception.hpp> #include <connect/ncbi_socket.hpp> /** @addtogroup ThreadedServer * * @{ */ BEGIN_NCBI_SCOPE class IServer_ConnectionFactory; class IServer_ConnectionBase; struct SServer_Parameters; class CServer_ConnectionPool; class CServer_Connection; /// Extended copy of the type EIO_Event allowing to distinguish between /// connection closing from client and from ourselves enum EServIO_Event { eServIO_Open = 0x00, eServIO_Read = 0x01, eServIO_Write = 0x02, eServIO_ReadWrite = 0x03, /**< eIO_Read | eIO_Write */ eServIO_ClientClose = 0x04, eServIO_OurClose = 0x08, eServIO_Inactivity = 0x10, eServIO_Delete = 0x20 }; /// Transform EIO_Event type to EServIO_Event inline EServIO_Event IOEventToServIOEvent(EIO_Event event) { return (EServIO_Event) event; } class CNetCacheServer; ///////////////////////////////////////////////////////////////////////////// /// /// CServer:: /// /// Thread-pool based server. On every event it allocates one of threads /// from pool to serve the event, thereby making possible to serve large /// number of concurrent connections efficiently. You need to subclass it /// only if you want to provide gentle shutdown ability (override /// ShutdownRequested) or process data in main thread on timeout (override /// ProcessTimeout and set parameter accept_timeout to non-zero value). /// class NCBI_XCONNECT_EXPORT CServer : protected CConnIniter { public: // 'ctors CServer(void); virtual ~CServer(); /// Register a listener void AddListener(IServer_ConnectionFactory* factory, unsigned short port); /// void SetParameters(const SServer_Parameters& new_params); /// void GetParameters(SServer_Parameters* params); /// Start listening before the main loop. If called, tries /// to listen on all requested ports for all listeners, correcting /// errors by calling listeners' OnFailure void StartListening(void); /// Enter the main loop void Run(void); /// Submit request to be executed by the server thread pool void SubmitRequest(const CRef<CStdRequest>& request); /// Mark connection as deferred for processing, i.e. do not poll on it /// and wait when IsReadyToProcess() will return true. void DeferConnectionProcessing(IServer_ConnectionBase* conn); void DeferConnectionProcessing(CSocket* sock); /// Close connection. Method should be called only when closing is /// initiated by server itself, because it will generate then event /// eServIO_OurClose. /// /// @sa EServIO_Event void CloseConnection(CSocket* sock); /// Add externally created connection to the connection pool which server /// polls on. Throws exception if pool is full. /// NOTE: events to this connection can come theoretically even /// NOTE: if connection gets some error or its peer closes it then conn /// object will be deleted after processing OnClose event. If you don't /// want that you have to call RemoveConnectionFromPool while handling /// OnClose. void AddConnectionToPool(CServer_Connection* conn); /// Remove externally created connection from pool. void RemoveConnectionFromPool(CServer_Connection* conn); /// Force poll cycle to make another iteration. /// Should be called if IsReadyToProcess() for some connection handler /// became true. void WakeUpPollCycle(void); /// Set custom suffix to use on all threads in the server's pool. /// Value can be set only before call to Run(), any change of the value /// after call to Run() will be ignored. void SetCustomThreadSuffix(const string& suffix) { m_ThreadSuffix = suffix; } protected: /// Initialize the server /// /// Called by Run method before poll cycle. virtual void Init(); /// Cleanup the server /// /// Called by Run method after poll cycle when all processing threads /// are stopped, but before releasing listening ports. Here you're still /// guaranteed that another instance running on the same set of ports will /// fail at StartListening point. virtual void Exit(); /// Runs synchronously when no socket activity has occurred in a /// while (as determined by m_AcceptTimeout). /// @sa m_Parameters->accept_timeout virtual void ProcessTimeout(void) { } /// Runs synchronously between iterations. /// @return /// whether to shut down service and return from Run. virtual bool ShutdownRequested(void) { return false; } private: void x_AddRequests(const vector<CRef<CStdRequest> >& reqs); void x_DoRun(void); friend class CNetCacheServer; CPoolOfThreads_ForServer* GetThreadPool(void) { return m_ThreadPool.get(); } auto_ptr<CPoolOfThreads_ForServer> m_ThreadPool; SServer_Parameters* m_Parameters; CServer_ConnectionPool* m_ConnectionPool; string m_ThreadSuffix; }; ///////////////////////////////////////////////////////////////////////////// /// /// Error codes for OnOverflow method in IServer_ConnectionHandler enum EOverflowReason { eOR_Unknown = 0, eOR_ConnectionPoolFull, eOR_RequestQueueFull, eOR_UnpollableSocket }; ///////////////////////////////////////////////////////////////////////////// /// /// IServer_ConnectionHandler:: /// /// Implement this interface to provide server functionality. /// class NCBI_XCONNECT_EXPORT IServer_ConnectionHandler { public: virtual ~IServer_ConnectionHandler() { } /// Following three methods are guaranteed to be called NOT /// at the same time as On*, so if you implement them /// you should not guard the variables which they can use with /// mutexes. /// @param alarm_time /// Set this parameter to a pointer to a CTime object to recieve /// an OnTimer event at the moment in time specified by this object. /// @return /// Returns the set of events for which Poll should check. virtual EIO_Event GetEventsToPollFor(const CTime** /*alarm_time*/) const { return eIO_Read; } /// Returns the timeout for this connection virtual const STimeout* GetTimeout(void) { return kDefaultTimeout; } /// Returns connection handler's perception of whether we open or not. /// It is unsafe to just close underlying socket because of the race, /// emerging due to the fact that the socket can linger for a while. virtual bool IsOpen(void) { return true; } /// Returns the handler's readiness to process input data or to write /// some output data. OnRead() and OnWrite() are not called unless this /// method return true. virtual bool IsReadyToProcess(void) const { return true; } /// Runs in response to an external event [asynchronous]. /// You can get socket by calling GetSocket(), if you close the socket /// this object will be destroyed. /// Individual events are: /// A client has just established this connection. virtual void OnOpen(void) = 0; /// The client has just sent data. virtual void OnRead(void) = 0; /// The client is ready to receive data. virtual void OnWrite(void) = 0; /// Type of connection closing enum EClosePeer { eOurClose, ///< Connection closed by ourselves eClientClose ///< Connection closed by other peer }; /// The connection has closed (with information on type of closing) virtual void OnClose(EClosePeer /*peer*/) { } /// Runs when a client has been idle for too long, prior to /// closing the connection [synchronous]. virtual void OnTimeout(void) { } /// This method is called at the moment in time specified earlier by the /// alarm_time parameter of the GetEventsToPollFor method [synchronous]. virtual void OnTimer(void) { } /// Runs when there are insufficient resources to queue a /// connection, prior to closing it. Provides a reason why the /// connection is being close, which can be reported back to the client. // See comment for CAcceptRequest::Process and CServer::CreateRequest virtual void OnOverflow(EOverflowReason) { } /// Get underlying socket CSocket& GetSocket(void) { return *m_Socket; } public: // TODO: make it protected. Public is for DEBUG purposes only friend class CServer_Connection; void SetSocket(CSocket *socket) { m_Socket = socket; } private: CSocket* m_Socket; }; ///////////////////////////////////////////////////////////////////////////// /// /// IServer_MessageHandler:: /// /// TODO: class NCBI_XCONNECT_EXPORT IServer_MessageHandler : public IServer_ConnectionHandler { public: IServer_MessageHandler() : m_Buffer(0) { } virtual ~IServer_MessageHandler() { BUF_Destroy(m_Buffer); } virtual void OnRead(void); // You should implement this look-ahead function to decide, did you get // a message in the series of read events. If not, you should return -1. // If yes, return number of chars, beyond well formed message. E.g., if // your message spans all the buffer, return 0. If you returned non-zero // value, this piece of data will be used in the next CheckMessage to // simplify client state management. // You also need to copy bytes, comprising the message from data to buffer. virtual int CheckMessage(BUF* buffer, const void *data, size_t size) = 0; // Process incoming message in the buffer, by using // BUF_Read(buffer, your_data_buffer, BUF_Size(buffer)). virtual void OnMessage(BUF buffer) = 0; private: BUF m_Buffer; }; int NCBI_XCONNECT_EXPORT Server_CheckLineMessage(BUF* buffer, const void *data, size_t size, bool& seen_CR); ///////////////////////////////////////////////////////////////////////////// /// /// IServer_LineMessageHandler:: /// /// TODO: class NCBI_XCONNECT_EXPORT IServer_LineMessageHandler : public IServer_MessageHandler { public: IServer_LineMessageHandler() : IServer_MessageHandler(), m_SeenCR(false) { } virtual int CheckMessage(BUF* buffer, const void *data, size_t size) { return Server_CheckLineMessage(buffer, data, size, m_SeenCR); } private: bool m_SeenCR; }; ///////////////////////////////////////////////////////////////////////////// /// /// IServer_StreamHandler:: /// /// TODO: class NCBI_XCONNECT_EXPORT IServer_StreamHandler : public IServer_ConnectionHandler { public: CNcbiIostream &GetStream(); private: CConn_SocketStream m_Stream; }; ///////////////////////////////////////////////////////////////////////////// /// /// IServer_ConnectionFactory:: /// /// Factory to be registered with CServer instance. You usually do not /// need to implement it, default template CServer_ConnectionFactory will /// suffice. You NEED to implement it manually to pass server-wide parameters /// to ConnectionHandler instances, e.g. for implementation of gentle shutdown. /// class NCBI_XCONNECT_EXPORT IServer_ConnectionFactory { public: /// What to do if the port is busy enum EListenAction { eLAFail = 0, // Can not live without this port, default eLAIgnore = 1, // Do nothing, throw away this listener eLARetry = 2 // Listener should provide another port to try }; virtual ~IServer_ConnectionFactory() { } /// @return /// a new instance of handler for connection virtual IServer_ConnectionHandler* Create(void) = 0; /// Return desired action if the port, mentioned in AddListener is busy. /// If the action is eLARetry, provide new port. The virtual EListenAction OnFailure(unsigned short* /* port */) { return eLAFail; } }; ///////////////////////////////////////////////////////////////////////////// /// /// CServer_ConnectionFactory:: /// /// Reasonable default implementation for IServer_ConnectionFactory /// template <class TServer_ConnectionHandler> class CServer_ConnectionFactory : public IServer_ConnectionFactory { public: virtual IServer_ConnectionHandler* Create() { return new TServer_ConnectionHandler(); } }; ///////////////////////////////////////////////////////////////////////////// /// /// SServer_Parameters:: /// /// Settings for CServer /// struct NCBI_XCONNECT_EXPORT SServer_Parameters { /// Maximum # of open connections unsigned int max_connections; /// Temporarily close listener when queue fills? bool temporarily_stop_listening; /// Maximum t between exit checks const STimeout* accept_timeout; /// For how long to keep inactive non-listening sockets open /// (default: 10 minutes) const STimeout* idle_timeout; // (settings for the thread pool) unsigned int init_threads; ///< Number of initial threads unsigned int max_threads; ///< Maximum simultaneous threads unsigned int spawn_threshold; ///< Controls when to spawn more threads /// Create structure with the default set of parameters SServer_Parameters(); }; ///////////////////////////////////////////////////////////////////////////// /// /// CServer_Exception:: /// /// Exceptions thrown by CServer::Run() /// class NCBI_XCONNECT_EXPORT CServer_Exception : EXCEPTION_VIRTUAL_BASE public CConnException { public: enum EErrCode { eBadParameters, ///< Out-of-range parameters given eCouldntListen, ///< Unable to bind listening port ePoolOverflow ///< Connection pool overflowed }; virtual const char* GetErrCodeString(void) const; NCBI_EXCEPTION_DEFAULT(CServer_Exception, CConnException); }; END_NCBI_SCOPE /* @} */ #endif /* CONNECT___SERVER__HPP */
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to find minimum time required to rot all oranges. int orangesRotting(vector<vector<int>>& grid) { // Code here int n = grid.size(); int m = grid[0].size(); // BFS traversal // stores index of rotten oranges queue<pair<int,int>> rotten; // first count total oranges in grid and push the rotten // into the queue to be processed int totOranges = 0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ // if cell not empty if(grid[i][j]!=0){ totOranges++; // if rotten push to queue if(grid[i][j]==2) rotten.push({i,j}); } } } int mx[] = { 0,0,-1,1}; int my[] = {-1,1, 0,0}; // count of total oranges rotted or will rot int cntRot = 0, days = 0; while(!rotten.empty()){ // getting number of oranges rotten each day int k = rotten.size(); cntRot += k; while(k--){ int x = rotten.front().first, y = rotten.front().second; rotten.pop(); // traversing all 4 directions from current node for(int i=0;i<4;i++){ int nx = x+mx[i], ny = y+my[i]; // if index out of bound or orange not present // or rotten from before then ignore if(nx<0 or ny<0 or nx>=n or ny>=m or grid[nx][ny]!=1) continue; // else rot the fresh orange and push to queue grid[nx][ny] = 2; rotten.push({nx,ny}); } } // at end of day we check if rotten isn't empty // means another day is required to rot oranges // increasing day to rot all fresh oranges if(!rotten.empty()) days++; } // now check if all oranges in grid have rotted or not // then return number of days else not possible return -1 return (totOranges==cntRot)?days:-1; } }; // { Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int n, m; cin >> n >> m; vector<vector<int>>grid(n, vector<int>(m, -1)); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> grid[i][j]; } } Solution obj; int ans = obj.orangesRotting(grid); cout << ans << "\n"; } return 0; } // } Driver Code Ends
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
12