text
stringlengths 5
1.04M
|
|---|
/// @file
/// @ingroup lxmax
/// @copyright Copyright 2020 David Butler / The Impersonal Stereo. All rights reserved.
/// @license Use of this source code is governed by the MIT License found in the LICENSE.md file.
#pragma once
#include <cmath>
#include <vector>
#include <mutex>
#include <Poco/Net/DatagramSocket.h>
#include <Poco/Net/MulticastSocket.h>
#include <Poco/Timer.h>
#include <Poco/UUIDGenerator.h>
#include "common.hpp"
#include "hash_functions.hpp"
#include "dmx_packet_artnet.hpp"
#include "dmx_packet_sacn.hpp"
namespace lxmax
{
struct dmx_input_universe_config
{
dmx_protocol protocol;
universe_address internal_universe;
universe_address protocol_universe;
universe_address sync_address;
int priority;
Poco::Net::IPAddress send_address;
};
class dmx_input_service
{
const milliseconds k_full_update_interval { 1000 };
bool _isRunning { false };
Poco::Timer _timer { 0, static_cast<int>(std::round(1000. / k_dmx_framerate_max)) };
Poco::Net::DatagramSocket _socket;
Poco::Net::MulticastSocket _multicast_socket;
universe_buffer_map _universe_buffers;
universe_updated_set _updated_universes;
std::mutex _config_mutex;
std::vector<dmx_input_universe_config> _configs;
const std::string _system_name;
const Poco::UUID _system_id;
uint8_t _artnet_sequence = 1;
uint8_t _sacn_sequence = 0;
timestamp _last_full_update_time;
public:
dmx_input_service()
: _system_name(Poco::Environment::nodeName()),
_system_id(Poco::UUIDGenerator::defaultGenerator().createFromName(Poco::UUID(), _system_name))
{
Poco::Net::initializeNetwork();
_socket.bind(Poco::Net::SocketAddress(Poco::Net::IPAddress("0.0.0.0"), k_artnet_port));
_socket.setBroadcast(true);
_multicast_socket.bind(Poco::Net::SocketAddress(Poco::Net::IPAddress("0.0.0.0"), k_sacn_port));
_multicast_socket.setInterface(Poco::Net::NetworkInterface::forIndex(1));
_multicast_socket.setLoopback(true);
_universe_buffers.insert(universe_buffer_map_entry(universe_address(1), universe_buffer()));
}
void start()
{
_timer.start(Poco::TimerCallback<dmx_input_service>(*this, &dmx_input_service::on_timer));
_isRunning = true;
}
void stop()
{
_timer.stop();
_isRunning = false;
}
void update_configs(const std::vector<dmx_input_universe_config>& configs)
{
std::lock_guard<std::mutex> lock(_config_mutex);
update_multicast_groups(_configs, configs);
_configs = configs;
}
private:
void on_timer(Poco::Timer& timer);
void update_multicast_groups(const std::vector<dmx_input_universe_config>& old_configs,
const std::vector<dmx_input_universe_config>& new_configs);
};
}
|
//【P1583】魔法照片 - 洛谷 - 0
#include <iostream>
#include <algorithm>
struct People {
//int w, d, c;
int w, id;
} *a;
inline bool cmp(People p1, People p2) {
if (p1.w == p2.w)
return p1.id < p2.id;
return p1.w > p2.w;
}
int main() {
int n, k;
std::cin >> n >> k;
a = new People[n + 1];
int *e = new int[10 + 1];
for (int i = 1; i <= 10; ++i) {
std::cin >> e[i];
}
for (int i = 1; i <= n; ++i) {
std::cin >> a[i].w;
a[i].id = i;
}
std::sort(a + 1, a + n + 1, cmp);
for (int i = 1; i <= n; ++i) {
a[i].w += e[((i - 1) % 10) + 1];
}
std::sort(a + 1, a + n + 1, cmp);
for (int i = 1; i <= k; ++i) {
std::cout << a[i].id << " ";
}
std::cout << std::endl;
}
|
// Copyright (c) 2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zhbetchain.h"
#include "invalid.h"
#include "main.h"
#include "txdb.h"
#include "ui_interface.h"
// 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4)
#define SCRIPT_OFFSET 6
// For Script size (BIGNUM/Uint256 size)
#define BIGNUM_SIZE 4
bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, vector<CBigNum>& vValues)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (const CTxOut txOut : tx.vout) {
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false));
if(!TxOutToPublicCoin(txOut, coin, state))
return false;
if (coin.getDenomination() != denom)
continue;
vValues.push_back(coin.getValue());
}
}
return true;
}
bool BlockToPubcoinList(const CBlock& block, std::list<libzerocoin::PublicCoin>& listPubcoins, bool fFilterInvalid)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
// Filter out mints that have used invalid outpoints
if (fFilterInvalid) {
bool fValid = true;
for (const CTxIn in : tx.vin) {
if (!ValidOutPoint(in.prevout, INT_MAX)) {
fValid = false;
break;
}
}
if (!fValid)
continue;
}
uint256 txHash = tx.GetHash();
for (unsigned int i = 0; i < tx.vout.size(); i++) {
//Filter out mints that use invalid outpoints - edge case: invalid spend with minted change
if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX))
break;
const CTxOut txOut = tx.vout[i];
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false));
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
listPubcoins.emplace_back(pubCoin);
}
}
return true;
}
//return a list of zerocoin mints contained in a specific block
bool BlockToZerocoinMintList(const CBlock& block, std::list<CZerocoinMint>& vMints, bool fFilterInvalid)
{
for (const CTransaction& tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
// Filter out mints that have used invalid outpoints
if (fFilterInvalid) {
bool fValid = true;
for (const CTxIn in : tx.vin) {
if (!ValidOutPoint(in.prevout, INT_MAX)) {
fValid = false;
break;
}
}
if (!fValid)
continue;
}
uint256 txHash = tx.GetHash();
for (unsigned int i = 0; i < tx.vout.size(); i++) {
//Filter out mints that use invalid outpoints - edge case: invalid spend with minted change
if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX))
break;
const CTxOut txOut = tx.vout[i];
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false));
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
//version should not actually matter here since it is just a reference to the pubcoin, not to the privcoin
uint8_t version = 1;
CZerocoinMint mint = CZerocoinMint(pubCoin.getDenomination(), pubCoin.getValue(), 0, 0, false, version, nullptr);
mint.SetTxHash(tx.GetHash());
vMints.push_back(mint);
}
}
return true;
}
void FindMints(std::vector<CMintMeta> vMintsToFind, std::vector<CMintMeta>& vMintsToUpdate, std::vector<CMintMeta>& vMissingMints)
{
// see which mints are in our public zerocoin database. The mint should be here if it exists, unless
// something went wrong
for (CMintMeta meta : vMintsToFind) {
uint256 txHash;
if (!zerocoinDB->ReadCoinMint(meta.hashPubcoin, txHash)) {
vMissingMints.push_back(meta);
continue;
}
// make sure the txhash and block height meta data are correct for this mint
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(txHash, tx, hashBlock, true)) {
LogPrintf("%s : cannot find tx %s\n", __func__, txHash.GetHex());
vMissingMints.push_back(meta);
continue;
}
if (!mapBlockIndex.count(hashBlock)) {
LogPrintf("%s : cannot find block %s\n", __func__, hashBlock.GetHex());
vMissingMints.push_back(meta);
continue;
}
//see if this mint is spent
uint256 hashTxSpend = 0;
bool fSpent = zerocoinDB->ReadCoinSpend(meta.hashSerial, hashTxSpend);
//if marked as spent, check that it actually made it into the chain
CTransaction txSpend;
uint256 hashBlockSpend;
if (fSpent && !GetTransaction(hashTxSpend, txSpend, hashBlockSpend, true)) {
LogPrintf("%s : cannot find spend tx %s\n", __func__, hashTxSpend.GetHex());
meta.isUsed = false;
vMintsToUpdate.push_back(meta);
continue;
}
//The mint has been incorrectly labelled as spent in zerocoinDB and needs to be undone
int nHeightTx = 0;
uint256 hashSerial = meta.hashSerial;
uint256 txidSpend;
if (fSpent && !IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend)) {
LogPrintf("%s : cannot find block %s. Erasing coinspend from zerocoinDB.\n", __func__, hashBlockSpend.GetHex());
meta.isUsed = false;
vMintsToUpdate.push_back(meta);
continue;
}
// is the denomination correct?
for (auto& out : tx.vout) {
if (!out.IsZerocoinMint())
continue;
libzerocoin::PublicCoin pubcoin(Params().Zerocoin_Params(meta.nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION));
CValidationState state;
TxOutToPublicCoin(out, pubcoin, state);
if (GetPubCoinHash(pubcoin.getValue()) == meta.hashPubcoin && pubcoin.getDenomination() != meta.denom) {
LogPrintf("%s: found mismatched denom pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex());
meta.denom = pubcoin.getDenomination();
vMintsToUpdate.emplace_back(meta);
}
}
// if meta data is correct, then no need to update
if (meta.txid == txHash && meta.nHeight == mapBlockIndex[hashBlock]->nHeight && meta.isUsed == fSpent)
continue;
//mark this mint for update
meta.txid = txHash;
meta.nHeight = mapBlockIndex[hashBlock]->nHeight;
meta.isUsed = fSpent;
LogPrintf("%s: found updates for pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex());
vMintsToUpdate.push_back(meta);
}
}
int GetZerocoinStartHeight()
{
return Params().Zerocoin_StartHeight();
}
bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash)
{
txHash = 0;
return zerocoinDB->ReadCoinMint(bnPubcoin, txHash);
}
bool IsPubcoinInBlockchain(const uint256& hashPubcoin, uint256& txid)
{
txid = 0;
return zerocoinDB->ReadCoinMint(hashPubcoin, txid);
}
bool IsSerialKnown(const CBigNum& bnSerial)
{
uint256 txHash = 0;
return zerocoinDB->ReadCoinSpend(bnSerial, txHash);
}
bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx)
{
uint256 txHash = 0;
// if not in zerocoinDB then its not in the blockchain
if (!zerocoinDB->ReadCoinSpend(bnSerial, txHash))
return false;
return IsTransactionInChain(txHash, nHeightTx);
}
bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend)
{
CTransaction tx;
return IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend, tx);
}
bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend, CTransaction& tx)
{
txidSpend = 0;
// if not in zerocoinDB then its not in the blockchain
if (!zerocoinDB->ReadCoinSpend(hashSerial, txidSpend))
return false;
return IsTransactionInChain(txidSpend, nHeightTx, tx);
}
/* std::string ReindexZerocoinDB()
{
if (!zerocoinDB->WipeCoins("spends") || !zerocoinDB->WipeCoins("mints")) {
return _("Failed to wipe zerocoinDB");
}
uiInterface.ShowProgress(_("Reindexing zerocoin database..."), 0);
CBlockIndex* pindex = chainActive[Params().Zerocoin_StartHeight()];
std::vector<std::pair<libzerocoin::CoinSpend, uint256> > vSpendInfo;
std::vector<std::pair<libzerocoin::PublicCoin, uint256> > vMintInfo;
while (pindex) {
uiInterface.ShowProgress(_("Reindexing zerocoin database..."), std::max(1, std::min(99, (int)((double)(pindex->nHeight - Params().Zerocoin_StartHeight()) / (double)(chainActive.Height() - Params().Zerocoin_StartHeight()) * 100))));
if (pindex->nHeight % 1000 == 0)
LogPrintf("Reindexing zerocoin : block %d...\n", pindex->nHeight);
CBlock block;
if (!ReadBlockFromDisk(block, pindex)) {
return _("Reindexing zerocoin failed");
}
for (const CTransaction& tx : block.vtx) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (tx.IsCoinBase())
break;
if (tx.ContainsZerocoins()) {
uint256 txid = tx.GetHash();
//Record Serials
if (tx.IsZerocoinSpend()) {
for (auto& in : tx.vin) {
if (!in.scriptSig.IsZerocoinSpend())
continue;
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(in);
vSpendInfo.push_back(make_pair(spend, txid));
}
}
//Record mints
if (tx.IsZerocoinMint()) {
for (auto& out : tx.vout) {
if (!out.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin coin(Params().Zerocoin_Params(pindex->nHeight < Params().Zerocoin_Block_V2_Start()));
TxOutToPublicCoin(out, coin, state);
vMintInfo.push_back(make_pair(coin, txid));
}
}
}
}
}
// Flush the zerocoinDB to disk every 100 blocks
if (pindex->nHeight % 100 == 0) {
if ((!vSpendInfo.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpendInfo)) || (!vMintInfo.empty() && !zerocoinDB->WriteCoinMintBatch(vMintInfo)))
return _("Error writing zerocoinDB to disk");
vSpendInfo.clear();
vMintInfo.clear();
}
pindex = chainActive.Next(pindex);
}
uiInterface.ShowProgress("", 100);
// Final flush to disk in case any remaining information exists
if ((!vSpendInfo.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpendInfo)) || (!vMintInfo.empty() && !zerocoinDB->WriteCoinMintBatch(vMintInfo)))
return _("Error writing zerocoinDB to disk");
uiInterface.ShowProgress("", 100);
return "";
} */
bool RemoveSerialFromDB(const CBigNum& bnSerial)
{
return zerocoinDB->EraseCoinSpend(bnSerial);
}
libzerocoin::CoinSpend TxInToZerocoinSpend(const CTxIn& txin)
{
// extract the CoinSpend from the txin
std::vector<char, zero_after_free_allocator<char> > dataTxIn;
dataTxIn.insert(dataTxIn.end(), txin.scriptSig.begin() + BIGNUM_SIZE, txin.scriptSig.end());
CDataStream serializedCoinSpend(dataTxIn, SER_NETWORK, PROTOCOL_VERSION);
libzerocoin::ZerocoinParams* paramsAccumulator = Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start());
libzerocoin::CoinSpend spend(Params().Zerocoin_Params(true), paramsAccumulator, serializedCoinSpend);
return spend;
}
bool TxOutToPublicCoin(const CTxOut& txout, libzerocoin::PublicCoin& pubCoin, CValidationState& state)
{
CBigNum publicZerocoin;
vector<unsigned char> vchZeroMint;
vchZeroMint.insert(vchZeroMint.end(), txout.scriptPubKey.begin() + SCRIPT_OFFSET,
txout.scriptPubKey.begin() + txout.scriptPubKey.size());
publicZerocoin.setvch(vchZeroMint);
libzerocoin::CoinDenomination denomination = libzerocoin::AmountToZerocoinDenomination(txout.nValue);
LogPrint("zero", "%s ZCPRINT denomination %d pubcoin %s\n", __func__, denomination, publicZerocoin.GetHex());
if (denomination == libzerocoin::ZQ_ERROR)
return state.DoS(100, error("TxOutToPublicCoin : txout.nValue is not correct"));
libzerocoin::PublicCoin checkPubCoin(Params().Zerocoin_Params(false), publicZerocoin, denomination);
pubCoin = checkPubCoin;
return true;
}
//return a list of zerocoin spends contained in a specific block, list may have many denominations
std::list<libzerocoin::CoinDenomination> ZerocoinSpendListFromBlock(const CBlock& block, bool fFilterInvalid)
{
std::list<libzerocoin::CoinDenomination> vSpends;
for (const CTransaction tx : block.vtx) {
if (!tx.IsZerocoinSpend())
continue;
for (const CTxIn txin : tx.vin) {
if (!txin.scriptSig.IsZerocoinSpend())
continue;
if (fFilterInvalid) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin);
if (invalid_out::ContainsSerial(spend.getCoinSerialNumber()))
continue;
}
libzerocoin::CoinDenomination c = libzerocoin::IntToZerocoinDenomination(txin.nSequence);
vSpends.push_back(c);
}
}
return vSpends;
}
|
/*
* Author: Brendan Le Foll <brendan.le.foll@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "uart.h"
namespace mraa {
/**
* @brief API to UART (enabling only)
*
* This file defines the UART interface for libmraa
*/
class Uart {
public:
/**
* Uart Constructor, takes a pin number which will map directly to the
* linux uart number, this 'enables' the uart, nothing more
*
* @param uart the index of the uart set to use
*/
Uart(int uart) {
m_uart = mraa_uart_init(uart);
}
/**
* Uart destructor
*/
~Uart() {
return;
}
private:
mraa_uart_context m_uart;
};
}
|
// (C) Copyright 2002-2007 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//-----------------------------------------------------------------------------
//----- [!output IMPL_FILE] : Implementation of [!output CLASS_NAME_ROOT]
//-----------------------------------------------------------------------------
#include "StdAfx.h"
#include "[!output HEADER_FILE]"
//-----------------------------------------------------------------------------
ACRX_CONS_DEFINE_MEMBERS([!output CLASS_NAME_ROOT], [!output BASE_CLASS], 1)
//-----------------------------------------------------------------------------
[!output CLASS_NAME_ROOT]::[!output CLASS_NAME_ROOT] (AcApDocument *pDoc) : [!output BASE_CLASS](), mpDocument(pDoc) {
if ( pDoc )
pDoc->transactionManager ()->addReactor (this) ;
}
//-----------------------------------------------------------------------------
[!output CLASS_NAME_ROOT]::~[!output CLASS_NAME_ROOT] () {
Detach () ;
}
//-----------------------------------------------------------------------------
void [!output CLASS_NAME_ROOT]::Attach (AcApDocument *pDoc) {
Detach () ;
if ( mpDocument == NULL ) {
if ( (mpDocument =pDoc) != NULL )
pDoc->transactionManager ()->addReactor (this) ;
}
}
void [!output CLASS_NAME_ROOT]::Detach () {
if ( mpDocument ) {
mpDocument->transactionManager ()->removeReactor (this) ;
mpDocument =NULL ;
}
}
AcApDocument *[!output CLASS_NAME_ROOT]::Subject () const {
return (mpDocument) ;
}
bool [!output CLASS_NAME_ROOT]::IsAttached () const {
return (mpDocument != NULL) ;
}
|
// Copyright 2018 The MACE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cmath>
#include "mace/core/operator.h"
namespace mace {
namespace ops {
template <DeviceType D, class T>
class LocalResponseNormOp;
template <>
class LocalResponseNormOp<DeviceType::CPU, float> : public Operation {
public:
explicit LocalResponseNormOp(OpConstructContext *context)
: Operation(context),
depth_radius_(Operation::GetOptionalArg<int>("depth_radius", 5)),
bias_(Operation::GetOptionalArg<float>("bias", 1.0f)),
alpha_(Operation::GetOptionalArg<float>("alpha", 1.0f)),
beta_(Operation::GetOptionalArg<float>("beta", 0.5f)) {}
MaceStatus Run(OpContext *context) override {
MACE_UNUSED(context);
const Tensor *input = this->Input(0);
MACE_CHECK(input->dim_size() == 4, "input must be 4-dimensional. ",
input->dim_size());
Tensor *output = this->Output(0);
MACE_RETURN_IF_ERROR(output->ResizeLike(input));
const index_t batch = input->dim(0);
const index_t channels = input->dim(1);
const index_t height = input->dim(2);
const index_t width = input->dim(3);
const float *input_ptr = input->data<float>();
float *output_ptr = output->mutable_data<float>();
index_t image_size = height * width;
index_t batch_size = channels * image_size;
#pragma omp parallel for collapse(2) schedule(runtime)
for (index_t b = 0; b < batch; ++b) {
for (index_t c = 0; c < channels; ++c) {
const int begin_input_c = std::max(static_cast<index_t>(0),
c - depth_radius_);
const int end_input_c = std::min(channels, c + depth_radius_ + 1);
index_t pos = b * batch_size;
for (index_t hw = 0; hw < height * width; ++hw, ++pos) {
float accum = 0.f;
for (int input_c = begin_input_c; input_c < end_input_c; ++input_c) {
const float input_val = input_ptr[pos + input_c * image_size];
accum += input_val * input_val;
}
const float multiplier = std::pow(bias_ + alpha_ * accum, -beta_);
output_ptr[pos + c * image_size] =
input_ptr[pos + c * image_size] * multiplier;
}
}
}
return MaceStatus::MACE_SUCCESS;
}
private:
int depth_radius_;
float bias_;
float alpha_;
float beta_;
};
void RegisterLocalResponseNorm(OpRegistryBase *op_registry) {
MACE_REGISTER_OP(op_registry, "LocalResponseNorm",
LocalResponseNormOp, DeviceType::CPU, float);
}
} // namespace ops
} // namespace mace
|
#ifndef MACROS_HPP__
#define MACROS_HPP__
#define TEST_SUITE REGISTER_NEW_TEST_SUITE();
#endif
|
#include <bits/stdc++.h>
using namespace std;
typedef struct {
int index;
int processTime;
int fin_time;
}pairs;
typedef struct {
int index;
int burst;
}arr;
void sort(int *arrival_times, int * burst_times, int n){
int temp;
for (int i=0; i< n-1; i++){
for(int j=0; j< n-i-1; j++){
if(arrival_times[j]>arrival_times[j+1]){
temp = arrival_times[j];
arrival_times[j] = arrival_times[j+1];
arrival_times[j+1] = temp;
temp = burst_times[j];
burst_times[j] = burst_times[j+1];
burst_times[j+1] = temp;
}
}
}
}
bool compare(const arr& l, const arr &m){
return l.burst<m.burst;
}
void FCFS(int * arrival_times, int *burst_times, int n){
float avg = 0;
int total_time = 0;
for (int i=0; i< n; i++){
if(arrival_times[i]>total_time)
total_time = arrival_times[i];
total_time = total_time + burst_times[i];
avg = avg + total_time- arrival_times[i];
//cout << avg << endl;
}
avg = avg/n;
cout << " Average Turnaround time with FCFS = " << avg << endl;
}
void PSJF(int *arrival_times, int* burst_times, int n){
float avg =0;
int time =0;
arr times[n];
int job =1;
int finTime[n];
vector <arr> process;
arr temp;
for(int i=0;i<n;i++){
times[i].index =i;
times[i].burst = burst_times[i];
}
process.push_back(times[0]);
while(!process.empty() || job<n){
time++;
while(job<n && arrival_times[job]<=time){
process.push_back(times[job]);
job++;
}
if(!process.empty()){
temp = process[0];
process.erase(process.begin());
temp.burst = temp.burst-1;
if(temp.burst==0)
finTime[temp.index]=time;
else
process.push_back(temp);
sort(process.begin(), process.end(), compare);
}
}
for (int i=0; i<n;i++){
avg += (finTime[i]- arrival_times[i]);
}
avg = avg/n;
cout << "Average turnaround time for PSJF is : " << avg << endl;
}
void RoundRobin(int *arrival_times, int *burst_times, int n, int delta){
float avg=0;
int time =0;
queue <pairs> t;
int job =0;
pairs times[n];
for(int i=0;i<n;i++){
times[i].index =i;
times[i].fin_time = 0;
times[i].processTime =0;
}
t.push(times[0]);
pairs temp;
while(job<n){
time = time+delta;
while(arrival_times[job+1]<= time && (job+1)<n){
t.push(times[job+1]);
job++;
}
if(t.empty())
continue;
temp = t.front();
t.pop();
temp.processTime+=delta;
times[temp.index].processTime+=delta;
if(temp.processTime > burst_times[temp.index]){
time = time-(temp.processTime-burst_times[temp.index]);
times[temp.index].fin_time = time;
}
else if (temp.processTime == burst_times[temp.index]){
times[temp.index].fin_time = time;
}
else
t.push(times[temp.index]);
if(job==n-1)
break;
}
while(!t.empty()){
time = time+delta;
temp = t.front();
t.pop();
temp.processTime+=delta;
times[temp.index].processTime+=delta;
if(temp.processTime > burst_times[temp.index]){
time = time-(temp.processTime-burst_times[temp.index]);
times[temp.index].fin_time = time;
}
else if (temp.processTime == burst_times[temp.index]){
times[temp.index].fin_time = time;
}
else
t.push(times[temp.index]);
}
for (int i=0; i<n;i++){
avg += (times[i].fin_time- arrival_times[i]);
}
avg = avg/n;
cout << "Average turnaround time for RoundRobin is : " << avg << endl;
}
int main(){
int n;
float mean;
srand(210);
cout << "Enter number of processes " << endl;
cin >> n;
int arrivals[n];
int bursts[n];
cout << "Enter mean " << endl;
cin >> mean;
arrivals[0]=0;
int fin_time;
for(int i=1; i< n; i++)
{
float time = ((float)rand())/RAND_MAX;
fin_time = (int)(fmod((-1.0/mean)*log(time),11.0));
arrivals[i] = arrivals[i-1]+fin_time;
//cout << arrivals[i] << " ";
}
cout << "\n";
for(int i=0; i<n ;i++)
{
float time = ((float)rand())/RAND_MAX;
//cout << i << " ";
fin_time = (int)(fmod(((-1.0/mean)*log(time)),20.0)) + 1;
bursts[i] = fin_time;
}
ofstream f;
f.open("Timedetails1009.txt");
f << "Time arrivals are :\n";
for(int i=0; i<n ;i++){
f << arrivals[i];
f << " ";
}
f << "\n Bursts time are : \n";
for(int i=0; i<n;i++){
f << bursts[i];
f << " ";
}
f.close();
sort(arrivals, bursts,n);
// First Come First Serve
FCFS(arrivals, bursts, n);
// Preemptive Shortest Job First
PSJF(arrivals, bursts, n);
// Round Robins with varying delta
RoundRobin(arrivals, bursts, n, 1);
RoundRobin(arrivals, bursts, n, 2);
RoundRobin(arrivals, bursts, n, 5);
return 0;
}
|
#ifndef OPENPOSE_PYTHON_HPP
#define OPENPOSE_PYTHON_HPP
#define BOOST_DATE_TIME_NO_LIB
#include <openpose/flags.hpp>
#include <openpose/headers.hpp>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <opencv2/core/core.hpp>
#include <stdexcept>
#ifdef _WIN32
#define OP_EXPORT __declspec(dllexport)
#else
#define OP_EXPORT
#endif
namespace op
{
namespace py = pybind11;
void parse_gflags(const std::vector<std::string>& argv)
{
try
{
std::vector<char*> argv_vec;
for (auto& arg : argv)
argv_vec.emplace_back((char*)arg.c_str());
char** cast = &argv_vec[0];
int size = (int)argv_vec.size();
gflags::ParseCommandLineFlags(&size, &cast, true);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void init_int(py::dict d)
{
try
{
std::vector<std::string> argv;
argv.emplace_back("openpose.py");
for (auto item : d){
// Sanity check
std::size_t found = std::string(py::str(item.first)).find("=");
if (found != std::string::npos)
error("PyOpenPose does not support equal sign flags (e.g., "
+ std::string(py::str(item.first)) + ").", __LINE__, __FUNCTION__, __FILE__);
// Add argument
argv.emplace_back("--" + std::string(py::str(item.first)) + "=" + std::string(py::str(item.second)));
}
parse_gflags(argv);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void init_argv(std::vector<std::string> argv)
{
try
{
argv.insert(argv.begin(), "openpose.py");
parse_gflags(argv);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
class WrapperPython{
public:
std::unique_ptr<Wrapper> opWrapper;
WrapperPython(int mode = 0)
{
opLog("Starting OpenPose Python Wrapper...", Priority::High);
// Construct opWrapper
opWrapper = std::unique_ptr<Wrapper>(new Wrapper(static_cast<ThreadManagerMode>(mode)));
}
void configure(py::dict params = py::dict())
{
try
{
if (params.size())
init_int(params);
// logging_level
checkBool(
0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.",
__LINE__, __FUNCTION__, __FILE__);
ConfigureLog::setPriorityThreshold((Priority)FLAGS_logging_level);
Profiler::setDefaultX(FLAGS_profile_speed);
// Applying user defined configuration - GFlags to program variables
// outputSize
const auto outputSize = flagsToPoint(op::String(FLAGS_output_resolution), "-1x-1");
// netInputSize
const auto netInputSize = flagsToPoint(op::String(FLAGS_net_resolution), "-1x368");
// faceNetInputSize
const auto faceNetInputSize = flagsToPoint(op::String(FLAGS_face_net_resolution), "368x368 (multiples of 16)");
// handNetInputSize
const auto handNetInputSize = flagsToPoint(op::String(FLAGS_hand_net_resolution), "368x368 (multiples of 16)");
// poseMode
const auto poseMode = flagsToPoseMode(FLAGS_body);
// poseModel
const auto poseModel = flagsToPoseModel(op::String(FLAGS_model_pose));
// JSON saving
if (!FLAGS_write_keypoint.empty())
opLog("Flag `write_keypoint` is deprecated and will eventually be removed."
" Please, use `write_json` instead.", Priority::Max);
// keypointScaleMode
const auto keypointScaleMode = flagsToScaleMode(FLAGS_keypoint_scale);
// heatmaps to add
const auto heatMapTypes = flagsToHeatMaps(FLAGS_heatmaps_add_parts, FLAGS_heatmaps_add_bkg,
FLAGS_heatmaps_add_PAFs);
const auto heatMapScaleMode = flagsToHeatMapScaleMode(FLAGS_heatmaps_scale);
// >1 camera view?
const auto multipleView = (FLAGS_3d || FLAGS_3d_views > 1);
// Face and hand detectors
const auto faceDetector = flagsToDetector(FLAGS_face_detector);
const auto handDetector = flagsToDetector(FLAGS_hand_detector);
// Enabling Google Logging
const bool enableGoogleLogging = true;
// Pose configuration (use WrapperStructPose{} for default and recommended configuration)
const op::WrapperStructPose wrapperStructPose{
poseMode, netInputSize, outputSize, keypointScaleMode, FLAGS_num_gpu, FLAGS_num_gpu_start,
FLAGS_scale_number, (float)FLAGS_scale_gap, op::flagsToRenderMode(FLAGS_render_pose, multipleView),
poseModel, !FLAGS_disable_blending, (float)FLAGS_alpha_pose, (float)FLAGS_alpha_heatmap,
FLAGS_part_to_show, op::String(FLAGS_model_folder), heatMapTypes, heatMapScaleMode, FLAGS_part_candidates,
(float)FLAGS_render_threshold, FLAGS_number_people_max, FLAGS_maximize_positives, FLAGS_fps_max,
op::String(FLAGS_prototxt_path), op::String(FLAGS_caffemodel_path),
(float)FLAGS_upsampling_ratio, enableGoogleLogging};
opWrapper->configure(wrapperStructPose);
// Face configuration (use WrapperStructFace{} to disable it)
const WrapperStructFace wrapperStructFace{
FLAGS_face, faceDetector, faceNetInputSize,
flagsToRenderMode(FLAGS_face_render, multipleView, FLAGS_render_pose),
(float)FLAGS_face_alpha_pose, (float)FLAGS_face_alpha_heatmap, (float)FLAGS_face_render_threshold};
opWrapper->configure(wrapperStructFace);
// Hand configuration (use WrapperStructHand{} to disable it)
const WrapperStructHand wrapperStructHand{
FLAGS_hand, handDetector, handNetInputSize, FLAGS_hand_scale_number, (float)FLAGS_hand_scale_range,
flagsToRenderMode(FLAGS_hand_render, multipleView, FLAGS_render_pose), (float)FLAGS_hand_alpha_pose,
(float)FLAGS_hand_alpha_heatmap, (float)FLAGS_hand_render_threshold};
opWrapper->configure(wrapperStructHand);
// Extra functionality configuration (use WrapperStructExtra{} to disable it)
const WrapperStructExtra wrapperStructExtra{
FLAGS_3d, FLAGS_3d_min_views, FLAGS_identification, FLAGS_tracking, FLAGS_ik_threads};
opWrapper->configure(wrapperStructExtra);
// Output (comment or use default argument to disable any output)
const WrapperStructOutput wrapperStructOutput{
FLAGS_cli_verbose, op::String(FLAGS_write_keypoint), op::stringToDataFormat(FLAGS_write_keypoint_format),
op::String(FLAGS_write_json), op::String(FLAGS_write_coco_json), FLAGS_write_coco_json_variants,
FLAGS_write_coco_json_variant, op::String(FLAGS_write_images), op::String(FLAGS_write_images_format),
op::String(FLAGS_write_video), FLAGS_write_video_fps, FLAGS_write_video_with_audio,
op::String(FLAGS_write_heatmaps), op::String(FLAGS_write_heatmaps_format), op::String(FLAGS_write_video_3d),
op::String(FLAGS_write_video_adam), op::String(FLAGS_write_bvh), op::String(FLAGS_udp_host),
op::String(FLAGS_udp_port)};
opWrapper->configure(wrapperStructOutput);
// No GUI. Equivalent to: opWrapper.configure(WrapperStructGui{});
// Set to single-thread (for sequential processing and/or debugging and/or reducing latency)
if (FLAGS_disable_multi_thread)
opWrapper->disableMultiThreading();
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void start()
{
try
{
opWrapper->start();
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void stop()
{
try
{
opWrapper->stop();
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void exec()
{
try
{
const auto cameraSize = flagsToPoint(op::String(FLAGS_camera_resolution), "-1x-1");
ProducerType producerType;
op::String producerString;
std::tie(producerType, producerString) = flagsToProducer(
op::String(FLAGS_image_dir), op::String(FLAGS_video), op::String(FLAGS_ip_camera), FLAGS_camera,
FLAGS_flir_camera, FLAGS_flir_camera_index);
// Producer (use default to disable any input)
const WrapperStructInput wrapperStructInput{
producerType, producerString, FLAGS_frame_first, FLAGS_frame_step, FLAGS_frame_last,
FLAGS_process_real_time, FLAGS_frame_flip, FLAGS_frame_rotate, FLAGS_frames_repeat,
cameraSize, op::String(FLAGS_camera_parameter_path), FLAGS_frame_undistort, FLAGS_3d_views};
opWrapper->configure(wrapperStructInput);
// GUI (comment or use default argument to disable any visual output)
const WrapperStructGui wrapperStructGui{
flagsToDisplayMode(FLAGS_display, FLAGS_3d), !FLAGS_no_gui_verbose, FLAGS_fullscreen};
opWrapper->configure(wrapperStructGui);
opWrapper->exec();
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void emplaceAndPop(std::vector<std::shared_ptr<Datum>>& l)
{
try
{
auto datumsPtr = std::make_shared<std::vector<std::shared_ptr<Datum>>>(l);
opWrapper->emplaceAndPop(datumsPtr);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
void waitAndEmplace(std::vector<std::shared_ptr<Datum>>& l)
{
try
{
auto datumsPtr = std::make_shared<std::vector<std::shared_ptr<Datum>>>(l);
opWrapper->waitAndEmplace(datumsPtr);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
bool waitAndPop(std::vector<std::shared_ptr<Datum>>& l)
{
try
{
auto datumsPtr = std::make_shared<std::vector<std::shared_ptr<Datum>>>(l);
return opWrapper->waitAndPop(datumsPtr);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return false;
}
}
};
std::vector<std::string> getImagesFromDirectory(const std::string& directoryPath)
{
try
{
return getFilesOnDirectory(directoryPath, Extensions::Images);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return {};
}
}
PYBIND11_MODULE(pyopenpose, m) {
// Functions for Init Params
m.def("init_int", &init_int, "Init Function");
m.def("init_argv", &init_argv, "Init Function");
m.def("get_gpu_number", &getGpuNumber, "Get Total GPU");
m.def("get_images_on_directory", &getImagesFromDirectory, "Get Images On Directory");
// Pose Mapping
// Code example in doc/output.md, section Keypoint Ordering in C++/Python
m.def("getPoseBodyPartMapping", &getPoseBodyPartMapping, "getPoseBodyPartMapping");
m.def("getPoseNumberBodyParts", &getPoseNumberBodyParts, "getPoseNumberBodyParts");
m.def("getPosePartPairs", &getPosePartPairs, "getPosePartPairs");
m.def("getPoseMapIndex", &getPoseMapIndex, "getPoseMapIndex");
py::enum_<PoseModel>(m, "PoseModel", py::arithmetic())
.value("BODY_25", PoseModel::BODY_25)
.value("COCO_18", PoseModel::COCO_18)
.value("MPI_15", PoseModel::MPI_15)
.value("MPI_15_4", PoseModel::MPI_15_4)
.value("BODY_25B", PoseModel::BODY_25B)
.value("BODY_135", PoseModel::BODY_135)
.export_values();
// OpenposePython
py::class_<WrapperPython>(m, "WrapperPython")
.def(py::init<>())
.def(py::init<int>())
.def("configure", &WrapperPython::configure)
.def("start", &WrapperPython::start)
.def("stop", &WrapperPython::stop)
.def("execute", &WrapperPython::exec)
.def("emplaceAndPop", &WrapperPython::emplaceAndPop)
.def("waitAndEmplace", &WrapperPython::waitAndEmplace)
.def("waitAndPop", &WrapperPython::waitAndPop)
;
// Datum Object
py::class_<Datum, std::shared_ptr<Datum>>(m, "Datum")
.def(py::init<>())
.def_readwrite("id", &Datum::id)
.def_readwrite("subId", &Datum::subId)
.def_readwrite("subIdMax", &Datum::subIdMax)
.def_readwrite("name", &Datum::name)
.def_readwrite("frameNumber", &Datum::frameNumber)
.def_readwrite("cvInputData", &Datum::cvInputData)
.def_readwrite("inputNetData", &Datum::inputNetData)
.def_readwrite("outputData", &Datum::outputData)
.def_readwrite("cvOutputData", &Datum::cvOutputData)
.def_readwrite("cvOutputData3D", &Datum::cvOutputData3D)
.def_readwrite("poseKeypoints", &Datum::poseKeypoints)
.def_readwrite("poseIds", &Datum::poseIds)
.def_readwrite("poseScores", &Datum::poseScores)
.def_readwrite("poseHeatMaps", &Datum::poseHeatMaps)
.def_readwrite("poseCandidates", &Datum::poseCandidates)
.def_readwrite("faceRectangles", &Datum::faceRectangles)
.def_readwrite("faceKeypoints", &Datum::faceKeypoints)
.def_readwrite("faceHeatMaps", &Datum::faceHeatMaps)
.def_readwrite("handRectangles", &Datum::handRectangles)
.def_readwrite("handKeypoints", &Datum::handKeypoints)
.def_readwrite("handHeatMaps", &Datum::handHeatMaps)
.def_readwrite("poseKeypoints3D", &Datum::poseKeypoints3D)
.def_readwrite("faceKeypoints3D", &Datum::faceKeypoints3D)
.def_readwrite("handKeypoints3D", &Datum::handKeypoints3D)
.def_readwrite("cameraMatrix", &Datum::cameraMatrix)
.def_readwrite("cameraExtrinsics", &Datum::cameraExtrinsics)
.def_readwrite("cameraIntrinsics", &Datum::cameraIntrinsics)
.def_readwrite("poseNetOutput", &Datum::poseNetOutput)
.def_readwrite("scaleInputToNetInputs", &Datum::scaleInputToNetInputs)
.def_readwrite("netInputSizes", &Datum::netInputSizes)
.def_readwrite("scaleInputToOutput", &Datum::scaleInputToOutput)
.def_readwrite("netOutputSize", &Datum::netOutputSize)
.def_readwrite("scaleNetToOutput", &Datum::scaleNetToOutput)
.def_readwrite("elementRendered", &Datum::elementRendered)
;
// Rectangle
py::class_<Rectangle<float>>(m, "Rectangle")
.def("__repr__", [](Rectangle<float> &a) { return a.toString(); })
.def(py::init<>())
.def(py::init<float, float, float, float>())
.def_readwrite("x", &Rectangle<float>::x)
.def_readwrite("y", &Rectangle<float>::y)
.def_readwrite("width", &Rectangle<float>::width)
.def_readwrite("height", &Rectangle<float>::height)
;
// Point
py::class_<Point<int>>(m, "Point")
.def("__repr__", [](Point<int> &a) { return a.toString(); })
.def(py::init<>())
.def(py::init<int, int>())
.def_readwrite("x", &Point<int>::x)
.def_readwrite("y", &Point<int>::y)
;
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
}
}
// Numpy - op::Array<float> interop
namespace pybind11 { namespace detail {
template <> struct type_caster<op::Array<float>> {
public:
PYBIND11_TYPE_CASTER(op::Array<float>, _("numpy.ndarray"));
// Cast numpy to op::Array<float>
bool load(handle src, bool imp)
{
try
{
UNUSED(imp);
// array b(src, true);
array b = reinterpret_borrow<array>(src);
buffer_info info = b.request();
if (info.format != format_descriptor<float>::format())
op::error("op::Array only supports float32 now", __LINE__, __FUNCTION__, __FILE__);
//std::vector<int> a(info.shape);
std::vector<int> shape(std::begin(info.shape), std::end(info.shape));
// No copy
value = op::Array<float>(shape, (float*)info.ptr);
// Copy
//value = op::Array<float>(shape);
//memcpy(value.getPtr(), info.ptr, value.getVolume()*sizeof(float));
return true;
}
catch (const std::exception& e)
{
op::error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return {};
}
}
// Cast op::Array<float> to numpy
static handle cast(const op::Array<float> &m, return_value_policy, handle defval)
{
UNUSED(defval);
std::string format = format_descriptor<float>::format();
return array(buffer_info(
m.getPseudoConstPtr(),/* Pointer to buffer */
sizeof(float), /* Size of one scalar */
format, /* Python struct-style format descriptor */
m.getSize().size(), /* Number of dimensions */
m.getSize(), /* Buffer dimensions */
m.getStride() /* Strides (in bytes) for each index */
)).release();
}
};
}} // namespace pybind11::detail
// Numpy - op::Matrix interop
namespace pybind11 { namespace detail {
template <> struct type_caster<op::Matrix> {
public:
PYBIND11_TYPE_CASTER(op::Matrix, _("numpy.ndarray"));
// Cast numpy to op::Matrix
bool load(handle src, bool)
{
/* Try a default converting into a Python */
//array b(src, true);
array b = reinterpret_borrow<array>(src);
buffer_info info = b.request();
const int ndims = (int)info.ndim;
decltype(CV_32F) dtype;
size_t elemsize;
if (info.format == format_descriptor<float>::format())
{
if (ndims == 3)
dtype = CV_32FC3;
else
dtype = CV_32FC1;
elemsize = sizeof(float);
}
else if (info.format == format_descriptor<double>::format())
{
if (ndims == 3)
dtype = CV_64FC3;
else
dtype = CV_64FC1;
elemsize = sizeof(double);
}
else if (info.format == format_descriptor<unsigned char>::format())
{
if (ndims == 3)
dtype = CV_8UC3;
else
dtype = CV_8UC1;
elemsize = sizeof(unsigned char);
}
else
{
throw std::logic_error("Unsupported type");
return false;
}
std::vector<int> shape = {(int)info.shape[0], (int)info.shape[1]};
value = op::Matrix(shape[0], shape[1], dtype, info.ptr);
// value = cv::Mat(cv::Size(shape[1], shape[0]), dtype, info.ptr, cv::Mat::AUTO_STEP);
return true;
}
// Cast op::Matrix to numpy
static handle cast(const op::Matrix &matrix, return_value_policy, handle defval)
{
UNUSED(defval);
std::string format = format_descriptor<unsigned char>::format();
size_t elemsize = sizeof(unsigned char);
int dim;
switch(matrix.type()) {
case CV_8U:
format = format_descriptor<unsigned char>::format();
elemsize = sizeof(unsigned char);
dim = 2;
break;
case CV_8UC3:
format = format_descriptor<unsigned char>::format();
elemsize = sizeof(unsigned char);
dim = 3;
break;
case CV_32F:
format = format_descriptor<float>::format();
elemsize = sizeof(float);
dim = 2;
break;
case CV_64F:
format = format_descriptor<double>::format();
elemsize = sizeof(double);
dim = 2;
break;
default:
throw std::logic_error("Unsupported type");
}
std::vector<size_t> bufferdim;
std::vector<size_t> strides;
if (dim == 2) {
bufferdim = {(size_t) matrix.rows(), (size_t) matrix.cols()};
strides = {elemsize * (size_t) matrix.cols(), elemsize};
} else if (dim == 3) {
bufferdim = {(size_t) matrix.rows(), (size_t) matrix.cols(), (size_t) 3};
strides = {(size_t) elemsize * matrix.cols() * 3, (size_t) elemsize * 3, (size_t) elemsize};
}
return array(buffer_info(
matrix.dataPseudoConst(), /* Pointer to buffer */
elemsize, /* Size of one scalar */
format, /* Python struct-style format descriptor */
dim, /* Number of dimensions */
bufferdim, /* Buffer dimensions */
strides /* Strides (in bytes) for each index */
)).release();
}
};
}} // namespace pybind11::detail
#endif
|
#include "follower_connections.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/un.h>
#include <string>
#include <netdb.h>
#include <iostream>
using namespace std;
FollowerConnections::FollowerConnections(int nThread) : Connections(nThread) {
}
FollowerConnections::~FollowerConnections() {
}
void FollowerConnections::initialize(IAgent *parent) {
Connections::initialize(parent);
this->parent = parent;
}
void FollowerConnections::handler(int fd, Message &m) {
string strIp = this->getSource(fd,m);
if(m.getType() == Message::Type::REQUEST) {
if(m.getArgument() == Message::Argument::IPERF) {
if(m.getCommand() == Message::Command::START) {
Message res;
res.setType(Message::Type::RESPONSE);
res.setCommand(Message::Command::START);
int port = this->parent->getIperfPort();
if(port > 0) {
res.setArgument(Message::Argument::POSITIVE);
res.setData(port);
}else {
res.setArgument(Message::Argument::NEGATIVE);
}
//send response
if(this->sendMessage(fd, res)) {
}
}
}else if(m.getArgument() == Message::Argument::ESTIMATE) {
if(m.getCommand() == Message::Command::START) {
Message res;
res.setType(Message::Type::RESPONSE);
res.setCommand(Message::Command::START);
int port = this->parent->getEstimatePort();
string a = string(" ");
string port_ = to_string(port);
Message::node val(a,strIp,port_);
if(port > 0) {
res.setArgument(Message::Argument::POSITIVE);
res.setData(val);
}else {
res.setArgument(Message::Argument::NEGATIVE);
}
//send response
if(this->sendMessage(fd, res)) {
}
}
}else if(m.getArgument() == Message::Argument::NODES) {
if(m.getCommand() == Message::Command::GET) {
//build array of nodes
vector<Message::node> nodes = this->parent->getStorage()->getNodes();
//send nodes
Message res;
res.setType(Message::Type::RESPONSE);
res.setCommand(Message::Command::GET);
res.setArgument(Message::Argument::POSITIVE);
res.setData(nodes);
if(this->sendMessage(fd, res)) {
}
}else if(m.getCommand() == Message::Command::SET) {
Message res; //--------------------------------
res.setType(Message::Type::RESPONSE);
res.setCommand(Message::Command::SET);
//refresh all the nodes with the array of nodes
vector<Message::node> ips;
if(!m.getData(ips)) {
res.setArgument(Message::Argument::NEGATIVE);
}else {
res.setArgument(Message::Argument::POSITIVE);
}
//ips now contains the ip of the nodes
this->parent->getStorage()->refreshNodes(ips);
//send report
if(this->sendMessage(fd, res)) {
}
}
}else if(m.getArgument() == Message::Argument::REPORT) {
if(m.getCommand() == Message::Command::GET) {
//build report
Message res;
res.setType(Message::Type::RESPONSE);
res.setCommand(Message::Command::GET);
res.setArgument(Message::Argument::POSITIVE);
Report r;
r.setHardware(this->parent->getStorage()->getHardware());
r.setLatency(this->parent->getStorage()->getLatency());
r.setBandwidth(this->parent->getStorage()->getBandwidth());
r.setIot(this->parent->getStorage()->getIots());
res.setData(r);
//send report
if(this->sendMessage(fd, res)) {
}
}
}else if(m.getArgument() == Message::Argument::ROLES) {
if(m.getCommand() == Message::Command::SET) {
Message::leader_update update;
//contains the list of new leaders
m.getData(update);
cout << "Selected Leaders: "<< update.selected.size() << endl;
for(auto &node : update.selected) {
if(node.ip == "::1" || node.ip == "127.0.0.1") {
node.ip = strIp;
}
}
this->parent->changeRole(update.selected);
}
}
}else if(m.getType() == Message::Type::NOTIFY) {
if(m.getCommand() == Message::Command::UPDATE) {
if(m.getArgument() == Message::Argument::NODES) {
//data contains 2 array: new and deleted nodes
vector<Message::node> ipsNew;
vector<Message::node> ipsRem;
if(!m.getData(ipsNew,ipsRem))
return;
//update the nodes
this->parent->getStorage()->updateNodes(ipsNew,ipsRem);
}
}
}
}
vector<Message::node> FollowerConnections::requestNodes(Message::node ipS) {
int Socket = openConnection(ipS.ip, ipS.port);
if(Socket < 0) {
return vector<Message::node>();
}
//build request message
Message m;
m.setSender(this->parent->getMyNode());
m.setType(Message::Type::REQUEST);
m.setCommand(Message::Command::GET);
m.setArgument(Message::Argument::NODES);
vector<Message::node> nodes;
bool result = false;
//send request message
if(this->sendMessage(Socket, m)) {
Message res;
if(this->getMessage(Socket, res)) {
if( res.getType()==Message::Type::RESPONSE &&
res.getCommand() == Message::Command::NODELIST &&
res.getArgument() == Message::Argument::POSITIVE) {
if(res.getData(nodes)) {
result = true;
}
}
}
}
close(Socket);
if(result)
return nodes;
return vector<Message::node>();
}
vector<Message::node> FollowerConnections::requestMNodes(Message::node ipS) {
int Socket = openConnection(ipS.ip, ipS.port);
if(Socket < 0) {
return vector<Message::node>();
}
fflush(stdout);
//build request message
Message m;
m.setSender(this->parent->getMyNode());
m.setType(Message::Type::REQUEST);
m.setCommand(Message::Command::GET);
m.setArgument(Message::Argument::MNODES);
vector<Message::node> nodes;
bool result = false;
//send request message
if(this->sendMessage(Socket, m)) {
Message res;
if(this->getMessage(Socket, res)) {
if( res.getType()==Message::Type::RESPONSE &&
res.getCommand() == Message::Command::MNODELIST &&
res.getArgument() == Message::Argument::POSITIVE) {
if(res.getData(nodes)) {
result = true;
}
}
}
}
close(Socket);
if(result) {
for(auto &node : nodes) {
if(node.ip == "::1") {
node.ip = ipS.ip;
}
}
return nodes;
}
return vector<Message::node>();
}
bool FollowerConnections::sendHello(Message::node ipS) {
cout << "Trying server " << ipS.id << " " << ipS.ip << ":" << ipS.port <<endl;
int Socket = openConnection(ipS.ip, ipS.port);
if(Socket < 0) {
return false;
}
fflush(stdout);
char buffer[10];
//build hello message
Message m;
m.setSender(this->parent->getMyNode());
m.setType(Message::Type::NOTIFY);
m.setCommand(Message::Command::HELLO);
Report r;
r.setHardware(this->parent->getStorage()->getHardware());
m.setData(r);
bool result = false;
//send hello message
if(this->sendMessage(Socket, m)) {
Message res;
if(this->getMessage(Socket, res)) {
if( res.getType()==Message::Type::RESPONSE &&
res.getCommand() == Message::Command::HELLO &&
res.getArgument() == Message::Argument::POSITIVE) {
Message::node node;
vector<Message::node> vec;
if(res.getData(node, vec)) {
cout << "My id: " << node.id << " " << node.ip << ":" << node.port << endl;
this->parent->getStorage()->setFilter(ipS.ip);
this->parent->getStorage()->refreshNodes(vec);
result = true;
cout << "Server: " << ipS.id << " " << ipS.ip << ":" << ipS.port << endl;
}
}
}
}
close(Socket);
return result;
}
optional<pair<int64_t,Message::node>> FollowerConnections::sendUpdate(Message::node ipS, pair<int64_t,Message::node> update) {
int Socket = openConnection(ipS.ip, ipS.port);
if(Socket < 0) {
return nullopt;
}
fflush(stdout);
char buffer[10];
//build update message
Message m;
m.setSender(this->parent->getMyNode());
m.setType(Message::Type::NOTIFY);
m.setCommand(Message::Command::UPDATE);
m.setArgument(Message::Argument::REPORT);
Report r;
r.setHardware(this->parent->getStorage()->getHardware());
r.setIot(this->parent->getStorage()->getIots());
int64_t now = this->parent->getStorage()->getTime();
if(ipS == update.second) {
int64_t time = update.first;
r.setLatency(this->parent->getStorage()->getLatency(time));
r.setBandwidth(this->parent->getStorage()->getBandwidth(time));
} else { //send all data
r.setLatency(this->parent->getStorage()->getLatency());
r.setBandwidth(this->parent->getStorage()->getBandwidth());
}
m.setData(r);
std::optional<std::pair<int64_t,Message::node>> result = nullopt;
//send update message
if(this->sendMessage(Socket, m)) {
Message res;
if(this->getMessage(Socket, res)) {
if( res.getType()==Message::Type::RESPONSE &&
res.getCommand() == Message::Command::UPDATE &&
res.getArgument() == Message::Argument::POSITIVE) {
result = std::make_pair(now, ipS);
this->parent->getStorage()->saveState();
}
}
}
close(Socket);
return result;
}
int FollowerConnections::sendStartIperfTest(Message::node ip) {
int Socket = openConnection(ip.ip, ip.port);
if(Socket < 0) {
return -1;
}
fflush(stdout);
char buffer[10];
//build start iperf message
Message m;
m.setSender(this->parent->getMyNode());
m.setType(Message::Type::REQUEST);
m.setCommand(Message::Command::START);
m.setArgument(Message::Argument::IPERF);
int port = -1;
//send start iperf message
if(this->sendMessage(Socket, m)) {
Message res;
if(this->getMessage(Socket, res)) {
if( res.getType()==Message::Type::RESPONSE &&
res.getCommand() == Message::Command::START &&
res.getArgument() == Message::Argument::POSITIVE) {
res.getData(port);
}
}
}
close(Socket);
return port;
}
int FollowerConnections::sendStartEstimateTest(Message::node ip, std::string &myIp) {
int Socket = openConnection(ip.ip, ip.port);
if(Socket < 0) {
return -1;
}
fflush(stdout);
char buffer[10];
//build start estimate message
Message m;
m.setSender(this->parent->getMyNode());
m.setType(Message::Type::REQUEST);
m.setCommand(Message::Command::START);
m.setArgument(Message::Argument::ESTIMATE);
int port = -1;
//send start estimate message
if(this->sendMessage(Socket, m)) {
Message res;
if(this->getMessage(Socket, res)) {
if( res.getType()==Message::Type::RESPONSE &&
res.getCommand() == Message::Command::START &&
res.getArgument() == Message::Argument::POSITIVE) {
Message::node val;
res.getData(val);
port = stol(val.port);
myIp = val.ip;
}
}
}
close(Socket);
return port;
}
|
//===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format ARM assembly language.
//
//===----------------------------------------------------------------------===//
#include "ARMAsmPrinter.h"
#include "ARM.h"
#include "ARMConstantPoolValue.h"
#include "ARMMachineFunctionInfo.h"
#include "ARMTargetMachine.h"
#include "ARMTargetObjectFile.h"
#include "MCTargetDesc/ARMAddressingModes.h"
#include "MCTargetDesc/ARMInstPrinter.h"
#include "MCTargetDesc/ARMMCExpr.h"
#include "TargetInfo/ARMTargetInfo.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCELFStreamer.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "llvm/MC/MCObjectStreamer.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/ARMBuildAttributes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetParser.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
#define DEBUG_TYPE "asm-printer"
ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
std::unique_ptr<MCStreamer> Streamer)
: AsmPrinter(TM, std::move(Streamer)), Subtarget(nullptr), AFI(nullptr),
MCP(nullptr), InConstantPool(false), OptimizationGoals(-1) {}
void ARMAsmPrinter::emitFunctionBodyEnd() {
// Make sure to terminate any constant pools that were at the end
// of the function.
if (!InConstantPool)
return;
InConstantPool = false;
OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
}
void ARMAsmPrinter::emitFunctionEntryLabel() {
if (AFI->isThumbFunction()) {
OutStreamer->emitAssemblerFlag(MCAF_Code16);
OutStreamer->emitThumbFunc(CurrentFnSym);
} else {
OutStreamer->emitAssemblerFlag(MCAF_Code32);
}
OutStreamer->emitLabel(CurrentFnSym);
}
void ARMAsmPrinter::emitXXStructor(const DataLayout &DL, const Constant *CV) {
uint64_t Size = getDataLayout().getTypeAllocSize(CV->getType());
assert(Size && "C++ constructor pointer had zero size!");
const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
assert(GV && "C++ constructor pointer was not a GlobalValue!");
const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
ARMII::MO_NO_FLAG),
(Subtarget->isTargetELF()
? MCSymbolRefExpr::VK_ARM_TARGET1
: MCSymbolRefExpr::VK_None),
OutContext);
OutStreamer->emitValue(E, Size);
}
void ARMAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
if (PromotedGlobals.count(GV))
// The global was promoted into a constant pool. It should not be emitted.
return;
AsmPrinter::emitGlobalVariable(GV);
}
/// runOnMachineFunction - This uses the emitInstruction()
/// method to print assembly for each instruction.
///
bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
AFI = MF.getInfo<ARMFunctionInfo>();
MCP = MF.getConstantPool();
Subtarget = &MF.getSubtarget<ARMSubtarget>();
SetupMachineFunction(MF);
const Function &F = MF.getFunction();
const TargetMachine& TM = MF.getTarget();
// Collect all globals that had their storage promoted to a constant pool.
// Functions are emitted before variables, so this accumulates promoted
// globals from all functions in PromotedGlobals.
for (auto *GV : AFI->getGlobalsPromotedToConstantPool())
PromotedGlobals.insert(GV);
// Calculate this function's optimization goal.
unsigned OptimizationGoal;
if (F.hasOptNone())
// For best debugging illusion, speed and small size sacrificed
OptimizationGoal = 6;
else if (F.hasMinSize())
// Aggressively for small size, speed and debug illusion sacrificed
OptimizationGoal = 4;
else if (F.hasOptSize())
// For small size, but speed and debugging illusion preserved
OptimizationGoal = 3;
else if (TM.getOptLevel() == CodeGenOpt::Aggressive)
// Aggressively for speed, small size and debug illusion sacrificed
OptimizationGoal = 2;
else if (TM.getOptLevel() > CodeGenOpt::None)
// For speed, but small size and good debug illusion preserved
OptimizationGoal = 1;
else // TM.getOptLevel() == CodeGenOpt::None
// For good debugging, but speed and small size preserved
OptimizationGoal = 5;
// Combine a new optimization goal with existing ones.
if (OptimizationGoals == -1) // uninitialized goals
OptimizationGoals = OptimizationGoal;
else if (OptimizationGoals != (int)OptimizationGoal) // conflicting goals
OptimizationGoals = 0;
if (Subtarget->isTargetCOFF()) {
bool Internal = F.hasInternalLinkage();
COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
: COFF::IMAGE_SYM_CLASS_EXTERNAL;
int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
OutStreamer->EmitCOFFSymbolStorageClass(Scl);
OutStreamer->EmitCOFFSymbolType(Type);
OutStreamer->EndCOFFSymbolDef();
}
// Emit the rest of the function body.
emitFunctionBody();
// Emit the XRay table for this function.
emitXRayTable();
// If we need V4T thumb mode Register Indirect Jump pads, emit them.
// These are created per function, rather than per TU, since it's
// relatively easy to exceed the thumb branch range within a TU.
if (! ThumbIndirectPads.empty()) {
OutStreamer->emitAssemblerFlag(MCAF_Code16);
emitAlignment(Align(2));
for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
OutStreamer->emitLabel(TIP.second);
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
.addReg(TIP.first)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
}
ThumbIndirectPads.clear();
}
// We didn't modify anything.
return false;
}
void ARMAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
raw_ostream &O) {
assert(MO.isGlobal() && "caller should check MO.isGlobal");
unsigned TF = MO.getTargetFlags();
if (TF & ARMII::MO_LO16)
O << ":lower16:";
else if (TF & ARMII::MO_HI16)
O << ":upper16:";
GetARMGVSymbol(MO.getGlobal(), TF)->print(O, MAI);
printOffset(MO.getOffset(), O);
}
void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
raw_ostream &O) {
const MachineOperand &MO = MI->getOperand(OpNum);
switch (MO.getType()) {
default: llvm_unreachable("<unknown operand type>");
case MachineOperand::MO_Register: {
Register Reg = MO.getReg();
assert(Register::isPhysicalRegister(Reg));
assert(!MO.getSubReg() && "Subregs should be eliminated!");
if(ARM::GPRPairRegClass.contains(Reg)) {
const MachineFunction &MF = *MI->getParent()->getParent();
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Reg = TRI->getSubReg(Reg, ARM::gsub_0);
}
O << ARMInstPrinter::getRegisterName(Reg);
break;
}
case MachineOperand::MO_Immediate: {
O << '#';
unsigned TF = MO.getTargetFlags();
if (TF == ARMII::MO_LO16)
O << ":lower16:";
else if (TF == ARMII::MO_HI16)
O << ":upper16:";
O << MO.getImm();
break;
}
case MachineOperand::MO_MachineBasicBlock:
MO.getMBB()->getSymbol()->print(O, MAI);
return;
case MachineOperand::MO_GlobalAddress: {
PrintSymbolOperand(MO, O);
break;
}
case MachineOperand::MO_ConstantPoolIndex:
if (Subtarget->genExecuteOnly())
llvm_unreachable("execute-only should not generate constant pools");
GetCPISymbol(MO.getIndex())->print(O, MAI);
break;
}
}
MCSymbol *ARMAsmPrinter::GetCPISymbol(unsigned CPID) const {
// The AsmPrinter::GetCPISymbol superclass method tries to use CPID as
// indexes in MachineConstantPool, which isn't in sync with indexes used here.
const DataLayout &DL = getDataLayout();
return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
"CPI" + Twine(getFunctionNumber()) + "_" +
Twine(CPID));
}
//===--------------------------------------------------------------------===//
MCSymbol *ARMAsmPrinter::
GetARMJTIPICJumpTableLabel(unsigned uid) const {
const DataLayout &DL = getDataLayout();
SmallString<60> Name;
raw_svector_ostream(Name) << DL.getPrivateGlobalPrefix() << "JTI"
<< getFunctionNumber() << '_' << uid;
return OutContext.getOrCreateSymbol(Name);
}
bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
const char *ExtraCode, raw_ostream &O) {
// Does this asm operand have a single letter operand modifier?
if (ExtraCode && ExtraCode[0]) {
if (ExtraCode[1] != 0) return true; // Unknown modifier.
switch (ExtraCode[0]) {
default:
// See if this is a generic print operand
return AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O);
case 'P': // Print a VFP double precision register.
case 'q': // Print a NEON quad precision register.
printOperand(MI, OpNum, O);
return false;
case 'y': // Print a VFP single precision register as indexed double.
if (MI->getOperand(OpNum).isReg()) {
Register Reg = MI->getOperand(OpNum).getReg();
const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
// Find the 'd' register that has this 's' register as a sub-register,
// and determine the lane number.
for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
if (!ARM::DPRRegClass.contains(*SR))
continue;
bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
return false;
}
}
return true;
case 'B': // Bitwise inverse of integer or symbol without a preceding #.
if (!MI->getOperand(OpNum).isImm())
return true;
O << ~(MI->getOperand(OpNum).getImm());
return false;
case 'L': // The low 16 bits of an immediate constant.
if (!MI->getOperand(OpNum).isImm())
return true;
O << (MI->getOperand(OpNum).getImm() & 0xffff);
return false;
case 'M': { // A register range suitable for LDM/STM.
if (!MI->getOperand(OpNum).isReg())
return true;
const MachineOperand &MO = MI->getOperand(OpNum);
Register RegBegin = MO.getReg();
// This takes advantage of the 2 operand-ness of ldm/stm and that we've
// already got the operands in registers that are operands to the
// inline asm statement.
O << "{";
if (ARM::GPRPairRegClass.contains(RegBegin)) {
const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Register Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
}
O << ARMInstPrinter::getRegisterName(RegBegin);
// FIXME: The register allocator not only may not have given us the
// registers in sequence, but may not be in ascending registers. This
// will require changes in the register allocator that'll need to be
// propagated down here if the operands change.
unsigned RegOps = OpNum + 1;
while (MI->getOperand(RegOps).isReg()) {
O << ", "
<< ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
RegOps++;
}
O << "}";
return false;
}
case 'R': // The most significant register of a pair.
case 'Q': { // The least significant register of a pair.
if (OpNum == 0)
return true;
const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
if (!FlagsOP.isImm())
return true;
unsigned Flags = FlagsOP.getImm();
// This operand may not be the one that actually provides the register. If
// it's tied to a previous one then we should refer instead to that one
// for registers and their classes.
unsigned TiedIdx;
if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
unsigned OpFlags = MI->getOperand(OpNum).getImm();
OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
}
Flags = MI->getOperand(OpNum).getImm();
// Later code expects OpNum to be pointing at the register rather than
// the flags.
OpNum += 1;
}
unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
unsigned RC;
bool FirstHalf;
const ARMBaseTargetMachine &ATM =
static_cast<const ARMBaseTargetMachine &>(TM);
// 'Q' should correspond to the low order register and 'R' to the high
// order register. Whether this corresponds to the upper or lower half
// depends on the endianess mode.
if (ExtraCode[0] == 'Q')
FirstHalf = ATM.isLittleEndian();
else
// ExtraCode[0] == 'R'.
FirstHalf = !ATM.isLittleEndian();
const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
if (InlineAsm::hasRegClassConstraint(Flags, RC) &&
ARM::GPRPairRegClass.hasSubClassEq(TRI->getRegClass(RC))) {
if (NumVals != 1)
return true;
const MachineOperand &MO = MI->getOperand(OpNum);
if (!MO.isReg())
return true;
const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Register Reg =
TRI->getSubReg(MO.getReg(), FirstHalf ? ARM::gsub_0 : ARM::gsub_1);
O << ARMInstPrinter::getRegisterName(Reg);
return false;
}
if (NumVals != 2)
return true;
unsigned RegOp = FirstHalf ? OpNum : OpNum + 1;
if (RegOp >= MI->getNumOperands())
return true;
const MachineOperand &MO = MI->getOperand(RegOp);
if (!MO.isReg())
return true;
Register Reg = MO.getReg();
O << ARMInstPrinter::getRegisterName(Reg);
return false;
}
case 'e': // The low doubleword register of a NEON quad register.
case 'f': { // The high doubleword register of a NEON quad register.
if (!MI->getOperand(OpNum).isReg())
return true;
Register Reg = MI->getOperand(OpNum).getReg();
if (!ARM::QPRRegClass.contains(Reg))
return true;
const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Register SubReg =
TRI->getSubReg(Reg, ExtraCode[0] == 'e' ? ARM::dsub_0 : ARM::dsub_1);
O << ARMInstPrinter::getRegisterName(SubReg);
return false;
}
// This modifier is not yet supported.
case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
return true;
case 'H': { // The highest-numbered register of a pair.
const MachineOperand &MO = MI->getOperand(OpNum);
if (!MO.isReg())
return true;
const MachineFunction &MF = *MI->getParent()->getParent();
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Register Reg = MO.getReg();
if(!ARM::GPRPairRegClass.contains(Reg))
return false;
Reg = TRI->getSubReg(Reg, ARM::gsub_1);
O << ARMInstPrinter::getRegisterName(Reg);
return false;
}
}
}
printOperand(MI, OpNum, O);
return false;
}
bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNum, const char *ExtraCode,
raw_ostream &O) {
// Does this asm operand have a single letter operand modifier?
if (ExtraCode && ExtraCode[0]) {
if (ExtraCode[1] != 0) return true; // Unknown modifier.
switch (ExtraCode[0]) {
case 'A': // A memory operand for a VLD1/VST1 instruction.
default: return true; // Unknown modifier.
case 'm': // The base register of a memory operand.
if (!MI->getOperand(OpNum).isReg())
return true;
O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
return false;
}
}
const MachineOperand &MO = MI->getOperand(OpNum);
assert(MO.isReg() && "unexpected inline asm memory operand");
O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
return false;
}
static bool isThumb(const MCSubtargetInfo& STI) {
return STI.getFeatureBits()[ARM::ModeThumb];
}
void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
const MCSubtargetInfo *EndInfo) const {
// If either end mode is unknown (EndInfo == NULL) or different than
// the start mode, then restore the start mode.
const bool WasThumb = isThumb(StartInfo);
if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
OutStreamer->emitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
}
}
void ARMAsmPrinter::emitStartOfAsmFile(Module &M) {
const Triple &TT = TM.getTargetTriple();
// Use unified assembler syntax.
OutStreamer->emitAssemblerFlag(MCAF_SyntaxUnified);
// Emit ARM Build Attributes
if (TT.isOSBinFormatELF())
emitAttributes();
// Use the triple's architecture and subarchitecture to determine
// if we're thumb for the purposes of the top level code16 assembler
// flag.
if (!M.getModuleInlineAsm().empty() && TT.isThumb())
OutStreamer->emitAssemblerFlag(MCAF_Code16);
}
static void
emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
MachineModuleInfoImpl::StubValueTy &MCSym) {
// L_foo$stub:
OutStreamer.emitLabel(StubLabel);
// .indirect_symbol _foo
OutStreamer.emitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
if (MCSym.getInt())
// External to current translation unit.
OutStreamer.emitIntValue(0, 4/*size*/);
else
// Internal to current translation unit.
//
// When we place the LSDA into the TEXT section, the type info
// pointers need to be indirect and pc-rel. We accomplish this by
// using NLPs; however, sometimes the types are local to the file.
// We need to fill in the value for the NLP in those cases.
OutStreamer.emitValue(
MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
4 /*size*/);
}
void ARMAsmPrinter::emitEndOfAsmFile(Module &M) {
const Triple &TT = TM.getTargetTriple();
if (TT.isOSBinFormatMachO()) {
// All darwin targets use mach-o.
const TargetLoweringObjectFileMachO &TLOFMacho =
static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
MachineModuleInfoMachO &MMIMacho =
MMI->getObjFileInfo<MachineModuleInfoMachO>();
// Output non-lazy-pointers for external and common global variables.
MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
if (!Stubs.empty()) {
// Switch with ".non_lazy_symbol_pointer" directive.
OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
emitAlignment(Align(4));
for (auto &Stub : Stubs)
emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
Stubs.clear();
OutStreamer->AddBlankLine();
}
Stubs = MMIMacho.GetThreadLocalGVStubList();
if (!Stubs.empty()) {
// Switch with ".non_lazy_symbol_pointer" directive.
OutStreamer->SwitchSection(TLOFMacho.getThreadLocalPointerSection());
emitAlignment(Align(4));
for (auto &Stub : Stubs)
emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
Stubs.clear();
OutStreamer->AddBlankLine();
}
// Funny Darwin hack: This flag tells the linker that no global symbols
// contain code that falls through to other global symbols (e.g. the obvious
// implementation of multiple entry points). If this doesn't occur, the
// linker can safely perform dead code stripping. Since LLVM never
// generates code that does this, it is always safe to set.
OutStreamer->emitAssemblerFlag(MCAF_SubsectionsViaSymbols);
}
// The last attribute to be emitted is ABI_optimization_goals
MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
if (OptimizationGoals > 0 &&
(Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI()))
ATS.emitAttribute(ARMBuildAttrs::ABI_optimization_goals, OptimizationGoals);
OptimizationGoals = -1;
ATS.finishAttributeSection();
}
//===----------------------------------------------------------------------===//
// Helper routines for emitStartOfAsmFile() and emitEndOfAsmFile()
// FIXME:
// The following seem like one-off assembler flags, but they actually need
// to appear in the .ARM.attributes section in ELF.
// Instead of subclassing the MCELFStreamer, we do the work here.
// Returns true if all functions have the same function attribute value.
// It also returns true when the module has no functions.
static bool checkFunctionsAttributeConsistency(const Module &M, StringRef Attr,
StringRef Value) {
return !any_of(M, [&](const Function &F) {
return F.getFnAttribute(Attr).getValueAsString() != Value;
});
}
void ARMAsmPrinter::emitAttributes() {
MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
ATS.switchVendor("aeabi");
// Compute ARM ELF Attributes based on the default subtarget that
// we'd have constructed. The existing ARM behavior isn't LTO clean
// anyhow.
// FIXME: For ifunc related functions we could iterate over and look
// for a feature string that doesn't match the default one.
const Triple &TT = TM.getTargetTriple();
StringRef CPU = TM.getTargetCPU();
StringRef FS = TM.getTargetFeatureString();
std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
if (!FS.empty()) {
if (!ArchFS.empty())
ArchFS = (Twine(ArchFS) + "," + FS).str();
else
ArchFS = std::string(FS);
}
const ARMBaseTargetMachine &ATM =
static_cast<const ARMBaseTargetMachine &>(TM);
const ARMSubtarget STI(TT, std::string(CPU), ArchFS, ATM,
ATM.isLittleEndian());
// Emit build attributes for the available hardware.
ATS.emitTargetAttributes(STI);
// RW data addressing.
if (isPositionIndependent()) {
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
ARMBuildAttrs::AddressRWPCRel);
} else if (STI.isRWPI()) {
// RWPI specific attributes.
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
ARMBuildAttrs::AddressRWSBRel);
}
// RO data addressing.
if (isPositionIndependent() || STI.isROPI()) {
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
ARMBuildAttrs::AddressROPCRel);
}
// GOT use.
if (isPositionIndependent()) {
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
ARMBuildAttrs::AddressGOT);
} else {
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
ARMBuildAttrs::AddressDirect);
}
// Set FP Denormals.
if (checkFunctionsAttributeConsistency(*MMI->getModule(),
"denormal-fp-math",
"preserve-sign") ||
TM.Options.FPDenormalMode == FPDenormal::PreserveSign)
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
ARMBuildAttrs::PreserveFPSign);
else if (checkFunctionsAttributeConsistency(*MMI->getModule(),
"denormal-fp-math",
"positive-zero") ||
TM.Options.FPDenormalMode == FPDenormal::PositiveZero)
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
ARMBuildAttrs::PositiveZero);
else if (!TM.Options.UnsafeFPMath)
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
ARMBuildAttrs::IEEEDenormals);
else {
if (!STI.hasVFP2Base()) {
// When the target doesn't have an FPU (by design or
// intention), the assumptions made on the software support
// mirror that of the equivalent hardware support *if it
// existed*. For v7 and better we indicate that denormals are
// flushed preserving sign, and for V6 we indicate that
// denormals are flushed to positive zero.
if (STI.hasV7Ops())
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
ARMBuildAttrs::PreserveFPSign);
} else if (STI.hasVFP3Base()) {
// In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
// the sign bit of the zero matches the sign bit of the input or
// result that is being flushed to zero.
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
ARMBuildAttrs::PreserveFPSign);
}
// For VFPv2 implementations it is implementation defined as
// to whether denormals are flushed to positive zero or to
// whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
// LLVM has chosen to flush this to positive zero (most likely for
// GCC compatibility), so that's the chosen value here (the
// absence of its emission implies zero).
}
// Set FP exceptions and rounding
if (checkFunctionsAttributeConsistency(*MMI->getModule(),
"no-trapping-math", "true") ||
TM.Options.NoTrappingFPMath)
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
ARMBuildAttrs::Not_Allowed);
else if (!TM.Options.UnsafeFPMath) {
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
// If the user has permitted this code to choose the IEEE 754
// rounding at run-time, emit the rounding attribute.
if (TM.Options.HonorSignDependentRoundingFPMathOption)
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
}
// TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
// equivalent of GCC's -ffinite-math-only flag.
if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
ARMBuildAttrs::Allowed);
else
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
ARMBuildAttrs::AllowIEEE754);
// FIXME: add more flags to ARMBuildAttributes.h
// 8-bytes alignment stuff.
ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
// Hard float. Use both S and D registers and conform to AAPCS-VFP.
if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
// FIXME: To support emitting this build attribute as GCC does, the
// -mfp16-format option and associated plumbing must be
// supported. For now the __fp16 type is exposed by default, so this
// attribute should be emitted with value 1.
ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
ARMBuildAttrs::FP16FormatIEEE);
if (MMI) {
if (const Module *SourceModule = MMI->getModule()) {
// ABI_PCS_wchar_t to indicate wchar_t width
// FIXME: There is no way to emit value 0 (wchar_t prohibited).
if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
SourceModule->getModuleFlag("wchar_size"))) {
int WCharWidth = WCharWidthValue->getZExtValue();
assert((WCharWidth == 2 || WCharWidth == 4) &&
"wchar_t width must be 2 or 4 bytes");
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
}
// ABI_enum_size to indicate enum width
// FIXME: There is no way to emit value 0 (enums prohibited) or value 3
// (all enums contain a value needing 32 bits to encode).
if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
SourceModule->getModuleFlag("min_enum_size"))) {
int EnumWidth = EnumWidthValue->getZExtValue();
assert((EnumWidth == 1 || EnumWidth == 4) &&
"Minimum enum width must be 1 or 4 bytes");
int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
}
}
}
// We currently do not support using R9 as the TLS pointer.
if (STI.isRWPI())
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
ARMBuildAttrs::R9IsSB);
else if (STI.isR9Reserved())
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
ARMBuildAttrs::R9Reserved);
else
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
ARMBuildAttrs::R9IsGPR);
}
//===----------------------------------------------------------------------===//
static MCSymbol *getBFLabel(StringRef Prefix, unsigned FunctionNumber,
unsigned LabelId, MCContext &Ctx) {
MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
+ "BF" + Twine(FunctionNumber) + "_" + Twine(LabelId));
return Label;
}
static MCSymbol *getPICLabel(StringRef Prefix, unsigned FunctionNumber,
unsigned LabelId, MCContext &Ctx) {
MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
+ "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
return Label;
}
static MCSymbolRefExpr::VariantKind
getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
switch (Modifier) {
case ARMCP::no_modifier:
return MCSymbolRefExpr::VK_None;
case ARMCP::TLSGD:
return MCSymbolRefExpr::VK_TLSGD;
case ARMCP::TPOFF:
return MCSymbolRefExpr::VK_TPOFF;
case ARMCP::GOTTPOFF:
return MCSymbolRefExpr::VK_GOTTPOFF;
case ARMCP::SBREL:
return MCSymbolRefExpr::VK_ARM_SBREL;
case ARMCP::GOT_PREL:
return MCSymbolRefExpr::VK_ARM_GOT_PREL;
case ARMCP::SECREL:
return MCSymbolRefExpr::VK_SECREL;
}
llvm_unreachable("Invalid ARMCPModifier!");
}
MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
unsigned char TargetFlags) {
if (Subtarget->isTargetMachO()) {
bool IsIndirect =
(TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
if (!IsIndirect)
return getSymbol(GV);
// FIXME: Remove this when Darwin transition to @GOT like syntax.
MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
MachineModuleInfoMachO &MMIMachO =
MMI->getObjFileInfo<MachineModuleInfoMachO>();
MachineModuleInfoImpl::StubValueTy &StubSym =
GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
: MMIMachO.getGVStubEntry(MCSym);
if (!StubSym.getPointer())
StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
!GV->hasInternalLinkage());
return MCSym;
} else if (Subtarget->isTargetCOFF()) {
assert(Subtarget->isTargetWindows() &&
"Windows is the only supported COFF target");
bool IsIndirect =
(TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB));
if (!IsIndirect)
return getSymbol(GV);
SmallString<128> Name;
if (TargetFlags & ARMII::MO_DLLIMPORT)
Name = "__imp_";
else if (TargetFlags & ARMII::MO_COFFSTUB)
Name = ".refptr.";
getNameWithPrefix(Name, GV);
MCSymbol *MCSym = OutContext.getOrCreateSymbol(Name);
if (TargetFlags & ARMII::MO_COFFSTUB) {
MachineModuleInfoCOFF &MMICOFF =
MMI->getObjFileInfo<MachineModuleInfoCOFF>();
MachineModuleInfoImpl::StubValueTy &StubSym =
MMICOFF.getGVStubEntry(MCSym);
if (!StubSym.getPointer())
StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV), true);
}
return MCSym;
} else if (Subtarget->isTargetELF()) {
return getSymbol(GV);
}
llvm_unreachable("unexpected target");
}
void ARMAsmPrinter::emitMachineConstantPoolValue(
MachineConstantPoolValue *MCPV) {
const DataLayout &DL = getDataLayout();
int Size = DL.getTypeAllocSize(MCPV->getType());
ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
if (ACPV->isPromotedGlobal()) {
// This constant pool entry is actually a global whose storage has been
// promoted into the constant pool. This global may be referenced still
// by debug information, and due to the way AsmPrinter is set up, the debug
// info is immutable by the time we decide to promote globals to constant
// pools. Because of this, we need to ensure we emit a symbol for the global
// with private linkage (the default) so debug info can refer to it.
//
// However, if this global is promoted into several functions we must ensure
// we don't try and emit duplicate symbols!
auto *ACPC = cast<ARMConstantPoolConstant>(ACPV);
for (const auto *GV : ACPC->promotedGlobals()) {
if (!EmittedPromotedGlobalLabels.count(GV)) {
MCSymbol *GVSym = getSymbol(GV);
OutStreamer->emitLabel(GVSym);
EmittedPromotedGlobalLabels.insert(GV);
}
}
return emitGlobalConstant(DL, ACPC->getPromotedGlobalInit());
}
MCSymbol *MCSym;
if (ACPV->isLSDA()) {
MCSym = getCurExceptionSym();
} else if (ACPV->isBlockAddress()) {
const BlockAddress *BA =
cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
MCSym = GetBlockAddressSymbol(BA);
} else if (ACPV->isGlobalValue()) {
const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
// On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
// flag the global as MO_NONLAZY.
unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
MCSym = GetARMGVSymbol(GV, TF);
} else if (ACPV->isMachineBasicBlock()) {
const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
MCSym = MBB->getSymbol();
} else {
assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
auto Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
MCSym = GetExternalSymbolSymbol(Sym);
}
// Create an MCSymbol for the reference.
const MCExpr *Expr =
MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
OutContext);
if (ACPV->getPCAdjustment()) {
MCSymbol *PCLabel =
getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
ACPV->getLabelId(), OutContext);
const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
PCRelExpr =
MCBinaryExpr::createAdd(PCRelExpr,
MCConstantExpr::create(ACPV->getPCAdjustment(),
OutContext),
OutContext);
if (ACPV->mustAddCurrentAddress()) {
// We want "(<expr> - .)", but MC doesn't have a concept of the '.'
// label, so just emit a local label end reference that instead.
MCSymbol *DotSym = OutContext.createTempSymbol();
OutStreamer->emitLabel(DotSym);
const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
}
Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
}
OutStreamer->emitValue(Expr, Size);
}
void ARMAsmPrinter::emitJumpTableAddrs(const MachineInstr *MI) {
const MachineOperand &MO1 = MI->getOperand(1);
unsigned JTI = MO1.getIndex();
// Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
// ARM mode tables.
emitAlignment(Align(4));
// Emit a label for the jump table.
MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
OutStreamer->emitLabel(JTISymbol);
// Mark the jump table as data-in-code.
OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
// Emit each entry of the table.
const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
for (MachineBasicBlock *MBB : JTBBs) {
// Construct an MCExpr for the entry. We want a value of the form:
// (BasicBlockAddr - TableBeginAddr)
//
// For example, a table with entries jumping to basic blocks BB0 and BB1
// would look like:
// LJTI_0_0:
// .word (LBB0 - LJTI_0_0)
// .word (LBB1 - LJTI_0_0)
const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
if (isPositionIndependent() || Subtarget->isROPI())
Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
OutContext),
OutContext);
// If we're generating a table of Thumb addresses in static relocation
// model, we need to add one to keep interworking correctly.
else if (AFI->isThumbFunction())
Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
OutContext);
OutStreamer->emitValue(Expr, 4);
}
// Mark the end of jump table data-in-code region.
OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
}
void ARMAsmPrinter::emitJumpTableInsts(const MachineInstr *MI) {
const MachineOperand &MO1 = MI->getOperand(1);
unsigned JTI = MO1.getIndex();
// Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
// ARM mode tables.
emitAlignment(Align(4));
// Emit a label for the jump table.
MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
OutStreamer->emitLabel(JTISymbol);
// Emit each entry of the table.
const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
for (MachineBasicBlock *MBB : JTBBs) {
const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
OutContext);
// If this isn't a TBB or TBH, the entries are direct branch instructions.
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
.addExpr(MBBSymbolExpr)
.addImm(ARMCC::AL)
.addReg(0));
}
}
void ARMAsmPrinter::emitJumpTableTBInst(const MachineInstr *MI,
unsigned OffsetWidth) {
assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
const MachineOperand &MO1 = MI->getOperand(1);
unsigned JTI = MO1.getIndex();
if (Subtarget->isThumb1Only())
emitAlignment(Align(4));
MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
OutStreamer->emitLabel(JTISymbol);
// Emit each entry of the table.
const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
// Mark the jump table as data-in-code.
OutStreamer->emitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
: MCDR_DataRegionJT16);
for (auto MBB : JTBBs) {
const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
OutContext);
// Otherwise it's an offset from the dispatch instruction. Construct an
// MCExpr for the entry. We want a value of the form:
// (BasicBlockAddr - TBBInstAddr + 4) / 2
//
// For example, a TBB table with entries jumping to basic blocks BB0 and BB1
// would look like:
// LJTI_0_0:
// .byte (LBB0 - (LCPI0_0 + 4)) / 2
// .byte (LBB1 - (LCPI0_0 + 4)) / 2
// where LCPI0_0 is a label defined just before the TBB instruction using
// this table.
MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
const MCExpr *Expr = MCBinaryExpr::createAdd(
MCSymbolRefExpr::create(TBInstPC, OutContext),
MCConstantExpr::create(4, OutContext), OutContext);
Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
OutContext);
OutStreamer->emitValue(Expr, OffsetWidth);
}
// Mark the end of jump table data-in-code region. 32-bit offsets use
// actual branch instructions here, so we don't mark those as a data-region
// at all.
OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
// Make sure the next instruction is 2-byte aligned.
emitAlignment(Align(2));
}
void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
assert(MI->getFlag(MachineInstr::FrameSetup) &&
"Only instruction which are involved into frame setup code are allowed");
MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
const MachineFunction &MF = *MI->getParent()->getParent();
const TargetRegisterInfo *TargetRegInfo =
MF.getSubtarget().getRegisterInfo();
const MachineRegisterInfo &MachineRegInfo = MF.getRegInfo();
Register FramePtr = TargetRegInfo->getFrameRegister(MF);
unsigned Opc = MI->getOpcode();
unsigned SrcReg, DstReg;
if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
// Two special cases:
// 1) tPUSH does not have src/dst regs.
// 2) for Thumb1 code we sometimes materialize the constant via constpool
// load. Yes, this is pretty fragile, but for now I don't see better
// way... :(
SrcReg = DstReg = ARM::SP;
} else {
SrcReg = MI->getOperand(1).getReg();
DstReg = MI->getOperand(0).getReg();
}
// Try to figure out the unwinding opcode out of src / dst regs.
if (MI->mayStore()) {
// Register saves.
assert(DstReg == ARM::SP &&
"Only stack pointer as a destination reg is supported");
SmallVector<unsigned, 4> RegList;
// Skip src & dst reg, and pred ops.
unsigned StartOp = 2 + 2;
// Use all the operands.
unsigned NumOffset = 0;
// Amount of SP adjustment folded into a push.
unsigned Pad = 0;
switch (Opc) {
default:
MI->print(errs());
llvm_unreachable("Unsupported opcode for unwinding information");
case ARM::tPUSH:
// Special case here: no src & dst reg, but two extra imp ops.
StartOp = 2; NumOffset = 2;
LLVM_FALLTHROUGH;
case ARM::STMDB_UPD:
case ARM::t2STMDB_UPD:
case ARM::VSTMDDB_UPD:
assert(SrcReg == ARM::SP &&
"Only stack pointer as a source reg is supported");
for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
i != NumOps; ++i) {
const MachineOperand &MO = MI->getOperand(i);
// Actually, there should never be any impdef stuff here. Skip it
// temporary to workaround PR11902.
if (MO.isImplicit())
continue;
// Registers, pushed as a part of folding an SP update into the
// push instruction are marked as undef and should not be
// restored when unwinding, because the function can modify the
// corresponding stack slots.
if (MO.isUndef()) {
assert(RegList.empty() &&
"Pad registers must come before restored ones");
unsigned Width =
TargetRegInfo->getRegSizeInBits(MO.getReg(), MachineRegInfo) / 8;
Pad += Width;
continue;
}
// Check for registers that are remapped (for a Thumb1 prologue that
// saves high registers).
Register Reg = MO.getReg();
if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(Reg))
Reg = RemappedReg;
RegList.push_back(Reg);
}
break;
case ARM::STR_PRE_IMM:
case ARM::STR_PRE_REG:
case ARM::t2STR_PRE:
assert(MI->getOperand(2).getReg() == ARM::SP &&
"Only stack pointer as a source reg is supported");
RegList.push_back(SrcReg);
break;
}
if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
// Account for the SP adjustment, folded into the push.
if (Pad)
ATS.emitPad(Pad);
}
} else {
// Changes of stack / frame pointer.
if (SrcReg == ARM::SP) {
int64_t Offset = 0;
switch (Opc) {
default:
MI->print(errs());
llvm_unreachable("Unsupported opcode for unwinding information");
case ARM::MOVr:
case ARM::tMOVr:
Offset = 0;
break;
case ARM::ADDri:
case ARM::t2ADDri:
case ARM::t2ADDri12:
case ARM::t2ADDspImm:
case ARM::t2ADDspImm12:
Offset = -MI->getOperand(2).getImm();
break;
case ARM::SUBri:
case ARM::t2SUBri:
case ARM::t2SUBri12:
case ARM::t2SUBspImm:
case ARM::t2SUBspImm12:
Offset = MI->getOperand(2).getImm();
break;
case ARM::tSUBspi:
Offset = MI->getOperand(2).getImm()*4;
break;
case ARM::tADDspi:
case ARM::tADDrSPi:
Offset = -MI->getOperand(2).getImm()*4;
break;
case ARM::tLDRpci: {
// Grab the constpool index and check, whether it corresponds to
// original or cloned constpool entry.
unsigned CPI = MI->getOperand(1).getIndex();
const MachineConstantPool *MCP = MF.getConstantPool();
if (CPI >= MCP->getConstants().size())
CPI = AFI->getOriginalCPIdx(CPI);
assert(CPI != -1U && "Invalid constpool index");
// Derive the actual offset.
const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
// FIXME: Check for user, it should be "add" instruction!
Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
break;
}
}
if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
if (DstReg == FramePtr && FramePtr != ARM::SP)
// Set-up of the frame pointer. Positive values correspond to "add"
// instruction.
ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
else if (DstReg == ARM::SP) {
// Change of SP by an offset. Positive values correspond to "sub"
// instruction.
ATS.emitPad(Offset);
} else {
// Move of SP to a register. Positive values correspond to an "add"
// instruction.
ATS.emitMovSP(DstReg, -Offset);
}
}
} else if (DstReg == ARM::SP) {
MI->print(errs());
llvm_unreachable("Unsupported opcode for unwinding information");
} else if (Opc == ARM::tMOVr) {
// If a Thumb1 function spills r8-r11, we copy the values to low
// registers before pushing them. Record the copy so we can emit the
// correct ".save" later.
AFI->EHPrologueRemappedRegs[DstReg] = SrcReg;
} else {
MI->print(errs());
llvm_unreachable("Unsupported opcode for unwinding information");
}
}
}
// Simple pseudo-instructions have their lowering (with expansion to real
// instructions) auto-generated.
#include "ARMGenMCPseudoLowering.inc"
void ARMAsmPrinter::emitInstruction(const MachineInstr *MI) {
const DataLayout &DL = getDataLayout();
MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
const MachineFunction &MF = *MI->getParent()->getParent();
const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
unsigned FramePtr = STI.useR7AsFramePointer() ? ARM::R7 : ARM::R11;
// If we just ended a constant pool, mark it as such.
if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
InConstantPool = false;
}
// Emit unwinding stuff for frame-related instructions
if (Subtarget->isTargetEHABICompatible() &&
MI->getFlag(MachineInstr::FrameSetup))
EmitUnwindingInstruction(MI);
// Do any auto-generated pseudo lowerings.
if (emitPseudoExpansionLowering(*OutStreamer, MI))
return;
assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
"Pseudo flag setting opcode should be expanded early");
// Check for manual lowerings.
unsigned Opc = MI->getOpcode();
switch (Opc) {
case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
case ARM::LEApcrel:
case ARM::tLEApcrel:
case ARM::t2LEApcrel: {
// FIXME: Need to also handle globals and externals
MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
ARM::t2LEApcrel ? ARM::t2ADR
: (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
: ARM::ADR))
.addReg(MI->getOperand(0).getReg())
.addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
// Add predicate operands.
.addImm(MI->getOperand(2).getImm())
.addReg(MI->getOperand(3).getReg()));
return;
}
case ARM::LEApcrelJT:
case ARM::tLEApcrelJT:
case ARM::t2LEApcrelJT: {
MCSymbol *JTIPICSymbol =
GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
ARM::t2LEApcrelJT ? ARM::t2ADR
: (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
: ARM::ADR))
.addReg(MI->getOperand(0).getReg())
.addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
// Add predicate operands.
.addImm(MI->getOperand(2).getImm())
.addReg(MI->getOperand(3).getReg()));
return;
}
// Darwin call instructions are just normal call instructions with different
// clobber semantics (they clobber R9).
case ARM::BX_CALL: {
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
.addReg(ARM::LR)
.addReg(ARM::PC)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0)
// Add 's' bit operand (always reg0 for this)
.addReg(0));
assert(Subtarget->hasV4TOps());
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
.addReg(MI->getOperand(0).getReg()));
return;
}
case ARM::tBX_CALL: {
if (Subtarget->hasV5TOps())
llvm_unreachable("Expected BLX to be selected for v5t+");
// On ARM v4t, when doing a call from thumb mode, we need to ensure
// that the saved lr has its LSB set correctly (the arch doesn't
// have blx).
// So here we generate a bl to a small jump pad that does bx rN.
// The jump pads are emitted after the function body.
Register TReg = MI->getOperand(0).getReg();
MCSymbol *TRegSym = nullptr;
for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
if (TIP.first == TReg) {
TRegSym = TIP.second;
break;
}
}
if (!TRegSym) {
TRegSym = OutContext.createTempSymbol();
ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
}
// Create a link-saving branch to the Reg Indirect Jump Pad.
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
// Predicate comes first here.
.addImm(ARMCC::AL).addReg(0)
.addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
return;
}
case ARM::BMOVPCRX_CALL: {
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
.addReg(ARM::LR)
.addReg(ARM::PC)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0)
// Add 's' bit operand (always reg0 for this)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
.addReg(ARM::PC)
.addReg(MI->getOperand(0).getReg())
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0)
// Add 's' bit operand (always reg0 for this)
.addReg(0));
return;
}
case ARM::BMOVPCB_CALL: {
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
.addReg(ARM::LR)
.addReg(ARM::PC)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0)
// Add 's' bit operand (always reg0 for this)
.addReg(0));
const MachineOperand &Op = MI->getOperand(0);
const GlobalValue *GV = Op.getGlobal();
const unsigned TF = Op.getTargetFlags();
MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
.addExpr(GVSymExpr)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::MOVi16_ga_pcrel:
case ARM::t2MOVi16_ga_pcrel: {
MCInst TmpInst;
TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
unsigned TF = MI->getOperand(1).getTargetFlags();
const GlobalValue *GV = MI->getOperand(1).getGlobal();
MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
MCSymbol *LabelSym =
getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
MI->getOperand(2).getImm(), OutContext);
const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
const MCExpr *PCRelExpr =
ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
MCBinaryExpr::createAdd(LabelSymExpr,
MCConstantExpr::create(PCAdj, OutContext),
OutContext), OutContext), OutContext);
TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
// Add predicate operands.
TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
TmpInst.addOperand(MCOperand::createReg(0));
// Add 's' bit operand (always reg0 for this)
TmpInst.addOperand(MCOperand::createReg(0));
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case ARM::MOVTi16_ga_pcrel:
case ARM::t2MOVTi16_ga_pcrel: {
MCInst TmpInst;
TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
? ARM::MOVTi16 : ARM::t2MOVTi16);
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
unsigned TF = MI->getOperand(2).getTargetFlags();
const GlobalValue *GV = MI->getOperand(2).getGlobal();
MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
MCSymbol *LabelSym =
getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
MI->getOperand(3).getImm(), OutContext);
const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
const MCExpr *PCRelExpr =
ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
MCBinaryExpr::createAdd(LabelSymExpr,
MCConstantExpr::create(PCAdj, OutContext),
OutContext), OutContext), OutContext);
TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
// Add predicate operands.
TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
TmpInst.addOperand(MCOperand::createReg(0));
// Add 's' bit operand (always reg0 for this)
TmpInst.addOperand(MCOperand::createReg(0));
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case ARM::t2BFi:
case ARM::t2BFic:
case ARM::t2BFLi:
case ARM::t2BFr:
case ARM::t2BFLr: {
// This is a Branch Future instruction.
const MCExpr *BranchLabel = MCSymbolRefExpr::create(
getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
MI->getOperand(0).getIndex(), OutContext),
OutContext);
auto MCInst = MCInstBuilder(Opc).addExpr(BranchLabel);
if (MI->getOperand(1).isReg()) {
// For BFr/BFLr
MCInst.addReg(MI->getOperand(1).getReg());
} else {
// For BFi/BFLi/BFic
const MCExpr *BranchTarget;
if (MI->getOperand(1).isMBB())
BranchTarget = MCSymbolRefExpr::create(
MI->getOperand(1).getMBB()->getSymbol(), OutContext);
else if (MI->getOperand(1).isGlobal()) {
const GlobalValue *GV = MI->getOperand(1).getGlobal();
BranchTarget = MCSymbolRefExpr::create(
GetARMGVSymbol(GV, MI->getOperand(1).getTargetFlags()), OutContext);
} else if (MI->getOperand(1).isSymbol()) {
BranchTarget = MCSymbolRefExpr::create(
GetExternalSymbolSymbol(MI->getOperand(1).getSymbolName()),
OutContext);
} else
llvm_unreachable("Unhandled operand kind in Branch Future instruction");
MCInst.addExpr(BranchTarget);
}
if (Opc == ARM::t2BFic) {
const MCExpr *ElseLabel = MCSymbolRefExpr::create(
getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
MI->getOperand(2).getIndex(), OutContext),
OutContext);
MCInst.addExpr(ElseLabel);
MCInst.addImm(MI->getOperand(3).getImm());
} else {
MCInst.addImm(MI->getOperand(2).getImm())
.addReg(MI->getOperand(3).getReg());
}
EmitToStreamer(*OutStreamer, MCInst);
return;
}
case ARM::t2BF_LabelPseudo: {
// This is a pseudo op for a label used by a branch future instruction
// Emit the label.
OutStreamer->emitLabel(getBFLabel(DL.getPrivateGlobalPrefix(),
getFunctionNumber(),
MI->getOperand(0).getIndex(), OutContext));
return;
}
case ARM::tPICADD: {
// This is a pseudo op for a label + instruction sequence, which looks like:
// LPC0:
// add r0, pc
// This adds the address of LPC0 to r0.
// Emit the label.
OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
getFunctionNumber(),
MI->getOperand(2).getImm(), OutContext));
// Form and emit the add.
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
.addReg(MI->getOperand(0).getReg())
.addReg(MI->getOperand(0).getReg())
.addReg(ARM::PC)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::PICADD: {
// This is a pseudo op for a label + instruction sequence, which looks like:
// LPC0:
// add r0, pc, r0
// This adds the address of LPC0 to r0.
// Emit the label.
OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
getFunctionNumber(),
MI->getOperand(2).getImm(), OutContext));
// Form and emit the add.
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
.addReg(MI->getOperand(0).getReg())
.addReg(ARM::PC)
.addReg(MI->getOperand(1).getReg())
// Add predicate operands.
.addImm(MI->getOperand(3).getImm())
.addReg(MI->getOperand(4).getReg())
// Add 's' bit operand (always reg0 for this)
.addReg(0));
return;
}
case ARM::PICSTR:
case ARM::PICSTRB:
case ARM::PICSTRH:
case ARM::PICLDR:
case ARM::PICLDRB:
case ARM::PICLDRH:
case ARM::PICLDRSB:
case ARM::PICLDRSH: {
// This is a pseudo op for a label + instruction sequence, which looks like:
// LPC0:
// OP r0, [pc, r0]
// The LCP0 label is referenced by a constant pool entry in order to get
// a PC-relative address at the ldr instruction.
// Emit the label.
OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
getFunctionNumber(),
MI->getOperand(2).getImm(), OutContext));
// Form and emit the load
unsigned Opcode;
switch (MI->getOpcode()) {
default:
llvm_unreachable("Unexpected opcode!");
case ARM::PICSTR: Opcode = ARM::STRrs; break;
case ARM::PICSTRB: Opcode = ARM::STRBrs; break;
case ARM::PICSTRH: Opcode = ARM::STRH; break;
case ARM::PICLDR: Opcode = ARM::LDRrs; break;
case ARM::PICLDRB: Opcode = ARM::LDRBrs; break;
case ARM::PICLDRH: Opcode = ARM::LDRH; break;
case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
}
EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
.addReg(MI->getOperand(0).getReg())
.addReg(ARM::PC)
.addReg(MI->getOperand(1).getReg())
.addImm(0)
// Add predicate operands.
.addImm(MI->getOperand(3).getImm())
.addReg(MI->getOperand(4).getReg()));
return;
}
case ARM::CONSTPOOL_ENTRY: {
if (Subtarget->genExecuteOnly())
llvm_unreachable("execute-only should not generate constant pools");
/// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
/// in the function. The first operand is the ID# for this instruction, the
/// second is the index into the MachineConstantPool that this is, the third
/// is the size in bytes of this constant pool entry.
/// The required alignment is specified on the basic block holding this MI.
unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex();
// If this is the first entry of the pool, mark it.
if (!InConstantPool) {
OutStreamer->emitDataRegion(MCDR_DataRegion);
InConstantPool = true;
}
OutStreamer->emitLabel(GetCPISymbol(LabelId));
const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
if (MCPE.isMachineConstantPoolEntry())
emitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
else
emitGlobalConstant(DL, MCPE.Val.ConstVal);
return;
}
case ARM::JUMPTABLE_ADDRS:
emitJumpTableAddrs(MI);
return;
case ARM::JUMPTABLE_INSTS:
emitJumpTableInsts(MI);
return;
case ARM::JUMPTABLE_TBB:
case ARM::JUMPTABLE_TBH:
emitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
return;
case ARM::t2BR_JT: {
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
.addReg(ARM::PC)
.addReg(MI->getOperand(0).getReg())
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::t2TBB_JT:
case ARM::t2TBH_JT: {
unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
// Lower and emit the PC label, then the instruction itself.
OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
.addReg(MI->getOperand(0).getReg())
.addReg(MI->getOperand(1).getReg())
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::tTBB_JT:
case ARM::tTBH_JT: {
bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
Register Base = MI->getOperand(0).getReg();
Register Idx = MI->getOperand(1).getReg();
assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
// Multiply up idx if necessary.
if (!Is8Bit)
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
.addReg(Idx)
.addReg(ARM::CPSR)
.addReg(Idx)
.addImm(1)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
if (Base == ARM::PC) {
// TBB [base, idx] =
// ADDS idx, idx, base
// LDRB idx, [idx, #4] ; or LDRH if TBH
// LSLS idx, #1
// ADDS pc, pc, idx
// When using PC as the base, it's important that there is no padding
// between the last ADDS and the start of the jump table. The jump table
// is 4-byte aligned, so we ensure we're 4 byte aligned here too.
//
// FIXME: Ideally we could vary the LDRB index based on the padding
// between the sequence and jump table, however that relies on MCExprs
// for load indexes which are currently not supported.
OutStreamer->emitCodeAlignment(4);
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
.addReg(Idx)
.addReg(Idx)
.addReg(Base)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
.addReg(Idx)
.addReg(Idx)
.addImm(Is8Bit ? 4 : 2)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
} else {
// TBB [base, idx] =
// LDRB idx, [base, idx] ; or LDRH if TBH
// LSLS idx, #1
// ADDS pc, pc, idx
unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
.addReg(Idx)
.addReg(Base)
.addReg(Idx)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
}
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
.addReg(Idx)
.addReg(ARM::CPSR)
.addReg(Idx)
.addImm(1)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
.addReg(ARM::PC)
.addReg(ARM::PC)
.addReg(Idx)
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::tBR_JTr:
case ARM::BR_JTr: {
// mov pc, target
MCInst TmpInst;
unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
ARM::MOVr : ARM::tMOVr;
TmpInst.setOpcode(Opc);
TmpInst.addOperand(MCOperand::createReg(ARM::PC));
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
// Add predicate operands.
TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
TmpInst.addOperand(MCOperand::createReg(0));
// Add 's' bit operand (always reg0 for this)
if (Opc == ARM::MOVr)
TmpInst.addOperand(MCOperand::createReg(0));
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case ARM::BR_JTm_i12: {
// ldr pc, target
MCInst TmpInst;
TmpInst.setOpcode(ARM::LDRi12);
TmpInst.addOperand(MCOperand::createReg(ARM::PC));
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
// Add predicate operands.
TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
TmpInst.addOperand(MCOperand::createReg(0));
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case ARM::BR_JTm_rs: {
// ldr pc, target
MCInst TmpInst;
TmpInst.setOpcode(ARM::LDRrs);
TmpInst.addOperand(MCOperand::createReg(ARM::PC));
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
// Add predicate operands.
TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
TmpInst.addOperand(MCOperand::createReg(0));
EmitToStreamer(*OutStreamer, TmpInst);
return;
}
case ARM::BR_JTadd: {
// add pc, target, idx
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
.addReg(ARM::PC)
.addReg(MI->getOperand(0).getReg())
.addReg(MI->getOperand(1).getReg())
// Add predicate operands.
.addImm(ARMCC::AL)
.addReg(0)
// Add 's' bit operand (always reg0 for this)
.addReg(0));
return;
}
case ARM::SPACE:
OutStreamer->emitZeros(MI->getOperand(1).getImm());
return;
case ARM::TRAP: {
// Non-Darwin binutils don't yet support the "trap" mnemonic.
// FIXME: Remove this special case when they do.
if (!Subtarget->isTargetMachO()) {
uint32_t Val = 0xe7ffdefeUL;
OutStreamer->AddComment("trap");
ATS.emitInst(Val);
return;
}
break;
}
case ARM::TRAPNaCl: {
uint32_t Val = 0xe7fedef0UL;
OutStreamer->AddComment("trap");
ATS.emitInst(Val);
return;
}
case ARM::tTRAP: {
// Non-Darwin binutils don't yet support the "trap" mnemonic.
// FIXME: Remove this special case when they do.
if (!Subtarget->isTargetMachO()) {
uint16_t Val = 0xdefe;
OutStreamer->AddComment("trap");
ATS.emitInst(Val, 'n');
return;
}
break;
}
case ARM::t2Int_eh_sjlj_setjmp:
case ARM::t2Int_eh_sjlj_setjmp_nofp:
case ARM::tInt_eh_sjlj_setjmp: {
// Two incoming args: GPR:$src, GPR:$val
// mov $val, pc
// adds $val, #7
// str $val, [$src, #4]
// movs r0, #0
// b LSJLJEH
// movs r0, #1
// LSJLJEH:
Register SrcReg = MI->getOperand(0).getReg();
Register ValReg = MI->getOperand(1).getReg();
MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
OutStreamer->AddComment("eh_setjmp begin");
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
.addReg(ValReg)
.addReg(ARM::PC)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
.addReg(ValReg)
// 's' bit operand
.addReg(ARM::CPSR)
.addReg(ValReg)
.addImm(7)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
.addReg(ValReg)
.addReg(SrcReg)
// The offset immediate is #4. The operand value is scaled by 4 for the
// tSTR instruction.
.addImm(1)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
.addReg(ARM::R0)
.addReg(ARM::CPSR)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
.addExpr(SymbolExpr)
.addImm(ARMCC::AL)
.addReg(0));
OutStreamer->AddComment("eh_setjmp end");
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
.addReg(ARM::R0)
.addReg(ARM::CPSR)
.addImm(1)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
OutStreamer->emitLabel(Label);
return;
}
case ARM::Int_eh_sjlj_setjmp_nofp:
case ARM::Int_eh_sjlj_setjmp: {
// Two incoming args: GPR:$src, GPR:$val
// add $val, pc, #8
// str $val, [$src, #+4]
// mov r0, #0
// add pc, pc, #0
// mov r0, #1
Register SrcReg = MI->getOperand(0).getReg();
Register ValReg = MI->getOperand(1).getReg();
OutStreamer->AddComment("eh_setjmp begin");
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
.addReg(ValReg)
.addReg(ARM::PC)
.addImm(8)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0)
// 's' bit operand (always reg0 for this).
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
.addReg(ValReg)
.addReg(SrcReg)
.addImm(4)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
.addReg(ARM::R0)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0)
// 's' bit operand (always reg0 for this).
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
.addReg(ARM::PC)
.addReg(ARM::PC)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0)
// 's' bit operand (always reg0 for this).
.addReg(0));
OutStreamer->AddComment("eh_setjmp end");
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
.addReg(ARM::R0)
.addImm(1)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0)
// 's' bit operand (always reg0 for this).
.addReg(0));
return;
}
case ARM::Int_eh_sjlj_longjmp: {
// ldr sp, [$src, #8]
// ldr $scratch, [$src, #4]
// ldr r7, [$src]
// bx $scratch
Register SrcReg = MI->getOperand(0).getReg();
Register ScratchReg = MI->getOperand(1).getReg();
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
.addReg(ARM::SP)
.addReg(SrcReg)
.addImm(8)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
.addReg(ScratchReg)
.addReg(SrcReg)
.addImm(4)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
if (STI.isTargetDarwin() || STI.isTargetWindows()) {
// These platforms always use the same frame register
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
.addReg(FramePtr)
.addReg(SrcReg)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
} else {
// If the calling code might use either R7 or R11 as
// frame pointer register, restore it into both.
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
.addReg(ARM::R7)
.addReg(SrcReg)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
.addReg(ARM::R11)
.addReg(SrcReg)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
}
assert(Subtarget->hasV4TOps());
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
.addReg(ScratchReg)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::tInt_eh_sjlj_longjmp: {
// ldr $scratch, [$src, #8]
// mov sp, $scratch
// ldr $scratch, [$src, #4]
// ldr r7, [$src]
// bx $scratch
Register SrcReg = MI->getOperand(0).getReg();
Register ScratchReg = MI->getOperand(1).getReg();
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
.addReg(ScratchReg)
.addReg(SrcReg)
// The offset immediate is #8. The operand value is scaled by 4 for the
// tLDR instruction.
.addImm(2)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
.addReg(ARM::SP)
.addReg(ScratchReg)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
.addReg(ScratchReg)
.addReg(SrcReg)
.addImm(1)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
if (STI.isTargetDarwin() || STI.isTargetWindows()) {
// These platforms always use the same frame register
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
.addReg(FramePtr)
.addReg(SrcReg)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
} else {
// If the calling code might use either R7 or R11 as
// frame pointer register, restore it into both.
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
.addReg(ARM::R7)
.addReg(SrcReg)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
.addReg(ARM::R11)
.addReg(SrcReg)
.addImm(0)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
}
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
.addReg(ScratchReg)
// Predicate.
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::tInt_WIN_eh_sjlj_longjmp: {
// ldr.w r11, [$src, #0]
// ldr.w sp, [$src, #8]
// ldr.w pc, [$src, #4]
Register SrcReg = MI->getOperand(0).getReg();
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
.addReg(ARM::R11)
.addReg(SrcReg)
.addImm(0)
// Predicate
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
.addReg(ARM::SP)
.addReg(SrcReg)
.addImm(8)
// Predicate
.addImm(ARMCC::AL)
.addReg(0));
EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
.addReg(ARM::PC)
.addReg(SrcReg)
.addImm(4)
// Predicate
.addImm(ARMCC::AL)
.addReg(0));
return;
}
case ARM::PATCHABLE_FUNCTION_ENTER:
LowerPATCHABLE_FUNCTION_ENTER(*MI);
return;
case ARM::PATCHABLE_FUNCTION_EXIT:
LowerPATCHABLE_FUNCTION_EXIT(*MI);
return;
case ARM::PATCHABLE_TAIL_CALL:
LowerPATCHABLE_TAIL_CALL(*MI);
return;
}
MCInst TmpInst;
LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
EmitToStreamer(*OutStreamer, TmpInst);
}
//===----------------------------------------------------------------------===//
// Target Registry Stuff
//===----------------------------------------------------------------------===//
// Force static initialization.
extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmPrinter() {
RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
}
|
/* SPDX-License-Identifier: MIT */
/**
@file ntv2driverprocamp.cpp
@brief Implementation of driver procamp utility functions.
@copyright (C) 2003-2021 AJA Video Systems, Inc.
@note Because this module is compiled into the driver, it must remain straight ANSI 'C' -- no C++ or STL.
Since the Linux driver is not C++ based, a devicenumber is required in some functions in place of "this" pointer.
**/
#include "ntv2driverprocamp.h"
#if defined(NTV2_BUILDING_DRIVER)
#ifdef AJALinux
#include <linux/jiffies.h>
#include "registerio.h"
#include "driverdbg.h"
#include "ntv2driverdbgmsgctl.h"
#define ENABLE_DEBUG_PRINT
#endif
#ifdef AJAMac
#include <IOKit/IOLib.h>
#include "MacDriver.h"
#define MSG IOLog
#define MsgsEnabled(x) (false) // set this to 'true' to enable debug IOLogs
#define ENABLE_DEBUG_PRINT
#endif
typedef enum
{
isSDProc,
isHDProc
} SDIProcType;
#ifndef AJAMac // see MacDriver.h
static bool I2CWriteData(ULWord deviceNumber, ULWord value);
static bool I2CWriteControl(ULWord deviceNumber, ULWord value);
static bool WaitForI2CReady(ULWord deviceNumber);
static bool I2CInhibitHardwareReads(ULWord deviceNumber);
static bool I2CEnableHardwareReads(ULWord deviceNumber);
#endif
/*****************************************************************************************
* SetVirtualProcampRegister
*****************************************************************************************/
bool SetVirtualProcampRegister( VirtualRegisterNum virtualRegisterNum,
ULWord value,
VirtualProcAmpRegisters *regs)
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("Got set of procamp vreg %d, value 0x%x\n", virtualRegisterNum, value);
#endif
switch (virtualRegisterNum)
{
case kVRegProcAmpSDRegsInitialized:
regs->SD.initialized = value;
break;
case kVRegProcAmpStandardDefBrightness:
regs->SD.brightness = value;
break;
case kVRegProcAmpStandardDefContrast:
regs->SD.contrast = value;
break;
case kVRegProcAmpStandardDefSaturation:
regs->SD.saturationCb = value;
regs->SD.saturationCr = value;
break;
case kVRegProcAmpStandardDefHue:
regs->SD.hue = value;
break;
case kVRegProcAmpStandardDefCbOffset:
regs->SD.CbOffset = value;
break;
case kVRegProcAmpStandardDefCrOffset:
regs->SD.CrOffset = value;
break;
case kVRegProcAmpHDRegsInitialized:
regs->HD.initialized = value;
break;
case kVRegProcAmpHighDefContrast:
regs->HD.contrast = value;
break;
case kVRegProcAmpHighDefSaturationCb:
regs->HD.saturationCb = value;
break;
case kVRegProcAmpHighDefSaturationCr:
regs->HD.saturationCr = value;
break;
case kVRegProcAmpHighDefBrightness:
regs->HD.brightness = value;
break;
case kVRegProcAmpHighDefCbOffset:
regs->HD.CbOffset = value;
break;
case kVRegProcAmpHighDefCrOffset:
regs->HD.CrOffset = value;
break;
case kVRegProcAmpHighDefHue: // Not supported in hardware
return false;
default:
return false;
}
return true;
}
/*****************************************************************************************
* GetVirtualProcampRegister
*****************************************************************************************/
bool GetVirtualProcampRegister( VirtualRegisterNum virtualRegisterNum,
ULWord *value,
VirtualProcAmpRegisters *regs)
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("Got get of procamp vreg %d, fetching value\n", virtualRegisterNum);
#endif
switch (virtualRegisterNum)
{
case kVRegProcAmpSDRegsInitialized:
*value = regs->SD.initialized;
break;
case kVRegProcAmpStandardDefBrightness:
*value = regs->SD.brightness;
break;
case kVRegProcAmpStandardDefContrast:
*value = regs->SD.contrast;
break;
case kVRegProcAmpStandardDefSaturation:
if (regs->SD.saturationCb != regs->SD.saturationCr)
return false;
*value = regs->SD.saturationCb;
break;
case kVRegProcAmpStandardDefHue:
*value = regs->SD.hue;
break;
case kVRegProcAmpStandardDefCbOffset:
*value = regs->SD.CbOffset;
break;
case kVRegProcAmpStandardDefCrOffset:
*value = regs->SD.CrOffset;
break;
case kVRegProcAmpHDRegsInitialized:
*value = regs->HD.initialized;
break;
case kVRegProcAmpHighDefContrast:
*value = regs->HD.contrast;
break;
case kVRegProcAmpHighDefSaturationCb:
*value = regs->HD.saturationCb;
break;
case kVRegProcAmpHighDefSaturationCr:
*value = regs->HD.saturationCr;
break;
case kVRegProcAmpHighDefBrightness:
*value = regs->HD.brightness;
break;
case kVRegProcAmpHighDefCbOffset:
*value = regs->HD.CbOffset;
break;
case kVRegProcAmpHighDefCrOffset:
*value = regs->HD.CrOffset;
break;
case kVRegProcAmpHighDefHue:
return false; // Not supported
default:
return false; // Not supported
}
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("Got get of procamp vreg %d, value 0x%x\n", virtualRegisterNum, *value);
#endif
return true;
}
/*****************************************************************************************
* RestoreHardwareProcampRegisters
*****************************************************************************************/
// Call this function to restore ProcAmp registers (from virtual register)
#ifdef AJAMac
bool MacDriver::RestoreHardwareProcampRegisters( ULWord deviceNumber,
NTV2DeviceID deviceID,
VirtualProcAmpRegisters *regs,
HardwareProcAmpRegisterImage *hwRegImage)
#else
bool RestoreHardwareProcampRegisters( ULWord deviceNumber,
NTV2DeviceID deviceID,
VirtualProcAmpRegisters *regs,
HardwareProcAmpRegisterImage *hwRegImage)
#endif
{
ULWord regVal;
ULWord regNum;
// If SD controls initialized
if ( GetVirtualProcampRegister( (VirtualRegisterNum)kVRegProcAmpSDRegsInitialized, ®Val, regs ) && regVal != 0)
{
for ( regNum = (ULWord)kVRegProcAmpStandardDefBrightness; regNum < (ULWord)kVRegProcAmpEndStandardDefRange; regNum++ )
{
// Fetch cached value and skip unsupported registers
if ( GetVirtualProcampRegister( (VirtualRegisterNum)regNum, ®Val, regs ) )
{
if (!WriteHardwareProcampRegister( deviceNumber, deviceID, (VirtualRegisterNum)regNum, regVal, hwRegImage ))
{
return false;
}
}
}
}
// If HD controls initialized
if ( GetVirtualProcampRegister( (VirtualRegisterNum)kVRegProcAmpHDRegsInitialized, ®Val, regs ) && regVal != 0)
{
for ( regNum = (ULWord)kVRegProcAmpHighDefBrightness; regNum < (ULWord)kVRegProcAmpEndHighDefRange; regNum++ )
{
// Fetch cached value and skip unsupported registers
if ( GetVirtualProcampRegister( (VirtualRegisterNum)regNum, ®Val, regs ) )
{
if (!WriteHardwareProcampRegister( deviceNumber, deviceID, (VirtualRegisterNum)regNum, regVal, hwRegImage ))
{
return false;
}
}
}
}
return true;
}
/*****************************************************************************************
* WriteHardwareProcampRegister
*****************************************************************************************/
// This function is necessary because:
// 1) We can't read the I2C registers and
// 2) The HD registers are spread across various I2C addresses
//
#ifdef AJAMac
bool MacDriver::WriteHardwareProcampRegister( ULWord deviceNumber,
NTV2DeviceID deviceID,
VirtualRegisterNum virtualRegisterNum,
ULWord value,
HardwareProcAmpRegisterImage *hwRegImage)
#else
bool WriteHardwareProcampRegister( ULWord deviceNumber,
NTV2DeviceID deviceID,
VirtualRegisterNum virtualRegisterNum,
ULWord value,
HardwareProcAmpRegisterImage *hwRegImage)
#endif
{
ULWord mask;
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("Got write to hw reg of procamp vreg %d, value 0x%x\n", virtualRegisterNum, value);
#endif
// Fetch mask.
switch (virtualRegisterNum)
{
case kVRegProcAmpStandardDefBrightness:
case kVRegProcAmpStandardDefContrast:
case kVRegProcAmpStandardDefSaturation:
case kVRegProcAmpStandardDefHue:
case kVRegProcAmpStandardDefCbOffset:
case kVRegProcAmpStandardDefCrOffset:
return false;
break;
case kVRegProcAmpHighDefContrast:
case kVRegProcAmpHighDefSaturationCb:
case kVRegProcAmpHighDefSaturationCr:
case kVRegProcAmpHighDefBrightness:
case kVRegProcAmpHighDefCbOffset:
case kVRegProcAmpHighDefCrOffset:
return false;
break;
case kVRegProcAmpHighDefHue: // Not supported in hardware.
return false;
default: // Other non-procamp virtual regs
return false;
}
value &= mask; // Note: We may be nuking some high bits from a previously signed value to shoehorn it into a hw register
switch (virtualRegisterNum)
{
case kVRegProcAmpStandardDefBrightness:
hwRegImage->SD.brightness = value;
return I2CWriteDataSingle(deviceNumber, kRegADV7189BBrightness, hwRegImage->SD.brightness);
case kVRegProcAmpStandardDefContrast:
hwRegImage->SD.contrast= value;
return I2CWriteDataSingle(deviceNumber, kRegADV7189BContrast, hwRegImage->SD.contrast);
case kVRegProcAmpStandardDefSaturation:
hwRegImage->SD.saturationCb = value;
hwRegImage->SD.saturationCr = value;
return I2CWriteDataDoublet( deviceNumber,
kRegADV7189BSaturationCb, hwRegImage->SD.saturationCb,
kRegADV7189BSaturationCr, hwRegImage->SD.saturationCr);
case kVRegProcAmpStandardDefHue:
hwRegImage->SD.hue = value;
return I2CWriteDataSingle(deviceNumber, kRegADV7189BHue, hwRegImage->SD.hue);
case kVRegProcAmpStandardDefCbOffset:
hwRegImage->SD.CbOffset = value;
return I2CWriteDataSingle(deviceNumber, kRegADV7189BCbOffset, hwRegImage->SD.CbOffset);
case kVRegProcAmpStandardDefCrOffset:
hwRegImage->SD.CrOffset = value;
return I2CWriteDataSingle(deviceNumber, kRegADV7189BCrOffset, hwRegImage->SD.CrOffset);
// The high def regs are scattered across various I2C addresses.
// Messy.
// TODO: If performance response is sluggish, a possible optimization is
// to write only register(s) that change. I2C writes are slow, 100uSec.
// Maybe fast enough...
case kVRegProcAmpHighDefContrast:
hwRegImage->HD.hex73 = BIT_7 | BIT_6 | (value >> 4);
hwRegImage->HD.hex74 &= 0x0f; // Preserve saturation Cb portion
hwRegImage->HD.hex74 |= (value & 0x0f) << 4;
return I2CWriteDataDoublet( deviceNumber,
0x73, hwRegImage->HD.hex73,
0x74, hwRegImage->HD.hex74);
case kVRegProcAmpHighDefSaturationCb:
hwRegImage->HD.hex74 &= 0xf0; // Preserve contrast portion
hwRegImage->HD.hex74 |= value >> 6;
hwRegImage->HD.hex75 &= 0x03; // Preserve saturation Cr portion
hwRegImage->HD.hex75 |= (value & 0x3f) <<2;
return I2CWriteDataDoublet( deviceNumber,
0x74, hwRegImage->HD.hex74,
0x75, hwRegImage->HD.hex75);
case kVRegProcAmpHighDefSaturationCr:
hwRegImage->HD.hex75 &= 0xfc; // Preserve Saturation Cb portion
hwRegImage->HD.hex75 |= value >> 8;
hwRegImage->HD.hex76 = value & 0xff;
return I2CWriteDataDoublet( deviceNumber,
0x75, hwRegImage->HD.hex75,
0x76, hwRegImage->HD.hex76);
case kVRegProcAmpHighDefBrightness:
hwRegImage->HD.hex77 = value >> 4; // Bits 7, 6 should be clear
hwRegImage->HD.hex78 &= 0x0f; // Preserve Cb Offset portion
hwRegImage->HD.hex78 |= (value & 0x0f) << 4;
return I2CWriteDataDoublet( deviceNumber,
0x77, hwRegImage->HD.hex77,
0x78, hwRegImage->HD.hex78);
case kVRegProcAmpHighDefCbOffset:
hwRegImage->HD.hex78 &= 0xf0; // Preserve brightness portion
hwRegImage->HD.hex78 |= value >> 6;
hwRegImage->HD.hex79 &= 0x03; // Preserve Cr Offset portion
hwRegImage->HD.hex79 |= (value & 0x3f) << 2;
return I2CWriteDataDoublet( deviceNumber,
0x78, hwRegImage->HD.hex78,
0x79, hwRegImage->HD.hex79);
case kVRegProcAmpHighDefCrOffset:
hwRegImage->HD.hex79 &= 0xfc; // Preserve Cb offset portion
hwRegImage->HD.hex79 |= value >> 8;
hwRegImage->HD.hex7A = value & 0xff;
return I2CWriteDataDoublet( deviceNumber,
0x79, hwRegImage->HD.hex79,
0x7A, hwRegImage->HD.hex7A);
case kVRegProcAmpHighDefHue: // Hardware doesn't support HD hue adjust
return false;
default: // Other non-procamp virtual regs
return false;
}
return true;
}
/*****************************************************************************************
* I2CWriteDataSingle
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::I2CWriteDataSingle(ULWord deviceNumber, UByte I2CAddress, UByte I2CData)
#else
bool I2CWriteDataSingle(ULWord deviceNumber, UByte I2CAddress, UByte I2CData)
#endif
{
ULWord I2CCommand = I2CAddress;
bool retVal;
if (!I2CInhibitHardwareReads(deviceNumber))
{
retVal = false;
goto bail;
}
I2CCommand <<= 8;
I2CCommand |= I2CData;
retVal = I2CWriteData(deviceNumber, I2CCommand);
bail:
if(!I2CEnableHardwareReads(deviceNumber))
retVal = false;
return retVal;
}
/*****************************************************************************************
* I2CInhibitHardwareReads
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::I2CInhibitHardwareReads(ULWord deviceNumber)
#else
static bool I2CInhibitHardwareReads(ULWord deviceNumber)
#endif
{
bool retVal = true;
// Unspecified bad things can happen if I2C double writes are
// interfered with. Guard access with a mutex.
#ifdef AJALinux
NTV2PrivateParams *pNTV2Params;
pNTV2Params = getNTV2Params(deviceNumber);
if(down_interruptible(&pNTV2Params->_I2CMutex))
{
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CInhibitHardwareReads: down_interruptible() failed.\n");
return false;
}
#endif
#ifdef AJAMac
// We're assuming that this will only be called from INSIDE the IOCommandGate, so we're already protected from pre-emption
#endif
if(!I2CWriteControl(deviceNumber, BIT(16))) // Inhibit I2C status register reads at vertical
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CInhibitHardwareReads: WriteControl() failed.\n");
#endif
retVal = false;
I2CWriteControl(deviceNumber, 0); // Enable I2C status register reads at vertical
}
else
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CInhibitHardwareReads: I2C inhibit set.\n");
#endif
}
#ifdef AJALinux
up(&pNTV2Params->_I2CMutex);
#endif
return retVal;
}
/*****************************************************************************************
* I2CEnableHardwareReads
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::I2CEnableHardwareReads(ULWord deviceNumber)
#else
static bool I2CEnableHardwareReads(ULWord deviceNumber)
#endif
{
bool retVal = true;
#ifdef AJALinux
NTV2PrivateParams *pNTV2Params;
pNTV2Params = getNTV2Params(deviceNumber);
if(down_interruptible(&pNTV2Params->_I2CMutex))
return false;
#endif
#ifdef AJAMac
// We're assuming that this will only be called from INSIDE the IOCommandGate, so we're already protected from preemption
#endif
if(!I2CWriteControl(deviceNumber, 0)) // Inhibit I2C status register reads at vertical
{
retVal = false;
}
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CEnableHardwareReads: I2C inhibit cleared.\n");
#endif
#ifdef AJALinux
up(&pNTV2Params->_I2CMutex);
#endif
return retVal;
}
/*****************************************************************************************
* I2CWriteDataDoublet
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::I2CWriteDataDoublet( ULWord deviceNumber,
UByte I2CAddress1, UByte I2CData1,
UByte I2CAddress2, UByte I2CData2)
#else
bool I2CWriteDataDoublet( ULWord deviceNumber,
UByte I2CAddress1, UByte I2CData1,
UByte I2CAddress2, UByte I2CData2)
#endif
{
bool retVal = true;
ULWord I2CCommand;
if (!I2CInhibitHardwareReads(deviceNumber))
{
retVal = false;
goto bail;
}
I2CCommand = I2CAddress1;
I2CCommand <<= 8;
I2CCommand |= I2CData1;
if (!I2CWriteData(deviceNumber, I2CCommand))
{
retVal = false;
goto bail;
}
I2CCommand = I2CAddress2;
I2CCommand <<= 8;
I2CCommand |= I2CData2;
if(!I2CWriteData(deviceNumber, I2CCommand))
{
retVal = false;
goto bail;
}
bail:
if(!I2CEnableHardwareReads(deviceNumber))
retVal = false;
return retVal;
}
/*****************************************************************************************
* WaitForI2CReady
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::WaitForI2CReady(ULWord deviceNumber)
#else
static bool WaitForI2CReady(ULWord deviceNumber)
#endif
{
ULWord registerValue;
#ifdef AJALinux
unsigned long timeoutJiffies, deadline; // ULWord typedef makes time_before() issue bogus warnings.
#endif
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("WaitForI2CReady: Waiting...\n");
#endif
#ifdef AJALinux
// Round up to granularity of HZ
timeoutJiffies = ntv2_getRoundedUpTimeoutJiffies(10); // Timeout after 10 msec
deadline = jiffies + timeoutJiffies;
// Busy wait. If I2C busy, write should complete in about 100 usec, unless something
// is very broken.
do
{
registerValue = ReadRegister(deviceNumber, kRegI2CWriteControl, NO_MASK, NO_SHIFT);
if ((registerValue & BIT(31)) == 0) // Not busy?
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("WaitForI2CReady: Got ready.\n");
#endif
return true;
}
} while( time_before( jiffies, deadline));
#endif
#ifdef AJAMac
int maxMSecs = 10; // we'll wait a maximum of 10 msec
do
{
ReadRegisterImmediate(kRegI2CWriteControl, (uint32_t *)®isterValue);
if ((registerValue & BIT(31)) == 0) // Not busy?
{
// if (maxMSecs < 10)
// IOLog("WaitForI2CReady: waited %d msecs for I2C Ready.\n", maxMSecs);
return true;
}
IOSleep(1); // sleep 1 msec & try again
} while (--maxMSecs > 0);
#endif
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("WaitForI2CReady: Timed out.\n");
#endif
return false; // Timed out, + not implemented for Windows yet.
}
/*****************************************************************************************
* I2CWriteData
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::I2CWriteData(ULWord deviceNumber, ULWord value)
#else
static bool I2CWriteData(ULWord deviceNumber, ULWord value)
#endif
{
// wait for the hardware to be ready
if (WaitForI2CReady(deviceNumber) == false)
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CWriteData: First WaitForI2CReady() failed.\n");
#endif
return false;
}
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CWriteData: writing register 0x%02x = 0x%02x (device #%d)\n", (value & 0xFF00) >> 8, (value & 0xFF), deviceNumber);
#endif
// write the data to the hardware
#ifdef AJALinux
WriteRegister( deviceNumber,
kRegI2CWriteData,
value,
NO_MASK,
NO_SHIFT);
#endif
#ifdef AJAMac
WriteRegisterImmediate(kRegI2CWriteData, value);
#endif
// wait for the I2C to complete writing
if (WaitForI2CReady(deviceNumber) == false) {
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CWriteData: Second WaitForI2CReady() failed.\n");
#endif
return false;
}
#if defined(AJALinux) || defined(AJAMac)
return true;
#else
return false; // Not implemented for Windows yet.
#endif
}
/*****************************************************************************************
* I2CWriteControl
*****************************************************************************************/
#ifdef AJAMac
bool MacDriver::I2CWriteControl(ULWord deviceNumber, ULWord value)
#else
static bool I2CWriteControl(ULWord deviceNumber, ULWord value)
#endif
{
#ifdef ENABLE_DEBUG_PRINT
if (MsgsEnabled(NTV2_DRIVER_I2C_DEBUG_MESSAGES))
MSG("I2CWriteControl: writing 0x%08x to device #%d.\n", value, deviceNumber);
#endif
#ifdef AJALinux
WriteRegister( deviceNumber,
kRegI2CWriteControl,
value,
NO_MASK,
NO_SHIFT);
return true;
#endif
#ifdef AJAMac
return WriteRegisterImmediate(kRegI2CWriteControl, value);
#endif
return false; // Not implemented for Windows yet.
}
#endif // defined(NTV2_BUILDING_DRIVER)
|
/*
* CStubMakerMain.cpp
*
* Created on: 2016/04/19
* Author: Kensuke
*/
#include <iostream>
#include <exception>
#include <sstream>
#include <iomanip>
#include "CFuncExtracter.h"
#include "CArgExtracter.h"
#include "CCSrcCreator.h"
#include "CCSrcStubCreator.h"
#include "CCSrcIFCreator.h"
#include "CCHeaderCreator.h"
#include "CCHeaderStubCreator.h"
#include "CStubMakerMain.h"
CStubMakerMain::CStubMakerMain()
: mMacroSize(10)
, mFileName(String(""))
{
this->mFileDataList = new list<CFileData *>();
this->mParamInfoList = new list<CParamInfo *>();
}
CStubMakerMain::CStubMakerMain(String FileName)
: mMacroSize(10)
, mFileName(FileName)
{
this->mFileDataList = new list<CFileData *>();
this->mParamInfoList = new list<CParamInfo *>();
}
CStubMakerMain::~CStubMakerMain()
{
list<CParamInfo *>::iterator ParamInfoListIterator;
ParamInfoListIterator = this->mParamInfoList->begin();
while (this->mParamInfoList->end() != ParamInfoListIterator) {
CParamInfo *ParamInfo = *ParamInfoListIterator;
delete ParamInfo;
ParamInfoListIterator++;
}
delete this->mParamInfoList;
list<CFileData *>::iterator FileDatalistIterator;
FileDatalistIterator = this->mFileDataList->begin();
while (this->mFileDataList->end() != FileDatalistIterator) {
CFileData *FileData = *FileDatalistIterator;
delete FileData;
FileDatalistIterator++;
}
delete this->mFileDataList;
}
#define MAJOR_VERSION (1)
#define MINOR_VERSION (0)
String CStubMakerMain::GetVersion()
{
stringstream MajorStringStream;
stringstream MinorStringStream;
String VersionString;
MajorStringStream << hex << uppercase << MAJOR_VERSION;
MinorStringStream << hex << uppercase <<
setw(2) << setfill('0') << MINOR_VERSION;
VersionString = MajorStringStream.str() +
String(".") +
MinorStringStream.str();
return (VersionString);
}
/**
* 引数で指定されたファイルから、関数の宣言情報を抜き出す。
*/
VOID CStubMakerMain::Parse(String FileName)
{
CFileParser FileParser;
FileParser.Parse(FileName, this->mFileDataList);
}
/**
* 関数宣言情報を、CParamInfoクラスに変換・格納する。
*/
VOID CStubMakerMain::Extract(VOID)
{
CParamInfo *ParamInfo;
AExtracter *Extracter;
list<CFileData *>::iterator FileDataListIterator;
FileDataListIterator = this->mFileDataList->begin();
while (this->mFileDataList->end() != FileDataListIterator) {
/*
* CFileDataごとに、1関数分(引数含む)が格納されている。
* そのため、CFileDataオブジェクトごとに、データを抜き出し、
* CParamInfoオブジェクトに格納する。
*/
CFileData *FileData = *FileDataListIterator;
list<String> *Content = (list<String> *)FileData->getContent();
ParamInfo = new CParamInfo(); //抜き出した関数情報の格納先
//関数情報抜き出し
Extracter = new CFuncExtracter();
Extracter->Extract(*Content, ParamInfo);
delete Extracter;
//引数情報の抜き出し
Extracter = new CArgExtracter();
Extracter->Extract(*Content, ParamInfo);
delete Extracter;
this->mParamInfoList->push_back(ParamInfo);
FileDataListIterator++;
}
}
VOID CStubMakerMain::CreateStub(String FileName,
list<AStubCreater *> *StubCreatorList)
{
list<AStubCreater *>::iterator it;
it = StubCreatorList->begin();
while (StubCreatorList->end() != it) {
AStubCreater *StubCreator = *it;
StubCreator->setBuffSize(this->mMacroSize);
StubCreator->Create(FileName, this->mParamInfoList);
it++;
}
}
VOID CStubMakerMain::CreateStub(String FileName)
{
CCSrcCreator SrcCreator;
CCHeaderCreator HeaderCreator;
list<AStubCreater *> StubCreatorList;
StubCreatorList.push_back((AStubCreater *)(&SrcCreator));
StubCreatorList.push_back((AStubCreater *)(&HeaderCreator));
this->CreateStub(FileName, &StubCreatorList);
}
VOID CStubMakerMain::RunOperation(VOID)
{
this->RunOperation(this->mFileName);
}
VOID CStubMakerMain::RunOperation(String FileName)
{
try {
this->Parse(FileName);
this->Extract();
this->CreateStub(FileName);
} catch (length_error &e) {
cout << "ファイル名が不正です。" << endl;
} catch (invalid_argument &e) {
cout << "データが不正です。" << endl;
}
}
|
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Hannes Hauswedell <hannes.hauswedell AT fu-berlin.de>
* \brief Provides seqan3::views::char_to.
*/
#pragma once
#include <seqan3/alphabet/concept.hpp>
#include <seqan3/core/type_traits/basic.hpp>
#include <seqan3/range/views/deep.hpp>
#include <seqan3/std/ranges>
namespace seqan3::views
{
/*!\name Alphabet related views
* \{
*/
/*!\brief A view over an alphabet, given a range of characters.
* \tparam urng_t The type of the range being processed. See below for requirements. [template parameter is
* omitted in pipe notation]
* \tparam alphabet_t The alphabet to convert to; must satisfy seqan3::alphabet.
* \param[in] urange The range being processed. [parameter is omitted in pipe notation]
* \returns A range of converted elements. See below for the properties of the returned range.
* \ingroup views
*
* \details
*
* \header_file{seqan3/range/views/char_to.hpp}
*
* ### View properties
*
* This view is a **deep view** Given a range-of-range as input (as opposed to just a range), it will apply
* the transformation on the innermost range (instead of the outermost range).
*
* | Concepts and traits | `urng_t` (underlying range type) | `rrng_t` (returned range type) |
* |----------------------------------|:-------------------------------------:|:--------------------------------------------------:|
* | std::ranges::input_range | *required* | *preserved* |
* | std::ranges::forward_range | | *preserved* |
* | std::ranges::bidirectional_range | | *preserved* |
* | std::ranges::random_access_range | | *preserved* |
* | std::ranges::contiguous_range | | *lost* |
* | | | |
* | std::ranges::viewable_range | *required* | *guaranteed* |
* | std::ranges::view | | *guaranteed* |
* | std::ranges::sized_range | | *preserved* |
* | std::ranges::common_range | | *preserved* |
* | std::ranges::output_range | | *lost* |
* | seqan3::const_iterable_range | | *preserved* |
* | | | |
* | std::ranges::range_reference_t | seqan3::alphabet_char_t<alphabet_t> | `alphabet_t` |
*
* See the \link views views submodule documentation \endlink for detailed descriptions of the view properties.
*
* ### Example
*
* \include test/snippet/range/views/char_to.cpp
* \hideinitializer
*/
template <alphabet alphabet_type>
inline auto const char_to = deep{std::views::transform([] (auto && in)
{
static_assert(std::common_reference_with<decltype(in), alphabet_char_t<alphabet_type>>,
"The innermost value type must have a common reference to underlying char type of alphabet_type.");
// call element-wise assign_char from the alphabet
return assign_char_to(in, alphabet_type{});
})};
//!\}
} // namespace seqan3::views
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2013 Chris Higgs
Copyright (C) 2015 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
//#include "ql_patterns_observable.hpp"
#ifndef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN
namespace QuantLib {
inline
void ObservableSettings::enableUpdates() {
updatesEnabled_ = true;
updatesDeferred_ = false;
// if there are outstanding deferred updates, do the notification
if (!deferredObservers_.empty()) {
bool successful = true;
std::string errMsg;
for (iterator i=deferredObservers_.begin();
i!=deferredObservers_.end(); ++i) {
try {
(*i)->update();
} catch (std::exception& e) {
successful = false;
errMsg = e.what();
} catch (...) {
successful = false;
}
}
deferredObservers_.clear();
QL_ENSURE(successful,
"could not notify one or more observers: {}" , errMsg);
}
}
inline
void Observable::notifyObservers() {
if (!settings_.updatesEnabled()) {
// if updates are only deferred, flag this for later notification
// these are held centrally by the settings singleton
settings_.registerDeferredObservers(observers_);
} else if (!observers_.empty()) {
bool successful = true;
std::string errMsg;
for (iterator i=observers_.begin(); i!=observers_.end(); ++i) {
try {
(*i)->update();
} catch (std::exception& e) {
// quite a dilemma. If we don't catch the exception,
// other observers will not receive the notification
// and might be left in an incorrect state. If we do
// catch it and continue the loop (as we do here) we
// lose the exception. The least evil might be to try
// and notify all observers, while raising an
// exception if something bad happened.
successful = false;
errMsg = e.what();
} catch (...) {
successful = false;
}
}
QL_ENSURE(successful,
"could not notify one or more observers: {}" , errMsg);
}
}
}
#else
#include <ql/functional.hpp>
#if defined(QL_USE_STD_FUNCTION)
#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/bind/bind.hpp>
#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))
#pragma GCC diagnostic pop
#endif
#endif
#include <boost/signals2/signal_type.hpp>
namespace QuantLib {
namespace detail {
class Signal {
public:
typedef boost::signals2::signal_type<
void(),
boost::signals2::keywords::mutex_type<boost::recursive_mutex> >
::type signal_type;
void connect(const signal_type::slot_type& slot) {
sig_.connect(slot);
}
template <class T>
void disconnect(const T& slot) {
sig_.disconnect(slot);
}
void operator()() const {
sig_();
}
private:
signal_type sig_;
};
}
void Observable::registerObserver(
const std::shared_ptr<Observer::Proxy>& observerProxy) {
{
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
observers_.insert(observerProxy);
}
detail::Signal::signal_type::slot_type slot(&Observer::Proxy::update,
observerProxy.get());
#if defined(QL_USE_STD_SHARED_PTR)
sig_->connect(slot.track_foreign(observerProxy));
#else
sig_->connect(slot.track(observerProxy));
#endif
}
void Observable::unregisterObserver(
const std::shared_ptr<Observer::Proxy>& observerProxy) {
{
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
observers_.erase(observerProxy);
}
if (settings_.updatesDeferred()) {
boost::lock_guard<boost::mutex> sLock(settings_.mutex_);
if (settings_.updatesDeferred()) {
settings_.unregisterDeferredObserver(observerProxy);
}
}
// signals2 needs boost::bind, std::bind does not work
sig_->disconnect(boost::bind(&Observer::Proxy::update,
observerProxy.get()));
}
void Observable::notifyObservers() {
if (settings_.updatesEnabled()) {
return (*sig_)();
}
boost::lock_guard<boost::mutex> sLock(settings_.mutex_);
if (settings_.updatesEnabled()) {
return (*sig_)();
}
else if (settings_.updatesDeferred()) {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
// if updates are only deferred, flag this for later notification
// these are held centrally by the settings singleton
settings_.registerDeferredObservers(observers_);
}
}
Observable::Observable()
: sig_(new detail::Signal()),
settings_(ObservableSettings::instance()) { }
Observable::Observable(const Observable&)
: sig_(new detail::Signal()),
settings_(ObservableSettings::instance()) {
// the observer set is not copied; no observer asked to
// register with this object
}
}
#endif
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "arith_uint256.h"
#include "uint256.h"
#include "version.h"
#include "test/test_konjungate.h"
#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <string>
#include <stdio.h>
BOOST_FIXTURE_TEST_SUITE(uint256_tests, BasicTestingSetup)
const unsigned char R1Array[] =
"\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2"
"\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d";
const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c";
const uint256 R1L = uint256(std::vector<unsigned char>(R1Array,R1Array+32));
const uint160 R1S = uint160(std::vector<unsigned char>(R1Array,R1Array+20));
const unsigned char R2Array[] =
"\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf"
"\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7";
const uint256 R2L = uint256(std::vector<unsigned char>(R2Array,R2Array+32));
const uint160 R2S = uint160(std::vector<unsigned char>(R2Array,R2Array+20));
const unsigned char ZeroArray[] =
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const uint256 ZeroL = uint256(std::vector<unsigned char>(ZeroArray,ZeroArray+32));
const uint160 ZeroS = uint160(std::vector<unsigned char>(ZeroArray,ZeroArray+20));
const unsigned char OneArray[] =
"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const uint256 OneL = uint256(std::vector<unsigned char>(OneArray,OneArray+32));
const uint160 OneS = uint160(std::vector<unsigned char>(OneArray,OneArray+20));
const unsigned char MaxArray[] =
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";
const uint256 MaxL = uint256(std::vector<unsigned char>(MaxArray,MaxArray+32));
const uint160 MaxS = uint160(std::vector<unsigned char>(MaxArray,MaxArray+20));
std::string ArrayToString(const unsigned char A[], unsigned int width)
{
std::stringstream Stream;
Stream << std::hex;
for (unsigned int i = 0; i < width; ++i)
{
Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1];
}
return Stream.str();
}
inline uint160 uint160S(const char *str)
{
uint160 rv;
rv.SetHex(str);
return rv;
}
inline uint160 uint160S(const std::string& str)
{
uint160 rv;
rv.SetHex(str);
return rv;
}
BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality
{
BOOST_CHECK(1 == 0+1);
// constructor uint256(vector<char>):
BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32));
BOOST_CHECK(R1S.ToString() == ArrayToString(R1Array,20));
BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32));
BOOST_CHECK(R2S.ToString() == ArrayToString(R2Array,20));
BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32));
BOOST_CHECK(ZeroS.ToString() == ArrayToString(ZeroArray,20));
BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32));
BOOST_CHECK(OneS.ToString() == ArrayToString(OneArray,20));
BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32));
BOOST_CHECK(MaxS.ToString() == ArrayToString(MaxArray,20));
BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32));
BOOST_CHECK(OneS.ToString() != ArrayToString(ZeroArray,20));
// == and !=
BOOST_CHECK(R1L != R2L && R1S != R2S);
BOOST_CHECK(ZeroL != OneL && ZeroS != OneS);
BOOST_CHECK(OneL != ZeroL && OneS != ZeroS);
BOOST_CHECK(MaxL != ZeroL && MaxS != ZeroS);
// String Constructor and Copy Constructor
BOOST_CHECK(uint256S("0x"+R1L.ToString()) == R1L);
BOOST_CHECK(uint256S("0x"+R2L.ToString()) == R2L);
BOOST_CHECK(uint256S("0x"+ZeroL.ToString()) == ZeroL);
BOOST_CHECK(uint256S("0x"+OneL.ToString()) == OneL);
BOOST_CHECK(uint256S("0x"+MaxL.ToString()) == MaxL);
BOOST_CHECK(uint256S(R1L.ToString()) == R1L);
BOOST_CHECK(uint256S(" 0x"+R1L.ToString()+" ") == R1L);
BOOST_CHECK(uint256S("") == ZeroL);
BOOST_CHECK(R1L == uint256S(R1ArrayHex));
BOOST_CHECK(uint256(R1L) == R1L);
BOOST_CHECK(uint256(ZeroL) == ZeroL);
BOOST_CHECK(uint256(OneL) == OneL);
BOOST_CHECK(uint160S("0x"+R1S.ToString()) == R1S);
BOOST_CHECK(uint160S("0x"+R2S.ToString()) == R2S);
BOOST_CHECK(uint160S("0x"+ZeroS.ToString()) == ZeroS);
BOOST_CHECK(uint160S("0x"+OneS.ToString()) == OneS);
BOOST_CHECK(uint160S("0x"+MaxS.ToString()) == MaxS);
BOOST_CHECK(uint160S(R1S.ToString()) == R1S);
BOOST_CHECK(uint160S(" 0x"+R1S.ToString()+" ") == R1S);
BOOST_CHECK(uint160S("") == ZeroS);
BOOST_CHECK(R1S == uint160S(R1ArrayHex));
BOOST_CHECK(uint160(R1S) == R1S);
BOOST_CHECK(uint160(ZeroS) == ZeroS);
BOOST_CHECK(uint160(OneS) == OneS);
}
BOOST_AUTO_TEST_CASE( comparison ) // <= >= < >
{
uint256 LastL;
for (int i = 255; i >= 0; --i) {
uint256 TmpL;
*(TmpL.begin() + (i>>3)) |= 1<<(7-(i&7));
BOOST_CHECK( LastL < TmpL );
LastL = TmpL;
}
BOOST_CHECK( ZeroL < R1L );
BOOST_CHECK( R2L < R1L );
BOOST_CHECK( ZeroL < OneL );
BOOST_CHECK( OneL < MaxL );
BOOST_CHECK( R1L < MaxL );
BOOST_CHECK( R2L < MaxL );
uint160 LastS;
for (int i = 159; i >= 0; --i) {
uint160 TmpS;
*(TmpS.begin() + (i>>3)) |= 1<<(7-(i&7));
BOOST_CHECK( LastS < TmpS );
LastS = TmpS;
}
BOOST_CHECK( ZeroS < R1S );
BOOST_CHECK( R2S < R1S );
BOOST_CHECK( ZeroS < OneS );
BOOST_CHECK( OneS < MaxS );
BOOST_CHECK( R1S < MaxS );
BOOST_CHECK( R2S < MaxS );
}
BOOST_AUTO_TEST_CASE( methods ) // GetHex SetHex begin() end() size() GetLow64 GetSerializeSize, Serialize, Unserialize
{
BOOST_CHECK(R1L.GetHex() == R1L.ToString());
BOOST_CHECK(R2L.GetHex() == R2L.ToString());
BOOST_CHECK(OneL.GetHex() == OneL.ToString());
BOOST_CHECK(MaxL.GetHex() == MaxL.ToString());
uint256 TmpL(R1L);
BOOST_CHECK(TmpL == R1L);
TmpL.SetHex(R2L.ToString()); BOOST_CHECK(TmpL == R2L);
TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == uint256());
TmpL.SetHex(R1L.ToString());
BOOST_CHECK(memcmp(R1L.begin(), R1Array, 32)==0);
BOOST_CHECK(memcmp(TmpL.begin(), R1Array, 32)==0);
BOOST_CHECK(memcmp(R2L.begin(), R2Array, 32)==0);
BOOST_CHECK(memcmp(ZeroL.begin(), ZeroArray, 32)==0);
BOOST_CHECK(memcmp(OneL.begin(), OneArray, 32)==0);
BOOST_CHECK(R1L.size() == sizeof(R1L));
BOOST_CHECK(sizeof(R1L) == 32);
BOOST_CHECK(R1L.size() == 32);
BOOST_CHECK(R2L.size() == 32);
BOOST_CHECK(ZeroL.size() == 32);
BOOST_CHECK(MaxL.size() == 32);
BOOST_CHECK(R1L.begin() + 32 == R1L.end());
BOOST_CHECK(R2L.begin() + 32 == R2L.end());
BOOST_CHECK(OneL.begin() + 32 == OneL.end());
BOOST_CHECK(MaxL.begin() + 32 == MaxL.end());
BOOST_CHECK(TmpL.begin() + 32 == TmpL.end());
BOOST_CHECK(R1L.GetSerializeSize(0,PROTOCOL_VERSION) == 32);
BOOST_CHECK(ZeroL.GetSerializeSize(0,PROTOCOL_VERSION) == 32);
std::stringstream ss;
R1L.Serialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+32));
TmpL.Unserialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(R1L == TmpL);
ss.str("");
ZeroL.Serialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+32));
TmpL.Unserialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ZeroL == TmpL);
ss.str("");
MaxL.Serialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+32));
TmpL.Unserialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(MaxL == TmpL);
ss.str("");
BOOST_CHECK(R1S.GetHex() == R1S.ToString());
BOOST_CHECK(R2S.GetHex() == R2S.ToString());
BOOST_CHECK(OneS.GetHex() == OneS.ToString());
BOOST_CHECK(MaxS.GetHex() == MaxS.ToString());
uint160 TmpS(R1S);
BOOST_CHECK(TmpS == R1S);
TmpS.SetHex(R2S.ToString()); BOOST_CHECK(TmpS == R2S);
TmpS.SetHex(ZeroS.ToString()); BOOST_CHECK(TmpS == uint160());
TmpS.SetHex(R1S.ToString());
BOOST_CHECK(memcmp(R1S.begin(), R1Array, 20)==0);
BOOST_CHECK(memcmp(TmpS.begin(), R1Array, 20)==0);
BOOST_CHECK(memcmp(R2S.begin(), R2Array, 20)==0);
BOOST_CHECK(memcmp(ZeroS.begin(), ZeroArray, 20)==0);
BOOST_CHECK(memcmp(OneS.begin(), OneArray, 20)==0);
BOOST_CHECK(R1S.size() == sizeof(R1S));
BOOST_CHECK(sizeof(R1S) == 20);
BOOST_CHECK(R1S.size() == 20);
BOOST_CHECK(R2S.size() == 20);
BOOST_CHECK(ZeroS.size() == 20);
BOOST_CHECK(MaxS.size() == 20);
BOOST_CHECK(R1S.begin() + 20 == R1S.end());
BOOST_CHECK(R2S.begin() + 20 == R2S.end());
BOOST_CHECK(OneS.begin() + 20 == OneS.end());
BOOST_CHECK(MaxS.begin() + 20 == MaxS.end());
BOOST_CHECK(TmpS.begin() + 20 == TmpS.end());
BOOST_CHECK(R1S.GetSerializeSize(0,PROTOCOL_VERSION) == 20);
BOOST_CHECK(ZeroS.GetSerializeSize(0,PROTOCOL_VERSION) == 20);
R1S.Serialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+20));
TmpS.Unserialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(R1S == TmpS);
ss.str("");
ZeroS.Serialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+20));
TmpS.Unserialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ZeroS == TmpS);
ss.str("");
MaxS.Serialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+20));
TmpS.Unserialize(ss,0,PROTOCOL_VERSION);
BOOST_CHECK(MaxS == TmpS);
ss.str("");
}
BOOST_AUTO_TEST_CASE( conversion )
{
BOOST_CHECK(ArithToUint256(UintToArith256(ZeroL)) == ZeroL);
BOOST_CHECK(ArithToUint256(UintToArith256(OneL)) == OneL);
BOOST_CHECK(ArithToUint256(UintToArith256(R1L)) == R1L);
BOOST_CHECK(ArithToUint256(UintToArith256(R2L)) == R2L);
BOOST_CHECK(UintToArith256(ZeroL) == 0);
BOOST_CHECK(UintToArith256(OneL) == 1);
BOOST_CHECK(ArithToUint256(0) == ZeroL);
BOOST_CHECK(ArithToUint256(1) == OneL);
BOOST_CHECK(arith_uint256(R1L.GetHex()) == UintToArith256(R1L));
BOOST_CHECK(arith_uint256(R2L.GetHex()) == UintToArith256(R2L));
BOOST_CHECK(R1L.GetHex() == UintToArith256(R1L).GetHex());
BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex());
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webcodecs/video_decoder_broker.h"
#include <memory>
#include <string>
#include "base/memory/weak_ptr.h"
#include "build/buildflag.h"
#include "media/base/decoder_factory.h"
#include "media/base/media_util.h"
#include "media/base/status_codes.h"
#include "media/base/video_decoder_config.h"
#include "media/mojo/buildflags.h"
#include "media/mojo/clients/mojo_decoder_factory.h"
#include "media/mojo/mojom/interface_factory.mojom.h"
#include "media/renderers/default_decoder_factory.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/modules/webcodecs/decoder_selector.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "ui/gfx/color_space.h"
using DecoderDetails = blink::VideoDecoderBroker::DecoderDetails;
namespace WTF {
template <>
struct CrossThreadCopier<media::VideoDecoderConfig>
: public CrossThreadCopierPassThrough<media::VideoDecoderConfig> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<media::Status>
: public CrossThreadCopierPassThrough<media::Status> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<base::Optional<DecoderDetails>>
: public CrossThreadCopierPassThrough<base::Optional<DecoderDetails>> {
STATIC_ONLY(CrossThreadCopier);
};
} // namespace WTF
namespace blink {
// Wrapper class for state and API calls that must be made from the
// |media_task_runner_|. Construction must happen on blink main thread to safely
// make use of ExecutionContext and Document. These GC blink types must not be
// stored/referenced by any other method.
class MediaVideoTaskWrapper {
public:
using CrossThreadOnceInitCB =
WTF::CrossThreadOnceFunction<void(media::Status status,
base::Optional<DecoderDetails>)>;
using CrossThreadOnceDecodeCB =
WTF::CrossThreadOnceFunction<void(media::DecodeStatus)>;
using CrossThreadOnceResetCB = WTF::CrossThreadOnceClosure;
MediaVideoTaskWrapper(
base::WeakPtr<CrossThreadVideoDecoderClient> weak_client,
ExecutionContext& execution_context,
media::GpuVideoAcceleratorFactories* gpu_factories,
scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner)
: weak_client_(std::move(weak_client)),
media_task_runner_(std::move(media_task_runner)),
main_task_runner_(std::move(main_task_runner)),
gpu_factories_(gpu_factories) {
DVLOG(2) << __func__;
DETACH_FROM_SEQUENCE(sequence_checker_);
// TODO(chcunningham): Enable this for workers. Currently only a
// frame-binding (RenderFrameHostImpl) is exposed.
// TODO(chcunningham): set_disconnect_handler?
// Mojo connection setup must occur here on the main thread where its safe
// to use |execution_context| APIs.
mojo::PendingRemote<media::mojom::InterfaceFactory> media_interface_factory;
execution_context.GetBrowserInterfaceBroker().GetInterface(
media_interface_factory.InitWithNewPipeAndPassReceiver());
// Mojo remote must be bound on media thread where it will be used.
//|Unretained| is safe because |this| must be destroyed on the media task
// runner.
PostCrossThreadTask(
*media_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(&MediaVideoTaskWrapper::BindOnTaskRunner,
WTF::CrossThreadUnretained(this),
std::move(media_interface_factory)));
// TODO(chcunningham): Research usage of this and consider how to unify for
// worker context (no document). What follows is borrowed from
// HTMLMediaElement.
Document* document = To<LocalDOMWindow>(execution_context).document();
if (document && document->GetFrame()) {
LocalFrame* frame = document->GetFrame();
target_color_space_ =
frame->GetPage()->GetChromeClient().GetScreenInfo(*frame).color_space;
}
}
virtual ~MediaVideoTaskWrapper() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
MediaVideoTaskWrapper(const MediaVideoTaskWrapper&) = delete;
MediaVideoTaskWrapper& operator=(const MediaVideoTaskWrapper&) = delete;
void Initialize(const media::VideoDecoderConfig& config,
CrossThreadOnceInitCB init_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
selector_ = std::make_unique<WebCodecsVideoDecoderSelector>(
media_task_runner_,
WTF::BindRepeating(&MediaVideoTaskWrapper::OnCreateDecoders,
WTF::Unretained(this)),
WTF::BindRepeating(&MediaVideoTaskWrapper::OnDecodeOutput,
WTF::Unretained(this)));
selector_->SelectDecoder(
config, WTF::Bind(&MediaVideoTaskWrapper::OnDecoderSelected,
WTF::Unretained(this), std::move(init_cb)));
}
void Decode(scoped_refptr<media::DecoderBuffer> buffer,
CrossThreadOnceDecodeCB decode_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!decoder_) {
std::move(decode_cb).Run(media::DecodeStatus::DECODE_ERROR);
return;
}
decoder_->Decode(std::move(buffer),
WTF::Bind(&MediaVideoTaskWrapper::OnDecodeDone,
WTF::Unretained(this), std::move(decode_cb)));
}
void Reset(CrossThreadOnceResetCB reset_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!decoder_) {
std::move(reset_cb).Run();
return;
}
decoder_->Reset(WTF::Bind(&MediaVideoTaskWrapper::OnReset,
WTF::Unretained(this), std::move(reset_cb)));
}
private:
void BindOnTaskRunner(
mojo::PendingRemote<media::mojom::InterfaceFactory> interface_factory) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
media_interface_factory_.Bind(std::move(interface_factory));
// Bind the |interface_factory_| above before passing to
// |external_decoder_factory|.
std::unique_ptr<media::DecoderFactory> external_decoder_factory;
#if BUILDFLAG(ENABLE_MOJO_VIDEO_DECODER)
external_decoder_factory = std::make_unique<media::MojoDecoderFactory>(
media_interface_factory_.get());
#endif
decoder_factory_ = std::make_unique<media::DefaultDecoderFactory>(
std::move(external_decoder_factory));
}
std::vector<std::unique_ptr<media::VideoDecoder>> OnCreateDecoders() {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// TODO(chcunningham): Add plumbing to enable overlays on Android. See
// handling in WebMediaPlayerImpl.
media::RequestOverlayInfoCB request_overlay_info_cb;
std::vector<std::unique_ptr<media::VideoDecoder>> video_decoders;
decoder_factory_->CreateVideoDecoders(
media_task_runner_, gpu_factories_, &null_media_log_,
request_overlay_info_cb, target_color_space_, &video_decoders);
return video_decoders;
}
void OnDecoderSelected(CrossThreadOnceInitCB init_cb,
std::unique_ptr<media::VideoDecoder> decoder) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We're done with it.
DCHECK(selector_);
selector_.reset();
decoder_ = std::move(decoder);
media::Status status(media::StatusCode::kDecoderUnsupportedConfig);
base::Optional<DecoderDetails> decoder_details;
if (decoder_) {
status = media::OkStatus();
decoder_details = DecoderDetails({decoder_->GetDisplayName(),
decoder_->IsPlatformDecoder(),
decoder_->NeedsBitstreamConversion(),
decoder_->GetMaxDecodeRequests()});
}
// Fire |init_cb|.
PostCrossThreadTask(
*main_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(std::move(init_cb), status, decoder_details));
}
void OnDecodeOutput(scoped_refptr<media::VideoFrame> frame) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
PostCrossThreadTask(
*main_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(&CrossThreadVideoDecoderClient::OnDecodeOutput,
weak_client_, std::move(frame),
decoder_->CanReadWithoutStalling()));
}
void OnDecodeDone(CrossThreadOnceDecodeCB decode_cb,
media::DecodeStatus status) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
PostCrossThreadTask(*main_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(std::move(decode_cb), status));
}
void OnReset(CrossThreadOnceResetCB reset_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
PostCrossThreadTask(*main_task_runner_, FROM_HERE, std::move(reset_cb));
}
base::WeakPtr<CrossThreadVideoDecoderClient> weak_client_;
scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
media::GpuVideoAcceleratorFactories* gpu_factories_;
mojo::Remote<media::mojom::InterfaceFactory> media_interface_factory_;
std::unique_ptr<WebCodecsVideoDecoderSelector> selector_;
std::unique_ptr<media::DefaultDecoderFactory> decoder_factory_;
std::unique_ptr<media::VideoDecoder> decoder_;
gfx::ColorSpace target_color_space_;
// TODO(chcunningham): Route MEDIA_LOG for WebCodecs.
media::NullMediaLog null_media_log_;
SEQUENCE_CHECKER(sequence_checker_);
};
constexpr char VideoDecoderBroker::kDefaultDisplayName[];
VideoDecoderBroker::VideoDecoderBroker(
ExecutionContext& execution_context,
media::GpuVideoAcceleratorFactories* gpu_factories)
: media_task_runner_(
gpu_factories
? gpu_factories->GetTaskRunner()
// TODO(chcunningham): Consider adding a new single thread task
// runner just for WebCodecs. This is still using the main thread,
// albeit at a lower priority than things like user gestures.
// http://crbug.com/1095786
// TODO(chcunningham): Should this be kInternalMediaRealTime? Why
// does WebAudio use that task type?
: execution_context.GetTaskRunner(TaskType::kInternalMedia)) {
DVLOG(2) << __func__;
media_tasks_ = std::make_unique<MediaVideoTaskWrapper>(
weak_factory_.GetWeakPtr(), execution_context, gpu_factories,
media_task_runner_,
execution_context.GetTaskRunner(TaskType::kInternalMedia));
}
VideoDecoderBroker::~VideoDecoderBroker() {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
media_task_runner_->DeleteSoon(FROM_HERE, std::move(media_tasks_));
}
std::string VideoDecoderBroker::GetDisplayName() const {
return decoder_details_ ? decoder_details_->display_name
: VideoDecoderBroker::kDefaultDisplayName;
}
bool VideoDecoderBroker::IsPlatformDecoder() const {
return decoder_details_ ? decoder_details_->is_platform_decoder : false;
}
void VideoDecoderBroker::Initialize(const media::VideoDecoderConfig& config,
bool low_delay,
media::CdmContext* cdm_context,
InitCB init_cb,
const OutputCB& output_cb,
const media::WaitingCB& waiting_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The following are not currently supported in WebCodecs.
// TODO(chcunningham): Should |low_delay| be supported? Should it be
// hard-coded to true?
DCHECK(!low_delay);
DCHECK(!cdm_context);
DCHECK(!waiting_cb);
output_cb_ = output_cb;
// Clear details from previously initialized decoder. New values will arrive
// via OnInitialize().
decoder_details_.reset();
MediaVideoTaskWrapper::CrossThreadOnceInitCB main_loop_init_cb(
WTF::Bind(&VideoDecoderBroker::OnInitialize, weak_factory_.GetWeakPtr(),
std::move(init_cb)));
PostCrossThreadTask(
*media_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(&MediaVideoTaskWrapper::Initialize,
WTF::CrossThreadUnretained(media_tasks_.get()),
config, std::move(main_loop_init_cb)));
}
void VideoDecoderBroker::OnInitialize(InitCB init_cb,
media::Status status,
base::Optional<DecoderDetails> details) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
decoder_details_ = details;
std::move(init_cb).Run(status);
}
void VideoDecoderBroker::Decode(scoped_refptr<media::DecoderBuffer> buffer,
DecodeCB decode_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
MediaVideoTaskWrapper::CrossThreadOnceDecodeCB main_loop_cb(
WTF::Bind(&VideoDecoderBroker::OnDecodeDone, weak_factory_.GetWeakPtr(),
std::move(decode_cb)));
PostCrossThreadTask(
*media_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(&MediaVideoTaskWrapper::Decode,
WTF::CrossThreadUnretained(media_tasks_.get()),
buffer, std::move(main_loop_cb)));
}
void VideoDecoderBroker::OnDecodeDone(DecodeCB decode_cb,
media::DecodeStatus status) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
std::move(decode_cb).Run(status);
}
void VideoDecoderBroker::Reset(base::OnceClosure reset_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
MediaVideoTaskWrapper::CrossThreadOnceResetCB main_loop_cb(
WTF::Bind(&VideoDecoderBroker::OnReset, weak_factory_.GetWeakPtr(),
std::move(reset_cb)));
PostCrossThreadTask(
*media_task_runner_, FROM_HERE,
WTF::CrossThreadBindOnce(&MediaVideoTaskWrapper::Reset,
WTF::CrossThreadUnretained(media_tasks_.get()),
std::move(main_loop_cb)));
}
bool VideoDecoderBroker::NeedsBitstreamConversion() const {
return decoder_details_ ? decoder_details_->needs_bitstream_conversion
: false;
}
bool VideoDecoderBroker::CanReadWithoutStalling() const {
return can_read_without_stalling_;
}
int VideoDecoderBroker::GetMaxDecodeRequests() const {
return decoder_details_ ? decoder_details_->max_decode_requests : 1;
}
void VideoDecoderBroker::OnReset(base::OnceClosure reset_cb) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
std::move(reset_cb).Run();
}
void VideoDecoderBroker::OnDecodeOutput(scoped_refptr<media::VideoFrame> frame,
bool can_read_without_stalling) {
DVLOG(2) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(output_cb_);
can_read_without_stalling_ = can_read_without_stalling;
output_cb_.Run(std::move(frame));
}
} // namespace blink
|
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/utilities/heap_allocator.h"
#include "test.h"
#include "gtest/gtest.h"
#include <iostream>
#include <random>
using namespace NEO;
const size_t sizeThreshold = 16 * 4096;
const size_t allocationAlignment = MemoryConstants::pageSize;
class HeapAllocatorUnderTest : public HeapAllocator {
public:
HeapAllocatorUnderTest(uint64_t address, uint64_t size, size_t alignment, size_t threshold) : HeapAllocator(address, size, alignment, threshold) {}
HeapAllocatorUnderTest(uint64_t address, uint64_t size, size_t alignment) : HeapAllocator(address, size, alignment) {}
HeapAllocatorUnderTest(uint64_t address, uint64_t size) : HeapAllocator(address, size) {}
uint64_t getLeftBound() const { return this->pLeftBound; }
uint64_t getRightBound() const { return this->pRightBound; }
uint64_t getavailableSize() const { return this->availableSize; }
size_t getThresholdSize() const { return this->sizeThreshold; }
using HeapAllocator::defragment;
uint64_t getFromFreedChunks(size_t size, std::vector<HeapChunk> &vec, size_t requiredAlignment) {
size_t sizeOfFreedChunk;
return HeapAllocator::getFromFreedChunks(size, vec, sizeOfFreedChunk, requiredAlignment);
}
void storeInFreedChunks(uint64_t ptr, size_t size, std::vector<HeapChunk> &vec) { return HeapAllocator::storeInFreedChunks(ptr, size, vec); }
std::vector<HeapChunk> &getFreedChunksSmall() { return this->freedChunksSmall; };
std::vector<HeapChunk> &getFreedChunksBig() { return this->freedChunksBig; };
using HeapAllocator::allocationAlignment;
};
TEST(HeapAllocatorTest, WhenHeapAllocatorIsCreatedWithAlignmentThenAlignmentIsSet) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment);
EXPECT_EQ(MemoryConstants::pageSize, heapAllocator->allocationAlignment);
}
TEST(HeapAllocatorTest, WhenHeapAllocatorIsCreatedThenThresholdAndAlignmentIsSet) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size);
EXPECT_NE(0u, heapAllocator->getThresholdSize());
EXPECT_EQ(MemoryConstants::pageSize, heapAllocator->allocationAlignment);
}
TEST(HeapAllocatorTest, WhenAllocatingThenUsageStatisticsAreUpdated) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size);
EXPECT_EQ(heapAllocator->getavailableSize(), heapAllocator->getLeftSize());
EXPECT_EQ(0u, heapAllocator->getUsedSize());
EXPECT_EQ((double)0.0, heapAllocator->getUsage());
size_t ptrSize = 4096;
auto ptr = heapAllocator->allocate(ptrSize);
EXPECT_EQ(4096u, heapAllocator->getUsedSize());
EXPECT_LT((double)0.0, heapAllocator->getUsage());
heapAllocator->free(ptr, ptrSize);
}
TEST(HeapAllocatorTest, GivenExactSizeChunkInFreedChunksWhenGetIsCalledThenChunkIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
uint64_t ptrFreed = 0x101000llu;
size_t sizeFreed = MemoryConstants::pageSize * 2;
freedChunks.emplace_back(ptrFreed, sizeFreed);
auto ptrReturned = heapAllocator->getFromFreedChunks(sizeFreed, freedChunks, allocationAlignment);
EXPECT_EQ(ptrFreed, ptrReturned); // ptr returned is the one that was stored
EXPECT_EQ(0u, freedChunks.size()); // entry in freed container is removed
}
TEST(HeapAllocatorTest, GivenOnlySmallerSizeChunksInFreedChunksWhenGetIsCalledThenNullptrIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
freedChunks.emplace_back(0x100000llu, 4096);
freedChunks.emplace_back(0x101000llu, 4096);
freedChunks.emplace_back(0x105000llu, 4096);
freedChunks.emplace_back(0x104000llu, 4096);
freedChunks.emplace_back(0x102000llu, 8192);
freedChunks.emplace_back(0x109000llu, 8192);
freedChunks.emplace_back(0x107000llu, 4096);
EXPECT_EQ(7u, freedChunks.size());
auto ptrReturned = heapAllocator->getFromFreedChunks(4 * 4096, freedChunks, allocationAlignment);
EXPECT_EQ(0llu, ptrReturned);
EXPECT_EQ(7u, freedChunks.size());
}
TEST(HeapAllocatorTest, GivenOnlyBiggerSizeChunksInFreedChunksWhenGetIsCalledThenBestFitChunkIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto pUpperBound = ptrBase + size;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
uint64_t ptrExpected = 0llu;
pUpperBound -= 4096;
freedChunks.emplace_back(pUpperBound, 4096);
pUpperBound -= 5 * 4096;
freedChunks.emplace_back(pUpperBound, 5 * 4096);
pUpperBound -= 4 * 4096;
freedChunks.emplace_back(pUpperBound, 4 * 4096);
ptrExpected = pUpperBound;
pUpperBound -= 5 * 4096;
freedChunks.emplace_back(pUpperBound, 5 * 4096);
pUpperBound -= 4 * 4096;
freedChunks.emplace_back(pUpperBound, 4 * 4096);
EXPECT_EQ(5u, freedChunks.size());
auto ptrReturned = heapAllocator->getFromFreedChunks(3 * 4096, freedChunks, allocationAlignment);
EXPECT_EQ(ptrExpected, ptrReturned);
EXPECT_EQ(4u, freedChunks.size());
}
TEST(HeapAllocatorTest, GivenOnlyMoreThanTwiceBiggerSizeChunksInFreedChunksWhenGetIsCalledThenSplittedChunkIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto pLowerBound = ptrBase;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
uint64_t ptrExpected = 0llu;
size_t requestedSize = 3 * 4096;
freedChunks.emplace_back(pLowerBound, 4096);
pLowerBound += 4096;
freedChunks.emplace_back(pLowerBound, 9 * 4096);
pLowerBound += 9 * 4096;
freedChunks.emplace_back(pLowerBound, 7 * 4096);
size_t deltaSize = 7 * 4096 - requestedSize;
ptrExpected = pLowerBound + deltaSize;
EXPECT_EQ(3u, freedChunks.size());
auto ptrReturned = heapAllocator->getFromFreedChunks(requestedSize, freedChunks, allocationAlignment);
EXPECT_EQ(ptrExpected, ptrReturned);
EXPECT_EQ(3u, freedChunks.size());
EXPECT_EQ(pLowerBound, freedChunks[2].ptr);
EXPECT_EQ(deltaSize, freedChunks[2].size);
}
TEST(HeapAllocatorTest, GivenStoredChunkAdjacentToLeftBoundaryOfIncomingChunkWhenStoreIsCalledThenChunkIsMerged) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto pLowerBound = ptrBase;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
uint64_t ptrExpected = 0llu;
size_t expectedSize = 9 * 4096;
freedChunks.emplace_back(pLowerBound, 4096);
pLowerBound += 4096;
freedChunks.emplace_back(pLowerBound, 9 * 4096);
ptrExpected = pLowerBound;
pLowerBound += 9 * 4096;
EXPECT_EQ(ptrExpected, freedChunks[1].ptr);
EXPECT_EQ(expectedSize, freedChunks[1].size);
EXPECT_EQ(2u, freedChunks.size());
auto ptrToStore = pLowerBound;
size_t sizeToStore = 2 * 4096;
expectedSize += sizeToStore;
heapAllocator->storeInFreedChunks(ptrToStore, sizeToStore, freedChunks);
EXPECT_EQ(2u, freedChunks.size());
EXPECT_EQ(ptrExpected, freedChunks[1].ptr);
EXPECT_EQ(expectedSize, freedChunks[1].size);
}
TEST(HeapAllocatorTest, GivenStoredChunkAdjacentToRightBoundaryOfIncomingChunkWhenStoreIsCalledThenChunkIsMerged) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto pLowerBound = ptrBase;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
uint64_t ptrExpected = 0llu;
size_t expectedSize = 9 * 4096;
freedChunks.emplace_back(pLowerBound, 4096);
pLowerBound += 4096;
pLowerBound += 4096; // space between stored chunk and chunk to store
auto ptrToStore = pLowerBound;
size_t sizeToStore = 2 * 4096;
pLowerBound += sizeToStore;
freedChunks.emplace_back(pLowerBound, 9 * 4096);
ptrExpected = pLowerBound;
EXPECT_EQ(ptrExpected, freedChunks[1].ptr);
EXPECT_EQ(expectedSize, freedChunks[1].size);
EXPECT_EQ(2u, freedChunks.size());
expectedSize += sizeToStore;
ptrExpected = ptrToStore;
heapAllocator->storeInFreedChunks(ptrToStore, sizeToStore, freedChunks);
EXPECT_EQ(2u, freedChunks.size());
EXPECT_EQ(ptrExpected, freedChunks[1].ptr);
EXPECT_EQ(expectedSize, freedChunks[1].size);
}
TEST(HeapAllocatorTest, GivenStoredChunkNotAdjacentToIncomingChunkWhenStoreIsCalledThenNewFreeChunkIsCreated) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto pLowerBound = ptrBase;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
freedChunks.emplace_back(pLowerBound, 4096);
pLowerBound += 4096;
freedChunks.emplace_back(pLowerBound, 9 * 4096);
pLowerBound += 9 * 4096;
pLowerBound += 9 * 4096;
uint64_t ptrToStore = pLowerBound;
size_t sizeToStore = 4096;
EXPECT_EQ(2u, freedChunks.size());
heapAllocator->storeInFreedChunks(ptrToStore, sizeToStore, freedChunks);
EXPECT_EQ(3u, freedChunks.size());
EXPECT_EQ(ptrToStore, freedChunks[2].ptr);
EXPECT_EQ(sizeToStore, freedChunks[2].size);
}
TEST(HeapAllocatorTest, GivenStoredChunkExpandableByIncomingChunkWhenStoreIsCalledThenChunksAreMerged) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
std::vector<HeapChunk> freedChunks;
freedChunks.emplace_back(0x100000llu, 4096);
freedChunks.emplace_back(0x103000llu, 4096);
EXPECT_EQ(2u, freedChunks.size());
uint64_t ptrToStore = 0x102000llu;
size_t sizeToStore = 2 * 4096;
heapAllocator->storeInFreedChunks(ptrToStore, sizeToStore, freedChunks);
EXPECT_EQ(2u, freedChunks.size());
auto ptrReturned = heapAllocator->getFromFreedChunks(2 * 4096, freedChunks, allocationAlignment);
EXPECT_EQ(0x102000llu, ptrReturned);
EXPECT_EQ(1u, freedChunks.size());
}
TEST(HeapAllocatorTest, WhenAllocatingThenEntryIsAddedToMap) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
size_t ptrSize = 4096;
uint64_t ptr = heapAllocator->allocate(ptrSize);
EXPECT_NE(0llu, ptr);
EXPECT_LE(ptrBase, ptr);
size_t ptrSize2 = sizeThreshold + 4096;
ptr = heapAllocator->allocate(ptrSize2);
EXPECT_NE(0llu, ptr);
EXPECT_LE(ptrBase, ptr);
}
TEST(HeapAllocatorTest, WhenFreeingThenEntryIsRemovedFromMapAndSpaceMadeAvailable) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024u * 4096u;
auto pLeftBound = ptrBase;
auto pRightBound = pLeftBound + size;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
size_t ptrSize = 4096;
uint64_t ptr = heapAllocator->allocate(ptrSize);
EXPECT_NE(0llu, ptr);
EXPECT_LE(ptrBase, ptr);
size_t ptrSize2 = sizeThreshold + 4096;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_EQ(heapAllocator->getLeftBound(), pLeftBound + sizeThreshold + 4096u);
EXPECT_EQ(heapAllocator->getRightBound(), pRightBound - 4096u);
EXPECT_EQ(heapAllocator->getavailableSize(), size - (sizeThreshold + 4096u) - 4096u);
heapAllocator->free(ptr, ptrSize);
heapAllocator->free(ptr2, ptrSize2);
EXPECT_EQ(heapAllocator->getavailableSize(), size);
EXPECT_EQ(heapAllocator->getLeftBound(), pLeftBound);
EXPECT_EQ(heapAllocator->getRightBound(), pRightBound);
}
TEST(HeapAllocatorTest, WhenAllocatingMultipleThenEachAllocationIsDistinct) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
size_t allocSize = 4096;
size_t doubleAllocSize = 4096 * 2;
for (uint32_t i = 0u; i < 2u; i++) {
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
doubleAllocSize = allocSize * 2;
auto pLeftBound = ptrBase;
auto pRightBound = pLeftBound + size;
uint64_t ptr1 = heapAllocator->allocate(allocSize);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
uint64_t ptr2 = heapAllocator->allocate(allocSize);
EXPECT_NE(0llu, ptr2);
uint64_t ptr3 = heapAllocator->allocate(doubleAllocSize);
EXPECT_NE(0llu, ptr3);
uint64_t ptr4 = heapAllocator->allocate(allocSize);
EXPECT_NE(0llu, ptr4);
EXPECT_NE(ptr1, ptr2);
EXPECT_NE(ptr1, ptr3);
EXPECT_NE(ptr1, ptr4);
EXPECT_NE(ptr2, ptr3);
EXPECT_NE(ptr2, ptr4);
EXPECT_NE(ptr3, ptr4);
size_t totalAllocationSize = 3 * allocSize + 2 * allocSize;
EXPECT_LE(heapAllocator->getavailableSize(), size - totalAllocationSize);
if (i == 0u) {
EXPECT_EQ(heapAllocator->getRightBound(), pRightBound - totalAllocationSize);
} else if (i == 1u) {
EXPECT_EQ(heapAllocator->getLeftBound(), pLeftBound + totalAllocationSize);
}
allocSize += sizeThreshold;
}
}
TEST(HeapAllocatorTest, GivenNoSpaceLeftWhenAllocatingThenZeroIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
size_t ptrSize = 4096;
uint64_t ptr1 = heapAllocator->allocate(ptrSize);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
size_t ptrSize2 = 1023 * 4096;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_NE(0llu, ptr2);
EXPECT_EQ(heapAllocator->getLeftBound(), heapAllocator->getRightBound());
EXPECT_EQ(0u, heapAllocator->getavailableSize());
size_t ptrSize3 = 8192;
uint64_t ptr3 = heapAllocator->allocate(ptrSize3);
EXPECT_EQ(0llu, ptr3);
}
TEST(HeapAllocatorTest, GivenReverseOrderWhenFreeingThenHeapAllocatorStateIsCorrect) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
auto pLeftBound = ptrBase;
auto pRightBound = pLeftBound + size;
size_t ptr1Size = 4096;
uint64_t ptr1 = heapAllocator->allocate(ptr1Size);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
size_t ptrSize2 = sizeThreshold + 4096;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_NE(0llu, ptr2);
size_t ptrSize3 = 8192;
uint64_t ptr3 = heapAllocator->allocate(ptrSize3);
EXPECT_NE(0llu, ptr3);
heapAllocator->free(ptr3, ptrSize3);
heapAllocator->free(ptr2, ptrSize2);
heapAllocator->free(ptr1, ptr1Size);
EXPECT_EQ(heapAllocator->getavailableSize(), size);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
EXPECT_EQ(heapAllocator->getLeftBound(), pLeftBound);
EXPECT_EQ(heapAllocator->getRightBound(), pRightBound);
}
TEST(HeapAllocatorTest, GivenNoMemoryLeftWhenAllocatingThenZeroIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 0;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
size_t ptrSize = 4096;
uint64_t ptr = heapAllocator->allocate(ptrSize);
EXPECT_EQ(0llu, ptr);
EXPECT_EQ(0u, heapAllocator->getavailableSize());
}
TEST(HeapAllocatorTest, GivenSizeGreaterThanMemoryLeftWhenAllocatingThenZeroIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 11 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, 3 * 4096);
size_t remainingSize = size;
// first small succeeds
size_t ptrSize = 4096;
uint64_t ptr = heapAllocator->allocate(ptrSize);
EXPECT_NE(0llu, ptr);
// second small suceeds
size_t ptrSize1 = 4096;
uint64_t ptr1 = heapAllocator->allocate(ptrSize1);
// free first to store on free list
heapAllocator->free(ptr, ptrSize);
remainingSize -= 4096;
EXPECT_NE(0llu, ptr1);
EXPECT_EQ(remainingSize, heapAllocator->getavailableSize());
// first big succeeds
size_t ptrSize2 = 4 * 4096;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_NE(0llu, ptr2);
// second big succeeds
size_t ptrSize3 = 4 * 4096;
uint64_t ptr3 = heapAllocator->allocate(ptrSize3);
EXPECT_NE(0llu, ptr3);
// free first big to store on free list
heapAllocator->free(ptr2, 4 * 4096);
remainingSize -= 4 * 4096;
EXPECT_EQ(remainingSize, heapAllocator->getavailableSize());
// third small fails
size_t ptrSize4 = 2 * 4096;
uint64_t ptr4 = heapAllocator->allocate(ptrSize4);
EXPECT_EQ(0llu, ptr4);
// third big fails
size_t ptrSize5 = 5 * 4096;
uint64_t ptr5 = heapAllocator->allocate(ptrSize5);
EXPECT_EQ(0llu, ptr5);
}
TEST(HeapAllocatorTest, GivenNullWhenFreeingThenNothingHappens) {
uint64_t ptrBase = 0x100000llu;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, sizeThreshold, allocationAlignment, sizeThreshold);
heapAllocator->free(0llu, 0);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
}
TEST(HeapAllocatorTest, WhenFreeingThenMemoryAvailableForAllocation) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
auto pLeftBound = ptrBase;
auto pRightBound = pLeftBound + size;
size_t ptrSize = 8192;
uint64_t ptr = heapAllocator->allocate(ptrSize);
EXPECT_NE(0llu, ptr);
EXPECT_LE(ptrBase, ptr);
size_t ptrSize1 = 8192;
uint64_t ptr1 = heapAllocator->allocate(ptrSize1);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
size_t ptrSize2 = 8192;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_NE(0llu, ptr2);
heapAllocator->free(ptr1, ptrSize1);
EXPECT_EQ(1u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
size_t ptrSize3 = 8192;
uint64_t ptr3 = heapAllocator->allocate(ptrSize3);
EXPECT_NE(0llu, ptr3);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
heapAllocator->free(ptr2, ptrSize2);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
heapAllocator->free(ptr3, ptrSize3);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
heapAllocator->free(ptr, ptrSize);
EXPECT_EQ(heapAllocator->getLeftBound(), pLeftBound);
EXPECT_EQ(heapAllocator->getRightBound(), pRightBound);
}
TEST(HeapAllocatorTest, WhenFreeingChunkThenMemoryAvailableForAllocation) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
auto pLeftBound = ptrBase;
auto pRightBound = pLeftBound + size;
size_t sizeAllocated = 0;
size_t ptrSize = 8192;
uint64_t ptr = heapAllocator->allocate(ptrSize);
EXPECT_NE(0llu, ptr);
EXPECT_LE(ptrBase, ptr);
sizeAllocated += 8192;
size_t ptrSize1 = 4 * 4096;
uint64_t ptr1 = heapAllocator->allocate(ptrSize1);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
sizeAllocated += 4 * 4096;
size_t ptrSize2 = 8192;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_NE(0llu, ptr2);
sizeAllocated += 8192;
EXPECT_EQ(size - sizeAllocated, heapAllocator->getavailableSize());
heapAllocator->free(ptr1, ptrSize1);
sizeAllocated -= 4 * 4096;
EXPECT_EQ(size - sizeAllocated, heapAllocator->getavailableSize());
EXPECT_EQ(1u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
size_t ptrSize3 = 3 * 4096;
uint64_t ptr3 = heapAllocator->allocate(ptrSize3);
EXPECT_NE(0llu, ptr3);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
sizeAllocated += 4 * 4096; // 4*4096 because this was chunk that was stored on free list
EXPECT_EQ(size - sizeAllocated, heapAllocator->getavailableSize());
heapAllocator->free(ptr2, ptrSize2);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
heapAllocator->free(ptr3, ptrSize3);
EXPECT_EQ(0u, heapAllocator->getFreedChunksSmall().size());
EXPECT_EQ(0u, heapAllocator->getFreedChunksBig().size());
heapAllocator->free(ptr, ptrSize);
EXPECT_EQ(heapAllocator->getLeftBound(), pLeftBound);
EXPECT_EQ(heapAllocator->getRightBound(), pRightBound);
EXPECT_EQ(size, heapAllocator->getavailableSize());
}
TEST(HeapAllocatorTest, GivenSmallAllocationGreaterThanAvailableSizeWhenAllocatingThenZeroIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
size_t ptrSize1 = size - 4096;
uint64_t ptr1 = heapAllocator->allocate(ptrSize1);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
EXPECT_EQ(4096u, heapAllocator->getavailableSize());
size_t ptrSize2 = 8192;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_EQ(0llu, ptr2);
}
TEST(HeapAllocatorTest, GivenBigAllocationGreaterThanAvailableSizeWhenAllocatingThenZeroIsReturned) {
uint64_t ptrBase = 0x100000llu;
size_t size = 1024 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
size_t ptrSize1 = 8192;
uint64_t ptr1 = heapAllocator->allocate(ptrSize1);
EXPECT_NE(0llu, ptr1);
EXPECT_LE(ptrBase, ptr1);
EXPECT_EQ(size - 8192u, heapAllocator->getavailableSize());
size_t ptrSize2 = size - 4096;
uint64_t ptr2 = heapAllocator->allocate(ptrSize2);
EXPECT_EQ(0llu, ptr2);
}
TEST(HeapAllocatorTest, WhenMemoryIsAllocatedThenAllocationsDoNotOverlap) {
std::ranlux24 generator(1);
const uint32_t maxIndex = 2000;
std::unique_ptr<uint64_t[]> ptrs(new uint64_t[maxIndex]);
std::unique_ptr<size_t[]> sizes(new size_t[maxIndex]);
memset(ptrs.get(), 0, sizeof(uint64_t) * maxIndex);
memset(sizes.get(), 0, sizeof(size_t) * maxIndex);
uint16_t *freeIndexes = new uint16_t[maxIndex];
std::unique_ptr<uint16_t[]> indexes(new uint16_t[maxIndex]);
memset(freeIndexes, 0, sizeof(uint16_t) * maxIndex);
memset(indexes.get(), 0, sizeof(uint16_t) * maxIndex);
// Generate random unique indexes
for (uint32_t i = 0; i < maxIndex; i++) {
uint16_t index = (generator() + 1) % maxIndex;
if (freeIndexes[index] == 0) {
indexes[i] = index;
freeIndexes[index] = 1;
}
}
delete[] freeIndexes;
uint64_t allocatorSize = 1024llu * 1024llu; // 1 MB
void *pBasePtr = alignedMalloc(static_cast<size_t>(allocatorSize), 4096);
uint64_t basePtr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(pBasePtr));
constexpr size_t reqAlignment = 4;
size_t bigAllocationThreshold = (512 + 256) * reqAlignment;
memset(pBasePtr, 0, static_cast<size_t>(allocatorSize));
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(basePtr, allocatorSize, allocationAlignment, bigAllocationThreshold);
heapAllocator->allocationAlignment = reqAlignment;
for (uint32_t i = 0; i < maxIndex; i++) {
if (indexes[i] != 0) {
size_t sizeToAllocate = (indexes[i] % 1024) * reqAlignment;
ASSERT_LT(sizeToAllocate, allocatorSize);
sizes[i] = sizeToAllocate;
ptrs[i] = heapAllocator->allocate(sizes[i]);
if (ptrs[i] == 0llu)
break;
uint8_t *pTemp = reinterpret_cast<uint8_t *>(ptrs[i]);
for (uint32_t j = 0; j < sizes[i] / 4096; j++) {
*pTemp += 1;
pTemp += 4096;
}
uint32_t indexToFree = indexes[i] % (i * 2 + 1);
if (ptrs[indexToFree]) {
memset(reinterpret_cast<void *>(ptrs[indexToFree]), 0, sizes[indexToFree]);
heapAllocator->free(ptrs[indexToFree], sizes[indexToFree]);
ptrs[indexToFree] = 0llu;
sizes[indexToFree] = 0;
}
}
}
uint8_t *pTemp = reinterpret_cast<uint8_t *>(pBasePtr);
for (uint32_t i = 0; i < allocatorSize / reqAlignment; i++) {
if (*pTemp > 1) {
EXPECT_TRUE(false) << "Heap from Allocator corrupted at page offset " << i << std::endl;
}
}
for (uint32_t i = 0; i < maxIndex; i++) {
if (ptrs[i] != 0) {
heapAllocator->free(ptrs[i], sizes[i]);
}
}
//at this point we should be able to allocate full size
size_t totalSize = (size_t)(allocatorSize - reqAlignment);
auto finalPtr = heapAllocator->allocate(totalSize);
EXPECT_NE(0llu, finalPtr);
heapAllocator->free(finalPtr, totalSize);
alignedFree(pBasePtr);
}
TEST(HeapAllocatorTest, GivenLargeAllocationsWhenFreeingThenSpaceIsDefragmented) {
uint64_t ptrBase = 0x100000llu;
uint64_t basePtr = 0x100000llu;
size_t size = 1024 * 4096;
size_t threshold = 4096;
size_t allocSize = 2 * MemoryConstants::pageSize;
size_t doubleallocSize = 2 * allocSize;
size_t tripleallocSize = 3 * allocSize;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, threshold);
std::vector<HeapChunk> &freedChunks = heapAllocator->getFreedChunksBig();
// 0, 1, 2 - can be merged to one
// 6,7,8,10 - can be merged to one
uint64_t ptrs[12];
ptrs[0] = heapAllocator->allocate(allocSize);
ptrs[1] = heapAllocator->allocate(allocSize);
ptrs[2] = heapAllocator->allocate(allocSize);
ptrs[3] = heapAllocator->allocate(tripleallocSize);
ptrs[4] = 0llu;
ptrs[5] = 0llu;
ptrs[6] = heapAllocator->allocate(allocSize);
ptrs[7] = heapAllocator->allocate(allocSize);
ptrs[8] = heapAllocator->allocate(doubleallocSize);
ptrs[9] = 0llu;
ptrs[10] = heapAllocator->allocate(allocSize);
ptrs[11] = heapAllocator->allocate(allocSize);
heapAllocator->free(ptrs[0], allocSize);
heapAllocator->free(ptrs[10], allocSize);
heapAllocator->free(ptrs[2], allocSize);
heapAllocator->free(ptrs[6], allocSize);
heapAllocator->free(ptrs[1], allocSize);
heapAllocator->free(ptrs[7], allocSize);
heapAllocator->free(ptrs[8], doubleallocSize);
// 0,1 merged on free,
// 2
// 6,7 - merged on free
// 8, 10 - merged on free
EXPECT_EQ(4u, freedChunks.size());
heapAllocator->defragment();
ASSERT_EQ(2u, freedChunks.size());
EXPECT_EQ(basePtr, freedChunks[0].ptr);
EXPECT_EQ(3 * allocSize, freedChunks[0].size);
EXPECT_EQ((basePtr + 6 * allocSize), freedChunks[1].ptr);
EXPECT_EQ(5 * allocSize, freedChunks[1].size);
}
TEST(HeapAllocatorTest, GivenSmallAllocationsWhenFreeingThenSpaceIsDefragmented) {
uint64_t ptrBase = 0x100000llu;
uint64_t basePtr = 0x100000;
size_t size = 1024 * 4096;
uint64_t upperLimitPtr = basePtr + size;
size_t threshold = 2 * MemoryConstants::pageSize;
size_t allocSize = MemoryConstants::pageSize;
size_t doubleallocSize = 2 * allocSize;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, threshold);
std::vector<HeapChunk> &freedChunks = heapAllocator->getFreedChunksSmall();
// 0, 1, 2 - can be merged to one
// 6,7,8,10 - can be merged to one
uint64_t ptrs[12];
ptrs[0] = heapAllocator->allocate(allocSize);
ptrs[1] = heapAllocator->allocate(allocSize);
ptrs[2] = heapAllocator->allocate(allocSize);
ptrs[3] = heapAllocator->allocate(doubleallocSize);
ptrs[4] = 0llu;
ptrs[5] = 0llu;
ptrs[6] = heapAllocator->allocate(allocSize);
ptrs[7] = heapAllocator->allocate(allocSize);
ptrs[8] = heapAllocator->allocate(doubleallocSize);
ptrs[9] = 0llu;
ptrs[10] = heapAllocator->allocate(allocSize);
ptrs[11] = heapAllocator->allocate(allocSize);
heapAllocator->free(ptrs[0], allocSize);
heapAllocator->free(ptrs[2], allocSize);
heapAllocator->free(ptrs[8], doubleallocSize);
heapAllocator->free(ptrs[1], allocSize);
heapAllocator->free(ptrs[6], allocSize);
heapAllocator->free(ptrs[7], allocSize);
heapAllocator->free(ptrs[10], allocSize);
// 0,1 merged on free,
// 2
// 6, - merged on free
// 7, 8, 10 - merged on free
EXPECT_EQ(4u, freedChunks.size());
heapAllocator->defragment();
ASSERT_EQ(2u, freedChunks.size());
EXPECT_EQ((upperLimitPtr - 3 * allocSize), freedChunks[0].ptr);
EXPECT_EQ(3 * allocSize, freedChunks[0].size);
EXPECT_EQ((upperLimitPtr - 10 * allocSize), freedChunks[1].ptr);
EXPECT_EQ(5 * allocSize, freedChunks[1].size);
}
TEST(HeapAllocatorTest, Given10SmallAllocationsWhenFreedInTheSameOrderThenLastChunkFreedReturnsWholeSpaceToFreeRange) {
uint64_t ptrBase = 0llu;
size_t size = 1024 * 4096;
size_t threshold = 2 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, threshold);
std::vector<HeapChunk> &freedChunks = heapAllocator->getFreedChunksSmall();
uint64_t ptrs[10];
size_t sizes[10];
for (uint32_t i = 0; i < 10; i++) {
sizes[i] = 4096;
ptrs[i] = heapAllocator->allocate(sizes[i]);
}
EXPECT_EQ(0u, freedChunks.size());
for (uint32_t i = 0; i < 10; i++) {
heapAllocator->free(ptrs[i], sizes[i]);
// After free chunk gets merged to existing one on freed list
if (i < 9) {
EXPECT_EQ(1u, freedChunks.size());
}
}
// Last chunk released merges freed chunk to free range
EXPECT_EQ(0u, freedChunks.size());
}
TEST(HeapAllocatorTest, Given10SmallAllocationsWhenMergedToBigAllocatedAsSmallSplittedAndReleasedThenItDoesNotGoToFreedBigChunksList) {
uint64_t ptrBase = 0llu;
uintptr_t basePtr = 0;
// Size for 10 small allocs plus one single 2 page plus some space
size_t size = (10 + 2 + 1) * 4096;
uintptr_t upperLimitPtr = basePtr + size;
size_t threshold = 4 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, threshold);
std::vector<HeapChunk> &freedChunksSmall = heapAllocator->getFreedChunksSmall();
std::vector<HeapChunk> &freedChunksBig = heapAllocator->getFreedChunksBig();
uint64_t ptrs[10];
size_t sizes[10];
// size smaller than threshold
size_t sizeOfSmallAlloc = 2 * 4096;
uint64_t smallAlloc = 0llu;
for (uint32_t i = 0; i < 10; i++) {
sizes[i] = 4096;
ptrs[i] = heapAllocator->allocate(sizes[i]);
}
EXPECT_EQ(0u, freedChunksSmall.size());
EXPECT_EQ(0u, freedChunksBig.size());
// Release 8 chunks
for (uint32_t i = 0; i < 8; i++) {
heapAllocator->free(ptrs[i], sizes[i]);
}
// Allocate small chunk, should be taken from freed list
smallAlloc = heapAllocator->allocate(sizeOfSmallAlloc);
EXPECT_NE(0llu, smallAlloc);
EXPECT_LE(upperLimitPtr - (8 * 4096), smallAlloc);
EXPECT_EQ(1u, freedChunksSmall.size());
heapAllocator->free(smallAlloc, sizeOfSmallAlloc);
// It should not go to freedBig list
EXPECT_EQ(0u, freedChunksBig.size());
// It should merge to freedSmall chunk
EXPECT_EQ(1u, freedChunksSmall.size());
// Release last 2 allocs
for (uint32_t i = 8; i < 10; i++) {
heapAllocator->free(ptrs[i], sizes[i]);
}
// In the end both lists should be empty
EXPECT_EQ(0u, freedChunksSmall.size());
EXPECT_EQ(0u, freedChunksBig.size());
}
TEST(HeapAllocatorTest, Given10SmallAllocationsWhenMergedToBigAllocatedAsSmallNotSplittedAndReleasedThenItDoesNotGoToFreedBigChunksList) {
uint64_t ptrBase = 0llu;
uintptr_t basePtr = 0;
// Size for 10 small allocs plus one single 3 page plus some space
size_t size = (10 + 3 + 1) * 4096;
uint64_t upperLimitPtr = basePtr + size;
size_t threshold = 4 * 4096;
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, threshold);
std::vector<HeapChunk> &freedChunksSmall = heapAllocator->getFreedChunksSmall();
std::vector<HeapChunk> &freedChunksBig = heapAllocator->getFreedChunksBig();
uint64_t ptrs[10];
size_t sizes[10];
// size smaller than threshold
size_t sizeOfSmallAlloc = 3 * 4096;
uint64_t smallAlloc = 0llu;
for (uint32_t i = 0; i < 10; i++) {
sizes[i] = 4096;
ptrs[i] = heapAllocator->allocate(sizes[i]);
}
EXPECT_EQ(0u, freedChunksSmall.size());
EXPECT_EQ(0u, freedChunksBig.size());
// Release 8 chunks
for (uint32_t i = 0; i < 5; i++) {
heapAllocator->free(ptrs[i], sizes[i]);
}
// Allocate small chunk, should be taken from freed list
smallAlloc = heapAllocator->allocate(sizeOfSmallAlloc);
EXPECT_NE(0llu, smallAlloc);
EXPECT_LE(upperLimitPtr - (5 * 4096), smallAlloc);
EXPECT_EQ(0u, freedChunksSmall.size());
heapAllocator->free(smallAlloc, sizeOfSmallAlloc);
// It should not go to freedBig list
EXPECT_EQ(0u, freedChunksBig.size());
// It should go to freedSmall chunk
EXPECT_EQ(1u, freedChunksSmall.size());
// Release remaining allocs
for (uint32_t i = 5; i < 10; i++) {
heapAllocator->free(ptrs[i], sizes[i]);
if (i < 9) {
// chunks should be merged to freedSmall chunk on list
EXPECT_EQ(1u, freedChunksSmall.size());
}
}
// In the end both lists should be empty
EXPECT_EQ(0u, freedChunksSmall.size());
EXPECT_EQ(0u, freedChunksBig.size());
}
TEST(HeapAllocatorTest, givenAlignedBoundWhenAllocatingMemoryWithCustomAlignmentFromLeftThenReturnAllocations) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
const size_t customAlignment = 32 * MemoryConstants::pageSize;
size_t ptrSize = 32 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase + ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(32 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
ptrSize = 32 * MemoryConstants::pageSize;
ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(32 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase + ptrSize, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
}
TEST(HeapAllocatorTest, givenAlignedBoundWhenAllocatingMemoryWithCustomAlignmentFromRightThenReturnAllocations) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
const size_t customAlignment = 8 * MemoryConstants::pageSize;
size_t ptrSize = 8 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize - ptrSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase, heapAllocator.getLeftBound());
EXPECT_EQ(8 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - ptrSize, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
ptrSize = 8 * MemoryConstants::pageSize;
ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize - 2 * ptrSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase, heapAllocator.getLeftBound());
EXPECT_EQ(8 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - 2 * ptrSize, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - 2 * ptrSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenAlignedBoundWhenAllocatingMemoryWithCustomAlignmentBiggerThanPtrSizeFromRightThenReturnAllocations) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
size_t customAlignment = 8 * MemoryConstants::pageSize;
size_t ptrSize = 8 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize - ptrSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase, heapAllocator.getLeftBound());
EXPECT_EQ(8 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - ptrSize, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
ptrSize = 8 * MemoryConstants::pageSize;
customAlignment = 32 * MemoryConstants::pageSize;
ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize - customAlignment, heapAllocator.getRightBound());
EXPECT_EQ(heapBase, heapAllocator.getLeftBound());
EXPECT_EQ(8 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - customAlignment, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - 2 * ptrSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenUnalignedBoundWhenAllocatingWithCustomAlignmentFromLeftThenAlignBoundBeforeAllocation) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, 0);
// Misalign the left bound
const size_t misaligningAllocationSize = 2 * MemoryConstants::pageSize;
size_t ptrSize = misaligningAllocationSize;
uint64_t ptr = heapAllocator.allocate(ptrSize);
EXPECT_EQ(heapBase, ptr);
EXPECT_EQ(misaligningAllocationSize, ptrSize);
EXPECT_EQ(heapBase + ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(heapSize - misaligningAllocationSize, heapAllocator.getavailableSize());
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
// Allocate with alignment
const size_t customAlignment = 8 * MemoryConstants::pageSize;
const size_t alignedAllocationSize = 16 * MemoryConstants::pageSize;
ptrSize = alignedAllocationSize;
ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(alignedAllocationSize, ptrSize);
EXPECT_EQ(heapBase + customAlignment, ptr);
EXPECT_EQ(heapBase + customAlignment + alignedAllocationSize, heapAllocator.getLeftBound());
EXPECT_EQ(heapSize - misaligningAllocationSize - alignedAllocationSize, heapAllocator.getavailableSize());
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
// Try to use w hole, we just created by aligning
const size_t additionalAllocationSize = customAlignment - misaligningAllocationSize;
ptrSize = additionalAllocationSize;
ptr = heapAllocator.allocate(ptrSize);
EXPECT_EQ(heapBase + misaligningAllocationSize, ptr);
EXPECT_EQ(additionalAllocationSize, ptrSize);
EXPECT_EQ(heapBase + customAlignment + alignedAllocationSize, heapAllocator.getLeftBound());
EXPECT_EQ(heapSize - customAlignment - alignedAllocationSize, heapAllocator.getavailableSize());
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
}
TEST(HeapAllocatorTest, givenUnalignedBoundWhenAllocatingWithCustomAlignmentFromRightThenAlignBoundBeforeAllocation) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, std::numeric_limits<size_t>::max());
// Misalign the right bound
const size_t misaligningAllocationSize = 2 * MemoryConstants::pageSize;
size_t ptrSize = misaligningAllocationSize;
uint64_t ptr = heapAllocator.allocate(ptrSize);
EXPECT_EQ(misaligningAllocationSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - misaligningAllocationSize, ptr);
EXPECT_EQ(heapBase + heapSize - misaligningAllocationSize, heapAllocator.getRightBound());
EXPECT_EQ(heapSize - misaligningAllocationSize, heapAllocator.getavailableSize());
EXPECT_EQ(0u, heapAllocator.getFreedChunksSmall().size());
// Allocate with alignment
const size_t customAlignment = 8 * MemoryConstants::pageSize;
const size_t alignedAllocationSize = 16 * MemoryConstants::pageSize;
ptrSize = alignedAllocationSize;
ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(alignedAllocationSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - customAlignment - alignedAllocationSize, ptr);
EXPECT_EQ(heapBase + heapSize - customAlignment - alignedAllocationSize, heapAllocator.getRightBound());
EXPECT_EQ(heapSize - misaligningAllocationSize - alignedAllocationSize, heapAllocator.getavailableSize());
EXPECT_EQ(1u, heapAllocator.getFreedChunksSmall().size());
// Try to use w hole, we just created by aligning
const size_t additionalAllocationSize = customAlignment - misaligningAllocationSize;
ptrSize = additionalAllocationSize;
ptr = heapAllocator.allocate(ptrSize);
EXPECT_EQ(heapBase + heapSize - customAlignment, ptr);
EXPECT_EQ(additionalAllocationSize, ptrSize);
EXPECT_EQ(heapBase + heapSize - customAlignment - alignedAllocationSize, heapAllocator.getRightBound());
EXPECT_EQ(heapSize - customAlignment - alignedAllocationSize, heapAllocator.getavailableSize());
EXPECT_EQ(0u, heapAllocator.getFreedChunksSmall().size());
}
TEST(HeapAllocatorTest, givenNoSpaceLeftWhenAllocatingWithCustomAlignmentFromLeftThenReturnZero) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, 0);
const size_t customAlignment = 256 * MemoryConstants::pageSize;
const size_t alignedAllocationSize = 256 * MemoryConstants::pageSize;
size_t ptrSize = alignedAllocationSize;
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + alignedAllocationSize, heapAllocator.getLeftBound());
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + 2 * alignedAllocationSize, heapAllocator.getLeftBound());
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + 3 * alignedAllocationSize, heapAllocator.getLeftBound());
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + 4 * alignedAllocationSize, heapAllocator.getLeftBound());
EXPECT_EQ(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + 4 * alignedAllocationSize, heapAllocator.getLeftBound());
}
TEST(HeapAllocatorTest, givenNoSpaceLeftWhenAllocatingWithCustomAlignmentFromRightThenReturnZero) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, std::numeric_limits<size_t>::max());
const size_t customAlignment = 256 * MemoryConstants::pageSize;
const size_t alignedAllocationSize = 256 * MemoryConstants::pageSize;
size_t ptrSize = alignedAllocationSize;
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + heapSize - alignedAllocationSize, heapAllocator.getRightBound());
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + heapSize - 2 * alignedAllocationSize, heapAllocator.getRightBound());
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + heapSize - 3 * alignedAllocationSize, heapAllocator.getRightBound());
EXPECT_NE(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + heapSize - 4 * alignedAllocationSize, heapAllocator.getRightBound());
EXPECT_EQ(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment));
EXPECT_EQ(heapBase + heapSize - 4 * alignedAllocationSize, heapAllocator.getRightBound());
}
TEST(HeapAllocatorTest, givenNoSpaceLeftAfterAligningWhenAllocatingWithCustomAlignmentFromLeftThenReturnZero) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
const size_t alignedAllocationSize = 64 * MemoryConstants::pageSize;
// First create a state, where we have desired size free, but not aligned
size_t ptrSize = 16 * MemoryConstants::pageSize;
EXPECT_NE(0ull, heapAllocator.allocate(ptrSize));
EXPECT_EQ(heapBase + heapSize - 16 * MemoryConstants::pageSize, heapAllocator.getRightBound());
ptrSize = heapSize - alignedAllocationSize - ptrSize;
EXPECT_NE(0ull, heapAllocator.allocate(ptrSize));
EXPECT_EQ(heapBase + ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(alignedAllocationSize, heapAllocator.getavailableSize());
// Aligned allocation should fail
ptrSize = alignedAllocationSize;
EXPECT_EQ(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, ptrSize));
EXPECT_EQ(alignedAllocationSize, heapAllocator.getavailableSize());
// Unaligned allocation can be done
ptrSize = alignedAllocationSize;
EXPECT_NE(0ull, heapAllocator.allocate(ptrSize));
EXPECT_EQ(0ull, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenNoSpaceLeftAfterAligningWhenAllocatingWithCustomAlignmentFromRightThenReturnZero) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
const size_t alignedAllocationSize = 8 * MemoryConstants::pageSize;
// First create a state, where we have desired size free, but not aligned
size_t ptrSize = 4 * MemoryConstants::pageSize;
EXPECT_NE(0ull, heapAllocator.allocate(ptrSize));
EXPECT_EQ(heapBase + heapSize - 4 * MemoryConstants::pageSize, heapAllocator.getRightBound());
ptrSize = heapSize - alignedAllocationSize - ptrSize;
EXPECT_NE(0ull, heapAllocator.allocate(ptrSize));
EXPECT_EQ(heapBase + ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(alignedAllocationSize, heapAllocator.getavailableSize());
// Aligned allocation should fail
ptrSize = alignedAllocationSize;
EXPECT_EQ(0ull, heapAllocator.allocateWithCustomAlignment(ptrSize, ptrSize));
EXPECT_EQ(alignedAllocationSize, heapAllocator.getavailableSize());
// Unaligned allocation can be done
ptrSize = alignedAllocationSize;
EXPECT_NE(0ull, heapAllocator.allocate(ptrSize));
EXPECT_EQ(0ull, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenSizeNotAlignedToCustomAlignmentWhenAllocatingMemoryWithCustomAlignmentThenDoNotAlignToCustomAlignment) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
const size_t customAlignment = 32 * MemoryConstants::pageSize;
size_t ptrSize = 49 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase + ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(49 * MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenSizeNotAlignedToBaseAllocatorAlignmentWhenAllocatingMemoryWithCustomAlignmentThenDoNotAlignToBaseAlignment) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, 0);
const size_t customAlignment = 32 * MemoryConstants::pageSize;
size_t ptrSize = 1;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + heapSize, heapAllocator.getRightBound());
EXPECT_EQ(heapBase + ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(MemoryConstants::pageSize, ptrSize);
EXPECT_EQ(heapBase, ptr);
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenAlignedFreedChunkAvailableWhenAllocatingMemoryWithCustomAlignmentFromLeftThenReturnUseFreedChunk) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
// First create an aligned freed chunk
size_t ptrSize = 32 * MemoryConstants::pageSize;
const uint64_t freeChunkAddress = heapAllocator.allocate(ptrSize);
heapAllocator.allocate(ptrSize);
heapAllocator.free(freeChunkAddress, ptrSize);
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
// Allocate with custom alignment using the freed chunk
const size_t customAlignment = 32 * MemoryConstants::pageSize;
ptrSize = 32 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(freeChunkAddress, ptr);
EXPECT_EQ(heapSize - 2 * ptrSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenAlignedFreedChunkSlightlyBiggerThanAllocationeWhenAllocatingMemoryWithCustomAlignmentFromLeftThenUseEntireFreedChunk) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
// First create an aligned freed chunk
size_t ptrSize = 48 * MemoryConstants::pageSize;
const uint64_t freeChunkAddress = heapAllocator.allocate(ptrSize);
heapAllocator.allocate(ptrSize);
heapAllocator.free(freeChunkAddress, ptrSize);
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
// Allocate with custom alignment using the freed chunk
const size_t customAlignment = 32 * MemoryConstants::pageSize;
size_t ptrSize2 = 32 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize2, customAlignment);
EXPECT_EQ(ptrSize, ptrSize2);
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(0u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(freeChunkAddress, ptr);
EXPECT_EQ(heapSize - 2 * ptrSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenAlignedFreedChunkTwoTimesBiggerThanAllocationeWhenAllocatingMemoryWithCustomAlignmentFromLeftThenUseAPortionOfTheFreedChunk) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, sizeThreshold);
// First create an aligned freed chunk
size_t ptrSize = 64 * MemoryConstants::pageSize;
const uint64_t freeChunkAddress = heapAllocator.allocate(ptrSize);
heapAllocator.allocate(ptrSize);
heapAllocator.free(freeChunkAddress, ptrSize);
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize, heapAllocator.getavailableSize());
// Allocate with custom alignment using the freed chunk
const size_t customAlignment = 32 * MemoryConstants::pageSize;
size_t ptrSize2 = 32 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize2, customAlignment);
EXPECT_EQ(32 * MemoryConstants::pageSize, ptrSize2);
EXPECT_EQ(heapBase + 2 * ptrSize, heapAllocator.getLeftBound());
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(freeChunkAddress + 32 * MemoryConstants::pageSize, ptr);
EXPECT_EQ(heapSize - ptrSize - ptrSize2, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenUnalignedFreedChunkAvailableWhenAllocatingMemoryWithCustomAlignmentFromLeftThenDoNotUseFreedChunk) {
const uint64_t heapBase = 0x100000llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, 1);
// First create an unaligned freed chunk
size_t ptrSize = MemoryConstants::pageSize;
heapAllocator.allocate(ptrSize);
ptrSize = 32 * MemoryConstants::pageSize;
const uint64_t freeChunkAddress = heapAllocator.allocate(ptrSize);
heapAllocator.allocate(ptrSize);
heapAllocator.free(freeChunkAddress, ptrSize);
EXPECT_EQ(heapBase + 65 * MemoryConstants::pageSize, heapAllocator.getLeftBound());
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - ptrSize - MemoryConstants::pageSize, heapAllocator.getavailableSize());
// Allocate with custom alignment, the freed chunk cannot be used
const size_t customAlignment = 32 * MemoryConstants::pageSize;
ptrSize = 32 * MemoryConstants::pageSize;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, customAlignment);
EXPECT_EQ(heapBase + 128 * MemoryConstants::pageSize, heapAllocator.getLeftBound());
EXPECT_EQ(heapBase + 96 * MemoryConstants::pageSize, ptr);
EXPECT_EQ(2u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - 2 * ptrSize - MemoryConstants::pageSize, heapAllocator.getavailableSize());
// Allocate without custom alignment, the freed chunk can be used
ptrSize = 32 * MemoryConstants::pageSize;
ptr = heapAllocator.allocate(ptrSize);
EXPECT_EQ(heapBase + 128 * MemoryConstants::pageSize, heapAllocator.getLeftBound());
EXPECT_EQ(freeChunkAddress, ptr);
EXPECT_EQ(1u, heapAllocator.getFreedChunksBig().size());
EXPECT_EQ(heapSize - 3 * ptrSize - MemoryConstants::pageSize, heapAllocator.getavailableSize());
}
TEST(HeapAllocatorTest, givenZeroAlignmentPassedWhenAllocatingMemoryWithCustomAlignmentThenUseDefaultAllocatorAlignment) {
const uint64_t heapBase = 0x111111llu;
const size_t heapSize = 1024u * 4096u;
HeapAllocatorUnderTest heapAllocator(heapBase, heapSize, allocationAlignment, 0);
size_t ptrSize = 1;
uint64_t ptr = heapAllocator.allocateWithCustomAlignment(ptrSize, 0u);
EXPECT_EQ(alignUp(heapBase, allocationAlignment), ptr);
}
|
/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "main/core.h"
#include "ir.h"
#include "linker.h"
#include "ir_uniform.h"
#include "string_to_uint_map.h"
/* These functions are put in a "private" namespace instead of being marked
* static so that the unit tests can access them. See
* http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code
*/
namespace linker {
static gl_uniform_storage *
get_storage(struct gl_shader_program *prog, const char *name)
{
unsigned id;
if (prog->UniformHash->get(id, name))
return &prog->data->UniformStorage[id];
assert(!"No uniform storage found!");
return NULL;
}
void
copy_constant_to_storage(union gl_constant_value *storage,
const ir_constant *val,
const enum glsl_base_type base_type,
const unsigned int elements,
unsigned int boolean_true)
{
for (unsigned int i = 0; i < elements; i++) {
switch (base_type) {
case GLSL_TYPE_UINT:
storage[i].u = val->value.u[i];
break;
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
storage[i].i = val->value.i[i];
break;
case GLSL_TYPE_FLOAT:
storage[i].f = val->value.f[i];
break;
case GLSL_TYPE_DOUBLE:
case GLSL_TYPE_UINT64:
case GLSL_TYPE_INT64:
/* XXX need to check on big-endian */
memcpy(&storage[i * 2].u, &val->value.d[i], sizeof(double));
break;
case GLSL_TYPE_BOOL:
storage[i].b = val->value.b[i] ? boolean_true : 0;
break;
case GLSL_TYPE_ARRAY:
case GLSL_TYPE_STRUCT:
case GLSL_TYPE_IMAGE:
case GLSL_TYPE_ATOMIC_UINT:
case GLSL_TYPE_INTERFACE:
case GLSL_TYPE_VOID:
case GLSL_TYPE_SUBROUTINE:
case GLSL_TYPE_FUNCTION:
case GLSL_TYPE_ERROR:
/* All other types should have already been filtered by other
* paths in the caller.
*/
assert(!"Should not get here.");
break;
}
}
}
/**
* Initialize an opaque uniform from the value of an explicit binding
* qualifier specified in the shader. Atomic counters are different because
* they have no storage and should be handled elsewhere.
*/
static void
set_opaque_binding(void *mem_ctx, gl_shader_program *prog,
const ir_variable *var, const glsl_type *type,
const char *name, int *binding)
{
if (type->is_array() && type->fields.array->is_array()) {
const glsl_type *const element_type = type->fields.array;
for (unsigned int i = 0; i < type->length; i++) {
const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
set_opaque_binding(mem_ctx, prog, var, element_type,
element_name, binding);
}
} else {
struct gl_uniform_storage *const storage = get_storage(prog, name);
if (!storage)
return;
const unsigned elements = MAX2(storage->array_elements, 1);
/* Section 4.4.6 (Opaque-Uniform Layout Qualifiers) of the GLSL 4.50 spec
* says:
*
* "If the binding identifier is used with an array, the first element
* of the array takes the specified unit and each subsequent element
* takes the next consecutive unit."
*/
for (unsigned int i = 0; i < elements; i++) {
storage->storage[i].i = (*binding)++;
}
for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) {
gl_linked_shader *shader = prog->_LinkedShaders[sh];
if (!shader)
continue;
if (!storage->opaque[sh].active)
continue;
if (storage->type->is_sampler()) {
for (unsigned i = 0; i < elements; i++) {
const unsigned index = storage->opaque[sh].index + i;
if (var->data.bindless) {
if (index >= shader->Program->sh.NumBindlessSamplers)
break;
shader->Program->sh.BindlessSamplers[index].unit =
storage->storage[i].i;
shader->Program->sh.BindlessSamplers[index].bound = true;
shader->Program->sh.HasBoundBindlessSampler = true;
} else {
if (index >= ARRAY_SIZE(shader->Program->SamplerUnits))
break;
shader->Program->SamplerUnits[index] =
storage->storage[i].i;
}
}
} else if (storage->type->is_image()) {
for (unsigned i = 0; i < elements; i++) {
const unsigned index = storage->opaque[sh].index + i;
if (var->data.bindless) {
if (index >= shader->Program->sh.NumBindlessImages)
break;
shader->Program->sh.BindlessImages[index].unit =
storage->storage[i].i;
shader->Program->sh.BindlessImages[index].bound = true;
shader->Program->sh.HasBoundBindlessImage = true;
} else {
if (index >= ARRAY_SIZE(shader->Program->sh.ImageUnits))
break;
shader->Program->sh.ImageUnits[index] =
storage->storage[i].i;
}
}
}
}
}
}
static void
set_block_binding(gl_shader_program *prog, const char *block_name,
unsigned mode, int binding)
{
unsigned num_blocks = mode == ir_var_uniform ?
prog->data->NumUniformBlocks :
prog->data->NumShaderStorageBlocks;
struct gl_uniform_block *blks = mode == ir_var_uniform ?
prog->data->UniformBlocks : prog->data->ShaderStorageBlocks;
for (unsigned i = 0; i < num_blocks; i++) {
if (!strcmp(blks[i].Name, block_name)) {
blks[i].Binding = binding;
return;
}
}
unreachable("Failed to initialize block binding");
}
void
set_uniform_initializer(void *mem_ctx, gl_shader_program *prog,
const char *name, const glsl_type *type,
ir_constant *val, unsigned int boolean_true)
{
const glsl_type *t_without_array = type->without_array();
if (type->is_record()) {
for (unsigned int i = 0; i < type->length; i++) {
const glsl_type *field_type = type->fields.structure[i].type;
const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
type->fields.structure[i].name);
set_uniform_initializer(mem_ctx, prog, field_name,
field_type, val->get_record_field(i),
boolean_true);
}
return;
} else if (t_without_array->is_record() ||
(type->is_array() && type->fields.array->is_array())) {
const glsl_type *const element_type = type->fields.array;
for (unsigned int i = 0; i < type->length; i++) {
const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
set_uniform_initializer(mem_ctx, prog, element_name,
element_type, val->const_elements[i],
boolean_true);
}
return;
}
struct gl_uniform_storage *const storage = get_storage(prog, name);
if (!storage)
return;
if (val->type->is_array()) {
const enum glsl_base_type base_type =
val->const_elements[0]->type->base_type;
const unsigned int elements = val->const_elements[0]->type->components();
unsigned int idx = 0;
unsigned dmul = glsl_base_type_is_64bit(base_type) ? 2 : 1;
assert(val->type->length >= storage->array_elements);
for (unsigned int i = 0; i < storage->array_elements; i++) {
copy_constant_to_storage(& storage->storage[idx],
val->const_elements[i],
base_type,
elements,
boolean_true);
idx += elements * dmul;
}
} else {
copy_constant_to_storage(storage->storage,
val,
val->type->base_type,
val->type->components(),
boolean_true);
if (storage->type->is_sampler()) {
for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) {
gl_linked_shader *shader = prog->_LinkedShaders[sh];
if (shader && storage->opaque[sh].active) {
unsigned index = storage->opaque[sh].index;
shader->Program->SamplerUnits[index] = storage->storage[0].i;
}
}
}
}
}
}
void
link_set_uniform_initializers(struct gl_shader_program *prog,
unsigned int boolean_true)
{
void *mem_ctx = NULL;
for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
struct gl_linked_shader *shader = prog->_LinkedShaders[i];
if (shader == NULL)
continue;
foreach_in_list(ir_instruction, node, shader->ir) {
ir_variable *const var = node->as_variable();
if (!var || (var->data.mode != ir_var_uniform &&
var->data.mode != ir_var_shader_storage))
continue;
if (!mem_ctx)
mem_ctx = ralloc_context(NULL);
if (var->data.explicit_binding) {
const glsl_type *const type = var->type;
if (type->without_array()->is_sampler() ||
type->without_array()->is_image()) {
int binding = var->data.binding;
linker::set_opaque_binding(mem_ctx, prog, var, var->type,
var->name, &binding);
} else if (var->is_in_buffer_block()) {
const glsl_type *const iface_type = var->get_interface_type();
/* If the variable is an array and it is an interface instance,
* we need to set the binding for each array element. Just
* checking that the variable is an array is not sufficient.
* The variable could be an array element of a uniform block
* that lacks an instance name. For example:
*
* uniform U {
* float f[4];
* };
*
* In this case "f" would pass is_in_buffer_block (above) and
* type->is_array(), but it will fail is_interface_instance().
*/
if (var->is_interface_instance() && var->type->is_array()) {
for (unsigned i = 0; i < var->type->length; i++) {
const char *name =
ralloc_asprintf(mem_ctx, "%s[%u]", iface_type->name, i);
/* Section 4.4.3 (Uniform Block Layout Qualifiers) of the
* GLSL 4.20 spec says:
*
* "If the binding identifier is used with a uniform
* block instanced as an array then the first element
* of the array takes the specified block binding and
* each subsequent element takes the next consecutive
* uniform block binding point."
*/
linker::set_block_binding(prog, name, var->data.mode,
var->data.binding + i);
}
} else {
linker::set_block_binding(prog, iface_type->name,
var->data.mode,
var->data.binding);
}
} else if (type->contains_atomic()) {
/* we don't actually need to do anything. */
} else {
assert(!"Explicit binding not on a sampler, UBO or atomic.");
}
} else if (var->constant_initializer) {
linker::set_uniform_initializer(mem_ctx, prog, var->name,
var->type, var->constant_initializer,
boolean_true);
}
}
}
ralloc_free(mem_ctx);
}
|
#ifndef BOOST_MPL_AUX_PUSH_FRONT_IMPL_HPP_INCLUDED
#define BOOST_MPL_AUX_PUSH_FRONT_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2008
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: push_front_impl.hpp 55679 2009-08-20 07:50:16Z agurtovoy $
// $Date: 2009-08-20 09:50:16 +0200 (jeu., 20 août 2009) $
// $Revision: 55679 $
#include <boost/mpl/push_front_fwd.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/aux_/has_type.hpp>
#include <boost/mpl/aux_/traits_lambda_spec.hpp>
#include <boost/mpl/aux_/config/forwarding.hpp>
#include <boost/mpl/aux_/config/static_constant.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace mpl {
struct has_push_front_arg {};
// agurt 05/feb/04: no default implementation; the stub definition is needed
// to enable the default 'has_push_front' implementation below
template< typename Tag >
struct push_front_impl
{
template< typename Sequence, typename T > struct apply
{
// should be instantiated only in the context of 'has_push_front_impl';
// if you've got an assert here, you are requesting a 'push_front'
// specialization that doesn't exist.
BOOST_MPL_ASSERT_MSG(
( boost::is_same< T, has_push_front_arg >::value )
, REQUESTED_PUSH_FRONT_SPECIALIZATION_FOR_SEQUENCE_DOES_NOT_EXIST
, ( Sequence )
);
};
};
template< typename Tag >
struct has_push_front_impl
{
template< typename Seq > struct apply
#if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING)
: aux::has_type< push_front< Seq, has_push_front_arg > >
{
#else
{
typedef aux::has_type< push_front< Seq, has_push_front_arg > > type;
BOOST_STATIC_CONSTANT(bool, value =
(aux::has_type< push_front< Seq, has_push_front_arg > >::value)
);
#endif
};
};
BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC(2, push_front_impl)
BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC(1, has_push_front_impl)
}}
#endif // BOOST_MPL_AUX_PUSH_FRONT_IMPL_HPP_INCLUDED
|
/*=========================================================================
Program: GDCM (Grassroots DICOM). A DICOM library
Copyright (c) 2006-2011 Mathieu Malaterre
All rights reserved.
See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "gdcmSHA1.h"
#include "gdcmSystem.h"
#ifdef GDCM_USE_SYSTEM_OPENSSL
#include <openssl/sha.h>
#endif
#include <string.h> // memcmp
#include <stdlib.h> // malloc
#include <stdio.h> // sprintf
/*
*/
namespace gdcm
{
class SHA1Internals
{
public:
#ifdef GDCM_USE_SYSTEM_OPENSSL
SHA_CTX ctx;
#endif
};
SHA1::SHA1()
{
Internals = new SHA1Internals;
}
SHA1::~SHA1()
{
delete Internals;
}
bool SHA1::Compute(const char *buffer, unsigned long buf_len, char digest[])
{
#ifdef GDCM_USE_SYSTEM_OPENSSL
if( !buffer || !buf_len )
{
return false;
}
unsigned char output[20];
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, buffer, buf_len);
SHA1_Final(output, &ctx);
for (int di = 0; di < 20; ++di)
{
sprintf(digest+2*di, "%02x", output[di]);
}
digest[2*20] = '\0';
return true;
#else
(void)buffer;
(void)buf_len;
(void)digest;
return false;
#endif
}
#ifdef GDCM_USE_SYSTEM_OPENSSL
static bool process_file(const char *filename, unsigned char *digest)
{
if( !filename || !digest ) return false;
FILE *file = fopen(filename, "rb");
if(!file)
{
return false;
}
size_t file_size = System::FileSize(filename);
void *buffer = malloc(file_size);
if(!buffer)
{
fclose(file);
return false;
}
size_t read = fread(buffer, 1, file_size, file);
if( read != file_size ) return false;
SHA_CTX ctx;
int ret = SHA1_Init(&ctx);
if( !ret ) return false;
ret = SHA1_Update(&ctx, buffer, file_size);
if( !ret ) return false;
ret = SHA1_Final(digest, &ctx);
if( !ret ) return false;
/*printf("MD5 (\"%s\") = ", test[i]); */
/*for (int di = 0; di < 16; ++di)
{
printf("%02x", digest[di]);
}*/
//printf("\t%s\n", filename);
free(buffer);
fclose(file);
return true;
}
#endif
bool SHA1::ComputeFile(const char *filename, char digest_str[20*2+1])
{
#ifdef GDCM_USE_SYSTEM_OPENSSL
// If not file exist
// return false;
unsigned char digest[20];
/* Do the file */
if( !process_file(filename, digest) )
{
return false;
}
for (int di = 0; di < 20; ++di)
{
sprintf(digest_str+2*di, "%02x", digest[di]);
}
digest_str[2*20] = '\0';
return true;
#else
(void)filename;
(void)digest_str;
return false;
#endif
}
} // end namespace gdcm
|
// Copyright (c) 2017-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <gtest/gtest.h>
#include <thread>
#include <iostream>
#include "blackwidow/blackwidow.h"
using namespace blackwidow;
int main() {
BlackwidowOptions bw_options;
blackwidow::BlackWidow db;
blackwidow::Status s;
std::string path = "./db";
if (access(path.c_str(), F_OK)) {
mkdir(path.c_str(), 0755);
}
bw_options.options.create_if_missing = true;
s = db.Open(bw_options, path);
uint64_t result = 0;
s = db.GetUsage("all", &result);
return 0;
}
|
/* Copyright 2019 Diligent Graphics 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
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
// The source code in this file is derived from ColorBuffer.cpp and GraphicsCore.cpp developed by Minigraph
// Original source files header:
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Developed by Minigraph
//
// Author: James Stanard
//
#include "pch.h"
#include "d3dx12_win.h"
#include "RenderDeviceD3D12Impl.h"
#include "GenerateMips.h"
#include "CommandContext.h"
#include "TextureViewD3D12Impl.h"
#include "TextureD3D12Impl.h"
#include "GenerateMips/GenerateMipsLinearCS.h"
#include "GenerateMips/GenerateMipsLinearOddCS.h"
#include "GenerateMips/GenerateMipsLinearOddXCS.h"
#include "GenerateMips/GenerateMipsLinearOddYCS.h"
#include "GenerateMips/GenerateMipsGammaCS.h"
#include "GenerateMips/GenerateMipsGammaOddCS.h"
#include "GenerateMips/GenerateMipsGammaOddXCS.h"
#include "GenerateMips/GenerateMipsGammaOddYCS.h"
namespace Diligent
{
GenerateMipsHelper::GenerateMipsHelper(ID3D12Device *pd3d12Device)
{
CD3DX12_ROOT_PARAMETER Params[3];
Params[0].InitAsConstants(6, 0);
CD3DX12_DESCRIPTOR_RANGE SRVRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
Params[1].InitAsDescriptorTable(1, &SRVRange);
CD3DX12_DESCRIPTOR_RANGE UAVRange(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 4, 0);
Params[2].InitAsDescriptorTable(1, &UAVRange);
CD3DX12_STATIC_SAMPLER_DESC SamplerLinearClampDesc(
0, D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
CD3DX12_ROOT_SIGNATURE_DESC RootSigDesc;
RootSigDesc.NumParameters = _countof(Params);
RootSigDesc.pParameters = Params;
RootSigDesc.NumStaticSamplers = 1;
RootSigDesc.pStaticSamplers = &SamplerLinearClampDesc;
RootSigDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
CComPtr<ID3DBlob> signature;
CComPtr<ID3DBlob> error;
HRESULT hr = D3D12SerializeRootSignature(&RootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error);
hr = pd3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(m_pGenerateMipsRS), reinterpret_cast<void**>( static_cast<ID3D12RootSignature**>(&m_pGenerateMipsRS)));
CHECK_D3D_RESULT_THROW(hr, "Failed to create root signature for mipmap generation");
D3D12_COMPUTE_PIPELINE_STATE_DESC PSODesc = {};
PSODesc.pRootSignature = m_pGenerateMipsRS;
PSODesc.NodeMask = 0;
PSODesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
#define CreatePSO(PSO, ShaderByteCode) \
PSODesc.CS.pShaderBytecode = ShaderByteCode;\
PSODesc.CS.BytecodeLength = sizeof(ShaderByteCode);\
hr = pd3d12Device->CreateComputePipelineState(&PSODesc, __uuidof(PSO), reinterpret_cast<void**>( static_cast<ID3D12PipelineState**>(&PSO))); \
CHECK_D3D_RESULT_THROW(hr, "Failed to create Pipeline state for mipmap generation"); \
PSO->SetName(L"Generate mips PSO");
CreatePSO(m_pGenerateMipsLinearPSO[0], g_pGenerateMipsLinearCS);
CreatePSO(m_pGenerateMipsLinearPSO[1], g_pGenerateMipsLinearOddXCS);
CreatePSO(m_pGenerateMipsLinearPSO[2], g_pGenerateMipsLinearOddYCS);
CreatePSO(m_pGenerateMipsLinearPSO[3], g_pGenerateMipsLinearOddCS);
CreatePSO(m_pGenerateMipsGammaPSO[0], g_pGenerateMipsGammaCS);
CreatePSO(m_pGenerateMipsGammaPSO[1], g_pGenerateMipsGammaOddXCS);
CreatePSO(m_pGenerateMipsGammaPSO[2], g_pGenerateMipsGammaOddYCS);
CreatePSO(m_pGenerateMipsGammaPSO[3], g_pGenerateMipsGammaOddCS);
}
void GenerateMipsHelper::GenerateMips(ID3D12Device* pd3d12Device, TextureViewD3D12Impl* pTexView, CommandContext& Ctx)const
{
auto& ComputeCtx = Ctx.AsComputeContext();
ComputeCtx.SetRootSignature(m_pGenerateMipsRS);
auto* pTexD3D12 = pTexView->GetTexture<TextureD3D12Impl>();
const auto& TexDesc = pTexD3D12->GetDesc();
const auto& ViewDesc = pTexView->GetDesc();
bool IsAllSlices = (TexDesc.Type != RESOURCE_DIM_TEX_1D_ARRAY &&
TexDesc.Type != RESOURCE_DIM_TEX_2D_ARRAY &&
TexDesc.Type != RESOURCE_DIM_TEX_CUBE_ARRAY) ||
TexDesc.ArraySize == ViewDesc.NumArraySlices;
bool IsAllMips = ViewDesc.NumMipLevels == TexDesc.MipLevels;
auto SRVDescriptorHandle = pTexView->GetTexArraySRV();
if (!pTexD3D12->IsInKnownState())
{
LOG_ERROR_MESSAGE("Unable to generate mips for texture '", TexDesc.Name, "' because the texture state is unknown");
return;
}
if (pTexD3D12->GetState() == RESOURCE_STATE_UNDEFINED)
{
// If texture state is undefined, transition it to shader resource state.
// We need all subresources to be in a defined state at the end of the procedure.
Ctx.TransitionResource(pTexD3D12, RESOURCE_STATE_SHADER_RESOURCE);
}
const auto OriginalState = pTexD3D12->GetState();
pTexD3D12->SetState(RESOURCE_STATE_UNKNOWN); // Switch to manual state management
// If we are processing the entire texture, we will leave it in SHADER_RESOURCE layout.
// Otherwise we will transition affected subresources back to original layout.
const auto FinalState = (IsAllSlices && IsAllMips) ? RESOURCE_STATE_SHADER_RESOURCE : OriginalState;
auto BottomMip = ViewDesc.NumMipLevels - 1;
for (uint32_t TopMip = 0; TopMip < BottomMip; )
{
uint32_t SrcWidth = std::max(TexDesc.Width >> (TopMip + ViewDesc.MostDetailedMip), 1u);
uint32_t SrcHeight = std::max(TexDesc.Height >> (TopMip + ViewDesc.MostDetailedMip), 1u);
uint32_t DstWidth = std::max(SrcWidth >> 1, 1u);
uint32_t DstHeight = std::max(SrcHeight >> 1, 1u);
// Determine if the first downsample is more than 2:1. This happens whenever
// the source width or height is odd.
uint32_t NonPowerOfTwo = (SrcWidth & 1) | (SrcHeight & 1) << 1;
if (TexDesc.Format == TEX_FORMAT_RGBA8_UNORM_SRGB)
ComputeCtx.SetPipelineState(m_pGenerateMipsGammaPSO[NonPowerOfTwo]);
else
ComputeCtx.SetPipelineState(m_pGenerateMipsLinearPSO[NonPowerOfTwo]);
// We can downsample up to four times, but if the ratio between levels is not
// exactly 2:1, we have to shift our blend weights, which gets complicated or
// expensive. Maybe we can update the code later to compute sample weights for
// each successive downsample. We use _BitScanForward to count number of zeros
// in the low bits. Zeros indicate we can divide by two without truncating.
uint32_t AdditionalMips;
_BitScanForward((unsigned long*)&AdditionalMips, DstWidth | DstHeight);
uint32_t NumMips = 1 + (AdditionalMips > 3 ? 3 : AdditionalMips);
if (TopMip + NumMips > BottomMip)
NumMips = BottomMip - TopMip;
// These are clamped to 1 after computing additional mips because clamped
// dimensions should not limit us from downsampling multiple times. (E.g.
// 16x1 -> 8x1 -> 4x1 -> 2x1 -> 1x1.)
if (DstWidth == 0)
DstWidth = 1;
if (DstHeight == 0)
DstHeight = 1;
D3D12_DESCRIPTOR_HEAP_TYPE HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
auto DescriptorAlloc = Ctx.AllocateDynamicGPUVisibleDescriptor(HeapType, 5);
CommandContext::ShaderDescriptorHeaps Heaps(DescriptorAlloc.GetDescriptorHeap());
ComputeCtx.SetDescriptorHeaps(Heaps);
Ctx.GetCommandList()->SetComputeRootDescriptorTable(1, DescriptorAlloc.GetGpuHandle(0));
Ctx.GetCommandList()->SetComputeRootDescriptorTable(2, DescriptorAlloc.GetGpuHandle(1));
struct RootCBData
{
Uint32 SrcMipLevel; // Texture level of source mip
Uint32 NumMipLevels; // Number of OutMips to write: [1, 4]
Uint32 FirstArraySlice;
Uint32 Dummy;
float TexelSize[2]; // 1.0 / OutMip1.Dimensions
};
RootCBData CBData
{
TopMip, // Mip levels are relateive to the view's most detailed mip
NumMips,
0, // Array slices are relative to the view's first array slice
0,
1.0f / static_cast<float>(DstWidth), 1.0f / static_cast<float>(DstHeight)
};
Ctx.GetCommandList()->SetComputeRoot32BitConstants(0, 6, &CBData, 0);
// TODO: Shouldn't we transition top mip to shader resource state?
D3D12_CPU_DESCRIPTOR_HANDLE DstDescriptorRange = DescriptorAlloc.GetCpuHandle();
const Uint32 MaxMipsHandledByCS = 4; // Max number of mip levels processed by one CS shader invocation
UINT DstRangeSize = 1 + MaxMipsHandledByCS;
D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRanges[5] = {};
SrcDescriptorRanges[0] = SRVDescriptorHandle;
UINT SrcRangeSizes[5] = { 1,1,1,1,1 };
// On Resource Binding Tier 2 hardware, all descriptor tables of type CBV and UAV declared in the set
// Root Signature must be populated and initialized, even if the shaders do not need the descriptor.
// So we must populate all 4 slots even though we may actually process less than 4 mip levels
// Copy top mip level UAV descriptor handle to all unused slots
for (Uint32 u = 0; u < MaxMipsHandledByCS; ++u)
SrcDescriptorRanges[1 + u] = pTexView->GetMipLevelUAV(TopMip + std::min(u + 1, NumMips));
pd3d12Device->CopyDescriptors(1, &DstDescriptorRange, &DstRangeSize, 1 + MaxMipsHandledByCS, SrcDescriptorRanges, SrcRangeSizes, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
// Transition top mip level to the shader resource state
StateTransitionDesc SrcMipBarrier{pTexD3D12, TopMip == 0 ? OriginalState : RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE, false};
if (SrcMipBarrier.OldState != SrcMipBarrier.NewState)
{
SrcMipBarrier.FirstMipLevel = ViewDesc.MostDetailedMip + TopMip;
SrcMipBarrier.MipLevelsCount = 1;
SrcMipBarrier.FirstArraySlice = ViewDesc.FirstArraySlice;
SrcMipBarrier.ArraySliceCount = ViewDesc.NumArraySlices;
Ctx.TransitionResource(SrcMipBarrier);
}
// Transition dst mip levels to UAV state
StateTransitionDesc DstMipsBarrier{pTexD3D12, OriginalState, RESOURCE_STATE_UNORDERED_ACCESS, false};
if (DstMipsBarrier.OldState != DstMipsBarrier.NewState)
{
DstMipsBarrier.FirstMipLevel = ViewDesc.MostDetailedMip + TopMip + 1;
DstMipsBarrier.MipLevelsCount = NumMips;
DstMipsBarrier.FirstArraySlice = ViewDesc.FirstArraySlice;
DstMipsBarrier.ArraySliceCount = ViewDesc.NumArraySlices;
Ctx.TransitionResource(DstMipsBarrier);
}
ComputeCtx.Dispatch((DstWidth + 7) / 8, (DstHeight + 7) / 8, ViewDesc.NumArraySlices);
// Transition the lowest level back to original layout or leave it in RESOURCE_STATE_SHADER_RESOURCE
// if all subresources are processed
if (SrcMipBarrier.NewState != FinalState)
{
SrcMipBarrier.OldState = SrcMipBarrier.NewState;
SrcMipBarrier.NewState = FinalState;
Ctx.TransitionResource(SrcMipBarrier);
}
if (DstMipsBarrier.NewState != FinalState)
{
DstMipsBarrier.OldState = DstMipsBarrier.NewState;
DstMipsBarrier.NewState = FinalState;
// Do not transition the bottom level if we have more mips to process
if (TopMip + NumMips < BottomMip)
--DstMipsBarrier.MipLevelsCount;
if (DstMipsBarrier.MipLevelsCount > 0)
Ctx.TransitionResource(DstMipsBarrier);
}
TopMip += NumMips;
}
// Set state
pTexD3D12->SetState(FinalState);
}
}
|
#include <algorithm>
#include <betterchain/chain/apply_context.hpp>
#include <betterchain/chain/chain_controller.hpp>
#include <betterchain/chain/wasm_interface.hpp>
#include <betterchain/chain/generated_transaction_object.hpp>
#include <betterchain/chain/scope_sequence_object.hpp>
#include <boost/container/flat_set.hpp>
using boost::container::flat_set;
namespace betterchain { namespace chain {
void apply_context::exec_one()
{
try {
auto native = mutable_controller.find_apply_handler(receiver, act.account, act.name);
if (native) {
(*native)(*this);
} else {
const auto &a = mutable_controller.get_database().get<account_object, by_name>(receiver);
if (a.code.size() > 0) {
// get code from cache
auto code = mutable_controller.get_wasm_cache().checkout_scoped(a.code_version, a.code.data(),
a.code.size());
// get wasm_interface
auto &wasm = wasm_interface::get();
wasm.apply(code, *this);
}
}
} FC_CAPTURE_AND_RETHROW((_pending_console_output.str()));
if (!_write_scopes.empty()) {
std::sort(_write_scopes.begin(), _write_scopes.end());
}
if (!_read_locks.empty()) {
std::sort(_read_locks.begin(), _read_locks.end());
// remove any write_scopes
auto r_iter = _read_locks.begin();
for( auto w_iter = _write_scopes.cbegin(); (w_iter != _write_scopes.cend()) && (r_iter != _read_locks.end()); ++w_iter) {
shard_lock w_lock = {receiver, *w_iter};
while(r_iter != _read_locks.end() && *r_iter < w_lock ) {
++r_iter;
}
if (*r_iter == w_lock) {
r_iter = _read_locks.erase(r_iter);
}
}
}
// create a receipt for this
vector<data_access_info> data_access;
data_access.reserve(_write_scopes.size() + _read_locks.size());
for (const auto& scope: _write_scopes) {
auto key = boost::make_tuple(scope, receiver);
const auto& scope_sequence = mutable_controller.get_database().find<scope_sequence_object, by_scope_receiver>(key);
if (scope_sequence == nullptr) {
try {
mutable_controller.get_mutable_database().create<scope_sequence_object>([&](scope_sequence_object &ss) {
ss.scope = scope;
ss.receiver = receiver;
ss.sequence = 1;
});
} FC_CAPTURE_AND_RETHROW((scope)(receiver));
data_access.emplace_back(data_access_info{data_access_info::write, scope, 0});
} else {
data_access.emplace_back(data_access_info{data_access_info::write, scope, scope_sequence->sequence});
try {
mutable_controller.get_mutable_database().modify(*scope_sequence, [&](scope_sequence_object& ss) {
ss.sequence += 1;
});
} FC_CAPTURE_AND_RETHROW((scope)(receiver));
}
}
for (const auto& lock: _read_locks) {
auto key = boost::make_tuple(lock.scope, lock.account);
const auto& scope_sequence = mutable_controller.get_database().find<scope_sequence_object, by_scope_receiver>(key);
if (scope_sequence == nullptr) {
data_access.emplace_back(data_access_info{data_access_info::read, lock.scope, 0});
} else {
data_access.emplace_back(data_access_info{data_access_info::read, lock.scope, scope_sequence->sequence});
}
}
results.applied_actions.emplace_back(action_trace {receiver, act, _pending_console_output.str(), 0, 0, move(data_access)});
_pending_console_output = std::ostringstream();
_read_locks.clear();
_write_scopes.clear();
}
void apply_context::exec()
{
_notified.push_back(act.account);
for( uint32_t i = 0; i < _notified.size(); ++i ) {
receiver = _notified[i];
exec_one();
}
for( uint32_t i = 0; i < _inline_actions.size(); ++i ) {
apply_context ncontext( mutable_controller, mutable_db, _inline_actions[i], trx_meta);
ncontext.exec();
append_results(move(ncontext.results));
}
} /// exec()
void apply_context::require_authorization( const account_name& account )const {
for( const auto& auth : act.authorization )
if( auth.actor == account ) return;
BETTERCHAIN_ASSERT( false, tx_missing_auth, "missing authority of ${account}", ("account",account));
}
void apply_context::require_authorization(const account_name& account,
const permission_name& permission)const {
for( const auto& auth : act.authorization )
if( auth.actor == account ) {
if( auth.permission == permission ) return;
}
BETTERCHAIN_ASSERT( false, tx_missing_auth, "missing authority of ${account}/${permission}",
("account",account)("permission",permission) );
}
static bool scopes_contain(const vector<scope_name>& scopes, const scope_name& scope) {
return std::find(scopes.begin(), scopes.end(), scope) != scopes.end();
}
static bool locks_contain(const vector<shard_lock>& locks, const account_name& account, const scope_name& scope) {
return std::find(locks.begin(), locks.end(), shard_lock{account, scope}) != locks.end();
}
void apply_context::require_write_lock(const scope_name& scope) {
if (trx_meta.allowed_write_locks) {
BETTERCHAIN_ASSERT( locks_contain(**trx_meta.allowed_write_locks, receiver, scope), block_lock_exception, "write lock \"${a}::${s}\" required but not provided", ("a", receiver)("s",scope) );
}
if (!scopes_contain(_write_scopes, scope)) {
_write_scopes.emplace_back(scope);
}
}
void apply_context::require_read_lock(const account_name& account, const scope_name& scope) {
if (trx_meta.allowed_read_locks || trx_meta.allowed_write_locks ) {
bool locked_for_read = trx_meta.allowed_read_locks && locks_contain(**trx_meta.allowed_read_locks, account, scope);
if (!locked_for_read && trx_meta.allowed_write_locks) {
locked_for_read = locks_contain(**trx_meta.allowed_write_locks, account, scope);
}
BETTERCHAIN_ASSERT( locked_for_read , block_lock_exception, "read lock \"${a}::${s}\" required but not provided", ("a", account)("s",scope) );
}
if (!locks_contain(_read_locks, account, scope)) {
_read_locks.emplace_back(shard_lock{account, scope});
}
}
bool apply_context::has_recipient( account_name code )const {
for( auto a : _notified )
if( a == code )
return true;
return false;
}
void apply_context::require_recipient( account_name code ) {
if( !has_recipient(code) )
_notified.push_back(code);
}
void apply_context::execute_inline( action &&a ) {
// todo: rethink this special case
if (receiver != config::system_account_name) {
controller.check_authorization({a}, flat_set<public_key_type>(), false, {receiver});
}
_inline_actions.emplace_back( move(a) );
}
void apply_context::execute_deferred( deferred_transaction&& trx ) {
try {
FC_ASSERT( trx.expiration > (controller.head_block_time() + fc::milliseconds(2*config::block_interval_ms)),
"transaction is expired when created" );
FC_ASSERT( trx.execute_after < trx.expiration, "transaction expires before it can execute" );
/// TODO: make default_max_gen_trx_count a producer parameter
FC_ASSERT( results.generated_transactions.size() < config::default_max_gen_trx_count );
FC_ASSERT( !trx.actions.empty(), "transaction must have at least one action");
// todo: rethink this special case
if (receiver != config::system_account_name) {
controller.check_authorization(trx.actions, flat_set<public_key_type>(), false, {receiver});
}
trx.sender = receiver; // "Attempting to send from another account"
trx.set_reference_block(controller.head_block_id());
/// TODO: make sure there isn't already a deferred transaction with this ID or senderID?
results.generated_transactions.emplace_back(move(trx));
} FC_CAPTURE_AND_RETHROW((trx));
}
void apply_context::cancel_deferred( uint32_t sender_id ) {
results.canceled_deferred.emplace_back(receiver, sender_id);
}
const contracts::table_id_object* apply_context::find_table( name scope, name code, name table ) {
require_read_lock(code, scope);
return db.find<table_id_object, contracts::by_scope_code_table>(boost::make_tuple(scope, code, table));
}
const contracts::table_id_object& apply_context::find_or_create_table( name scope, name code, name table ) {
require_read_lock(code, scope);
const auto* existing_tid = db.find<contracts::table_id_object, contracts::by_scope_code_table>(boost::make_tuple(scope, code, table));
if (existing_tid != nullptr) {
return *existing_tid;
}
require_write_lock(scope);
return mutable_db.create<contracts::table_id_object>([&](contracts::table_id_object &t_id){
t_id.scope = scope;
t_id.code = code;
t_id.table = table;
});
}
vector<account_name> apply_context::get_active_producers() const {
const auto& gpo = controller.get_global_properties();
vector<account_name> accounts;
for(const auto& producer : gpo.active_producers.producers)
accounts.push_back(producer.producer_name);
return accounts;
}
} } /// betterchain::chain
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "tinyformat.h"
#include "util.h"
#include <assert.h>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::REGTEST = "regtest";
void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp)
{
strUsage += HelpMessageGroup(_("Chain selection options:"));
strUsage += HelpMessageOpt("-testnet", _("Use the test chain"));
if (debugHelp) {
strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
"This is intended for regression testing tools and app development.");
}
}
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
nRPCPort = 6797;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseChainParams
{
public:
CBaseTestNetParams()
{
nRPCPort = 16797;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseChainParams
{
public:
CBaseRegTestParams()
{
nRPCPort = 26797;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
CBaseChainParams& BaseParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return mainParams;
else if (chain == CBaseChainParams::TESTNET)
return testNetParams;
else if (chain == CBaseChainParams::REGTEST)
return regTestParams;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectBaseParams(const std::string& chain)
{
pCurrentBaseParams = &BaseParams(chain);
}
std::string ChainNameFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
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 AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
///@file ReportFieldGeometryMeasures.cc
///
///@author
/// David Weinstein
/// Department of Computer Science
/// University of Utah
///@date March 2001
#include <Modules/Legacy/Fields/ReportFieldGeometryMeasures.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Algorithms/Legacy/Fields/RegisterWithCorrespondences.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/GeometryPrimitives/Vector.h>
using namespace SCIRun;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Modules::Fields;
/// @class ReportFieldGeometryMeasures
/// @brief Build a densematrix, where each row is a particular measure of the
/// input Field (e.g. the x-values, or the element size).
MODULE_INFO_DEF(ReportFieldGeometryMeasures, MiscField, SCIRun)
ALGORITHM_PARAMETER_DEF(Fields, MeasureLocation);
ALGORITHM_PARAMETER_DEF(Fields, XPositionFlag);
ALGORITHM_PARAMETER_DEF(Fields, YPositionFlag);
ALGORITHM_PARAMETER_DEF(Fields, ZPositionFlag);
ALGORITHM_PARAMETER_DEF(Fields, IndexFlag);
ALGORITHM_PARAMETER_DEF(Fields, SizeFlag);
ALGORITHM_PARAMETER_DEF(Fields, NormalsFlag);
ReportFieldGeometryMeasures::ReportFieldGeometryMeasures() : Module(staticInfo_)
{
INITIALIZE_PORT(InputField);
INITIALIZE_PORT(Output_Measures);
}
void ReportFieldGeometryMeasures::setStateDefaults()
{
auto state = get_state();
state->setValue(Parameters::MeasureLocation, std::string("Nodes"));
state->setValue(Parameters::XPositionFlag, true);
state->setValue(Parameters::YPositionFlag, true);
state->setValue(Parameters::ZPositionFlag, true);
state->setValue(Parameters::IndexFlag, false);
state->setValue(Parameters::SizeFlag, false);
state->setValue(Parameters::NormalsFlag, false);
}
void ReportFieldGeometryMeasures::execute()
{
auto fieldhandle = getRequiredInput(InputField);
auto state = get_state();
VMesh* mesh = fieldhandle->vmesh();
/// This is a hack for now, it is definitely not an optimal way
int syncflag = 0;
std::string simplex = state->getValue(Parameters::MeasureLocation).toString();
if (simplex == "Elements")
{
if (mesh->dimensionality() == 0) simplex = "Node";
else if (mesh->dimensionality() == 1) simplex = "Edge";
else if (mesh->dimensionality() == 2) simplex = "Face";
else if (mesh->dimensionality() == 3) simplex = "Cell";
}
if (simplex == "Nodes")
syncflag = Mesh::NODES_E | Mesh::NODE_NEIGHBORS_E;
else if (simplex == "Edges")
syncflag = Mesh::EDGES_E | Mesh::ELEM_NEIGHBORS_E;
else if (simplex == "Faces")
syncflag = Mesh::FACES_E | Mesh::ELEM_NEIGHBORS_E;
else if (simplex == "Cells")
syncflag = Mesh::CELLS_E;
mesh->synchronize(syncflag);
const bool normalsFlag = state->getValue(Parameters::NormalsFlag).toBool();
bool nnormals = normalsFlag && (state->getValue(Parameters::MeasureLocation).toString() == "Nodes");
bool fnormals = normalsFlag && (state->getValue(Parameters::MeasureLocation).toString() == "Faces");
if (nnormals && !mesh->has_normals())
{
warning("This mesh type does not contain normals, skipping.");
nnormals = false;
}
else if (fnormals && !mesh->has_normals())
{
warning("This mesh type does not contain normals, skipping.");
fnormals = false;
}
else if (normalsFlag && !(nnormals || fnormals))
{
warning("Cannot compute normals at that simplex location, skipping.");
}
if (nnormals || fnormals)
{
mesh->synchronize(Mesh::NORMALS_E);
}
const bool x = state->getValue(Parameters::XPositionFlag).toBool();
const bool y = state->getValue(Parameters::YPositionFlag).toBool();
const bool z = state->getValue(Parameters::ZPositionFlag).toBool();
const bool eidx = state->getValue(Parameters::IndexFlag).toBool();
const bool size = state->getValue(Parameters::SizeFlag).toBool();
size_type ncols=0;
if (x) ncols++;
if (y) ncols++;
if (z) ncols++;
if (eidx) ncols++;
if (size) ncols++;
if (nnormals) ncols+=3;
if (fnormals) ncols+=3;
if (ncols==0)
{
error("No measures selected.");
return;
}
DenseMatrixHandle output;
if (state->getValue(Parameters::MeasureLocation).toString() == "Nodes")
{
VMesh::Node::size_type nrows;
mesh->size(nrows);
output.reset(new DenseMatrix(nrows,ncols));
double* dataptr = output->data();
Point p; double vol;
for(VMesh::Node::index_type idx=0; idx<nrows; idx++)
{
mesh->get_center(p,idx);
vol = mesh->get_size(idx);
if (x) { *dataptr = p.x(); dataptr++; }
if (y) { *dataptr = p.y(); dataptr++; }
if (z) { *dataptr = p.z(); dataptr++; }
if (eidx) { *dataptr = static_cast<double>(idx); dataptr++; }
if (size) { *dataptr = vol; dataptr++; }
if (nnormals)
{
Vector v; mesh->get_normal(v,idx);
dataptr[0] = v.x(); dataptr[1] = v.y();
dataptr[2] = v.z(); dataptr += 3;
}
}
}
else if (state->getValue(Parameters::MeasureLocation).toString() == "Edges")
{
VMesh::Edge::size_type nrows;
mesh->size(nrows);
output.reset(new DenseMatrix(nrows, ncols));
double* dataptr = output->data();
Point p; double vol;
for(VMesh::Edge::index_type idx=0; idx<nrows; idx++)
{
mesh->get_center(p,idx);
vol = mesh->get_size(idx);
if (x) { *dataptr = p.x(); dataptr++; }
if (y) { *dataptr = p.y(); dataptr++; }
if (z) { *dataptr = p.z(); dataptr++; }
if (eidx) { *dataptr = static_cast<double>(idx); dataptr++; }
if (size) { *dataptr = vol; dataptr++; }
}
}
else if (state->getValue(Parameters::MeasureLocation).toString() == "Faces")
{
VMesh::Face::size_type nrows;
mesh->size(nrows);
output.reset(new DenseMatrix(nrows, ncols));
double* dataptr = output->data();
Point p; double vol;
VMesh::coords_type center;
mesh->get_element_center(center);
for(VMesh::Face::index_type idx=0; idx<nrows; idx++)
{
mesh->get_center(p,idx);
vol = mesh->get_size(idx);
if (x) { *dataptr = p.x(); dataptr++; }
if (y) { *dataptr = p.y(); dataptr++; }
if (z) { *dataptr = p.z(); dataptr++; }
if (eidx) { *dataptr = static_cast<double>(idx); dataptr++; }
if (size) { *dataptr = vol; dataptr++; }
if (fnormals)
{
Vector v; mesh->get_normal(v,center,VMesh::Elem::index_type(idx));
dataptr[0] = v.x(); dataptr[1] = v.y();
dataptr[2] =v.z(); dataptr += 3;
}
}
}
else if (state->getValue(Parameters::MeasureLocation).toString() == "Cells")
{
VMesh::Cell::size_type nrows;
mesh->size(nrows);
output.reset(new DenseMatrix(nrows, ncols));
double* dataptr = output->data();
Point p; double vol;
for(VMesh::Cell::index_type idx=0; idx<nrows; idx++)
{
mesh->get_center(p,idx);
vol = mesh->get_size(idx);
if (x) { *dataptr = p.x(); dataptr++; }
if (y) { *dataptr = p.y(); dataptr++; }
if (z) { *dataptr = p.z(); dataptr++; }
if (eidx) { *dataptr = static_cast<double>(idx); dataptr++; }
if (size) { *dataptr = vol; dataptr++; }
}
}
if (output && output->nrows() == 0)
{
warning("No measures added to matrix--output will be an empty matrix with zero rows.");
}
sendOutput(Output_Measures, output);
}
|
/****************************
Copyright © 2006-2015 Luke Salisbury
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
****************************/
#include "audio.h"
#include "engine.h"
#include "game_config.h"
#include "elix/elix_string.hpp"
#include "mokoi_game.h"
#include "core.h"
void Lux_Audio_DialogEnded()
{
lux::audio->StopDialog();
}
AudioSystem::AudioSystem()
{
enabled = lux::config->GetBoolean("audio.able");
if ( enabled )
{
lux::screen::display("Loading Audio System");
this->paused = false;
this->music = NULL;
this->bits = 0;
this->buffers = 512;
this->frequency = 22050;
this->outformat = MIX_DEFAULT_FORMAT;
this->channels = 2;
Mix_OpenAudio(this->frequency, this->outformat, this->channels, this->buffers);
Mix_QuerySpec(&this->frequency, &this->outformat, &this->channels);
this->bits = this->outformat&0xFF;
lux::core->SystemMessage(SYSTEM_MESSAGE_LOG) << "Audio System: " << this->frequency << "Hz " << this->bits << " bit " << ( this->channels > 1 ? "stereo" : "mono" ) << " - Buffer Size: " << this->buffers << " bytes." << std::endl;
std::string buffer;
std::stringstream audiolist_file;
if ( lux::game_data->GetStream( "./preload/audio.txt", &audiolist_file ) )
{
do
{
std::getline( audiolist_file, buffer );
elix::string::Trim(&buffer);
if ( !buffer.empty() )
{
lux::screen::display("Loading Audio: " + buffer);
this->LoadAudio("./soundfx/" + buffer);
}
} while ( !audiolist_file.eof() );
audiolist_file.clear();
}
}
}
AudioSystem::~AudioSystem ( )
{
if ( enabled )
{
this->soundfx.clear();
Mix_CloseAudio();
}
}
bool AudioSystem::Loop(LuxState engine_state)
{
return true;
}
bool AudioSystem::LoadAudio(std::string filename)
{
if ( !enabled )
return false;
uint8_t * data = NULL;
uint32_t size;
size = lux::game_data->GetFile(filename, &data, false);
if ( size )
{
SDL_RWops * src = SDL_RWFromMem(data, size);
if ( src )
{
this->soundfx[filename] = Mix_LoadWAV_RW(src, 1);
return true;
}
}
return false;
}
Mix_Chunk * AudioSystem::ReturnAudio(std::string filename)
{
if ( !enabled )
return NULL;
uint8_t * data = NULL;
uint32_t size;
size = lux::game_data->GetFile(filename, &data, false);
if ( size )
{
SDL_RWops * src = SDL_RWFromMem(data, size);
if ( src )
{
Mix_Chunk * audio = Mix_LoadWAV_RW(src, 1);
this->soundfx[filename] = audio;
return audio;
}
}
return NULL;
}
int32_t AudioSystem::PlayEffect ( std::string requestSound, int32_t x, int32_t y )
{
if ( !enabled )
return 0;
Mix_Chunk * sample = this->FindEffect( "./soundfx/" + requestSound);
if ( sample == NULL )
sample = this->ReturnAudio("./soundfx/" +requestSound);
if ( sample )
{
uint32_t len = this->EffectLength( sample );
int chan = Mix_PlayChannel(-1, sample, 0);
if ( chan == -1 )
{
lux::core->SystemMessage(__FILE__ , __LINE__, SYSTEM_MESSAGE_ERROR) << " | PlayEffect: " << Mix_GetError() << std::endl;
return 0;
}
else
{
//Mix_SetDistance(chan, 0);//to do.
//Mix_SetPosition(chan, Sint16 angle, Uint8 distance);
}
return (int32_t)len;
}
lux::core->SystemMessage(SYSTEM_MESSAGE_ERROR) << requestSound << " not found" << std::endl;
return 0;
}
void AudioSystem::StopDialog()
{
if ( !enabled )
return;
/* Mix_FreeMusic should also free up SDL_RWops */
Mix_FreeMusic( this->dialog );
this->dialog = NULL;
if ( this->music )
{
/* Restart Music */
Mix_PlayMusic(this->music, -1);
Mix_HookMusicFinished(NULL);
}
}
int32_t AudioSystem::PlayDialog( int32_t requestSound )
{
if ( !enabled )
return 0;
std::ostringstream filename("");
filename << "./dialog/en." << requestSound << ".ogg" ;
uint8_t * data = NULL;
uint32_t size;
size = lux::game_data->GetFile(filename.str(), &data, false);
if ( size )
{
SDL_RWops * src = SDL_RWFromMem(data, size);
if ( src )
{
this->dialog = Mix_LoadMUS_RW(src);
if ( Mix_PlayMusic(this->dialog, 1) == -1 )
{
lux::core->SystemMessage(__FILE__ , __LINE__, SYSTEM_MESSAGE_ERROR) << " | PlayDialog: " << Mix_GetError() << std::endl;
return 0;
}
Mix_HookMusicFinished( &Lux_Audio_DialogEnded );
return 1;
}
}
return 0;
}
int32_t AudioSystem::PlayMusic ( std::string requestMusic, int32_t loop, int32_t fadeLength )
{
if ( !enabled )
return 0;
uint8_t * data = NULL;
uint32_t size;
size = lux::game_data->GetFile("./music/" + requestMusic, &data, false);
if ( size )
{
SDL_RWops * src = SDL_RWFromMem(data, size);
if ( src )
{
if ( this->music )
{
Mix_FreeMusic( this->music );
this->music = NULL;
}
this->music = Mix_LoadMUS_RW( src );
if ( !this->music )
{
lux::core->SystemMessage(__FILE__ , __LINE__, SYSTEM_MESSAGE_ERROR) << " | PlayMusic: '" << requestMusic << "' " << Mix_GetError() << std::endl;
}
if ( Mix_FadeInMusic( this->music, loop, fadeLength ) == -1 )
{
lux::core->SystemMessage(__FILE__ , __LINE__, SYSTEM_MESSAGE_ERROR) << " | PlayMusic: '" << requestMusic << "' " << Mix_GetError() << std::endl;
return 0;
}
return 1;
}
}
lux::core->SystemMessage(__FILE__ , __LINE__, SYSTEM_MESSAGE_ERROR) << " | PlayMusic Error: '" << requestMusic << "' " << std::endl;
return 0;
}
int32_t AudioSystem::SetMusicVolume(int32_t volume)
{
if ( !enabled )
return 0;
return Mix_VolumeMusic(volume);
}
int32_t AudioSystem::SetEffectsVolume(int32_t volume)
{
if ( !enabled )
return 0;
return Mix_Volume(-1, volume);
}
void AudioSystem::Pause()
{
if ( !enabled )
return;
if ( this->paused )
{
Mix_ResumeMusic();
Mix_Resume(-1);
this->paused = false;
}
else
{
Mix_PauseMusic();
Mix_Pause(-1);
this->paused = true;
}
}
Mix_Chunk * AudioSystem::FindEffect(std::string name)
{
std::map<std::string,Mix_Chunk*>::iterator p;
p = this->soundfx.find(name);
if (p != this->soundfx.end())
{
return p->second;
}
return NULL;
}
uint32_t AudioSystem::EffectLength( Mix_Chunk * chunk )
{
uint32_t points = 0;
uint32_t frames = 0;
int freq = 0;
uint16_t fmt = 0;
int chans = 0;
/* Chunks are converted to audio device format... */
if ( !Mix_QuerySpec(&freq, &fmt, &chans) )
return 0; /* never called Mix_OpenAudio()?! */
/* bytes / samplesize == sample points */
points = (chunk->alen / ((fmt & 0xFF) / 8));
/* sample points / channels == sample frames */
frames = (points / chans);
/* (sample frames * 1000) / frequency == play length in ms */
return (frames * 1000) / freq;
}
|
/**
* @file <argos3/plugins/simulator/entities/wifi_equipped_entity.cpp>
*
* @author Carlo Pinciroli - <ilpincy@gmail.com>
*/
#include "wifi_equipped_entity.h"
#include <argos3/core/simulator/space/space.h>
namespace argos {
/****************************************/
/****************************************/
CWiFiEquippedEntity::CWiFiEquippedEntity(CComposableEntity* pc_parent) :
CEntity(pc_parent) {
Disable();
}
/****************************************/
/****************************************/
CWiFiEquippedEntity::CWiFiEquippedEntity(CComposableEntity* pc_parent,
const std::string& str_id) :
CEntity(pc_parent, str_id) {
Disable();
}
/****************************************/
/****************************************/
REGISTER_STANDARD_SPACE_OPERATIONS_ON_ENTITY(CWiFiEquippedEntity);
/****************************************/
/****************************************/
}
|
// Copyright (c) 2015 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "winpty_wcsnlen.h"
#include "WinptyAssert.h"
// Workaround. MinGW (from mingw.org) does not have wcsnlen. MinGW-w64 *does*
// have wcsnlen, but use this function for consistency.
size_t winpty_wcsnlen(const wchar_t *s, size_t maxlen) {
ASSERT(s != NULL);
for (size_t i = 0; i < maxlen; ++i) {
if (s[i] == L'\0') {
return i;
}
}
return maxlen;
}
|
#include "utils.hpp"
#include <iostream>
namespace utils {
std::string boolToString(bool b) {
if (b) {
return "True";
}
else {
return "False";
}
}
}
|
// Copyright 2014 BitPay, Inc.
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include <univalue.h>
#include "test/test_rapture.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(univalue_constructor)
{
UniValue v1;
BOOST_CHECK(v1.isNull());
UniValue v2(UniValue::VSTR);
BOOST_CHECK(v2.isStr());
UniValue v3(UniValue::VSTR, "foo");
BOOST_CHECK(v3.isStr());
BOOST_CHECK_EQUAL(v3.getValStr(), "foo");
UniValue numTest;
BOOST_CHECK(numTest.setNumStr("82"));
BOOST_CHECK(numTest.isNum());
BOOST_CHECK_EQUAL(numTest.getValStr(), "82");
uint64_t vu64 = 82;
UniValue v4(vu64);
BOOST_CHECK(v4.isNum());
BOOST_CHECK_EQUAL(v4.getValStr(), "82");
int64_t vi64 = -82;
UniValue v5(vi64);
BOOST_CHECK(v5.isNum());
BOOST_CHECK_EQUAL(v5.getValStr(), "-82");
int vi = -688;
UniValue v6(vi);
BOOST_CHECK(v6.isNum());
BOOST_CHECK_EQUAL(v6.getValStr(), "-688");
double vd = -7.21;
UniValue v7(vd);
BOOST_CHECK(v7.isNum());
BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21");
string vs("yawn");
UniValue v8(vs);
BOOST_CHECK(v8.isStr());
BOOST_CHECK_EQUAL(v8.getValStr(), "yawn");
const char *vcs = "zappa";
UniValue v9(vcs);
BOOST_CHECK(v9.isStr());
BOOST_CHECK_EQUAL(v9.getValStr(), "zappa");
}
BOOST_AUTO_TEST_CASE(univalue_typecheck)
{
UniValue v1;
BOOST_CHECK(v1.setNumStr("1"));
BOOST_CHECK(v1.isNum());
BOOST_CHECK_THROW(v1.get_bool(), runtime_error);
UniValue v2;
BOOST_CHECK(v2.setBool(true));
BOOST_CHECK_EQUAL(v2.get_bool(), true);
BOOST_CHECK_THROW(v2.get_int(), runtime_error);
UniValue v3;
BOOST_CHECK(v3.setNumStr("32482348723847471234"));
BOOST_CHECK_THROW(v3.get_int64(), runtime_error);
BOOST_CHECK(v3.setNumStr("1000"));
BOOST_CHECK_EQUAL(v3.get_int64(), 1000);
UniValue v4;
BOOST_CHECK(v4.setNumStr("2147483648"));
BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648ULL);
BOOST_CHECK_THROW(v4.get_int(), runtime_error);
BOOST_CHECK(v4.setNumStr("1000"));
BOOST_CHECK_EQUAL(v4.get_int(), 1000);
BOOST_CHECK_THROW(v4.get_str(), runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 1000);
BOOST_CHECK_THROW(v4.get_array(), runtime_error);
BOOST_CHECK_THROW(v4.getKeys(), runtime_error);
BOOST_CHECK_THROW(v4.getValues(), runtime_error);
BOOST_CHECK_THROW(v4.get_obj(), runtime_error);
UniValue v5;
BOOST_CHECK(v5.read("[true, 10]"));
BOOST_CHECK_NO_THROW(v5.get_array());
std::vector<UniValue> vals = v5.getValues();
BOOST_CHECK_THROW(vals[0].get_int(), runtime_error);
BOOST_CHECK_EQUAL(vals[0].get_bool(), true);
BOOST_CHECK_EQUAL(vals[1].get_int(), 10);
BOOST_CHECK_THROW(vals[1].get_bool(), runtime_error);
}
BOOST_AUTO_TEST_CASE(univalue_set)
{
UniValue v(UniValue::VSTR, "foo");
v.clear();
BOOST_CHECK(v.isNull());
BOOST_CHECK_EQUAL(v.getValStr(), "");
BOOST_CHECK(v.setObject());
BOOST_CHECK(v.isObject());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK_EQUAL(v.getType(), UniValue::VOBJ);
BOOST_CHECK(v.empty());
BOOST_CHECK(v.setArray());
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK(v.setStr("zum"));
BOOST_CHECK(v.isStr());
BOOST_CHECK_EQUAL(v.getValStr(), "zum");
BOOST_CHECK(v.setFloat(-1.01));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1.01");
BOOST_CHECK(v.setInt((int)1023));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setInt((int64_t)-1023LL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1023");
BOOST_CHECK(v.setInt((uint64_t)1023ULL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setNumStr("-688"));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-688");
BOOST_CHECK(v.setBool(false));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), false);
BOOST_CHECK_EQUAL(v.isFalse(), true);
BOOST_CHECK_EQUAL(v.getBool(), false);
BOOST_CHECK(v.setBool(true));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), true);
BOOST_CHECK_EQUAL(v.isFalse(), false);
BOOST_CHECK_EQUAL(v.getBool(), true);
BOOST_CHECK(!v.setNumStr("zombocom"));
BOOST_CHECK(v.setNull());
BOOST_CHECK(v.isNull());
}
BOOST_AUTO_TEST_CASE(univalue_array)
{
UniValue arr(UniValue::VARR);
UniValue v((int64_t)1023LL);
BOOST_CHECK(arr.push_back(v));
string vStr("zippy");
BOOST_CHECK(arr.push_back(vStr));
const char *s = "pippy";
BOOST_CHECK(arr.push_back(s));
vector<UniValue> vec;
v.setStr("boing");
vec.push_back(v);
v.setStr("going");
vec.push_back(v);
BOOST_CHECK(arr.push_backV(vec));
BOOST_CHECK_EQUAL(arr.empty(), false);
BOOST_CHECK_EQUAL(arr.size(), 5);
BOOST_CHECK_EQUAL(arr[0].getValStr(), "1023");
BOOST_CHECK_EQUAL(arr[1].getValStr(), "zippy");
BOOST_CHECK_EQUAL(arr[2].getValStr(), "pippy");
BOOST_CHECK_EQUAL(arr[3].getValStr(), "boing");
BOOST_CHECK_EQUAL(arr[4].getValStr(), "going");
BOOST_CHECK_EQUAL(arr[999].getValStr(), "");
arr.clear();
BOOST_CHECK(arr.empty());
BOOST_CHECK_EQUAL(arr.size(), 0);
}
BOOST_AUTO_TEST_CASE(univalue_object)
{
UniValue obj(UniValue::VOBJ);
string strKey, strVal;
UniValue v;
strKey = "age";
v.setInt(100);
BOOST_CHECK(obj.pushKV(strKey, v));
strKey = "first";
strVal = "John";
BOOST_CHECK(obj.pushKV(strKey, strVal));
strKey = "last";
const char *cVal = "Smith";
BOOST_CHECK(obj.pushKV(strKey, cVal));
strKey = "distance";
BOOST_CHECK(obj.pushKV(strKey, (int64_t) 25));
strKey = "time";
BOOST_CHECK(obj.pushKV(strKey, (uint64_t) 3600));
strKey = "calories";
BOOST_CHECK(obj.pushKV(strKey, (int) 12));
strKey = "temperature";
BOOST_CHECK(obj.pushKV(strKey, (double) 90.012));
UniValue obj2(UniValue::VOBJ);
BOOST_CHECK(obj2.pushKV("cat1", 9000));
BOOST_CHECK(obj2.pushKV("cat2", 12345));
BOOST_CHECK(obj.pushKVs(obj2));
BOOST_CHECK_EQUAL(obj.empty(), false);
BOOST_CHECK_EQUAL(obj.size(), 9);
BOOST_CHECK_EQUAL(obj["age"].getValStr(), "100");
BOOST_CHECK_EQUAL(obj["first"].getValStr(), "John");
BOOST_CHECK_EQUAL(obj["last"].getValStr(), "Smith");
BOOST_CHECK_EQUAL(obj["distance"].getValStr(), "25");
BOOST_CHECK_EQUAL(obj["time"].getValStr(), "3600");
BOOST_CHECK_EQUAL(obj["calories"].getValStr(), "12");
BOOST_CHECK_EQUAL(obj["temperature"].getValStr(), "90.012");
BOOST_CHECK_EQUAL(obj["cat1"].getValStr(), "9000");
BOOST_CHECK_EQUAL(obj["cat2"].getValStr(), "12345");
BOOST_CHECK_EQUAL(obj["nyuknyuknyuk"].getValStr(), "");
BOOST_CHECK(obj.exists("age"));
BOOST_CHECK(obj.exists("first"));
BOOST_CHECK(obj.exists("last"));
BOOST_CHECK(obj.exists("distance"));
BOOST_CHECK(obj.exists("time"));
BOOST_CHECK(obj.exists("calories"));
BOOST_CHECK(obj.exists("temperature"));
BOOST_CHECK(obj.exists("cat1"));
BOOST_CHECK(obj.exists("cat2"));
BOOST_CHECK(!obj.exists("nyuknyuknyuk"));
map<string, UniValue::VType> objTypes;
objTypes["age"] = UniValue::VNUM;
objTypes["first"] = UniValue::VSTR;
objTypes["last"] = UniValue::VSTR;
objTypes["distance"] = UniValue::VNUM;
objTypes["time"] = UniValue::VNUM;
objTypes["calories"] = UniValue::VNUM;
objTypes["temperature"] = UniValue::VNUM;
objTypes["cat1"] = UniValue::VNUM;
objTypes["cat2"] = UniValue::VNUM;
BOOST_CHECK(obj.checkObject(objTypes));
objTypes["cat2"] = UniValue::VSTR;
BOOST_CHECK(!obj.checkObject(objTypes));
obj.clear();
BOOST_CHECK(obj.empty());
BOOST_CHECK_EQUAL(obj.size(), 0);
}
static const char *json1 =
"[1.10000000,{\"key1\":\"str\\u0000\",\"key2\":800,\"key3\":{\"name\":\"martian http://test.com\"}}]";
BOOST_AUTO_TEST_CASE(univalue_readwrite)
{
UniValue v;
BOOST_CHECK(v.read(json1));
string strJson1(json1);
BOOST_CHECK(v.read(strJson1));
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 2);
BOOST_CHECK_EQUAL(v[0].getValStr(), "1.10000000");
UniValue obj = v[1];
BOOST_CHECK(obj.isObject());
BOOST_CHECK_EQUAL(obj.size(), 3);
BOOST_CHECK(obj["key1"].isStr());
std::string correctValue("str");
correctValue.push_back('\0');
BOOST_CHECK_EQUAL(obj["key1"].getValStr(), correctValue);
BOOST_CHECK(obj["key2"].isNum());
BOOST_CHECK_EQUAL(obj["key2"].getValStr(), "800");
BOOST_CHECK(obj["key3"].isObject());
BOOST_CHECK_EQUAL(strJson1, v.write());
/* Check for (correctly reporting) a parsing error if the initial
JSON construct is followed by more stuff. Note that whitespace
is, of course, exempt. */
BOOST_CHECK(v.read(" {}\n "));
BOOST_CHECK(v.isObject());
BOOST_CHECK(v.read(" []\n "));
BOOST_CHECK(v.isArray());
BOOST_CHECK(!v.read("@{}"));
BOOST_CHECK(!v.read("{} garbage"));
BOOST_CHECK(!v.read("[]{}"));
BOOST_CHECK(!v.read("{}[]"));
BOOST_CHECK(!v.read("{} 42"));
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <mathfunctions/MathFunctions.h>
#include <cmath>
namespace MathFunctions {
auto sqrt(double x) -> double { return std::sqrt(x); }
} // namespace MathFunctions
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/extensions/extension_install_checker.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
namespace {
const BlacklistState kBlacklistStateError = BLACKLISTED_MALWARE;
const char kDummyRequirementsError[] = "Requirements error";
const char kDummyPolicyError[] = "Cannot install extension";
const char kDummyPolicyError2[] = "Another policy error";
const char kDummyRequirementsError2[] = "Another requirements error";
const BlacklistState kBlacklistState2 = BLACKLISTED_SECURITY_VULNERABILITY;
} // namespace
// Stubs most of the checks since we are interested in validating the logic in
// the install checker. This class implements a synchronous version of all
// checks.
class ExtensionInstallCheckerForTest : public ExtensionInstallChecker {
public:
ExtensionInstallCheckerForTest()
: ExtensionInstallChecker(NULL),
requirements_check_called_(false),
blacklist_check_called_(false),
policy_check_called_(false),
blacklist_state_(NOT_BLACKLISTED) {}
~ExtensionInstallCheckerForTest() override {}
void set_requirements_error(const std::string& error) {
requirements_error_ = error;
}
void set_policy_check_error(const std::string& error) {
policy_check_error_ = error;
}
void set_blacklist_state(BlacklistState state) { blacklist_state_ = state; }
bool requirements_check_called() const { return requirements_check_called_; }
bool blacklist_check_called() const { return blacklist_check_called_; }
bool policy_check_called() const { return policy_check_called_; }
void MockCheckRequirements(int sequence_number) {
std::vector<std::string> errors;
if (!requirements_error_.empty())
errors.push_back(requirements_error_);
OnRequirementsCheckDone(sequence_number, errors);
}
void MockCheckBlacklistState(int sequence_number) {
OnBlacklistStateCheckDone(sequence_number, blacklist_state_);
}
protected:
void CheckRequirements() override {
requirements_check_called_ = true;
MockCheckRequirements(current_sequence_number());
}
void CheckManagementPolicy() override {
policy_check_called_ = true;
OnManagementPolicyCheckDone(policy_check_error_.empty(),
policy_check_error_);
}
void CheckBlacklistState() override {
blacklist_check_called_ = true;
MockCheckBlacklistState(current_sequence_number());
}
void ResetResults() override {
ExtensionInstallChecker::ResetResults();
requirements_check_called_ = false;
blacklist_check_called_ = false;
policy_check_called_ = false;
}
bool requirements_check_called_;
bool blacklist_check_called_;
bool policy_check_called_;
// Dummy errors for testing.
std::string requirements_error_;
std::string policy_check_error_;
BlacklistState blacklist_state_;
};
// This class implements asynchronous mocks of the requirements and blacklist
// checks.
class ExtensionInstallCheckerAsync : public ExtensionInstallCheckerForTest {
protected:
void CheckRequirements() override {
requirements_check_called_ = true;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&ExtensionInstallCheckerForTest::MockCheckRequirements,
base::Unretained(this), current_sequence_number()));
}
void CheckBlacklistState() override {
blacklist_check_called_ = true;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&ExtensionInstallCheckerForTest::MockCheckBlacklistState,
base::Unretained(this), current_sequence_number()));
}
};
class CheckObserver {
public:
CheckObserver() : result_(0), call_count_(0) {}
int result() const { return result_; }
int call_count() const { return call_count_; }
void OnChecksComplete(int checks_failed) {
result_ = checks_failed;
++call_count_;
}
void Wait() {
if (call_count_)
return;
base::RunLoop().RunUntilIdle();
}
private:
int result_;
int call_count_;
};
class ExtensionInstallCheckerTest : public testing::Test {
public:
ExtensionInstallCheckerTest() {}
~ExtensionInstallCheckerTest() override {}
void RunSecondInvocation(ExtensionInstallCheckerForTest* checker,
int checks_failed) {
EXPECT_GT(checks_failed, 0);
EXPECT_FALSE(checker->is_running());
ValidateExpectedCalls(ExtensionInstallChecker::CHECK_ALL, *checker);
// Set up different return values.
checker->set_blacklist_state(kBlacklistState2);
checker->set_policy_check_error(kDummyPolicyError2);
checker->set_requirements_error(kDummyRequirementsError2);
// Run the install checker again and ensure the second set of return values
// is received.
checker->Start(
ExtensionInstallChecker::CHECK_ALL,
false /* fail fast */,
base::Bind(&ExtensionInstallCheckerTest::ValidateSecondInvocation,
base::Unretained(this),
checker));
}
void ValidateSecondInvocation(ExtensionInstallCheckerForTest* checker,
int checks_failed) {
EXPECT_FALSE(checker->is_running());
EXPECT_EQ(ExtensionInstallChecker::CHECK_REQUIREMENTS |
ExtensionInstallChecker::CHECK_MANAGEMENT_POLICY,
checks_failed);
ValidateExpectedCalls(ExtensionInstallChecker::CHECK_ALL, *checker);
EXPECT_EQ(kBlacklistState2, checker->blacklist_state());
ExpectPolicyError(kDummyPolicyError2, *checker);
ExpectRequirementsError(kDummyRequirementsError2, *checker);
}
protected:
void SetAllErrors(ExtensionInstallCheckerForTest* checker) {
checker->set_blacklist_state(kBlacklistStateError);
checker->set_policy_check_error(kDummyPolicyError);
checker->set_requirements_error(kDummyRequirementsError);
}
void ValidateExpectedCalls(int call_mask,
const ExtensionInstallCheckerForTest& checker) {
bool expect_blacklist_checked =
(call_mask & ExtensionInstallChecker::CHECK_BLACKLIST) != 0;
bool expect_requirements_checked =
(call_mask & ExtensionInstallChecker::CHECK_REQUIREMENTS) != 0;
bool expect_policy_checked =
(call_mask & ExtensionInstallChecker::CHECK_MANAGEMENT_POLICY) != 0;
EXPECT_EQ(expect_blacklist_checked, checker.blacklist_check_called());
EXPECT_EQ(expect_policy_checked, checker.policy_check_called());
EXPECT_EQ(expect_requirements_checked, checker.requirements_check_called());
}
void ExpectRequirementsPass(const ExtensionInstallCheckerForTest& checker) {
EXPECT_TRUE(checker.requirement_errors().empty());
}
void ExpectRequirementsError(const char* expected_error,
const ExtensionInstallCheckerForTest& checker) {
EXPECT_FALSE(checker.requirement_errors().empty());
EXPECT_EQ(std::string(expected_error),
checker.requirement_errors().front());
}
void ExpectRequirementsError(const ExtensionInstallCheckerForTest& checker) {
ExpectRequirementsError(kDummyRequirementsError, checker);
}
void ExpectBlacklistPass(const ExtensionInstallCheckerForTest& checker) {
EXPECT_EQ(NOT_BLACKLISTED, checker.blacklist_state());
}
void ExpectBlacklistError(const ExtensionInstallCheckerForTest& checker) {
EXPECT_EQ(kBlacklistStateError, checker.blacklist_state());
}
void ExpectPolicyPass(const ExtensionInstallCheckerForTest& checker) {
EXPECT_TRUE(checker.policy_allows_load());
EXPECT_TRUE(checker.policy_error().empty());
}
void ExpectPolicyError(const char* expected_error,
const ExtensionInstallCheckerForTest& checker) {
EXPECT_FALSE(checker.policy_allows_load());
EXPECT_FALSE(checker.policy_error().empty());
EXPECT_EQ(std::string(expected_error), checker.policy_error());
}
void ExpectPolicyError(const ExtensionInstallCheckerForTest& checker) {
ExpectPolicyError(kDummyPolicyError, checker);
}
void RunChecker(ExtensionInstallCheckerForTest* checker,
bool fail_fast,
int checks_to_run,
int expected_checks_run,
int expected_result) {
CheckObserver observer;
checker->Start(checks_to_run,
fail_fast,
base::Bind(&CheckObserver::OnChecksComplete,
base::Unretained(&observer)));
observer.Wait();
EXPECT_FALSE(checker->is_running());
EXPECT_EQ(expected_result, observer.result());
EXPECT_EQ(1, observer.call_count());
ValidateExpectedCalls(expected_checks_run, *checker);
}
void DoRunAllChecksPass(ExtensionInstallCheckerForTest* checker) {
RunChecker(checker,
false /* fail fast */,
ExtensionInstallChecker::CHECK_ALL,
ExtensionInstallChecker::CHECK_ALL,
0);
ExpectRequirementsPass(*checker);
ExpectPolicyPass(*checker);
ExpectBlacklistPass(*checker);
}
void DoRunAllChecksFail(ExtensionInstallCheckerForTest* checker) {
SetAllErrors(checker);
RunChecker(checker,
false /* fail fast */,
ExtensionInstallChecker::CHECK_ALL,
ExtensionInstallChecker::CHECK_ALL,
ExtensionInstallChecker::CHECK_ALL);
ExpectRequirementsError(*checker);
ExpectPolicyError(*checker);
ExpectBlacklistError(*checker);
}
void DoRunSubsetOfChecks(ExtensionInstallCheckerForTest* checker) {
// Test check set 1.
int tests_to_run = ExtensionInstallChecker::CHECK_MANAGEMENT_POLICY |
ExtensionInstallChecker::CHECK_REQUIREMENTS;
SetAllErrors(checker);
RunChecker(checker, false, tests_to_run, tests_to_run, tests_to_run);
ExpectRequirementsError(*checker);
ExpectPolicyError(*checker);
ExpectBlacklistPass(*checker);
// Test check set 2.
tests_to_run = ExtensionInstallChecker::CHECK_BLACKLIST |
ExtensionInstallChecker::CHECK_REQUIREMENTS;
SetAllErrors(checker);
RunChecker(checker, false, tests_to_run, tests_to_run, tests_to_run);
ExpectRequirementsError(*checker);
ExpectPolicyPass(*checker);
ExpectBlacklistError(*checker);
// Test a single check.
tests_to_run = ExtensionInstallChecker::CHECK_BLACKLIST;
SetAllErrors(checker);
RunChecker(checker, false, tests_to_run, tests_to_run, tests_to_run);
ExpectRequirementsPass(*checker);
ExpectPolicyPass(*checker);
ExpectBlacklistError(*checker);
}
private:
// A message loop is required for the asynchronous tests.
base::MessageLoop message_loop;
};
class ExtensionInstallCheckerMultipleInvocationTest
: public ExtensionInstallCheckerTest {
public:
ExtensionInstallCheckerMultipleInvocationTest() : callback_count_(0) {}
~ExtensionInstallCheckerMultipleInvocationTest() override {}
void RunSecondInvocation(ExtensionInstallCheckerForTest* checker,
int checks_failed) {
ASSERT_EQ(0, callback_count_);
++callback_count_;
EXPECT_FALSE(checker->is_running());
EXPECT_GT(checks_failed, 0);
ValidateExpectedCalls(ExtensionInstallChecker::CHECK_ALL, *checker);
// Set up different return values.
checker->set_blacklist_state(kBlacklistState2);
checker->set_policy_check_error(kDummyPolicyError2);
checker->set_requirements_error(kDummyRequirementsError2);
// Run the install checker again and ensure the second set of return values
// is received.
checker->Start(ExtensionInstallChecker::CHECK_ALL,
false /* fail fast */,
base::Bind(&ExtensionInstallCheckerMultipleInvocationTest::
ValidateSecondInvocation,
base::Unretained(this),
checker));
}
void ValidateSecondInvocation(ExtensionInstallCheckerForTest* checker,
int checks_failed) {
ASSERT_EQ(1, callback_count_);
EXPECT_FALSE(checker->is_running());
EXPECT_EQ(ExtensionInstallChecker::CHECK_REQUIREMENTS |
ExtensionInstallChecker::CHECK_MANAGEMENT_POLICY,
checks_failed);
ValidateExpectedCalls(ExtensionInstallChecker::CHECK_ALL, *checker);
EXPECT_EQ(kBlacklistState2, checker->blacklist_state());
ExpectPolicyError(kDummyPolicyError2, *checker);
ExpectRequirementsError(kDummyRequirementsError2, *checker);
}
private:
int callback_count_;
};
// Test the case where all tests pass.
TEST_F(ExtensionInstallCheckerTest, AllSucceeded) {
ExtensionInstallCheckerForTest sync_checker;
DoRunAllChecksPass(&sync_checker);
ExtensionInstallCheckerAsync async_checker;
DoRunAllChecksPass(&async_checker);
}
// Test the case where all tests fail.
TEST_F(ExtensionInstallCheckerTest, AllFailed) {
ExtensionInstallCheckerForTest sync_checker;
DoRunAllChecksFail(&sync_checker);
ExtensionInstallCheckerAsync async_checker;
DoRunAllChecksFail(&async_checker);
}
// Test running only a subset of tests.
TEST_F(ExtensionInstallCheckerTest, RunSubsetOfChecks) {
ExtensionInstallCheckerForTest sync_checker;
ExtensionInstallCheckerAsync async_checker;
DoRunSubsetOfChecks(&sync_checker);
DoRunSubsetOfChecks(&async_checker);
}
// Test fail fast with synchronous callbacks.
TEST_F(ExtensionInstallCheckerTest, FailFastSync) {
// This test assumes some internal knowledge of the implementation - that
// the policy check runs first.
ExtensionInstallCheckerForTest checker;
SetAllErrors(&checker);
RunChecker(&checker,
true /* fail fast */,
ExtensionInstallChecker::CHECK_ALL,
ExtensionInstallChecker::CHECK_MANAGEMENT_POLICY,
ExtensionInstallChecker::CHECK_MANAGEMENT_POLICY);
ExpectRequirementsPass(checker);
ExpectPolicyError(checker);
ExpectBlacklistPass(checker);
// This test assumes some internal knowledge of the implementation - that
// the requirements check runs before the blacklist check.
SetAllErrors(&checker);
RunChecker(&checker,
true /* fail fast */,
ExtensionInstallChecker::CHECK_REQUIREMENTS |
ExtensionInstallChecker::CHECK_BLACKLIST,
ExtensionInstallChecker::CHECK_REQUIREMENTS,
ExtensionInstallChecker::CHECK_REQUIREMENTS);
ExpectRequirementsError(checker);
ExpectPolicyPass(checker);
ExpectBlacklistPass(checker);
}
// Test fail fast with asynchronous callbacks.
TEST_F(ExtensionInstallCheckerTest, FailFastAsync) {
// This test assumes some internal knowledge of the implementation - that
// the requirements check runs before the blacklist check. Both checks should
// be called, but the requirements check callback arrives first and the
// blacklist result will be discarded.
ExtensionInstallCheckerAsync checker;
SetAllErrors(&checker);
// The policy check is synchronous and needs to pass for the other tests to
// run.
checker.set_policy_check_error(std::string());
RunChecker(&checker,
true /* fail fast */,
ExtensionInstallChecker::CHECK_ALL,
ExtensionInstallChecker::CHECK_ALL,
ExtensionInstallChecker::CHECK_REQUIREMENTS);
ExpectRequirementsError(checker);
ExpectPolicyPass(checker);
ExpectBlacklistPass(checker);
}
// Test multiple invocations of the install checker. Wait for all checks to
// complete.
TEST_F(ExtensionInstallCheckerMultipleInvocationTest, CompleteAll) {
ExtensionInstallCheckerAsync checker;
SetAllErrors(&checker);
// Start the second check as soon as the callback of the first run is invoked.
checker.Start(
ExtensionInstallChecker::CHECK_ALL,
false /* fail fast */,
base::Bind(
&ExtensionInstallCheckerMultipleInvocationTest::RunSecondInvocation,
base::Unretained(this),
&checker));
base::RunLoop().RunUntilIdle();
}
// Test multiple invocations of the install checker and fail fast.
TEST_F(ExtensionInstallCheckerMultipleInvocationTest, FailFast) {
ExtensionInstallCheckerAsync checker;
SetAllErrors(&checker);
// The policy check is synchronous and needs to pass for the other tests to
// run.
checker.set_policy_check_error(std::string());
// Start the second check as soon as the callback of the first run is invoked.
checker.Start(
ExtensionInstallChecker::CHECK_ALL,
true /* fail fast */,
base::Bind(
&ExtensionInstallCheckerMultipleInvocationTest::RunSecondInvocation,
base::Unretained(this),
&checker));
base::RunLoop().RunUntilIdle();
}
} // namespace extensions
|
#include "./AudioMetadata_Format.hpp"
namespace android::media
{
// Fields
JObject AudioMetadata_Format::KEY_ATMOS_PRESENT()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_ATMOS_PRESENT",
"Landroid/media/AudioMetadata$Key;"
);
}
JObject AudioMetadata_Format::KEY_AUDIO_ENCODING()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_AUDIO_ENCODING",
"Landroid/media/AudioMetadata$Key;"
);
}
JObject AudioMetadata_Format::KEY_BIT_RATE()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_BIT_RATE",
"Landroid/media/AudioMetadata$Key;"
);
}
JObject AudioMetadata_Format::KEY_BIT_WIDTH()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_BIT_WIDTH",
"Landroid/media/AudioMetadata$Key;"
);
}
JObject AudioMetadata_Format::KEY_CHANNEL_MASK()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_CHANNEL_MASK",
"Landroid/media/AudioMetadata$Key;"
);
}
JObject AudioMetadata_Format::KEY_MIME()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_MIME",
"Landroid/media/AudioMetadata$Key;"
);
}
JObject AudioMetadata_Format::KEY_SAMPLE_RATE()
{
return getStaticObjectField(
"android.media.AudioMetadata$Format",
"KEY_SAMPLE_RATE",
"Landroid/media/AudioMetadata$Key;"
);
}
// QJniObject forward
AudioMetadata_Format::AudioMetadata_Format(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
} // namespace android::media
|
// Copyright (c) 2021 Srinivas Yadav
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <hpx/config.hpp>
#if defined(HPX_HAVE_CXX20_EXPERIMENTAL_SIMD)
#include <cstddef>
#include <experimental/simd>
namespace hpx { namespace parallel { namespace traits {
///////////////////////////////////////////////////////////////////////
template <typename T, typename Abi>
HPX_HOST_DEVICE HPX_FORCEINLINE int find_first_of(
std::experimental::simd_mask<T, Abi> const& msk)
{
if (std::experimental::any_of(msk))
{
return std::experimental::find_first_set(msk);
}
return -1;
}
}}} // namespace hpx::parallel::traits
#endif
|
// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include <QtCore/QString>
#include <QtCore/QList>
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "function/CFunctionDB.h"
#include "CQMessageBox.h"
#include "CQFunctionDM.h"
#include "qtUtilities.h"
CQFunctionDM::CQFunctionDM(QObject *parent)
: CQBaseDataModel(parent)
{
}
int CQFunctionDM::rowCount(const QModelIndex& C_UNUSED(parent)) const
{
return (int) CCopasiRootContainer::getFunctionList()->loadedFunctions().size() + 1;
}
int CQFunctionDM::columnCount(const QModelIndex& C_UNUSED(parent)) const
{
return TOTAL_COLS_FUNCTIONS;
}
Qt::ItemFlags CQFunctionDM::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
if (!isDefaultRow(index) && isFunctionReadOnly(index))
return QAbstractItemModel::flags(index);
if (index.column() == COL_NAME_FUNCTIONS)
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
else
return QAbstractItemModel::flags(index);
}
bool CQFunctionDM::isFunctionReadOnly(const QModelIndex &index) const
{
const CEvaluationTree *pFunc = CCopasiRootContainer::getFunctionList()->loadedFunctions()[index.row()];
switch (pFunc->getType())
{
case CEvaluationTree::PreDefined:
case CEvaluationTree::MassAction:
return true;
break;
case CEvaluationTree::UserDefined:
case CEvaluationTree::Function:
case CEvaluationTree::Expression:
case CEvaluationTree::MathExpression:
return false;
break;
}
return true;
}
QVariant CQFunctionDM::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= rowCount())
return QVariant();
if (index.column() > 0 && role == Qt::ForegroundRole && !(flags(index) & Qt::ItemIsEditable))
return QColor(Qt::darkGray);
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
if (isDefaultRow(index))
{
switch (index.column())
{
case COL_ROW_NUMBER:
return QVariant(QString(""));
case COL_NAME_FUNCTIONS:
return QVariant(QString("New Function"));
case COL_TYPE_FUNCTIONS:
return QVariant(QString(FROM_UTF8(CEvaluationTree::TypeName[4])));
default:
return QVariant(QString(""));
}
}
else
{
const CEvaluationTree *pFunc = CCopasiRootContainer::getFunctionList()->loadedFunctions()[index.row()];
if (pFunc == NULL)
return QVariant();
switch (index.column())
{
case COL_ROW_NUMBER:
return QVariant(index.row() + 1);
case COL_NAME_FUNCTIONS:
return QVariant(QString(FROM_UTF8(pFunc->getObjectName())));
case COL_TYPE_FUNCTIONS:
return QVariant(QString(FROM_UTF8(CEvaluationTree::TypeName[pFunc->getType()])));
case COL_MATH_DESC_FUNCTIONS:
return QVariant(QString(FROM_UTF8(pFunc->getInfix())));
case COL_SBML_ID_FUNCTIONS:
return QVariant();
}
}
}
return QVariant();
}
QVariant CQFunctionDM::headerData(int section, Qt::Orientation orientation,
int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
{
switch (section)
{
case COL_ROW_NUMBER:
return QVariant(QString("#"));
case COL_NAME_FUNCTIONS:
return QVariant(QString("Name"));
case COL_TYPE_FUNCTIONS:
return QVariant(QString("Type"));
case COL_MATH_DESC_FUNCTIONS:
return QVariant(QString("Mathematical Description"));
case COL_SBML_ID_FUNCTIONS:
return QVariant(QString("SBML ID"));
default:
return QVariant();
}
}
else
return QString("%1").arg(section + 1);
}
bool CQFunctionDM::setData(const QModelIndex &index, const QVariant &value,
int role)
{
if (index.isValid() && role == Qt::EditRole)
{
bool defaultRow = isDefaultRow(index);
if (defaultRow)
{
if (index.data() != value)
insertRow();
else
return false;
}
CEvaluationTree *pFunc = CCopasiRootContainer::getFunctionList()->loadedFunctions()[index.row()];
if (pFunc == NULL)
return false;
if (index.column() == COL_NAME_FUNCTIONS)
pFunc->setObjectName(TO_UTF8(value.toString()));
else if (index.column() == COL_TYPE_FUNCTIONS)
{
if (index.data() != value)
{
QString msg;
msg = "Type must not be changed for '" + FROM_UTF8(pFunc->getObjectName()) + "'.\n";
CQMessageBox::information(NULL,
"Unable to change Function Type",
msg,
QMessageBox::Ok, QMessageBox::Ok);
}
}
else if (index.column() == COL_MATH_DESC_FUNCTIONS)
{
if (index.data() != value)
{
if (!pFunc->setInfix(TO_UTF8(value.toString())))
{
QString msg;
msg = "Incorrect mathematical description'" + FROM_UTF8(pFunc->getObjectName()) + "'.\n";
CQMessageBox::information(NULL,
"Unable to change mathematical description",
msg,
QMessageBox::Ok, QMessageBox::Ok);
}
}
}
if (defaultRow && this->index(index.row(), COL_NAME_FUNCTIONS).data().toString() == "function")
pFunc->setObjectName(TO_UTF8(createNewName("function", COL_NAME_FUNCTIONS)));
emit dataChanged(index, index);
emit notifyGUI(ListViews::FUNCTION, ListViews::CHANGE, pFunc->getKey());
}
return true;
}
bool CQFunctionDM::insertRows(int position, int rows, const QModelIndex&)
{
beginInsertRows(QModelIndex(), position, position + rows - 1);
for (int row = 0; row < rows; ++row)
{
CFunction *pFunc;
CCopasiRootContainer::getFunctionList()->add(pFunc = new CKinFunction(TO_UTF8(createNewName("function", COL_NAME_FUNCTIONS))), true);
emit notifyGUI(ListViews::FUNCTION, ListViews::ADD, pFunc->getKey());
}
endInsertRows();
return true;
}
bool CQFunctionDM::removeRows(int position, int rows, const QModelIndex&)
{
if (rows <= 0)
return true;
std::vector< std::string > DeletedKeys;
DeletedKeys.resize(rows);
std::vector< std::string >::iterator itDeletedKey;
std::vector< std::string >::iterator endDeletedKey = DeletedKeys.end();
CCopasiVector< CFunction >::const_iterator itRow =
CCopasiRootContainer::getFunctionList()->loadedFunctions().begin() + position;
int row = 0;
for (itDeletedKey = DeletedKeys.begin(), row = 0; itDeletedKey != endDeletedKey; ++itDeletedKey, ++itRow, ++row)
{
if (isFunctionReadOnly(this->index(position + row, 0)))
{
*itDeletedKey = "";
}
else
{
*itDeletedKey = (*itRow)->getKey();
}
}
for (itDeletedKey = DeletedKeys.begin(), row = 0; itDeletedKey != endDeletedKey; ++itDeletedKey, ++row)
{
if (*itDeletedKey != "")
{
beginRemoveRows(QModelIndex(), position + row, position + row);
CCopasiRootContainer::getFunctionList()->removeFunction(*itDeletedKey);
emit notifyGUI(ListViews::FUNCTION, ListViews::DELETE, *itDeletedKey);
emit notifyGUI(ListViews::FUNCTION, ListViews::DELETE, ""); //Refresh all as there may be dependencies.
endRemoveRows();
}
}
return true;
}
bool CQFunctionDM::removeRows(QModelIndexList rows, const QModelIndex&)
{
if (rows.isEmpty())
return false;
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
assert(pDataModel != NULL);
CModel * pModel = pDataModel->getModel();
if (pModel == NULL)
return false;
//Build the list of pointers to items to be deleted
//before actually deleting any item.
QList <CEvaluationTree *> pFunctions;
QModelIndexList::const_iterator i;
for (i = rows.begin(); i != rows.end(); ++i)
{
if (!isDefaultRow(*i) && CCopasiRootContainer::getFunctionList()->loadedFunctions()[(*i).row()])
pFunctions.append(CCopasiRootContainer::getFunctionList()->loadedFunctions()[(*i).row()]);
}
QList <CEvaluationTree *>::const_iterator j;
for (j = pFunctions.begin(); j != pFunctions.end(); ++j)
{
CEvaluationTree * pFunction = *j;
size_t delRow =
CCopasiRootContainer::getFunctionList()->loadedFunctions().CCopasiVector< CFunction >::getIndex(pFunction);
if (delRow != C_INVALID_INDEX)
{
QMessageBox::StandardButton choice =
CQMessageBox::confirmDelete(NULL, "function",
FROM_UTF8(pFunction->getObjectName()),
pFunction->getDeletedObjects());
if (choice == QMessageBox::Ok)
removeRow((int) delRow);
}
}
return true;
}
|
/**
* Nsmf_PDUSession
* SMF PDU Session Service. © 2019, 3GPP Organizational Partners (ARIB, ATIS,
* CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 1.1.0.alpha-1
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.1.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TriggerType.h"
namespace oai {
namespace smf {
namespace model {
TriggerType::TriggerType() {}
TriggerType::~TriggerType() {}
void TriggerType::validate() {
// TODO: implement validation
}
web::json::value TriggerType::toJson() const {
web::json::value val = web::json::value::object();
return val;
}
void TriggerType::fromJson(const web::json::value& val) {}
void TriggerType::toMultipart(
std::shared_ptr<MultipartFormData> multipart,
const utility::string_t& prefix) const {
utility::string_t namePrefix = prefix;
if (namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) !=
utility::conversions::to_string_t(".")) {
namePrefix += utility::conversions::to_string_t(".");
}
}
void TriggerType::fromMultiPart(
std::shared_ptr<MultipartFormData> multipart,
const utility::string_t& prefix) {
utility::string_t namePrefix = prefix;
if (namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) !=
utility::conversions::to_string_t(".")) {
namePrefix += utility::conversions::to_string_t(".");
}
}
} // namespace model
} // namespace smf
} // namespace oai
|
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Test memcat
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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.
*
*/
/*
Test that we are cycling the servers we are creating during testing.
*/
#include <config.h>
#include <libtest/test.hpp>
#include <libmemcached/memcached.h>
using namespace libtest;
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
static std::string executable("clients/memcat");
static test_return_t help_test(void *)
{
const char *args[]= { "--help", 0 };
test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true));
return TEST_SUCCESS;
}
static test_return_t cat_test(void *)
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "--server=localhost:%d", int(default_port()));
const char *args[]= { buffer, "foo", 0 };
memcached_st *memc= memcached(buffer, strlen(buffer));
test_true(memc);
test_compare(MEMCACHED_SUCCESS,
memcached_set(memc, test_literal_param("foo"), 0, 0, 0, 0));
memcached_return_t rc;
test_null(memcached_get(memc, test_literal_param("foo"), 0, 0, &rc));
test_compare(MEMCACHED_SUCCESS, rc);
test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true));
test_null(memcached_get(memc, test_literal_param("foo"), 0, 0, &rc));
test_compare(MEMCACHED_SUCCESS, rc);
memcached_free(memc);
return TEST_SUCCESS;
}
static test_return_t NOT_FOUND_test(void *)
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "--server=localhost:%d", int(default_port()));
const char *args[]= { buffer, "foo", 0 };
memcached_st *memc= memcached(buffer, strlen(buffer));
test_true(memc);
test_compare(MEMCACHED_SUCCESS, memcached_flush(memc, 0));
memcached_return_t rc;
test_null(memcached_get(memc, test_literal_param("foo"), 0, 0, &rc));
test_compare(MEMCACHED_NOTFOUND, rc);
test_compare(EXIT_FAILURE, exec_cmdline(executable, args, true));
test_null(memcached_get(memc, test_literal_param("foo"), 0, 0, &rc));
test_compare(MEMCACHED_NOTFOUND, rc);
memcached_free(memc);
return TEST_SUCCESS;
}
test_st memcat_tests[] ={
{"--help", true, help_test },
{"cat(FOUND)", true, cat_test },
{"cat(NOT_FOUND)", true, NOT_FOUND_test },
{0, 0, 0}
};
collection_st collection[] ={
{"memcat", 0, 0, memcat_tests },
{0, 0, 0, 0}
};
static void *world_create(server_startup_st& servers, test_return_t& error)
{
if (libtest::has_memcached() == false)
{
error= TEST_SKIPPED;
return NULL;
}
if (not server_startup(servers, "memcached", libtest::default_port(), 0, NULL))
{
error= TEST_FAILURE;
}
return &servers;
}
void get_world(Framework *world)
{
world->collections(collection);
world->create(world_create);
}
|
// nnet2bin/nnet-get-egs.cc
// Copyright 2012-2013 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "hmm/transition-model.h"
#include "nnet2/nnet-example-functions.h"
namespace kaldi {
namespace nnet2 {
// returns an integer randomly drawn with expected value "expected_count"
// (will be either floor(expected_count) or ceil(expected_count)).
// this will go into an infinite loop if expected_count is very huge, but
// it should never be that huge.
// In the normal case, "expected_count" will be between zero and one.
int32 GetCount(double expected_count) {
KALDI_ASSERT(expected_count >= 0.0);
int32 ans = 0;
while (expected_count > 1.0) {
ans++;
expected_count--;
}
if (WithProb(expected_count)) ans++;
return ans;
}
static void ProcessFile(const MatrixBase<BaseFloat> &feats,
const Posterior &pdf_post, int32 left_context,
int32 right_context, int32 const_feat_dim,
BaseFloat keep_proportion, int64 *num_frames_written,
NnetExampleWriter *example_writer) {
KALDI_ASSERT(feats.NumRows() == static_cast<int32>(pdf_post.size()));
int32 feat_dim = feats.NumCols();
KALDI_ASSERT(const_feat_dim < feat_dim);
int32 basic_feat_dim = feat_dim - const_feat_dim;
// const_feat_dim will be set when we have online-estimated
// iVectors.
NnetExample eg;
Matrix<BaseFloat> input_frames(left_context + 1 + right_context,
basic_feat_dim);
eg.left_context = left_context;
eg.spk_info.Resize(const_feat_dim);
for (int32 i = 0; i < feats.NumRows(); i++) {
int32 count = GetCount(keep_proportion); // number of times
// we'll write this out (1 by default).
if (count > 0) {
// Set up "input_frames".
for (int32 j = -left_context; j <= right_context; j++) {
int32 j2 = j + i;
if (j2 < 0) j2 = 0;
if (j2 >= feats.NumRows()) j2 = feats.NumRows() - 1;
SubVector<BaseFloat> src(feats.Row(j2), 0, basic_feat_dim),
dest(input_frames, j + left_context);
dest.CopyFromVec(src);
}
eg.labels = pdf_post[i];
eg.input_frames = input_frames;
if (const_feat_dim > 0) {
// we'll normally reach here if we're using online-estimated iVectors.
SubVector<BaseFloat> const_part(feats.Row(i), basic_feat_dim,
const_feat_dim);
eg.spk_info.CopyFromVec(const_part);
}
std::ostringstream os;
os << ((*num_frames_written)++);
std::string key = os.str(); // key in the archive is the number of the
// example.
for (int32 c = 0; c < count; c++) example_writer->Write(key, eg);
}
}
}
} // namespace nnet2
} // namespace kaldi
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using namespace kaldi::nnet2;
typedef kaldi::int32 int32;
typedef kaldi::int64 int64;
const char *usage =
"Get frame-by-frame examples of data for neural network training.\n"
"Essentially this is a format change from features and posteriors\n"
"into a special frame-by-frame format. To split randomly into\n"
"different subsets, do nnet-copy-egs with --random=true, but\n"
"note that this does not randomize the order of frames.\n"
"\n"
"Usage: nnet-get-egs [options] <features-rspecifier> "
"<pdf-post-rspecifier> <training-examples-out>\n"
"\n"
"An example [where $feats expands to the actual features]:\n"
"nnet-get-egs --left-context=8 --right-context=8 \"$feats\" \\\n"
" \"ark:gunzip -c exp/nnet/ali.1.gz | ali-to-pdf exp/nnet/1.nnet "
"ark:- ark:- | ali-to-post ark:- ark:- |\" \\\n"
" ark:- \n"
"Note: the --left-context and --right-context would be derived from\n"
"the output of nnet-info.";
int32 left_context = 0, right_context = 0, const_feat_dim = 0;
int32 srand_seed = 0;
BaseFloat keep_proportion = 1.0;
ParseOptions po(usage);
po.Register("left-context", &left_context,
"Number of frames of left context "
"the neural net requires.");
po.Register("right-context", &right_context,
"Number of frames of right context "
"the neural net requires.");
po.Register("const-feat-dim", &const_feat_dim,
"If specified, the last "
"const-feat-dim dimensions of the feature input are treated as "
"constant over the context window (so are not spliced)");
po.Register(
"keep-proportion", &keep_proportion,
"If <1.0, this program will "
"randomly keep this proportion of the input samples. If >1.0, it will "
"in expectation copy a sample this many times. It will copy it a "
"number "
"of times equal to floor(keep-proportion) or ceil(keep-proportion).");
po.Register("srand", &srand_seed,
"Seed for random number generator "
"(only relevant if --keep-proportion != 1.0)");
po.Read(argc, argv);
srand(srand_seed);
if (po.NumArgs() != 3) {
po.PrintUsage();
exit(1);
}
std::string feature_rspecifier = po.GetArg(1),
pdf_post_rspecifier = po.GetArg(2),
examples_wspecifier = po.GetArg(3);
// Read in all the training files.
SequentialBaseFloatMatrixReader feat_reader(feature_rspecifier);
RandomAccessPosteriorReader pdf_post_reader(pdf_post_rspecifier);
NnetExampleWriter example_writer(examples_wspecifier);
int32 num_done = 0, num_err = 0;
int64 num_frames_written = 0;
for (; !feat_reader.Done(); feat_reader.Next()) {
std::string key = feat_reader.Key();
const Matrix<BaseFloat> &feats = feat_reader.Value();
if (!pdf_post_reader.HasKey(key)) {
KALDI_WARN << "No pdf-level posterior for key " << key;
num_err++;
} else {
const Posterior &pdf_post = pdf_post_reader.Value(key);
if (pdf_post.size() != feats.NumRows()) {
KALDI_WARN << "Posterior has wrong size " << pdf_post.size()
<< " versus " << feats.NumRows();
num_err++;
continue;
}
ProcessFile(feats, pdf_post, left_context, right_context,
const_feat_dim, keep_proportion, &num_frames_written,
&example_writer);
num_done++;
}
}
KALDI_LOG << "Finished generating examples, "
<< "successfully processed " << num_done
<< " feature files, wrote " << num_frames_written << " examples, "
<< num_err << " files had errors.";
return (num_done == 0 ? 1 : 0);
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return -1;
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/storage/blobfs/directory.h"
#include <fuchsia/device/c/fidl.h>
#include <lib/fidl-utils/bind.h>
#include <lib/sync/completion.h>
#include <stdlib.h>
#include <string.h>
#include <zircon/device/vfs.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <string_view>
#include <utility>
#include <fbl/ref_ptr.h>
#include "src/lib/digest/digest.h"
#include "src/lib/storage/vfs/cpp/metrics/events.h"
#include "src/lib/storage/vfs/cpp/vfs_types.h"
#include "src/storage/blobfs/blob.h"
#include "src/storage/blobfs/blobfs.h"
#include "src/storage/blobfs/metrics.h"
namespace blobfs {
Directory::Directory(Blobfs* bs) : blobfs_(bs) {}
BlobCache& Directory::GetCache() { return blobfs_->GetCache(); }
Directory::~Directory() = default;
zx_status_t Directory::GetNodeInfoForProtocol([[maybe_unused]] fs::VnodeProtocol protocol,
[[maybe_unused]] fs::Rights rights,
fs::VnodeRepresentation* info) {
*info = fs::VnodeRepresentation::Directory();
return ZX_OK;
}
fs::VnodeProtocolSet Directory::GetProtocols() const { return fs::VnodeProtocol::kDirectory; }
zx_status_t Directory::Readdir(fs::VdirCookie* cookie, void* dirents, size_t len,
size_t* out_actual) {
return blobfs_->Readdir(cookie, dirents, len, out_actual);
}
zx_status_t Directory::Read(void* data, size_t len, size_t off, size_t* out_actual) {
return ZX_ERR_NOT_FILE;
}
zx_status_t Directory::Write(const void* data, size_t len, size_t offset, size_t* out_actual) {
return ZX_ERR_NOT_FILE;
}
zx_status_t Directory::Append(const void* data, size_t len, size_t* out_end, size_t* out_actual) {
return ZX_ERR_NOT_FILE;
}
zx_status_t Directory::Lookup(std::string_view name, fbl::RefPtr<fs::Vnode>* out) {
TRACE_DURATION("blobfs", "Directory::Lookup", "name", name);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kLookUp);
assert(memchr(name.data(), '/', name.length()) == nullptr);
if (name == ".") {
// Special case: Accessing root directory via '.'
*out = fbl::RefPtr<Directory>(this);
return ZX_OK;
}
zx_status_t status;
Digest digest;
if ((status = digest.Parse(name.data(), name.length())) != ZX_OK) {
return status;
}
fbl::RefPtr<CacheNode> cache_node;
if ((status = GetCache().Lookup(digest, &cache_node)) != ZX_OK) {
return status;
}
auto vnode = fbl::RefPtr<Blob>::Downcast(std::move(cache_node));
blobfs_->GetMetrics()->UpdateLookup(vnode->SizeData());
*out = std::move(vnode);
return ZX_OK;
}
zx_status_t Directory::GetAttributes(fs::VnodeAttributes* a) {
*a = fs::VnodeAttributes();
a->mode = V_TYPE_DIR | V_IRUSR;
a->inode = fuchsia_io::wire::kInoUnknown;
a->content_size = 0;
a->storage_size = 0;
a->link_count = 1;
a->creation_time = 0;
a->modification_time = 0;
return ZX_OK;
}
zx_status_t Directory::Create(std::string_view name, uint32_t mode, fbl::RefPtr<fs::Vnode>* out) {
TRACE_DURATION("blobfs", "Directory::Create", "name", name, "mode", mode);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kCreate);
assert(memchr(name.data(), '/', name.length()) == nullptr);
Digest digest;
zx_status_t status;
if ((status = digest.Parse(name.data(), name.length())) != ZX_OK) {
return status;
}
fbl::RefPtr<Blob> vn = fbl::AdoptRef(new Blob(blobfs_, std::move(digest)));
if ((status = GetCache().Add(vn)) != ZX_OK) {
return status;
}
if ((status = vn->OpenValidating(fs::VnodeConnectionOptions(), nullptr)) != ZX_OK) {
return status;
}
*out = std::move(vn);
return ZX_OK;
}
#ifdef __Fuchsia__
zx_status_t Directory::QueryFilesystem(fuchsia_io::wire::FilesystemInfo* info) {
blobfs_->GetFilesystemInfo(info);
return ZX_OK;
}
zx_status_t Directory::GetDevicePath(size_t buffer_len, char* out_name, size_t* out_len) {
return blobfs_->Device()->GetDevicePath(buffer_len, out_name, out_len);
}
#endif // __Fuchsia__
zx_status_t Directory::Unlink(std::string_view name, bool must_be_dir) {
TRACE_DURATION("blobfs", "Directory::Unlink", "name", name, "must_be_dir", must_be_dir);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kUnlink);
assert(memchr(name.data(), '/', name.length()) == nullptr);
zx_status_t status;
Digest digest;
if ((status = digest.Parse(name.data(), name.length())) != ZX_OK) {
return status;
}
fbl::RefPtr<CacheNode> cache_node;
if ((status = GetCache().Lookup(digest, &cache_node)) != ZX_OK) {
return status;
}
auto vnode = fbl::RefPtr<Blob>::Downcast(std::move(cache_node));
blobfs_->GetMetrics()->UpdateLookup(vnode->SizeData());
return vnode->QueueUnlink();
}
void Directory::Sync(SyncCallback closure) {
blobfs_->Sync([this, cb = std::move(closure)](zx_status_t status) mutable {
// This callback will be issued on the journal thread in the normal case. This is important
// because the flush must happen there or it will block the main thread which would block
// processing other requests.
//
// If called during shutdown this may get issued on the main thread but then the flush
// transaction should be a no-op.
if (status == ZX_OK) {
status = blobfs_->Flush();
}
cb(status);
});
}
#ifdef __Fuchsia__
void Directory::HandleFsSpecificMessage(fidl::IncomingMessage& msg, fidl::Transaction* txn) {
fidl::WireDispatch<fuchsia_blobfs::Blobfs>(this, std::move(msg), txn);
}
void Directory::GetAllocatedRegions(GetAllocatedRegionsRequestView request,
GetAllocatedRegionsCompleter::Sync& completer) {
static_assert(sizeof(fuchsia_blobfs::wire::BlockRegion) == sizeof(BlockRegion));
static_assert(offsetof(fuchsia_blobfs::wire::BlockRegion, offset) ==
offsetof(BlockRegion, offset));
static_assert(offsetof(fuchsia_blobfs::wire::BlockRegion, length) ==
offsetof(BlockRegion, length));
zx::vmo vmo;
zx_status_t status = ZX_OK;
fbl::Vector<BlockRegion> buffer = blobfs_->GetAllocator()->GetAllocatedRegions();
uint64_t allocations = buffer.size();
if (allocations != 0) {
status = zx::vmo::create(sizeof(BlockRegion) * allocations, 0, &vmo);
if (status == ZX_OK) {
status = vmo.write(buffer.data(), 0, sizeof(BlockRegion) * allocations);
}
}
if (status == ZX_OK) {
completer.Reply(ZX_OK, std::move(vmo), allocations);
} else {
completer.Reply(status, zx::vmo(), 0);
}
}
void Directory::SetCorruptBlobHandler(SetCorruptBlobHandlerRequestView request,
SetCorruptBlobHandlerCompleter::Sync& completer) {
blobfs_->SetCorruptBlobHandler(std::move(request->handler));
completer.Reply(ZX_OK);
}
#endif // __Fuchsia__
} // namespace blobfs
|
//===-- MIDriverBase.cpp ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Third party headers:
#include "lldb/API/SBBroadcaster.h"
#include "lldb/API/SBEvent.h"
// In-house headers:
#include "MIDriverBase.h"
//++
//------------------------------------------------------------------------------------
// Details: CMIDriverBase constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
CMIDriverBase::CMIDriverBase()
: m_pDriverFallThru(nullptr), m_pDriverParent(nullptr), m_bExitApp(false) {}
//++
//------------------------------------------------------------------------------------
// Details: CMIDriverBase destructor.
// Type: Overrideable.
// Args: None.
// Return: None.
// Throws: None.
//--
CMIDriverBase::~CMIDriverBase() { m_pDriverFallThru = NULL; }
//++
//------------------------------------------------------------------------------------
// Details: This function allows *this driver to call on another driver to
// perform work
// should this driver not be able to handle the client data input.
// Type: Overrideable.
// Check the error message if the function returns a failure.
// Type: Overridden.
// Args: vCmd - (R) Command instruction to interpret.
// vwErrMsg - (W) Status description on command failing.
// Return: MIstatus::success - Command succeeded.
// MIstatus::failure - Command failed.
// Throws: None.
//--
bool CMIDriverBase::DoFallThruToAnotherDriver(const CMIUtilString &vCmd,
CMIUtilString &vwErrMsg) {
// Do nothing - override and implement. Use m_pDriverFallThru.
return MIstatus::success;
}
//++
//------------------------------------------------------------------------------------
// Details: This function allows *this driver to call on another driver to
// perform work
// should this driver not be able to handle the client data input.
// Type: Overrideable.
// Args: vrOtherDriver - (R) Reference to another driver object.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
bool CMIDriverBase::SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver) {
MIunused(vrOtherDriver);
// Do nothing - override and implement. Set m_pDriverFallThru.
return MIstatus::success;
}
//++
//------------------------------------------------------------------------------------
// Details: This function allows *this driver to call functionality on the
// parent driver
// ask for information for example.
// Type: Overrideable.
// Args: vrOtherDriver - (R) Reference to another driver object.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
bool CMIDriverBase::SetDriverParent(const CMIDriverBase &vrOtherDriver) {
MIunused(vrOtherDriver);
// Do nothing - override and implement. Set m_pDriverParent.
return MIstatus::success;
}
//++
//------------------------------------------------------------------------------------
// Details: Retrieve the parent driver to *this driver if one assigned. If
// assigned *this
// is the pass through driver that the parent driver passes work to.
// Type: Method.
// Args: None.
// Return: CMIDriverBase * - Pointer to a driver object.
// - NULL = there is not parent to *this driver.
// Throws: None.
//--
CMIDriverBase *CMIDriverBase::GetDriversParent() const {
return m_pDriverParent;
}
//++
//------------------------------------------------------------------------------------
// Details: Retrieve the pointer to the other fall through driver *this driver
// is using
// (or not using).
// Type: Method.
// Args: None.
// Return: CMIDriverBase * - Pointer to other driver.
// - NULL if no driver set.
// Throws: None.
//--
CMIDriverBase *CMIDriverBase::GetDriverToFallThruTo() const {
return m_pDriverFallThru;
}
//++
//------------------------------------------------------------------------------------
// Details: *this driver provides a file stream to other drivers on which *this
// driver
// write's out to and they read as expected input. *this driver is
// passing
// through commands to the (child) pass through assigned driver.
// Type: Overrideable.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
FILE *CMIDriverBase::GetStdin() const {
// Do nothing - override and implement
return nullptr;
}
//++
//------------------------------------------------------------------------------------
// Details: *this driver provides a file stream to other pass through assigned
// drivers
// so they know what to write to.
// Type: Overrideable.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
FILE *CMIDriverBase::GetStdout() const {
// Do nothing - override and implement
return nullptr;
}
//++
//------------------------------------------------------------------------------------
// Details: *this driver provides a error file stream to other pass through
// assigned drivers
// so they know what to write to.
// Type: Overrideable.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
FILE *CMIDriverBase::GetStderr() const {
// Do nothing - override and implement
return nullptr;
}
//++
//------------------------------------------------------------------------------------
// Details: Set the MI Driver's exit application flag. The application checks
// this flag
// after every stdin line is read so the exit may not be instantaneous.
// If vbForceExit is false the MI Driver queries its state and
// determines if is
// should exit or continue operating depending on that running state.
// Type: Overrideable.
// Args: vbForceExit - (R) True = Do not query, set state to exit, false =
// query if can/should exit right now.
// Return: None.
// Throws: None.
//--
void CMIDriverBase::SetExitApplicationFlag(const bool vbForceExit) {
MIunused(vbForceExit);
// Do nothing - override and implement
}
|
#pragma once
#include "use_asio.hpp"
#include <string>
#include <vector>
#include <string_view>
#ifdef _MSC_VER
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
#include "io_service_pool.hpp"
#include "connection.hpp"
#include "http_router.hpp"
#include "router.hpp"
#include "function_traits.hpp"
#include "url_encode_decode.hpp"
#include "http_cache.hpp"
#include "session_manager.hpp"
#include "cookie.hpp"
namespace cinatra {
//cache
template<typename T>
struct enable_cache {
enable_cache(T t) :value(t) {}
T value;
};
template<class service_pool_policy = io_service_pool>
class http_server_ : private noncopyable {
public:
template<class... Args>
explicit http_server_(Args&&... args) : io_service_pool_(std::forward<Args>(args)...)
#ifdef CINATRA_ENABLE_SSL
, ctx_(boost::asio::ssl::context::sslv23)
#endif
{
http_cache::get().set_cache_max_age(86400);
init_conn_callback();
}
void enable_http_cache(bool b) {
http_cache::get().enable_cache(b);
}
template<typename F>
void init_ssl_context(bool ssl_enable_v3, F&& f, std::string certificate_chain_file,
std::string private_key_file, std::string tmp_dh_file) {
#ifdef CINATRA_ENABLE_SSL
unsigned long ssl_options = boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::single_dh_use;
if (!ssl_enable_v3)
ssl_options |= boost::asio::ssl::context::no_sslv3;
ctx_.set_options(ssl_options);
ctx_.set_password_callback(std::forward<F>(f));
ctx_.use_certificate_chain_file(std::move(certificate_chain_file));
ctx_.use_private_key_file(std::move(private_key_file), boost::asio::ssl::context::pem);
ctx_.use_tmp_dh_file(std::move(tmp_dh_file));
#endif
}
//address :
// "0.0.0.0" : ipv4. use 'https://localhost/' to visit
// "::1" : ipv6. use 'https://[::1]/' to visit
// "" : ipv4 & ipv6.
bool listen(std::string_view address, std::string_view port) {
boost::asio::ip::tcp::resolver::query query(address.data(), port.data());
return listen(query);
}
//support ipv6 & ipv4
bool listen(std::string_view port) {
boost::asio::ip::tcp::resolver::query query(port.data());
return listen(query);
}
bool listen(const boost::asio::ip::tcp::resolver::query & query) {
boost::asio::ip::tcp::resolver resolver(io_service_pool_.get_io_service());
boost::asio::ip::tcp::resolver::iterator endpoints = resolver.resolve(query);
bool r = false;
for (; endpoints != boost::asio::ip::tcp::resolver::iterator(); ++endpoints) {
boost::asio::ip::tcp::endpoint endpoint = *endpoints;
auto acceptor = std::make_shared<boost::asio::ip::tcp::acceptor>(io_service_pool_.get_io_service());
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
try {
acceptor->bind(endpoint);
acceptor->listen();
start_accept(acceptor);
r = true;
}
catch (const std::exception& ex) {
std::cout << ex.what() << "\n";
//LOG_INFO << e.what();
}
}
return r;
}
void stop() {
io_service_pool_.stop();
}
void run() {
if (!fs::exists(public_root_path_.data())) {
fs::create_directories(public_root_path_.data());
}
if (!fs::exists(static_dir_.data())) {
fs::create_directories(static_dir_.data());
}
io_service_pool_.run();
}
intptr_t run_one() {
return io_service_pool_.run_one();
}
intptr_t poll() {
return io_service_pool_.poll();
}
intptr_t poll_one() {
return io_service_pool_.poll_one();
}
void set_static_dir(std::string&& path) {
static_dir_ = public_root_path_+std::move(path)+"/";
}
const std::string& static_dir() const {
return static_dir_;
}
//xM
void set_max_req_buf_size(std::size_t max_buf_size) {
max_req_buf_size_ = max_buf_size;
}
void set_keep_alive_timeout(long seconds) {
keep_alive_timeout_ = seconds;
}
template<typename T>
bool need_cache(T&& t) {
if constexpr(std::is_same_v<T, enable_cache<bool>>) {
return t.value;
}
else {
return false;
}
}
//set http handlers
template<http_method... Is, typename Function, typename... AP>
void set_http_handler(std::string_view name, Function&& f, AP&&... ap) {
if constexpr(has_type<enable_cache<bool>, std::tuple<std::decay_t<AP>...>>::value) {//for cache
bool b = false;
((!b&&(b = need_cache(std::forward<AP>(ap)))),...);
if (!b) {
http_cache::get().add_skip(name);
}else{
http_cache::get().add_single_cache(name);
}
auto tp = filter<enable_cache<bool>>(std::forward<AP>(ap)...);
auto lm = [this, name, f = std::move(f)](auto... ap) {
http_router_.register_handler<Is...>(name, std::move(f), std::move(ap)...);
};
std::apply(lm, std::move(tp));
}
else {
http_router_.register_handler<Is...>(name, std::forward<Function>(f), std::forward<AP>(ap)...);
}
}
void set_base_path(const std::string& key,const std::string& path)
{
base_path_[0] = std::move(key);
base_path_[1] = std::move(path);
}
void set_res_cache_max_age(std::time_t seconds)
{
static_res_cache_max_age_ = seconds;
}
std::time_t get_res_cache_max_age()
{
return static_res_cache_max_age_;
}
void set_cache_max_age(std::time_t seconds)
{
http_cache::get().set_cache_max_age(seconds);
}
std::time_t get_cache_max_age()
{
return http_cache::get().get_cache_max_age();
}
//don't begin with "./" or "/", not absolutely path
void set_public_root_directory(const std::string& name)
{
if(!name.empty()){
public_root_path_ = "./"+name+"/";
}
else {
public_root_path_ = "./";
}
}
std::string get_public_root_directory()
{
return public_root_path_;
}
void set_download_check(std::function<bool(request& req, response& res)> checker) {
download_check_ = std::move(checker);
}
//should be called before listen
void set_upload_check(std::function<bool(request& req, response& res)> checker) {
upload_check_ = std::move(checker);
}
void mapping_to_root_path(std::string relate_path) {
relate_paths_.emplace_back("."+std::move(relate_path));
}
private:
void start_accept(std::shared_ptr<boost::asio::ip::tcp::acceptor> const& acceptor) {
auto new_conn = std::make_shared<connection<Socket>>(
io_service_pool_.get_io_service(), max_req_buf_size_, keep_alive_timeout_, http_handler_, static_dir_,
upload_check_?&upload_check_ : nullptr
#ifdef CINATRA_ENABLE_SSL
, ctx_
#endif
);
acceptor->async_accept(new_conn->socket(), [this, new_conn, acceptor](const boost::system::error_code& e) {
if (!e) {
new_conn->socket().set_option(boost::asio::ip::tcp::no_delay(true));
new_conn->start();
}
else {
//LOG_INFO << "server::handle_accept: " << e.message();
}
start_accept(acceptor);
});
}
void set_static_res_handler()
{
set_http_handler<POST,GET>(STATIC_RESOURCE, [this](request& req, response& res){
if (download_check_) {
bool r = download_check_(req, res);
if (!r)
return;
}
auto state = req.get_state();
switch (state) {
case cinatra::data_proc_state::data_begin:
{
std::string relatice_file_name = req.get_relative_filename();
auto mime = req.get_mime({ relatice_file_name.data(), relatice_file_name.length()});
std::wstring source_path = fs::absolute(relatice_file_name).filename().wstring();
std::wstring root_path = fs::absolute(public_root_path_).filename().wstring();
if(source_path.find(fs::absolute(root_path).filename().wstring()) ==std::string::npos){
auto it = std::find_if(relate_paths_.begin(), relate_paths_.end(), [this, &relatice_file_name](auto& str) {
auto pos = relatice_file_name.find(str);
if (pos != std::string::npos) {
relatice_file_name = relatice_file_name.replace(0, str.size(),
public_root_path_.substr(0, public_root_path_.size() - 1));
}
return pos !=std::string::npos;
});
if (it == relate_paths_.end()) {
res.set_status_and_content(status_type::forbidden);
return;
}
}
auto in = std::make_shared<std::ifstream>(relatice_file_name,std::ios_base::binary);
if (!in->is_open()) {
res.set_status_and_content(status_type::not_found,"");
return;
}
if(is_small_file(in.get(),req)){
send_small_file(res, in.get(), mime);
return;
}
write_chunked_header(req, in, mime);
}
break;
case cinatra::data_proc_state::data_continue:
{
write_chunked_body(req);
}
break;
case cinatra::data_proc_state::data_end:
{
auto conn = req.get_conn();
conn->on_close();
}
break;
case cinatra::data_proc_state::data_error:
{
//network error
}
break;
}
},enable_cache{false});
}
bool is_small_file(std::ifstream* in,request& req) const {
auto file_begin = in->tellg();
in->seekg(0, std::ios_base::end);
auto file_size = in->tellg();
in->seekg(file_begin);
req.save_request_static_file_size(file_size);
return file_size <= 5 * 1024 * 1024;
}
void send_small_file(response& res, std::ifstream* in, std::string_view mime) {
res.add_header("Access-Control-Allow-origin", "*");
res.add_header("Content-type", std::string(mime.data(), mime.size()) + "; charset=utf8");
std::stringstream file_buffer;
file_buffer << in->rdbuf();
if (static_res_cache_max_age_>0)
{
std::string max_age = std::string("max-age=") + std::to_string(static_res_cache_max_age_);
res.add_header("Cache-Control", max_age.data());
}
#ifdef CINATRA_ENABLE_GZIP
res.set_status_and_content(status_type::ok, file_buffer.str(), res_content_type::none, content_encoding::gzip);
#else
res.set_status_and_content(status_type::ok, file_buffer.str());
#endif
}
void write_chunked_header(request& req, std::shared_ptr<std::ifstream> in, std::string_view mime) {
auto range_header = req.get_header_value("range");
req.set_range_flag(!range_header.empty());
req.set_range_start_pos(range_header);
std::string res_content_header = std::string(mime.data(), mime.size()) + "; charset=utf8";
res_content_header += std::string("\r\n") + std::string("Access-Control-Allow-origin: *");
res_content_header += std::string("\r\n") + std::string("Accept-Ranges: bytes");
if (static_res_cache_max_age_>0)
{
std::string max_age = std::string("max-age=") + std::to_string(static_res_cache_max_age_);
res_content_header += std::string("\r\n") + std::string("Cache-Control: ") + max_age;
}
auto conn = req.get_conn();
conn->set_tag(in);
if(req.is_range())
{
std::int64_t file_pos = req.get_range_start_pos();
in->seekg(file_pos);
auto end_str = std::to_string(req.get_request_static_file_size());
res_content_header += std::string("\r\n") +std::string("Content-Range: bytes ")+std::to_string(file_pos)+std::string("-")+std::to_string(req.get_request_static_file_size()-1)+std::string("/")+end_str;
}
conn->write_chunked_header(std::string_view(res_content_header.data(), res_content_header.size()),req.is_range());
}
void write_chunked_body(request& req) {
auto conn = req.get_conn();
auto in = std::any_cast<std::shared_ptr<std::ifstream>>(conn->get_tag());
std::string str;
const size_t len = 3 * 1024 * 1024;
str.resize(len);
in->read(&str[0], len);
size_t read_len = (size_t)in->gcount();
if (read_len != len) {
str.resize(read_len);
}
bool eof = (read_len == 0 || read_len != len);
conn->write_chunked_data(std::move(str), eof);
}
void init_conn_callback() {
set_static_res_handler();
http_handler_ = [this](request& req, response& res) {
res.set_base_path(this->base_path_[0],this->base_path_[1]);
res.set_url(req.get_url());
try {
bool success = http_router_.route(req.get_method(), req.get_url(), req, res);
if (!success) {
res.set_status_and_content(status_type::bad_request, "the url is not right");
}
}
catch (const std::exception& ex) {
res.set_status_and_content(status_type::internal_server_error, ex.what()+std::string(" exception in business function"));
}
catch (...) {
res.set_status_and_content(status_type::internal_server_error, "unknown exception in business function");
}
};
}
service_pool_policy io_service_pool_;
std::size_t max_req_buf_size_ = 3 * 1024 * 1024; //max request buffer size 3M
long keep_alive_timeout_ = 60; //max request timeout 60s
http_router http_router_;
std::string static_dir_ = "./public/static/"; //default
std::string base_path_[2] = {"base_path","/"};
std::time_t static_res_cache_max_age_ = 0;
std::string public_root_path_ = "./";
// https_config ssl_cfg_;
#ifdef CINATRA_ENABLE_SSL
boost::asio::ssl::context ctx_;
#endif
http_handler http_handler_ = nullptr;
std::function<bool(request& req, response& res)> download_check_;
std::vector<std::string> relate_paths_;
std::function<bool(request& req, response& res)> upload_check_ = nullptr;
};
using http_server = http_server_<io_service_pool>;
}
|
#pragma once
#include <QSlider>
#include "QtWidgets/QAbstractSlider/qabstractslider_macro.h"
#include "core/NodeWidget/nodewidget.h"
class NSlider : public QSlider, public NodeWidget {
Q_OBJECT
NODEWIDGET_IMPLEMENTATIONS(QSlider)
public:
using QSlider::QSlider; // inherit all constructors of QSlider
void connectSignalsToEventEmitter() {
// Qt Connects: Implement all signal connects here
QABSTRACT_SLIDER_SIGNALS
}
};
|
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <engine/shared/config.h>
#include <game/server/entities/wall.h>
//#include <game/server/entities/zoomkill.h>
#include <game/server/gamecontext.h>
#include <game/server/gameworld.h>
#include "br.h"
CGameControllerBR::CGameControllerBR(class CGameContext *pGameServer)
: IGameController(pGameServer)
{
m_pGameType = "Battle Royale";
//new CWall(&GameServer()->m_World);
}
void CGameControllerBR::Tick()
{
IGameController::Tick();
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/lex-models/model/Intent.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LexModelBuildingService
{
namespace Model
{
Intent::Intent() :
m_intentNameHasBeenSet(false),
m_intentVersionHasBeenSet(false)
{
}
Intent::Intent(const JsonValue& jsonValue) :
m_intentNameHasBeenSet(false),
m_intentVersionHasBeenSet(false)
{
*this = jsonValue;
}
Intent& Intent::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("intentName"))
{
m_intentName = jsonValue.GetString("intentName");
m_intentNameHasBeenSet = true;
}
if(jsonValue.ValueExists("intentVersion"))
{
m_intentVersion = jsonValue.GetString("intentVersion");
m_intentVersionHasBeenSet = true;
}
return *this;
}
JsonValue Intent::Jsonize() const
{
JsonValue payload;
if(m_intentNameHasBeenSet)
{
payload.WithString("intentName", m_intentName);
}
if(m_intentVersionHasBeenSet)
{
payload.WithString("intentVersion", m_intentVersion);
}
return payload;
}
} // namespace Model
} // namespace LexModelBuildingService
} // namespace Aws
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h"
#include <dwmapi.h>
#include "base/macros.h"
#include "base/process/process_handle.h"
#include "base/win/windows_version.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/browser_window_property_manager_win.h"
#include "chrome/browser/ui/views/frame/system_menu_insertion_delegate_win.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/browser/win/titlebar_config.h"
#include "chrome/common/chrome_constants.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/base/theme_provider.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/controls/menu/native_menu_win.h"
#include "ui/views/resources/grit/views_resources.h"
////////////////////////////////////////////////////////////////////////////////
// BrowserDesktopWindowTreeHostWin, public:
BrowserDesktopWindowTreeHostWin::BrowserDesktopWindowTreeHostWin(
views::internal::NativeWidgetDelegate* native_widget_delegate,
views::DesktopNativeWidgetAura* desktop_native_widget_aura,
BrowserView* browser_view,
BrowserFrame* browser_frame)
: DesktopWindowTreeHostWin(native_widget_delegate,
desktop_native_widget_aura),
browser_view_(browser_view),
browser_frame_(browser_frame),
did_gdi_clear_(false) {
}
BrowserDesktopWindowTreeHostWin::~BrowserDesktopWindowTreeHostWin() {
}
views::NativeMenuWin* BrowserDesktopWindowTreeHostWin::GetSystemMenu() {
if (!system_menu_.get()) {
SystemMenuInsertionDelegateWin insertion_delegate;
system_menu_.reset(
new views::NativeMenuWin(browser_frame_->GetSystemMenuModel(),
GetHWND()));
system_menu_->Rebuild(&insertion_delegate);
}
return system_menu_.get();
}
////////////////////////////////////////////////////////////////////////////////
// BrowserDesktopWindowTreeHostWin, BrowserDesktopWindowTreeHost implementation:
views::DesktopWindowTreeHost*
BrowserDesktopWindowTreeHostWin::AsDesktopWindowTreeHost() {
return this;
}
int BrowserDesktopWindowTreeHostWin::GetMinimizeButtonOffset() const {
return minimize_button_metrics_.GetMinimizeButtonOffsetX();
}
bool BrowserDesktopWindowTreeHostWin::UsesNativeSystemMenu() const {
return true;
}
////////////////////////////////////////////////////////////////////////////////
// BrowserDesktopWindowTreeHostWin, views::DesktopWindowTreeHostWin overrides:
int BrowserDesktopWindowTreeHostWin::GetInitialShowState() const {
STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
GetStartupInfo(&si);
return si.wShowWindow;
}
bool BrowserDesktopWindowTreeHostWin::GetClientAreaInsets(
gfx::Insets* insets) const {
// Always use default insets for opaque frame.
if (!ShouldUseNativeFrame())
return false;
// Use default insets for popups and apps, unless we are custom drawing the
// titlebar.
if (!ShouldCustomDrawSystemTitlebar() &&
!browser_view_->IsBrowserTypeNormal())
return false;
if (GetWidget()->IsFullscreen()) {
// In fullscreen mode there is no frame.
*insets = gfx::Insets();
} else {
const int frame_thickness =
display::win::ScreenWin::GetSystemMetricsForHwnd(
GetHWND(), SM_CXSIZEFRAME);
// Reduce the Windows non-client border size because we extend the border
// into our client area in UpdateDWMFrame(). The top inset must be 0 or
// else Windows will draw a full native titlebar outside the client area.
*insets = gfx::Insets(0, frame_thickness, frame_thickness,
frame_thickness) - GetClientEdgeThicknesses();
}
return true;
}
void BrowserDesktopWindowTreeHostWin::HandleCreate() {
DesktopWindowTreeHostWin::HandleCreate();
browser_window_property_manager_ =
BrowserWindowPropertyManager::CreateBrowserWindowPropertyManager(
browser_view_, GetHWND());
}
void BrowserDesktopWindowTreeHostWin::HandleDestroying() {
browser_window_property_manager_.reset();
DesktopWindowTreeHostWin::HandleDestroying();
}
void BrowserDesktopWindowTreeHostWin::HandleFrameChanged() {
// Reinitialize the status bubble, since it needs to be initialized
// differently depending on whether or not DWM composition is enabled
browser_view_->InitStatusBubble();
// We need to update the glass region on or off before the base class adjusts
// the window region.
UpdateDWMFrame();
DesktopWindowTreeHostWin::HandleFrameChanged();
}
void BrowserDesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(
float window_scale_factor) {
DesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(window_scale_factor);
minimize_button_metrics_.OnDpiChanged();
}
bool BrowserDesktopWindowTreeHostWin::PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
switch (message) {
case WM_ACTIVATE:
if (LOWORD(w_param) != WA_INACTIVE)
minimize_button_metrics_.OnHWNDActivated();
return false;
case WM_ENDSESSION:
chrome::SessionEnding();
return true;
case WM_INITMENUPOPUP:
GetSystemMenu()->UpdateStates();
return true;
}
return DesktopWindowTreeHostWin::PreHandleMSG(
message, w_param, l_param, result);
}
void BrowserDesktopWindowTreeHostWin::PostHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param) {
HWND hwnd = GetHWND();
switch (message) {
case WM_CREATE:
minimize_button_metrics_.Init(hwnd);
break;
case WM_WINDOWPOSCHANGED: {
UpdateDWMFrame();
// Windows lies to us about the position of the minimize button before a
// window is visible. We use this position to place the incognito avatar
// in RTL mode, so when the window is shown, we need to re-layout and
// schedule a paint for the non-client frame view so that the icon top has
// the correct position when the window becomes visible. This fixes bugs
// where the icon appears to overlay the minimize button. Note that we
// will call Layout every time SetWindowPos is called with SWP_SHOWWINDOW,
// however callers typically are careful about not specifying this flag
// unless necessary to avoid flicker. This may be invoked during creation
// on XP and before the non_client_view has been created.
WINDOWPOS* window_pos = reinterpret_cast<WINDOWPOS*>(l_param);
views::NonClientView* non_client_view = GetWidget()->non_client_view();
if (window_pos->flags & SWP_SHOWWINDOW && non_client_view) {
non_client_view->Layout();
non_client_view->SchedulePaint();
}
break;
}
case WM_ERASEBKGND: {
gfx::Insets insets;
if (!did_gdi_clear_ && GetClientAreaInsets(&insets)) {
// This is necessary to avoid white flashing in the titlebar area around
// the minimize/maximize/close buttons.
DCHECK_EQ(0, insets.top());
HDC dc = GetDC(hwnd);
MARGINS margins = GetDWMFrameMargins();
RECT client_rect;
GetClientRect(hwnd, &client_rect);
HBRUSH brush = CreateSolidBrush(0);
RECT rect = {0, 0, client_rect.right, margins.cyTopHeight};
FillRect(dc, &rect, brush);
DeleteObject(brush);
ReleaseDC(hwnd, dc);
did_gdi_clear_ = true;
}
break;
}
case WM_DWMCOLORIZATIONCOLORCHANGED: {
// The activation border may have changed color.
views::NonClientView* non_client_view = GetWidget()->non_client_view();
if (non_client_view)
non_client_view->SchedulePaint();
break;
}
}
}
views::FrameMode BrowserDesktopWindowTreeHostWin::GetFrameMode() const {
const views::FrameMode system_frame_mode =
ShouldCustomDrawSystemTitlebar()
? views::FrameMode::SYSTEM_DRAWN_NO_CONTROLS
: views::FrameMode::SYSTEM_DRAWN;
// We don't theme popup or app windows, so regardless of whether or not a
// theme is active for normal browser windows, we don't want to use the custom
// frame for popups/apps.
if (!browser_view_->IsBrowserTypeNormal() &&
DesktopWindowTreeHostWin::GetFrameMode() ==
views::FrameMode::SYSTEM_DRAWN) {
return system_frame_mode;
}
// Otherwise, we use the native frame when we're told we should by the theme
// provider (e.g. no custom theme is active).
return GetWidget()->GetThemeProvider()->ShouldUseNativeFrame()
? system_frame_mode
: views::FrameMode::CUSTOM_DRAWN;
}
bool BrowserDesktopWindowTreeHostWin::ShouldUseNativeFrame() const {
if (!views::DesktopWindowTreeHostWin::ShouldUseNativeFrame())
return false;
// This function can get called when the Browser window is closed i.e. in the
// context of the BrowserView destructor.
if (!browser_view_->browser())
return false;
// We don't theme popup or app windows, so regardless of whether or not a
// theme is active for normal browser windows, we don't want to use the custom
// frame for popups/apps.
if (!browser_view_->IsBrowserTypeNormal())
return true;
// Otherwise, we use the native frame when we're told we should by the theme
// provider (e.g. no custom theme is active).
return GetWidget()->GetThemeProvider()->ShouldUseNativeFrame();
}
bool BrowserDesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent()
const {
return !ShouldCustomDrawSystemTitlebar() &&
views::DesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent();
}
void BrowserDesktopWindowTreeHostWin::FrameTypeChanged() {
views::DesktopWindowTreeHostWin::FrameTypeChanged();
did_gdi_clear_ = false;
}
////////////////////////////////////////////////////////////////////////////////
// BrowserDesktopWindowTreeHostWin, private:
void BrowserDesktopWindowTreeHostWin::UpdateDWMFrame() {
// For "normal" windows on Aero, we always need to reset the glass area
// correctly, even if we're not currently showing the native frame (e.g.
// because a theme is showing), so we explicitly check for that case rather
// than checking browser_frame_->ShouldUseNativeFrame() here. Using that here
// would mean we wouldn't reset the glass area to zero when moving from the
// native frame to an opaque frame, leading to graphical glitches behind the
// opaque frame. Instead, we use that function below to tell us whether the
// frame is currently native or opaque.
if (!GetWidget()->client_view() || !browser_view_->IsBrowserTypeNormal() ||
!DesktopWindowTreeHostWin::ShouldUseNativeFrame())
return;
MARGINS margins = GetDWMFrameMargins();
DwmExtendFrameIntoClientArea(GetHWND(), &margins);
}
gfx::Insets
BrowserDesktopWindowTreeHostWin::GetClientEdgeThicknesses() const {
// Maximized windows have no visible client edge; the content goes to
// the edge of the screen. Restored windows on Windows 10 don't paint
// the full 3D client edge, but paint content right to the edge of the
// client area.
if (IsMaximized() ||
(base::win::GetVersion() >= base::win::VERSION_WIN10))
return gfx::Insets();
const ui::ThemeProvider* const tp = GetWidget()->GetThemeProvider();
return gfx::Insets(
0, tp->GetImageSkiaNamed(IDR_CONTENT_LEFT_SIDE)->width(),
tp->GetImageSkiaNamed(IDR_CONTENT_BOTTOM_CENTER)->height(),
tp->GetImageSkiaNamed(IDR_CONTENT_RIGHT_SIDE)->width());
}
MARGINS BrowserDesktopWindowTreeHostWin::GetDWMFrameMargins() const {
// Don't extend the glass in at all if it won't be visible.
if (!ShouldUseNativeFrame() || GetWidget()->IsFullscreen() ||
ShouldCustomDrawSystemTitlebar())
return MARGINS{0};
// The glass should extend to the bottom of the tabstrip.
HWND hwnd = GetHWND();
gfx::Rect tabstrip_bounds(
browser_frame_->GetBoundsForTabStrip(browser_view_->tabstrip()));
tabstrip_bounds =
display::win::ScreenWin::DIPToClientRect(hwnd, tabstrip_bounds);
// Extend inwards far enough to go under the semitransparent client edges.
const gfx::Insets thicknesses = GetClientEdgeThicknesses();
gfx::Point left_top = display::win::ScreenWin::DIPToClientPoint(
hwnd, gfx::Point(thicknesses.left(), thicknesses.top()));
gfx::Point right_bottom = display::win::ScreenWin::DIPToClientPoint(
hwnd, gfx::Point(thicknesses.right(), thicknesses.bottom()));
if (base::win::GetVersion() < base::win::VERSION_WIN8) {
// The 2 px (not DIP) at the inner edges of the glass are a light and
// dark line, so we must inset further to account for those.
constexpr gfx::Vector2d kDWMEdgeThickness(2, 2);
left_top += kDWMEdgeThickness;
right_bottom += kDWMEdgeThickness;
}
return MARGINS{left_top.x(), right_bottom.x(),
tabstrip_bounds.bottom() + left_top.y(), right_bottom.y()};
}
////////////////////////////////////////////////////////////////////////////////
// BrowserDesktopWindowTreeHost, public:
// static
BrowserDesktopWindowTreeHost*
BrowserDesktopWindowTreeHost::CreateBrowserDesktopWindowTreeHost(
views::internal::NativeWidgetDelegate* native_widget_delegate,
views::DesktopNativeWidgetAura* desktop_native_widget_aura,
BrowserView* browser_view,
BrowserFrame* browser_frame) {
return new BrowserDesktopWindowTreeHostWin(native_widget_delegate,
desktop_native_widget_aura,
browser_view,
browser_frame);
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2018-2019 The NXBoost developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
namespace {
inline std::string ValueString(const std::vector<unsigned char>& vch)
{
if (vch.size() <= 4)
return strprintf("%d", CScriptNum(vch, false).getint());
else
return HexStr(vch);
}
} // anon namespace
using namespace std;
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_NOP2 : return "OP_NOP2";
case OP_NOP3 : return "OP_NOP3";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
// zerocoin
case OP_ZEROCOINMINT : return "OP_ZEROCOINMINT";
case OP_ZEROCOINSPEND : return "OP_ZEROCOINSPEND";
case OP_ZEROCOINPUBLICSPEND : return "OP_ZEROCOINPUBLICSPEND";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += 20;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsNormalPaymentScript() const
{
if(this->size() != 25) return false;
std::string str;
opcodetype opcode;
const_iterator pc = begin();
int i = 0;
while (pc < end())
{
GetOp(pc, opcode);
if( i == 0 && opcode != OP_DUP) return false;
else if(i == 1 && opcode != OP_HASH160) return false;
else if(i == 3 && opcode != OP_EQUALVERIFY) return false;
else if(i == 4 && opcode != OP_CHECKSIG) return false;
else if(i == 5) return false;
i++;
}
return true;
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
this->at(0) == OP_HASH160 &&
this->at(1) == 0x14 &&
this->at(22) == OP_EQUAL);
}
bool CScript::StartsWithOpcode(const opcodetype opcode) const
{
return (!this->empty() && this->at(0) == opcode);
}
bool CScript::IsZerocoinMint() const
{
return StartsWithOpcode(OP_ZEROCOINMINT);
}
bool CScript::IsZerocoinSpend() const
{
return StartsWithOpcode(OP_ZEROCOINSPEND);
}
bool CScript::IsZerocoinPublicSpend() const
{
return StartsWithOpcode(OP_ZEROCOINPUBLICSPEND);
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
std::string CScript::ToString() const
{
std::string str;
opcodetype opcode;
std::vector<unsigned char> vch;
const_iterator pc = begin();
while (pc < end())
{
if (!str.empty())
str += " ";
if (!GetOp(pc, opcode, vch))
{
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4) {
str += ValueString(vch);
} else {
str += GetOpName(opcode);
if (opcode == OP_ZEROCOINSPEND) {
//Zerocoinspend has no further op codes.
break;
}
}
}
return str;
}
|
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "rss20parser.h"
#include <QDomDocument>
#include <QDomElement>
#include <QStringList>
#include <QtDebug>
#include <util/sll/domchildrenrange.h>
#include <util/sll/prelude.h>
namespace LC
{
namespace Aggregator
{
RSS20Parser& RSS20Parser::Instance ()
{
static RSS20Parser inst;
return inst;
}
bool RSS20Parser::CouldParse (const QDomDocument& doc) const
{
QDomElement root = doc.documentElement ();
return root.tagName () == "rss" &&
root.attribute ("version") == "2.0";
}
channels_container_t RSS20Parser::Parse (const QDomDocument& doc,
const IDType_t& feedId) const
{
channels_container_t channels;
QDomElement root = doc.documentElement ();
for (const auto& channel : Util::DomChildren (root, "channel"))
{
auto chan = std::make_shared<Channel> (Channel::CreateForFeed (feedId));
chan->Title_ = channel.firstChildElement ("title").text ().trimmed ();
chan->Description_ = channel.firstChildElement ("description").text ();
chan->Link_ = GetLink (channel);
chan->LastBuild_ = RFC822TimeToQDateTime (channel.firstChildElement ("lastBuildDate").text ());
chan->Language_ = channel.firstChildElement ("language").text ();
chan->Author_ = GetAuthor (channel);
if (chan->Author_.isEmpty ())
chan->Author_ = channel.firstChildElement ("managingEditor").text ();
if (chan->Author_.isEmpty ())
chan->Author_ = channel.firstChildElement ("webMaster").text ();
chan->PixmapURL_ = channel.firstChildElement ("image").attribute ("url");
chan->Items_ = Util::Map (Util::DomChildren (channel, "item"),
[this, cid = chan->ChannelID_] (const QDomElement& item) { return ParseItem (item, cid); });
if (!chan->LastBuild_.isValid ())
chan->LastBuild_ = chan->Items_.isEmpty () ?
QDateTime::currentDateTime () :
chan->Items_.front ()->PubDate_;
channels.push_back (chan);
}
return channels;
}
Item_ptr RSS20Parser::ParseItem (const QDomElement& item, const IDType_t& channelId) const
{
auto result = std::make_shared<Item> (Item::CreateForChannel (channelId));
result->Title_ = UnescapeHTML (item.firstChildElement ("title").text ());
if (result->Title_.isEmpty ())
result->Title_ = "<>";
result->Link_ = item.firstChildElement ("link").text ();
result->Description_ = item.firstChildElement ("description").text ();
GetDescription (item, result->Description_);
QDomNodeList duration = item.elementsByTagNameNS (ITunes_, "duration");
if (duration.size ())
{
if (!result->Description_.isEmpty ())
result->Description_ += "<br /><br />";
result->Description_ += QObject::tr ("Duration: %1")
.arg (duration.at (0).toElement ().text ());
}
QString pubDateText = item.firstChildElement ("pubDate").text ();
if (pubDateText.size ())
{
result->PubDate_ = RFC822TimeToQDateTime (pubDateText);
if (!result->PubDate_.isValid () || result->PubDate_.isNull ())
result->PubDate_ = QDateTime::currentDateTime ();
}
result->Guid_ = item.firstChildElement ("guid").text ();
if (result->Guid_.isEmpty ())
result->Guid_ = "empty";
result->Categories_ = GetAllCategories (item);
result->Unread_ = true;
result->Author_ = GetAuthor (item);
result->NumComments_ = GetNumComments (item);
result->CommentsLink_ = GetCommentsRSS (item);
result->CommentsPageLink_ = GetCommentsLink (item);
result->Enclosures_ = GetEnclosures (item, result->ItemID_);
result->Enclosures_ += GetEncEnclosures (item, result->ItemID_);
QPair<double, double> point = GetGeoPoint (item);
result->Latitude_ = point.first;
result->Longitude_ = point.second;
result->MRSSEntries_ = GetMediaRSS (item, result->ItemID_);
return result;
}
}
}
|
#pragma once
#include <Tanker/Crypto/PrivateSignatureKey.hpp>
#include <Tanker/Crypto/PublicEncryptionKey.hpp>
#include <Tanker/Crypto/SealedPrivateEncryptionKey.hpp>
#include <Tanker/Trustchain/Actions/UserGroupMember2.hpp>
#include <Tanker/Trustchain/Actions/UserGroupProvisionalMember3.hpp>
#include <Tanker/Trustchain/GroupId.hpp>
#include <Tanker/Trustchain/Preprocessor/Actions/Implementation.hpp>
#include <utility>
#include <vector>
namespace Tanker::Trustchain::Actions
{
#define TANKER_TRUSTCHAIN_ACTIONS_USER_GROUP_ADDITION3_ATTRIBUTES \
(groupId, GroupId), (previousGroupBlockHash, Crypto::Hash), \
(members, std::vector<UserGroupMember2>), \
(provisionalMembers, std::vector<UserGroupProvisionalMember3>), \
(selfSignature, Crypto::Signature)
class UserGroupAddition3
{
public:
using Member = UserGroupMember2;
using ProvisionalMember = UserGroupProvisionalMember3;
TANKER_IMMUTABLE_ACTION_IMPLEMENTATION(
UserGroupAddition3,
TANKER_TRUSTCHAIN_ACTIONS_USER_GROUP_ADDITION3_ATTRIBUTES)
public:
UserGroupAddition3(
TrustchainId const& trustchainId,
GroupId const& groupId,
Crypto::Hash const& previousGroupBlockHash,
std::vector<Member> const& members,
std::vector<ProvisionalMember> const& provisionalMembers,
Crypto::Hash const& author,
Crypto::PrivateSignatureKey const& groupPrivateSignatureKey,
Crypto::PrivateSignatureKey const& devicePrivateSignatureKey);
std::vector<std::uint8_t> signatureData() const;
private:
friend void from_serialized(Serialization::SerializedSource&,
UserGroupAddition3&);
};
TANKER_TRUSTCHAIN_ACTION_DECLARE_SERIALIZATION(UserGroupAddition3)
TANKER_TRUSTCHAIN_ACTION_DECLARE_TO_JSON(UserGroupAddition3)
}
|
/**
* @file Benchmark.cpp
*
* @brief Benchmarking tests for Zerocoin.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017-2018 The PIVX developers
#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>
#include <fstream>
// #include <curses.h>
#include <exception>
#include <cstdlib>
#include <sys/time.h>
#include "streams.h"
#include "libzerocoin/ParamGeneration.h"
#include "libzerocoin/Denominations.h"
#include "libzerocoin/Coin.h"
#include "libzerocoin/CoinSpend.h"
#include "libzerocoin/Accumulator.h"
#include "test_blockchainenergy.h"
using namespace std;
using namespace libzerocoin;
#define COLOR_STR_GREEN "\033[32m"
#define COLOR_STR_NORMAL "\033[0m"
#define COLOR_STR_RED "\033[31m"
#define TESTS_COINS_TO_ACCUMULATE 50
// Global test counters
uint32_t ggNumTests = 0;
uint32_t ggSuccessfulTests = 0;
// Global coin array
PrivateCoin *ggCoins[TESTS_COINS_TO_ACCUMULATE];
// Global params
ZerocoinParams *gg_Params;
//////////
// Utility routines
//////////
class Timer
{
timeval timer[2];
public:
timeval start()
{
gettimeofday(&this->timer[0], NULL);
return this->timer[0];
}
timeval stop()
{
gettimeofday(&this->timer[1], NULL);
return this->timer[1];
}
int duration() const
{
int secs(this->timer[1].tv_sec - this->timer[0].tv_sec);
int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec);
if(usecs < 0)
{
--secs;
usecs += 1000000;
}
return static_cast<int>(secs * 1000 + usecs / 1000.0 + 0.5);
}
};
// Global timer
Timer timer;
void
gLogTestResult(string testName, bool (*testPtr)())
{
string colorGreen(COLOR_STR_GREEN);
string colorNormal(COLOR_STR_NORMAL);
string colorRed(COLOR_STR_RED);
cout << "Testing if " << testName << "..." << endl;
bool testResult = testPtr();
if (testResult == true) {
cout << "\t" << colorGreen << "[PASS]" << colorNormal << endl;
ggSuccessfulTests++;
} else {
cout << colorRed << "\t[FAIL]" << colorNormal << endl;
}
ggNumTests++;
}
CBigNum
gGetTestModulus()
{
static CBigNum testModulus(0);
// TODO: should use a hard-coded RSA modulus for testing
if (!testModulus) {
CBigNum p, q;
p = CBigNum::generatePrime(1024, false);
q = CBigNum::generatePrime(1024, false);
testModulus = p * q;
}
return testModulus;
}
//////////
// Test routines
//////////
bool
Testb_GenRSAModulus()
{
CBigNum result = gGetTestModulus();
if (!result) {
return false;
}
else {
return true;
}
}
bool
Testb_CalcParamSizes()
{
bool result = true;
#if 0
uint32_t pLen, qLen;
try {
calculateGroupParamLengths(4000, 80, &pLen, &qLen);
if (pLen < 1024 || qLen < 256) {
result = false;
}
calculateGroupParamLengths(4000, 96, &pLen, &qLen);
if (pLen < 2048 || qLen < 256) {
result = false;
}
calculateGroupParamLengths(4000, 112, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
calculateGroupParamLengths(4000, 120, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
calculateGroupParamLengths(4000, 128, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
} catch (exception &e) {
result = false;
}
#endif
return result;
}
bool
Testb_GenerateGroupParams()
{
uint32_t pLen = 1024, qLen = 256, count;
IntegerGroupParams group;
for (count = 0; count < 1; count++) {
try {
group = deriveIntegerGroupParams(calculateSeed(gGetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen);
} catch (std::runtime_error e) {
cout << "Caught exception " << e.what() << endl;
return false;
}
// Now perform some simple tests on the resulting parameters
if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) {
return false;
}
CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus);
//cout << "g^q mod p = " << c << endl;
if (!(c.isOne())) return false;
// Try at multiple parameter sizes
pLen = pLen * 1.5;
qLen = qLen * 1.5;
}
return true;
}
bool
Testb_ParamGen()
{
bool result = true;
try {
timer.start();
// Instantiating testParams runs the parameter generation code
ZerocoinParams testParams(gGetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL);
timer.stop();
cout << "\tPARAMGEN ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl;
} catch (runtime_error e) {
cout << e.what() << endl;
result = false;
}
return result;
}
bool
Testb_Accumulator()
{
// This test assumes a list of coins were generated during
// the Testb_MintCoin() test.
if (ggCoins[0] == NULL) {
return false;
}
try {
// Accumulate the coin list from first to last into one accumulator
Accumulator accOne(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE);
Accumulator accTwo(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE);
Accumulator accThree(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE);
Accumulator accFour(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE);
AccumulatorWitness wThree(gg_Params, accThree, ggCoins[0]->getPublicCoin());
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
accOne += ggCoins[i]->getPublicCoin();
accTwo += ggCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin();
accThree += ggCoins[i]->getPublicCoin();
wThree += ggCoins[i]->getPublicCoin();
if(i != 0) {
accFour += ggCoins[i]->getPublicCoin();
}
}
// Compare the accumulated results
if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) {
cout << "Accumulators don't match" << endl;
return false;
}
if(accFour.getValue() != wThree.getValue()) {
cout << "Witness math not working," << endl;
return false;
}
// Verify that the witness is correct
if (!wThree.VerifyWitness(accThree, ggCoins[0]->getPublicCoin()) ) {
cout << "Witness not valid" << endl;
return false;
}
} catch (runtime_error e) {
cout << e.what() << endl;
return false;
}
return true;
}
bool
Testb_MintCoin()
{
try {
// Generate a list of coins
timer.start();
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
ggCoins[i] = new PrivateCoin(gg_Params,CoinDenomination::ZQ_ONE);
}
timer.stop();
} catch (exception &e) {
return false;
}
cout << "\tMINT ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Coin: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << endl;
return true;
}
bool
Testb_MintAndSpend()
{
try {
// This test assumes a list of coins were generated in Testb_MintCoin()
if (ggCoins[0] == NULL)
{
// No coins: mint some.
Testb_MintCoin();
if (ggCoins[0] == NULL) {
return false;
}
}
// Accumulate the list of generated coins into a fresh accumulator.
// The first one gets marked as accumulated for a witness, the
// others just get accumulated normally.
Accumulator acc(&gg_Params->accumulatorParams,CoinDenomination::ZQ_ONE);
AccumulatorWitness wAcc(gg_Params, acc, ggCoins[0]->getPublicCoin());
timer.start();
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
acc += ggCoins[i]->getPublicCoin();
}
timer.stop();
cout << "\tACCUMULATOR ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << endl;
timer.start();
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
wAcc +=ggCoins[i]->getPublicCoin();
}
timer.stop();
cout << "\tWITNESS ELAPSED TIME: \n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << endl;
// Now spend the coin
timer.start();
CoinSpend spend(gg_Params, gg_Params, *(ggCoins[0]), acc, 0, wAcc, 0, SpendType::SPEND); //(0) presstab
timer.stop();
cout << "\tSPEND ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl;
// Serialize the proof and deserialize into newSpend
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
timer.start();
ss << spend;
timer.stop();
CoinSpend newSpend(gg_Params, gg_Params, ss);
cout << "\tSERIALIZE ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl;
// Finally, see if we can verify the deserialized proof (return our result)
timer.start();
bool ret = newSpend.Verify(acc);
timer.stop();
cout << "\tSPEND VERIFY ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl;
return ret;
} catch (runtime_error &e) {
cout << e.what() << endl;
return false;
}
return false;
}
void
Testb_RunAllTests()
{
// Make a new set of parameters from a random RSA modulus
gg_Params = new ZerocoinParams(gGetTestModulus());
ggNumTests = ggSuccessfulTests = 0;
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
ggCoins[i] = NULL;
}
// Run through all of the Zerocoin tests
gLogTestResult("an RSA modulus can be generated", Testb_GenRSAModulus);
gLogTestResult("parameter sizes are correct", Testb_CalcParamSizes);
gLogTestResult("group/field parameters can be generated", Testb_GenerateGroupParams);
gLogTestResult("parameter generation is correct", Testb_ParamGen);
gLogTestResult("coins can be minted", Testb_MintCoin);
gLogTestResult("the accumulator works", Testb_Accumulator);
gLogTestResult("a minted coin can be spent", Testb_MintAndSpend);
// Summarize test results
if (ggSuccessfulTests < ggNumTests) {
cout << endl << "ERROR: SOME TESTS FAILED" << endl;
}
// Clear any generated coins
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
delete ggCoins[i];
}
cout << ggSuccessfulTests << " out of " << ggNumTests << " tests passed." << endl << endl;
delete gg_Params;
}
BOOST_FIXTURE_TEST_SUITE(benchmark_zerocoin, TestingSetup)
BOOST_AUTO_TEST_CASE(benchmark_test)
{
cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " benchmark utility." << endl << endl;
Testb_RunAllTests();
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/wasm-engine.h"
#include "src/base/platform/time.h"
#include "src/diagnostics/code-tracer.h"
#include "src/diagnostics/compilation-statistics.h"
#include "src/execution/frames.h"
#include "src/logging/counters.h"
#include "src/objects/heap-number.h"
#include "src/objects/js-promise.h"
#include "src/objects/objects-inl.h"
#include "src/utils/ostreams.h"
#include "src/wasm/function-compiler.h"
#include "src/wasm/module-compiler.h"
#include "src/wasm/module-decoder.h"
#include "src/wasm/module-instantiate.h"
#include "src/wasm/streaming-decoder.h"
#include "src/wasm/wasm-objects-inl.h"
namespace v8 {
namespace internal {
namespace wasm {
#define TRACE_CODE_GC(...) \
do { \
if (FLAG_trace_wasm_code_gc) PrintF("[wasm-gc] " __VA_ARGS__); \
} while (false)
namespace {
// A task to log a set of {WasmCode} objects in an isolate. It does not own any
// data itself, since it is owned by the platform, so lifetime is not really
// bound to the wasm engine.
class LogCodesTask : public Task {
public:
LogCodesTask(base::Mutex* mutex, LogCodesTask** task_slot, Isolate* isolate,
WasmEngine* engine)
: mutex_(mutex),
task_slot_(task_slot),
isolate_(isolate),
engine_(engine) {
DCHECK_NOT_NULL(task_slot);
DCHECK_NOT_NULL(isolate);
}
~LogCodesTask() {
// If the platform deletes this task before executing it, we also deregister
// it to avoid use-after-free from still-running background threads.
if (!cancelled()) DeregisterTask();
}
void Run() override {
if (cancelled()) return;
DeregisterTask();
engine_->LogOutstandingCodesForIsolate(isolate_);
}
void Cancel() {
// Cancel will only be called on Isolate shutdown, which happens on the
// Isolate's foreground thread. Thus no synchronization needed.
isolate_ = nullptr;
}
bool cancelled() const { return isolate_ == nullptr; }
void DeregisterTask() {
// The task will only be deregistered from the foreground thread (executing
// this task or calling its destructor), thus we do not need synchronization
// on this field access.
if (task_slot_ == nullptr) return; // already deregistered.
// Remove this task from the {IsolateInfo} in the engine. The next
// logging request will allocate and schedule a new task.
base::MutexGuard guard(mutex_);
DCHECK_EQ(this, *task_slot_);
*task_slot_ = nullptr;
task_slot_ = nullptr;
}
private:
// The mutex of the WasmEngine.
base::Mutex* const mutex_;
// The slot in the WasmEngine where this LogCodesTask is stored. This is
// cleared by this task before execution or on task destruction.
LogCodesTask** task_slot_;
Isolate* isolate_;
WasmEngine* const engine_;
};
class WasmGCForegroundTask : public Task {
public:
explicit WasmGCForegroundTask(Isolate* isolate) : isolate_(isolate) {
DCHECK_NOT_NULL(isolate);
}
void Run() final {
if (isolate_ == nullptr) return; // cancelled.
WasmEngine* engine = isolate_->wasm_engine();
// If the foreground task is executing, there is no wasm code active. Just
// report an empty set of live wasm code.
#ifdef ENABLE_SLOW_DCHECKS
for (StackFrameIterator it(isolate_); !it.done(); it.Advance()) {
DCHECK_NE(StackFrame::WASM_COMPILED, it.frame()->type());
}
#endif
engine->ReportLiveCodeForGC(isolate_, Vector<WasmCode*>{});
}
void Cancel() { isolate_ = nullptr; }
private:
Isolate* isolate_;
};
} // namespace
struct WasmEngine::CurrentGCInfo {
explicit CurrentGCInfo(int8_t gc_sequence_index)
: gc_sequence_index(gc_sequence_index) {
DCHECK_NE(0, gc_sequence_index);
}
// Set of isolates that did not scan their stack yet for used WasmCode, and
// their scheduled foreground task.
std::unordered_map<Isolate*, WasmGCForegroundTask*> outstanding_isolates;
// Set of dead code. Filled with all potentially dead code on initialization.
// Code that is still in-use is removed by the individual isolates.
std::unordered_set<WasmCode*> dead_code;
// The number of GCs triggered in the native module that triggered this GC.
// This is stored in the histogram for each participating isolate during
// execution of that isolate's foreground task.
const int8_t gc_sequence_index;
// If during this GC, another GC was requested, we skipped that other GC (we
// only run one GC at a time). Remember though to trigger another one once
// this one finishes. {next_gc_sequence_index} is 0 if no next GC is needed,
// and >0 otherwise. It stores the {num_code_gcs_triggered} of the native
// module which triggered the next GC.
int8_t next_gc_sequence_index = 0;
// The start time of this GC; used for tracing and sampled via {Counters}.
// Can be null ({TimeTicks::IsNull()}) if timer is not high resolution.
base::TimeTicks start_time;
};
struct WasmEngine::IsolateInfo {
explicit IsolateInfo(Isolate* isolate)
: log_codes(WasmCode::ShouldBeLogged(isolate)),
async_counters(isolate->async_counters()) {
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8::Platform* platform = V8::GetCurrentPlatform();
foreground_task_runner = platform->GetForegroundTaskRunner(v8_isolate);
}
#ifdef DEBUG
~IsolateInfo() {
// Before destructing, the {WasmEngine} must have cleared outstanding code
// to log.
DCHECK_EQ(0, code_to_log.size());
}
#endif
// All native modules that are being used by this Isolate (currently only
// grows, never shrinks).
std::set<NativeModule*> native_modules;
// Caches whether code needs to be logged on this isolate.
bool log_codes;
// The currently scheduled LogCodesTask.
LogCodesTask* log_codes_task = nullptr;
// The vector of code objects that still need to be logged in this isolate.
std::vector<WasmCode*> code_to_log;
// The foreground task runner of the isolate (can be called from background).
std::shared_ptr<v8::TaskRunner> foreground_task_runner;
const std::shared_ptr<Counters> async_counters;
};
struct WasmEngine::NativeModuleInfo {
// Set of isolates using this NativeModule.
std::unordered_set<Isolate*> isolates;
// Set of potentially dead code. This set holds one ref for each code object,
// until code is detected to be really dead. At that point, the ref count is
// decremented and code is move to the {dead_code} set. If the code is finally
// deleted, it is also removed from {dead_code}.
std::unordered_set<WasmCode*> potentially_dead_code;
// Code that is not being executed in any isolate any more, but the ref count
// did not drop to zero yet.
std::unordered_set<WasmCode*> dead_code;
// Number of code GCs triggered because code in this native module became
// potentially dead.
int8_t num_code_gcs_triggered = 0;
};
WasmEngine::WasmEngine()
: code_manager_(&memory_tracker_, FLAG_wasm_max_code_space * MB) {}
WasmEngine::~WasmEngine() {
// Synchronize on all background compile tasks.
background_compile_task_manager_.CancelAndWait();
// All AsyncCompileJobs have been canceled.
DCHECK(async_compile_jobs_.empty());
// All Isolates have been deregistered.
DCHECK(isolates_.empty());
// All NativeModules did die.
DCHECK(native_modules_.empty());
}
bool WasmEngine::SyncValidate(Isolate* isolate, const WasmFeatures& enabled,
const ModuleWireBytes& bytes) {
// TODO(titzer): remove dependency on the isolate.
if (bytes.start() == nullptr || bytes.length() == 0) return false;
ModuleResult result =
DecodeWasmModule(enabled, bytes.start(), bytes.end(), true, kWasmOrigin,
isolate->counters(), allocator());
return result.ok();
}
MaybeHandle<AsmWasmData> WasmEngine::SyncCompileTranslatedAsmJs(
Isolate* isolate, ErrorThrower* thrower, const ModuleWireBytes& bytes,
Vector<const byte> asm_js_offset_table_bytes,
Handle<HeapNumber> uses_bitset) {
ModuleResult result =
DecodeWasmModule(kAsmjsWasmFeatures, bytes.start(), bytes.end(), false,
kAsmJsOrigin, isolate->counters(), allocator());
if (result.failed()) {
// This happens once in a while when we have missed some limit check
// in the asm parser. Output an error message to help diagnose, but crash.
std::cout << result.error().message();
UNREACHABLE();
}
// Transfer ownership of the WasmModule to the {Managed<WasmModule>} generated
// in {CompileToNativeModule}.
Handle<FixedArray> export_wrappers;
std::shared_ptr<NativeModule> native_module =
CompileToNativeModule(isolate, kAsmjsWasmFeatures, thrower,
std::move(result).value(), bytes, &export_wrappers);
if (!native_module) return {};
// Create heap objects for asm.js offset table to be stored in the module
// object.
Handle<ByteArray> asm_js_offset_table =
isolate->factory()->NewByteArray(asm_js_offset_table_bytes.length());
asm_js_offset_table->copy_in(0, asm_js_offset_table_bytes.begin(),
asm_js_offset_table_bytes.length());
return AsmWasmData::New(isolate, std::move(native_module), export_wrappers,
asm_js_offset_table, uses_bitset);
}
Handle<WasmModuleObject> WasmEngine::FinalizeTranslatedAsmJs(
Isolate* isolate, Handle<AsmWasmData> asm_wasm_data,
Handle<Script> script) {
std::shared_ptr<NativeModule> native_module =
asm_wasm_data->managed_native_module().get();
Handle<FixedArray> export_wrappers =
handle(asm_wasm_data->export_wrappers(), isolate);
size_t code_size_estimate =
wasm::WasmCodeManager::EstimateNativeModuleCodeSize(
native_module->module());
Handle<WasmModuleObject> module_object =
WasmModuleObject::New(isolate, std::move(native_module), script,
export_wrappers, code_size_estimate);
module_object->set_asm_js_offset_table(asm_wasm_data->asm_js_offset_table());
return module_object;
}
MaybeHandle<WasmModuleObject> WasmEngine::SyncCompile(
Isolate* isolate, const WasmFeatures& enabled, ErrorThrower* thrower,
const ModuleWireBytes& bytes) {
ModuleResult result =
DecodeWasmModule(enabled, bytes.start(), bytes.end(), false, kWasmOrigin,
isolate->counters(), allocator());
if (result.failed()) {
thrower->CompileFailed(result.error());
return {};
}
// Transfer ownership of the WasmModule to the {Managed<WasmModule>} generated
// in {CompileToModuleObject}.
Handle<FixedArray> export_wrappers;
std::shared_ptr<NativeModule> native_module =
CompileToNativeModule(isolate, enabled, thrower,
std::move(result).value(), bytes, &export_wrappers);
if (!native_module) return {};
Handle<Script> script =
CreateWasmScript(isolate, bytes, native_module->module()->source_map_url);
size_t code_size_estimate =
wasm::WasmCodeManager::EstimateNativeModuleCodeSize(
native_module->module());
// Create the module object.
// TODO(clemensh): For the same module (same bytes / same hash), we should
// only have one WasmModuleObject. Otherwise, we might only set
// breakpoints on a (potentially empty) subset of the instances.
// Create the compiled module object and populate with compiled functions
// and information needed at instantiation time. This object needs to be
// serializable. Instantiation may occur off a deserialized version of this
// object.
Handle<WasmModuleObject> module_object =
WasmModuleObject::New(isolate, std::move(native_module), script,
export_wrappers, code_size_estimate);
// Finish the Wasm script now and make it public to the debugger.
isolate->debug()->OnAfterCompile(script);
return module_object;
}
MaybeHandle<WasmInstanceObject> WasmEngine::SyncInstantiate(
Isolate* isolate, ErrorThrower* thrower,
Handle<WasmModuleObject> module_object, MaybeHandle<JSReceiver> imports,
MaybeHandle<JSArrayBuffer> memory) {
return InstantiateToInstanceObject(isolate, thrower, module_object, imports,
memory);
}
void WasmEngine::AsyncInstantiate(
Isolate* isolate, std::unique_ptr<InstantiationResultResolver> resolver,
Handle<WasmModuleObject> module_object, MaybeHandle<JSReceiver> imports) {
ErrorThrower thrower(isolate, "WebAssembly.instantiate()");
// Instantiate a TryCatch so that caught exceptions won't progagate out.
// They will still be set as pending exceptions on the isolate.
// TODO(clemensh): Avoid TryCatch, use Execution::TryCall internally to invoke
// start function and report thrown exception explicitly via out argument.
v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate));
catcher.SetVerbose(false);
catcher.SetCaptureMessage(false);
MaybeHandle<WasmInstanceObject> instance_object = SyncInstantiate(
isolate, &thrower, module_object, imports, Handle<JSArrayBuffer>::null());
if (!instance_object.is_null()) {
resolver->OnInstantiationSucceeded(instance_object.ToHandleChecked());
return;
}
if (isolate->has_pending_exception()) {
// The JS code executed during instantiation has thrown an exception.
// We have to move the exception to the promise chain.
Handle<Object> exception(isolate->pending_exception(), isolate);
isolate->clear_pending_exception();
*isolate->external_caught_exception_address() = false;
resolver->OnInstantiationFailed(exception);
thrower.Reset();
} else {
DCHECK(thrower.error());
resolver->OnInstantiationFailed(thrower.Reify());
}
}
void WasmEngine::AsyncCompile(
Isolate* isolate, const WasmFeatures& enabled,
std::shared_ptr<CompilationResultResolver> resolver,
const ModuleWireBytes& bytes, bool is_shared,
const char* api_method_name_for_errors) {
if (!FLAG_wasm_async_compilation) {
// Asynchronous compilation disabled; fall back on synchronous compilation.
ErrorThrower thrower(isolate, api_method_name_for_errors);
MaybeHandle<WasmModuleObject> module_object;
if (is_shared) {
// Make a copy of the wire bytes to avoid concurrent modification.
std::unique_ptr<uint8_t[]> copy(new uint8_t[bytes.length()]);
memcpy(copy.get(), bytes.start(), bytes.length());
ModuleWireBytes bytes_copy(copy.get(), copy.get() + bytes.length());
module_object = SyncCompile(isolate, enabled, &thrower, bytes_copy);
} else {
// The wire bytes are not shared, OK to use them directly.
module_object = SyncCompile(isolate, enabled, &thrower, bytes);
}
if (thrower.error()) {
resolver->OnCompilationFailed(thrower.Reify());
return;
}
Handle<WasmModuleObject> module = module_object.ToHandleChecked();
resolver->OnCompilationSucceeded(module);
return;
}
if (FLAG_wasm_test_streaming) {
std::shared_ptr<StreamingDecoder> streaming_decoder =
StartStreamingCompilation(
isolate, enabled, handle(isolate->context(), isolate),
api_method_name_for_errors, std::move(resolver));
streaming_decoder->OnBytesReceived(bytes.module_bytes());
streaming_decoder->Finish();
return;
}
// Make a copy of the wire bytes in case the user program changes them
// during asynchronous compilation.
std::unique_ptr<byte[]> copy(new byte[bytes.length()]);
memcpy(copy.get(), bytes.start(), bytes.length());
AsyncCompileJob* job =
CreateAsyncCompileJob(isolate, enabled, std::move(copy), bytes.length(),
handle(isolate->context(), isolate),
api_method_name_for_errors, std::move(resolver));
job->Start();
}
std::shared_ptr<StreamingDecoder> WasmEngine::StartStreamingCompilation(
Isolate* isolate, const WasmFeatures& enabled, Handle<Context> context,
const char* api_method_name,
std::shared_ptr<CompilationResultResolver> resolver) {
AsyncCompileJob* job =
CreateAsyncCompileJob(isolate, enabled, std::unique_ptr<byte[]>(nullptr),
0, context, api_method_name, std::move(resolver));
return job->CreateStreamingDecoder();
}
void WasmEngine::CompileFunction(Isolate* isolate, NativeModule* native_module,
uint32_t function_index, ExecutionTier tier) {
// Note we assume that "one-off" compilations can discard detected features.
WasmFeatures detected = kNoWasmFeatures;
WasmCompilationUnit::CompileWasmFunction(
isolate, native_module, &detected,
&native_module->module()->functions[function_index], tier);
}
std::shared_ptr<NativeModule> WasmEngine::ExportNativeModule(
Handle<WasmModuleObject> module_object) {
return module_object->shared_native_module();
}
Handle<WasmModuleObject> WasmEngine::ImportNativeModule(
Isolate* isolate, std::shared_ptr<NativeModule> shared_native_module) {
NativeModule* native_module = shared_native_module.get();
ModuleWireBytes wire_bytes(native_module->wire_bytes());
const WasmModule* module = native_module->module();
Handle<Script> script =
CreateWasmScript(isolate, wire_bytes, module->source_map_url);
size_t code_size = native_module->committed_code_space();
Handle<WasmModuleObject> module_object = WasmModuleObject::New(
isolate, std::move(shared_native_module), script, code_size);
CompileJsToWasmWrappers(isolate, native_module->module(),
handle(module_object->export_wrappers(), isolate));
{
base::MutexGuard lock(&mutex_);
DCHECK_EQ(1, isolates_.count(isolate));
isolates_[isolate]->native_modules.insert(native_module);
DCHECK_EQ(1, native_modules_.count(native_module));
native_modules_[native_module]->isolates.insert(isolate);
}
return module_object;
}
CompilationStatistics* WasmEngine::GetOrCreateTurboStatistics() {
base::MutexGuard guard(&mutex_);
if (compilation_stats_ == nullptr) {
compilation_stats_.reset(new CompilationStatistics());
}
return compilation_stats_.get();
}
void WasmEngine::DumpAndResetTurboStatistics() {
base::MutexGuard guard(&mutex_);
if (compilation_stats_ != nullptr) {
StdoutStream os;
os << AsPrintableStatistics{*compilation_stats_.get(), false} << std::endl;
}
compilation_stats_.reset();
}
CodeTracer* WasmEngine::GetCodeTracer() {
base::MutexGuard guard(&mutex_);
if (code_tracer_ == nullptr) code_tracer_.reset(new CodeTracer(-1));
return code_tracer_.get();
}
AsyncCompileJob* WasmEngine::CreateAsyncCompileJob(
Isolate* isolate, const WasmFeatures& enabled,
std::unique_ptr<byte[]> bytes_copy, size_t length, Handle<Context> context,
const char* api_method_name,
std::shared_ptr<CompilationResultResolver> resolver) {
AsyncCompileJob* job =
new AsyncCompileJob(isolate, enabled, std::move(bytes_copy), length,
context, api_method_name, std::move(resolver));
// Pass ownership to the unique_ptr in {async_compile_jobs_}.
base::MutexGuard guard(&mutex_);
async_compile_jobs_[job] = std::unique_ptr<AsyncCompileJob>(job);
return job;
}
std::unique_ptr<AsyncCompileJob> WasmEngine::RemoveCompileJob(
AsyncCompileJob* job) {
base::MutexGuard guard(&mutex_);
auto item = async_compile_jobs_.find(job);
DCHECK(item != async_compile_jobs_.end());
std::unique_ptr<AsyncCompileJob> result = std::move(item->second);
async_compile_jobs_.erase(item);
return result;
}
bool WasmEngine::HasRunningCompileJob(Isolate* isolate) {
base::MutexGuard guard(&mutex_);
DCHECK_EQ(1, isolates_.count(isolate));
for (auto& entry : async_compile_jobs_) {
if (entry.first->isolate() == isolate) return true;
}
return false;
}
void WasmEngine::DeleteCompileJobsOnIsolate(Isolate* isolate) {
// Under the mutex get all jobs to delete. Then delete them without holding
// the mutex, such that deletion can reenter the WasmEngine.
std::vector<std::unique_ptr<AsyncCompileJob>> jobs_to_delete;
{
base::MutexGuard guard(&mutex_);
DCHECK_EQ(1, isolates_.count(isolate));
for (auto it = async_compile_jobs_.begin();
it != async_compile_jobs_.end();) {
if (it->first->isolate() != isolate) {
++it;
continue;
}
jobs_to_delete.push_back(std::move(it->second));
it = async_compile_jobs_.erase(it);
}
}
}
namespace {
int GetGCTimeMicros(base::TimeTicks start) {
DCHECK(!start.IsNull());
int64_t duration_us = (base::TimeTicks::Now() - start).InMicroseconds();
return static_cast<int>(
std::min(std::max(int64_t{0}, duration_us), int64_t{kMaxInt}));
}
} // namespace
void WasmEngine::AddIsolate(Isolate* isolate) {
base::MutexGuard guard(&mutex_);
DCHECK_EQ(0, isolates_.count(isolate));
isolates_.emplace(isolate, base::make_unique<IsolateInfo>(isolate));
// Install sampling GC callback.
// TODO(v8:7424): For now we sample module sizes in a GC callback. This will
// bias samples towards apps with high memory pressure. We should switch to
// using sampling based on regular intervals independent of the GC.
auto callback = [](v8::Isolate* v8_isolate, v8::GCType type,
v8::GCCallbackFlags flags, void* data) {
Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
Counters* counters = isolate->counters();
WasmEngine* engine = isolate->wasm_engine();
base::MutexGuard lock(&engine->mutex_);
DCHECK_EQ(1, engine->isolates_.count(isolate));
for (auto* native_module : engine->isolates_[isolate]->native_modules) {
native_module->SampleCodeSize(counters, NativeModule::kSampling);
}
// If there is an ongoing code GC, sample its time here. This will record
// samples for very long-running or never ending GCs.
if (engine->current_gc_info_ &&
!engine->current_gc_info_->start_time.IsNull()) {
isolate->counters()->wasm_code_gc_time()->AddSample(
GetGCTimeMicros(engine->current_gc_info_->start_time));
}
};
isolate->heap()->AddGCEpilogueCallback(callback, v8::kGCTypeMarkSweepCompact,
nullptr);
}
void WasmEngine::RemoveIsolate(Isolate* isolate) {
base::MutexGuard guard(&mutex_);
auto it = isolates_.find(isolate);
DCHECK_NE(isolates_.end(), it);
std::unique_ptr<IsolateInfo> info = std::move(it->second);
isolates_.erase(it);
for (NativeModule* native_module : info->native_modules) {
DCHECK_EQ(1, native_modules_.count(native_module));
DCHECK_EQ(1, native_modules_[native_module]->isolates.count(isolate));
auto* info = native_modules_[native_module].get();
info->isolates.erase(isolate);
if (current_gc_info_) {
for (WasmCode* code : info->potentially_dead_code) {
current_gc_info_->dead_code.erase(code);
}
}
}
if (current_gc_info_) {
if (RemoveIsolateFromCurrentGC(isolate)) PotentiallyFinishCurrentGC();
}
if (auto* task = info->log_codes_task) task->Cancel();
if (!info->code_to_log.empty()) {
WasmCode::DecrementRefCount(VectorOf(info->code_to_log));
info->code_to_log.clear();
}
}
void WasmEngine::LogCode(WasmCode* code) {
base::MutexGuard guard(&mutex_);
NativeModule* native_module = code->native_module();
DCHECK_EQ(1, native_modules_.count(native_module));
for (Isolate* isolate : native_modules_[native_module]->isolates) {
DCHECK_EQ(1, isolates_.count(isolate));
IsolateInfo* info = isolates_[isolate].get();
if (info->log_codes == false) continue;
if (info->log_codes_task == nullptr) {
auto new_task = base::make_unique<LogCodesTask>(
&mutex_, &info->log_codes_task, isolate, this);
info->log_codes_task = new_task.get();
info->foreground_task_runner->PostTask(std::move(new_task));
}
if (info->code_to_log.empty()) {
isolate->stack_guard()->RequestLogWasmCode();
}
info->code_to_log.push_back(code);
code->IncRef();
}
}
void WasmEngine::EnableCodeLogging(Isolate* isolate) {
base::MutexGuard guard(&mutex_);
auto it = isolates_.find(isolate);
DCHECK_NE(isolates_.end(), it);
it->second->log_codes = true;
}
void WasmEngine::LogOutstandingCodesForIsolate(Isolate* isolate) {
// If by now we should not log code any more, do not log it.
if (!WasmCode::ShouldBeLogged(isolate)) return;
// Under the mutex, get the vector of wasm code to log. Then log and decrement
// the ref count without holding the mutex.
std::vector<WasmCode*> code_to_log;
{
base::MutexGuard guard(&mutex_);
DCHECK_EQ(1, isolates_.count(isolate));
code_to_log.swap(isolates_[isolate]->code_to_log);
}
if (code_to_log.empty()) return;
for (WasmCode* code : code_to_log) {
code->LogCode(isolate);
}
WasmCode::DecrementRefCount(VectorOf(code_to_log));
}
std::shared_ptr<NativeModule> WasmEngine::NewNativeModule(
Isolate* isolate, const WasmFeatures& enabled, size_t code_size_estimate,
bool can_request_more, std::shared_ptr<const WasmModule> module) {
std::shared_ptr<NativeModule> native_module =
code_manager_.NewNativeModule(this, isolate, enabled, code_size_estimate,
can_request_more, std::move(module));
base::MutexGuard lock(&mutex_);
auto pair = native_modules_.insert(std::make_pair(
native_module.get(), base::make_unique<NativeModuleInfo>()));
DCHECK(pair.second); // inserted new entry.
pair.first->second.get()->isolates.insert(isolate);
isolates_[isolate]->native_modules.insert(native_module.get());
return native_module;
}
void WasmEngine::FreeNativeModule(NativeModule* native_module) {
base::MutexGuard guard(&mutex_);
auto it = native_modules_.find(native_module);
DCHECK_NE(native_modules_.end(), it);
for (Isolate* isolate : it->second->isolates) {
DCHECK_EQ(1, isolates_.count(isolate));
IsolateInfo* info = isolates_[isolate].get();
DCHECK_EQ(1, info->native_modules.count(native_module));
info->native_modules.erase(native_module);
// If there are {WasmCode} objects of the deleted {NativeModule}
// outstanding to be logged in this isolate, remove them. Decrementing the
// ref count is not needed, since the {NativeModule} dies anyway.
size_t remaining = info->code_to_log.size();
if (remaining > 0) {
for (size_t i = 0; i < remaining; ++i) {
while (i < remaining &&
info->code_to_log[i]->native_module() == native_module) {
// Move the last remaining item to this slot (this can be the same
// as {i}, which is OK).
info->code_to_log[i] = info->code_to_log[--remaining];
}
}
info->code_to_log.resize(remaining);
}
}
// If there is a GC running which has references to code contained in the
// deleted {NativeModule}, remove those references.
if (current_gc_info_) {
for (auto it = current_gc_info_->dead_code.begin(),
end = current_gc_info_->dead_code.end();
it != end;) {
if ((*it)->native_module() == native_module) {
it = current_gc_info_->dead_code.erase(it);
} else {
++it;
}
}
TRACE_CODE_GC("Native module %p died, reducing dead code objects to %zu.\n",
native_module, current_gc_info_->dead_code.size());
}
native_modules_.erase(it);
}
namespace {
class SampleTopTierCodeSizeTask : public CancelableTask {
public:
SampleTopTierCodeSizeTask(Isolate* isolate,
std::weak_ptr<NativeModule> native_module)
: CancelableTask(isolate),
isolate_(isolate),
native_module_(std::move(native_module)) {}
void RunInternal() override {
if (std::shared_ptr<NativeModule> native_module = native_module_.lock()) {
native_module->SampleCodeSize(isolate_->counters(),
NativeModule::kAfterTopTier);
}
}
private:
Isolate* const isolate_;
const std::weak_ptr<NativeModule> native_module_;
};
} // namespace
void WasmEngine::SampleTopTierCodeSizeInAllIsolates(
const std::shared_ptr<NativeModule>& native_module) {
base::MutexGuard lock(&mutex_);
DCHECK_EQ(1, native_modules_.count(native_module.get()));
for (Isolate* isolate : native_modules_[native_module.get()]->isolates) {
DCHECK_EQ(1, isolates_.count(isolate));
IsolateInfo* info = isolates_[isolate].get();
info->foreground_task_runner->PostTask(
base::make_unique<SampleTopTierCodeSizeTask>(isolate, native_module));
}
}
void WasmEngine::ReportLiveCodeForGC(Isolate* isolate,
Vector<WasmCode*> live_code) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm"), "ReportLiveCodeForGC");
TRACE_CODE_GC("Isolate %d reporting %zu live code objects.\n", isolate->id(),
live_code.size());
base::MutexGuard guard(&mutex_);
// This report might come in late (note that we trigger both a stack guard and
// a foreground task). In that case, ignore it.
if (current_gc_info_ == nullptr) return;
if (!RemoveIsolateFromCurrentGC(isolate)) return;
isolate->counters()->wasm_module_num_triggered_code_gcs()->AddSample(
current_gc_info_->gc_sequence_index);
for (WasmCode* code : live_code) current_gc_info_->dead_code.erase(code);
PotentiallyFinishCurrentGC();
}
void WasmEngine::ReportLiveCodeFromStackForGC(Isolate* isolate) {
wasm::WasmCodeRefScope code_ref_scope;
std::unordered_set<wasm::WasmCode*> live_wasm_code;
for (StackFrameIterator it(isolate); !it.done(); it.Advance()) {
StackFrame* const frame = it.frame();
if (frame->type() != StackFrame::WASM_COMPILED) continue;
live_wasm_code.insert(WasmCompiledFrame::cast(frame)->wasm_code());
}
ReportLiveCodeForGC(isolate,
OwnedVector<WasmCode*>::Of(live_wasm_code).as_vector());
}
bool WasmEngine::AddPotentiallyDeadCode(WasmCode* code) {
base::MutexGuard guard(&mutex_);
auto it = native_modules_.find(code->native_module());
DCHECK_NE(native_modules_.end(), it);
NativeModuleInfo* info = it->second.get();
if (info->dead_code.count(code)) return false; // Code is already dead.
auto added = info->potentially_dead_code.insert(code);
if (!added.second) return false; // An entry already existed.
new_potentially_dead_code_size_ += code->instructions().size();
if (FLAG_wasm_code_gc) {
// Trigger a GC if 64kB plus 10% of committed code are potentially dead.
size_t dead_code_limit =
FLAG_stress_wasm_code_gc
? 0
: 64 * KB + code_manager_.committed_code_space() / 10;
if (new_potentially_dead_code_size_ > dead_code_limit) {
bool inc_gc_count =
info->num_code_gcs_triggered < std::numeric_limits<int8_t>::max();
if (current_gc_info_ == nullptr) {
if (inc_gc_count) ++info->num_code_gcs_triggered;
TRACE_CODE_GC(
"Triggering GC (potentially dead: %zu bytes; limit: %zu bytes).\n",
new_potentially_dead_code_size_, dead_code_limit);
TriggerGC(info->num_code_gcs_triggered);
} else if (current_gc_info_->next_gc_sequence_index == 0) {
if (inc_gc_count) ++info->num_code_gcs_triggered;
TRACE_CODE_GC(
"Scheduling another GC after the current one (potentially dead: "
"%zu bytes; limit: %zu bytes).\n",
new_potentially_dead_code_size_, dead_code_limit);
current_gc_info_->next_gc_sequence_index = info->num_code_gcs_triggered;
DCHECK_NE(0, current_gc_info_->next_gc_sequence_index);
}
}
}
return true;
}
void WasmEngine::FreeDeadCode(const DeadCodeMap& dead_code) {
base::MutexGuard guard(&mutex_);
FreeDeadCodeLocked(dead_code);
}
void WasmEngine::FreeDeadCodeLocked(const DeadCodeMap& dead_code) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm"), "FreeDeadCode");
DCHECK(!mutex_.TryLock());
for (auto& dead_code_entry : dead_code) {
NativeModule* native_module = dead_code_entry.first;
const std::vector<WasmCode*>& code_vec = dead_code_entry.second;
DCHECK_EQ(1, native_modules_.count(native_module));
auto* info = native_modules_[native_module].get();
TRACE_CODE_GC("Freeing %zu code object%s of module %p.\n", code_vec.size(),
code_vec.size() == 1 ? "" : "s", native_module);
for (WasmCode* code : code_vec) {
DCHECK_EQ(1, info->dead_code.count(code));
info->dead_code.erase(code);
}
native_module->FreeCode(VectorOf(code_vec));
}
}
void WasmEngine::TriggerGC(int8_t gc_sequence_index) {
DCHECK_NULL(current_gc_info_);
DCHECK(FLAG_wasm_code_gc);
new_potentially_dead_code_size_ = 0;
current_gc_info_.reset(new CurrentGCInfo(gc_sequence_index));
if (base::TimeTicks::IsHighResolution()) {
current_gc_info_->start_time = base::TimeTicks::Now();
}
// Add all potentially dead code to this GC, and trigger a GC task in each
// isolate.
for (auto& entry : native_modules_) {
NativeModuleInfo* info = entry.second.get();
if (info->potentially_dead_code.empty()) continue;
for (auto* isolate : native_modules_[entry.first]->isolates) {
auto& gc_task = current_gc_info_->outstanding_isolates[isolate];
if (!gc_task) {
auto new_task = base::make_unique<WasmGCForegroundTask>(isolate);
gc_task = new_task.get();
DCHECK_EQ(1, isolates_.count(isolate));
isolates_[isolate]->foreground_task_runner->PostTask(
std::move(new_task));
}
isolate->stack_guard()->RequestWasmCodeGC();
}
for (WasmCode* code : info->potentially_dead_code) {
current_gc_info_->dead_code.insert(code);
}
}
TRACE_CODE_GC(
"Starting GC. Total number of potentially dead code objects: %zu\n",
current_gc_info_->dead_code.size());
}
bool WasmEngine::RemoveIsolateFromCurrentGC(Isolate* isolate) {
DCHECK(!mutex_.TryLock());
DCHECK_NOT_NULL(current_gc_info_);
auto it = current_gc_info_->outstanding_isolates.find(isolate);
if (it == current_gc_info_->outstanding_isolates.end()) return false;
if (auto* fg_task = it->second) fg_task->Cancel();
current_gc_info_->outstanding_isolates.erase(it);
return true;
}
void WasmEngine::PotentiallyFinishCurrentGC() {
DCHECK(!mutex_.TryLock());
TRACE_CODE_GC(
"Remaining dead code objects: %zu; outstanding isolates: %zu.\n",
current_gc_info_->dead_code.size(),
current_gc_info_->outstanding_isolates.size());
// If there are more outstanding isolates, return immediately.
if (!current_gc_info_->outstanding_isolates.empty()) return;
// All remaining code in {current_gc_info->dead_code} is really dead.
// Move it from the set of potentially dead code to the set of dead code,
// and decrement its ref count.
size_t num_freed = 0;
DeadCodeMap dead_code;
for (WasmCode* code : current_gc_info_->dead_code) {
DCHECK_EQ(1, native_modules_.count(code->native_module()));
auto* native_module_info = native_modules_[code->native_module()].get();
DCHECK_EQ(1, native_module_info->potentially_dead_code.count(code));
native_module_info->potentially_dead_code.erase(code);
DCHECK_EQ(0, native_module_info->dead_code.count(code));
native_module_info->dead_code.insert(code);
if (code->DecRefOnDeadCode()) {
dead_code[code->native_module()].push_back(code);
++num_freed;
}
}
FreeDeadCodeLocked(dead_code);
int duration_us = 0;
if (!current_gc_info_->start_time.IsNull()) {
duration_us = GetGCTimeMicros(current_gc_info_->start_time);
for (auto& entry : isolates_) {
entry.second->async_counters->wasm_code_gc_time()->AddSample(duration_us);
}
}
TRACE_CODE_GC("Took %d us; found %zu dead code objects, freed %zu.\n",
duration_us, current_gc_info_->dead_code.size(), num_freed);
USE(num_freed);
int8_t next_gc_sequence_index = current_gc_info_->next_gc_sequence_index;
current_gc_info_.reset();
if (next_gc_sequence_index != 0) TriggerGC(next_gc_sequence_index);
}
namespace {
DEFINE_LAZY_LEAKY_OBJECT_GETTER(std::shared_ptr<WasmEngine>,
GetSharedWasmEngine)
} // namespace
// static
void WasmEngine::InitializeOncePerProcess() {
if (!FLAG_wasm_shared_engine) return;
*GetSharedWasmEngine() = std::make_shared<WasmEngine>();
}
// static
void WasmEngine::GlobalTearDown() {
if (!FLAG_wasm_shared_engine) return;
GetSharedWasmEngine()->reset();
}
// static
std::shared_ptr<WasmEngine> WasmEngine::GetWasmEngine() {
if (FLAG_wasm_shared_engine) return *GetSharedWasmEngine();
return std::make_shared<WasmEngine>();
}
// {max_mem_pages} is declared in wasm-limits.h.
uint32_t max_mem_pages() {
STATIC_ASSERT(kV8MaxWasmMemoryPages <= kMaxUInt32);
return std::min(uint32_t{kV8MaxWasmMemoryPages}, FLAG_wasm_max_mem_pages);
}
// {max_table_init_entries} is declared in wasm-limits.h.
uint32_t max_table_init_entries() {
return std::min(uint32_t{kV8MaxWasmTableInitEntries},
FLAG_wasm_max_table_size);
}
#undef TRACE_CODE_GC
} // namespace wasm
} // namespace internal
} // namespace v8
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include "vast/compression.hpp"
#include "vast/concept/printable/core/printer.hpp"
#include "vast/concept/printable/string/string.hpp"
namespace vast {
struct compression_printer : printer<compression_printer> {
using attribute = compression;
template <class Iterator>
bool print(Iterator& out, const compression& method) const {
using namespace printers;
switch (method) {
case compression::null:
return str.print(out, "null");
case compression::lz4:
return str.print(out, "lz4");
}
return false;
}
};
template <>
struct printer_registry<compression> {
using type = compression_printer;
};
} // namespace vast
|
#pragma once
#include "config.h"
#include "compiler.hh"
#include "Interface.hh"
#include "Transaction.hh"
class TransAlloc : public TObject {
public:
static constexpr TransItem::flags_type alloc_flag = TransItem::user0_bit;
typedef void (*free_type)(void*);
// used to free things only if successful commit
void transFree(void *ptr) {
Sto::new_item(this, ptr).template add_write<free_type, free_type>(::free);
}
// malloc() which will be freed on abort
void* transMalloc(size_t sz) {
void *ptr = malloc(sz);
Sto::new_item(this, ptr).template add_write<free_type, free_type>(::free).add_flags(alloc_flag);
return ptr;
}
// delete which only applies if transaction commits
template <typename T>
void transDelete(T *x) {
Sto::new_item(this, x).template add_write<free_type, free_type>(&ObjectDestroyer<T>::destroy_and_free);
}
// new which will be delete'd on abort.
// arguments go to T's constructor
template <typename T, typename... Args>
T* transNew(Args&&... args) {
T* x = new T(std::forward<Args>(args)...);
Sto::new_item(this, x).template add_write<free_type, free_type>(&ObjectDestroyer<T>::destroy_and_free).add_flags(alloc_flag);
return x;
}
bool lock(TransItem&, Transaction&) override { return true; }
bool check(TransItem&, Transaction&) override { return false; }
void install(TransItem&, Transaction&) override {}
void unlock(TransItem&) override {}
void cleanup(TransItem& item, bool committed) override {
if (committed == !item.has_flag(alloc_flag))
Transaction::rcu_call(item.write_value<free_type>(), item.key<void*>());
}
void print(std::ostream& w, const TransItem& item) const override {
w << "{TransAlloc @" << item.key<void*>();
if (item.write_value<int>())
w << ".alloc}";
else
w << ".free}";
}
};
|
// Font definition for LCD 3110 library
// 5 x 7 font
// 1 pixel space at left and bottom
// index = ASCII - 32
#include <avr/pgmspace.h>
//***** Small fonts (5x7) **********
// This does not strictly follow ASCII table
//
static const unsigned char smallFont[] PROGMEM =
{
0x00, 0x00, 0x00, 0x00, 0x00 , // sp
0x00, 0x00, 0x2f, 0x00, 0x00 , // !
0x00, 0x07, 0x00, 0x07, 0x00 , // "
0x14, 0x7f, 0x14, 0x7f, 0x14 , // #
0x24, 0x2a, 0x7f, 0x2a, 0x12 , // $
0x61, 0x66, 0x08, 0x33, 0x43 , // %
0x36, 0x49, 0x55, 0x22, 0x50 , // &
0x00, 0x05, 0x03, 0x00, 0x00 , // '
0x00, 0x1c, 0x22, 0x41, 0x00 , // (
0x00, 0x41, 0x22, 0x1c, 0x00 , // )
0x14, 0x08, 0x3E, 0x08, 0x14 , // *
0x08, 0x08, 0x3E, 0x08, 0x08 , // +
0x00, 0x00, 0x50, 0x30, 0x00 , // ,
0x10, 0x10, 0x10, 0x10, 0x10 , // -
0x00, 0x60, 0x60, 0x00, 0x00 , // .
0x20, 0x10, 0x08, 0x04, 0x02 , // /
0x3E, 0x51, 0x49, 0x45, 0x3E , // 0
0x00, 0x42, 0x7F, 0x40, 0x00 , // 1
0x42, 0x61, 0x51, 0x49, 0x46 , // 2
0x21, 0x41, 0x45, 0x4B, 0x31 , // 3
0x18, 0x14, 0x12, 0x7F, 0x10 , // 4
0x27, 0x45, 0x45, 0x45, 0x39 , // 5
0x3C, 0x4A, 0x49, 0x49, 0x30 , // 6
0x01, 0x71, 0x09, 0x05, 0x03 , // 7
0x36, 0x49, 0x49, 0x49, 0x36 , // 8
0x06, 0x49, 0x49, 0x29, 0x1E , // 9
0x00, 0x36, 0x36, 0x00, 0x00 , // :
0x00, 0x56, 0x36, 0x00, 0x00 , // ;
0x08, 0x14, 0x22, 0x41, 0x00 , // <
0x14, 0x14, 0x14, 0x14, 0x14 , // =
0x00, 0x41, 0x22, 0x14, 0x08 , // >
0x02, 0x01, 0x51, 0x09, 0x06 , // ?
0x32, 0x49, 0x59, 0x51, 0x3E , // @
0x7E, 0x11, 0x11, 0x11, 0x7E , // A
0x7F, 0x49, 0x49, 0x49, 0x36 , // B
0x3E, 0x41, 0x41, 0x41, 0x22 , // C
0x7F, 0x41, 0x41, 0x22, 0x1C , // D
0x7F, 0x49, 0x49, 0x49, 0x41 , // E
0x7F, 0x09, 0x09, 0x09, 0x01 , // F
0x3E, 0x41, 0x49, 0x49, 0x7A , // G
0x7F, 0x08, 0x08, 0x08, 0x7F , // H
0x00, 0x41, 0x7F, 0x41, 0x00 , // I
0x20, 0x40, 0x41, 0x3F, 0x01 , // J
0x7F, 0x08, 0x14, 0x22, 0x41 , // K
0x7F, 0x40, 0x40, 0x40, 0x40 , // L
0x7F, 0x02, 0x0C, 0x02, 0x7F , // M
0x7F, 0x04, 0x08, 0x10, 0x7F , // N
0x3E, 0x41, 0x41, 0x41, 0x3E , // O
0x7F, 0x09, 0x09, 0x09, 0x06 , // P
0x3E, 0x41, 0x51, 0x21, 0x5E , // Q
0x7F, 0x09, 0x19, 0x29, 0x46 , // R
0x46, 0x49, 0x49, 0x49, 0x31 , // S
0x01, 0x01, 0x7F, 0x01, 0x01 , // T
0x3F, 0x40, 0x40, 0x40, 0x3F , // U
0x1F, 0x20, 0x40, 0x20, 0x1F , // V
0x3F, 0x40, 0x38, 0x40, 0x3F , // W
0x63, 0x14, 0x08, 0x14, 0x63 , // X
0x07, 0x08, 0x70, 0x08, 0x07 , // Y
0x61, 0x51, 0x49, 0x45, 0x43 , // Z
0x00, 0x7F, 0x41, 0x41, 0x00 , // [
0x55, 0x2A, 0x55, 0x2A, 0x55 , // checker pattern
0x00, 0x41, 0x41, 0x7F, 0x00 , // ]
0x04, 0x02, 0x01, 0x02, 0x04 , // ^
0x40, 0x40, 0x40, 0x40, 0x40 , // _
0x00, 0x01, 0x02, 0x04, 0x00 , // '
0x20, 0x54, 0x54, 0x54, 0x78 , // a
0x7F, 0x48, 0x44, 0x44, 0x38 , // b
0x38, 0x44, 0x44, 0x44, 0x20 , // c
0x38, 0x44, 0x44, 0x48, 0x7F , // d
0x38, 0x54, 0x54, 0x54, 0x18 , // e
0x08, 0x7E, 0x09, 0x01, 0x02 , // f
0x0C, 0x52, 0x52, 0x52, 0x3E , // g
0x7F, 0x08, 0x04, 0x04, 0x78 , // h
0x00, 0x44, 0x7D, 0x40, 0x00 , // i
0x20, 0x40, 0x44, 0x3D, 0x00 , // j
0x7F, 0x10, 0x28, 0x44, 0x00 , // k
0x00, 0x41, 0x7F, 0x40, 0x00 , // l
0x7C, 0x04, 0x18, 0x04, 0x78 , // m
0x7C, 0x08, 0x04, 0x04, 0x78 , // n
0x38, 0x44, 0x44, 0x44, 0x38 , // o
0x7C, 0x14, 0x14, 0x14, 0x08 , // p
0x08, 0x14, 0x14, 0x18, 0x7C , // q
0x7C, 0x08, 0x04, 0x04, 0x08 , // r
0x48, 0x54, 0x54, 0x54, 0x20 , // s
0x04, 0x3F, 0x44, 0x40, 0x20 , // t
0x3C, 0x40, 0x40, 0x20, 0x7C , // u
0x1C, 0x20, 0x40, 0x20, 0x1C , // v
0x3C, 0x40, 0x30, 0x40, 0x3C , // w
0x44, 0x28, 0x10, 0x28, 0x44 , // x
0x0C, 0x50, 0x50, 0x50, 0x3C , // y
0x44, 0x64, 0x54, 0x4C, 0x44 , // z
0x00, 0x06, 0x09, 0x09, 0x06 // Degree symbol
};
|
#include "duktowindow.h"
#include "guibehind.h"
#include "platform.h"
#include "settings.h"
DuktoWindow::DuktoWindow(QWindow *parent) :
QmlApplicationViewer(parent), mGuiBehind(NULL){
this->setTitle(tr("Yetta"));
// this->setIcon(QIcon("/usr/share/pixmaps/.png"));
// 响应用户手册
mDaemonIpcDbus = new DaemonIpcDbus();
// this->setWindowTitle(tr("Kylin Ipmsg"));
// setWindowIcon(QIcon("/usr/share/pixmaps/kylin-ipmsg.png"));
QString iconPath = "/usr/share/icons/ukui-icon-theme-default/64x64/apps/kylin-ipmsg.png";
QFileInfo fi(iconPath);
if (!fi.exists()) {
iconPath = "/usr/share/icons/kylin-icon-theme/64x64/apps/kylin-ipmsg.png";
fi.setFile(iconPath);
if (!fi.exists()) {
iconPath = "/usr/share/pixmaps/kylin-ipmsg.png";
}
}
// this->setIcon(QIcon(iconPath));
this->setIcon(QIcon::fromTheme("kylin-ipmsg"));
setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);
// 固定窗口大小
int fixedWidth = 330;
int fixedHeight = 600;
setMaximumWidth(fixedWidth);
setMinimumWidth(fixedWidth);
setMaximumHeight(fixedHeight);
setMinimumHeight(fixedHeight);
// 固定初始窗口位置到屏幕中央
QRect availableGeometry = qApp->primaryScreen()->availableGeometry();
this->setGeometry((availableGeometry.width() - fixedWidth)/2,
(availableGeometry.height() - fixedHeight)/2,
fixedWidth, fixedHeight);
}
/*
* Summary: set gui reference
* Parameters:
* ref: gui behind object
* Return :
*/
void DuktoWindow::setGuiBehindReference(GuiBehind* ref){
mGuiBehind = ref;
}
/*
* Summary: close event
* Parameters:
* qt close event
* Return :
*/
void DuktoWindow::closeEvent(QCloseEvent *event){
// mGuiBehind->settings()->saveWindowGeometry(saveGeometry());
mGuiBehind->settings()->saveWindowGeometry(frameGeometry());
mGuiBehind->close();
qDebug() << "exit(0)exit(0)exit(0)exit(0)exit(0)";
event->accept();
exit(0);
}
void DuktoWindow::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_F1:
// qDebug() << "DuktoWindow keyPressEvent Key_F1" << mDaemonIpcDbus->daemonIsNotRunning();
if (!mDaemonIpcDbus->daemonIsNotRunning()){
//增加标题栏帮助菜单、F1快捷键打开用户手册
mDaemonIpcDbus->showGuide("kylin-ipmsg");
}
break;
default:
break;
}
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 19998 : 9998;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop DashDark server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "DashDark server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "masternode", &masternode, false, false, true },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "makekeypair", &makekeypair, true, false, true },
{ "getcheckpoint", &getcheckpoint, true, false, false },
{ "sendcheckpoint", &sendcheckpoint, true, false, false },
{ "enforcecheckpoint", &enforcecheckpoint, true, false, false },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: dashdark-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: dashdark-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: dashdark-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use dashdarkd";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=dashdarkrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"DashDark Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
LogPrintf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getpoolinfo" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "enforcecheckpoint" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "enforcecheckpoint" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
LogPrintf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
|
uint32_t to_uint32(const std::string& s) {
size_t l = s.size();
return (uint32_t)std::stoul(s.c_str(), &l, 16);
}
bytes to_bytes(const std::string& source) {
BOOST_REQUIRE(!(source.length() % 2));
bytes output(source.length()/2);
fc::from_hex(source, output.data(), output.size());
return output;
}
|
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "mkldnn_pad_node.h"
#include <legacy/ie_layers.h>
#include <string>
#include <cmath>
#include <mkldnn_types.h>
#include <mkldnn_extension_utils.h>
#include <limits>
#include "ie_parallel.hpp"
#include "common/cpu_memcpy.h"
#include "utils/bfloat16.hpp"
#include <mkldnn_selective_build.h>
using namespace mkldnn;
using namespace MKLDNNPlugin;
using namespace InferenceEngine;
MKLDNNPadNode::MKLDNNPadNode(const InferenceEngine::CNNLayerPtr& layer, const mkldnn::engine& eng, MKLDNNWeightsSharing::Ptr &cache)
: MKLDNNNode(layer, eng, cache) {}
void MKLDNNPadNode::getSupportedDescriptors() {
auto* padLayer = dynamic_cast<PadLayer*>(getCnnLayer().get());
if (padLayer == nullptr)
THROW_IE_EXCEPTION << "Cannot convert Pad layer.";
padsBegin = padLayer->GetParamAsUInts("pads_begin");
padsEnd = padLayer->GetParamAsUInts("pads_end");
SizeVector srcDims = padLayer->insData[0].lock()->getTensorDesc().getDims();
SizeVector dstDims = padLayer->outData[0]->getTensorDesc().getDims();
if (srcDims.size() != dstDims.size() || padsBegin.size() != srcDims.size() || padsEnd.size() != srcDims.size())
THROW_IE_EXCEPTION << padLayer->name << " Incorrect number of input/output dimensions!";
std::string pad_mode = padLayer->GetParamAsString("pad_mode");
if (pad_mode == "constant") {
padMode = CONSTANT;
padValue = padLayer->GetParamAsFloat("pad_value", 0.f);
} else if (pad_mode == "edge") {
padMode = EDGE;
} else if (pad_mode == "reflect") {
padMode = REFLECT;
for (size_t i = 0; i < srcDims.size(); i++) {
if ((srcDims[i] - 1) < padsBegin[i] || (srcDims[i] - 1) < padsEnd[i])
THROW_IE_EXCEPTION << padLayer->name << " Incorrect padsBegin or padsEnd for 'reflect' pad mode";
}
} else if (pad_mode == "symmetric") {
padMode = SYMMETRIC;
for (size_t i = 0; i < srcDims.size(); i++) {
if (srcDims[i] < padsBegin[i] || srcDims[i] < padsEnd[i])
THROW_IE_EXCEPTION << padLayer->name << " Incorrect padsBegin or padsEnd for 'symmetric' pad mode";
}
} else {
THROW_IE_EXCEPTION << padLayer->name
<< " Incorrect pad_mode. Only constants|edge|reflect|symmetric modes are supported!";
}
if (getParentEdges().size() != 1)
THROW_IE_EXCEPTION << "Incorrect number of input edges for layer " << getName();
if (getChildEdges().empty())
THROW_IE_EXCEPTION << "Incorrect number of output edges for layer " << getName();
}
void MKLDNNPadNode::initSupportedPrimitiveDescriptors() {
if (!supportedPrimitiveDescriptors.empty())
return;
std::vector<InferenceEngine::Precision> supportedPrecisions = {InferenceEngine::Precision::FP32, InferenceEngine::Precision::I32,
InferenceEngine::Precision::BF16, InferenceEngine::Precision::I8,
InferenceEngine::Precision::U8};
InferenceEngine::Precision precision = getCnnLayer()->insData[0].lock()->getPrecision();
if (std::find(supportedPrecisions.begin(), supportedPrecisions.end(), precision) == supportedPrecisions.end())
precision = precision.is_float() ? InferenceEngine::Precision::FP32 : InferenceEngine::Precision::I32;
auto dataType = MKLDNNExtensionUtils::IEPrecisionToDataType(precision);
auto srcDims = getParentEdgeAt(0)->getDims();
int numOfDims = srcDims.ToSizeVector().size();
InferenceEngine::LayerConfig config;
config.dynBatchSupport = false;
config.inConfs.resize(1);
config.outConfs.resize(1);
config.inConfs[0].inPlace = -1;
config.inConfs[0].constant = false;
config.outConfs[0].inPlace = -1;
config.outConfs[0].constant = false;
auto pushSupportedPrimitiveDescriptor = [&](memory::format_tag memoryFormat) {
config.inConfs[0].desc = MKLDNNMemoryDesc(getParentEdgeAt(0)->getDims(), dataType, memoryFormat);
config.outConfs[0].desc = MKLDNNMemoryDesc(getChildEdgeAt(0)->getDims(), dataType, memoryFormat);
supportedPrimitiveDescriptors.push_back({config, impl_desc_type::ref, memoryFormat});
};
if (numOfDims == 4)
pushSupportedPrimitiveDescriptor(mkldnn::memory::format_tag::nhwc);
else if (numOfDims == 5)
pushSupportedPrimitiveDescriptor(mkldnn::memory::format_tag::ndhwc);
pushSupportedPrimitiveDescriptor(MKLDNNMemory::GetPlainFormat(getParentEdgeAt(0)->getDims()));
auto canUseBlocked = [=](const size_t blockSize) {
return (padMode == CONSTANT && padsBegin[1] % blockSize == 0 && padsEnd[1] % blockSize == 0) ||
(padMode != CONSTANT && padsBegin[1] == 0 && padsEnd[1] == 0);
};
if (numOfDims == 4) {
if (srcDims[1] % 8 == 0 && canUseBlocked(8))
pushSupportedPrimitiveDescriptor(mkldnn::memory::format_tag::nChw8c);
if (srcDims[1] % 16 == 0 && canUseBlocked(16))
pushSupportedPrimitiveDescriptor(mkldnn::memory::format_tag::nChw16c);
} else if (numOfDims == 5) {
if (srcDims[1] % 8 == 0 && canUseBlocked(8))
pushSupportedPrimitiveDescriptor(mkldnn::memory::format_tag::nCdhw8c);
if (srcDims[1] % 16 == 0 && canUseBlocked(16))
pushSupportedPrimitiveDescriptor(mkldnn::memory::format_tag::nCdhw16c);
}
}
void MKLDNNPadNode::createPrimitive() {
auto& dstMemPtr = getChildEdgeAt(0)->getMemoryPtr();
auto& srcMemPtr = getParentEdgeAt(0)->getMemoryPtr();
if (!dstMemPtr || !dstMemPtr->GetPrimitivePtr())
THROW_IE_EXCEPTION << "Destination memory for Pad " << getName() << " didn't allocate.";
if (!srcMemPtr || !srcMemPtr->GetPrimitivePtr())
THROW_IE_EXCEPTION << "Input memory for Pad " << getName() << " didn't allocate.";
if (getSelectedPrimitiveDescriptor() == nullptr)
THROW_IE_EXCEPTION << "Preferable primitive descriptor for Pad " << getName() << " is not set.";
params.sizeData = this->getSelectedPrimitiveDescriptor()->getConfig().inConfs[0].desc.getPrecision().size();
params.srcDims = getParentEdgeAt(0)->getBlob()->getTensorDesc().getBlockingDesc().getBlockDims();
params.dstDims = getChildEdgeAt(0)->getBlob()->getTensorDesc().getBlockingDesc().getBlockDims();
size_t nDims = params.srcDims.size();
params.srcStrides.resize(nDims, 1);
params.dstStrides.resize(nDims, 1);
for (int i = nDims - 2; i >= 0; i--) {
params.srcStrides[i] = params.srcStrides[i + 1] * params.srcDims[i + 1];
params.dstStrides[i] = params.dstStrides[i + 1] * params.dstDims[i + 1];
}
if (getParentEdgeAt(0)->getMemory().GetDesc().isBlockedCFormat()) {
padsBegin[1] /= params.srcDims[params.srcDims.size() - 1];
padsEnd[1] /= params.srcDims[params.srcDims.size() - 1];
padsBegin.push_back(0);
padsEnd.push_back(0);
} else {
auto order = getParentEdgeAt(0)->getBlob()->getTensorDesc().getBlockingDesc().getOrder();
std::vector<unsigned int> newPadsBegin(padsBegin.size(), 0), newPadsEnd(padsEnd.size(), 0);
for (size_t i = 0; i < padsBegin.size(); ++i) {
newPadsBegin[i] = padsBegin[order[i]];
newPadsEnd[i] = padsEnd[order[i]];
}
padsBegin = newPadsBegin;
padsEnd = newPadsEnd;
}
int beginIdx = 0;
int endIdx = padsBegin.size() - 1;
for (int i = 0; i < padsBegin.size(); ++i) {
if (padsBegin[i] != 0 || padsEnd[i] != 0) {
beginIdx = i - 1;
break;
}
}
for (int i = padsBegin.size() - 1; i >= 0; --i) {
if (padsBegin[i] != 0 || padsEnd[i] != 0) {
endIdx = i;
break;
}
}
size_t nGluingLastDims = params.dstStrides[std::max(endIdx - 1, 0)];
params.nDimsForWork = std::max(endIdx - std::max(beginIdx, 0), 1);
params.workAmount = params.dstDims[0];
for (int i = 1; i <= beginIdx; ++i) {
params.workAmount *= params.dstDims[i];
params.dstDims[0] *= params.dstDims[i];
params.srcDims[0] *= params.srcDims[i];
params.dstStrides[0] /= params.dstDims[i];
params.srcStrides[0] /= params.srcDims[i];
}
if (beginIdx > 0) {
beginIdx++;
params.dstDims.erase(params.dstDims.begin() + 1, params.dstDims.begin() + beginIdx);
params.srcDims.erase(params.srcDims.begin() + 1, params.srcDims.begin() + beginIdx);
params.dstStrides.erase(params.dstStrides.begin() + 1, params.dstStrides.begin() + beginIdx);
params.srcStrides.erase(params.srcStrides.begin() + 1, params.srcStrides.begin() + beginIdx);
padsBegin.erase(padsBegin.begin() + 1, padsBegin.begin() + beginIdx);
padsEnd.erase(padsEnd.begin() + 1, padsEnd.begin() + beginIdx);
}
params.workAmount = params.workAmount * params.dstStrides[0] / nGluingLastDims;
params.lastDstDim = nGluingLastDims;
params.shift = params.dstStrides[params.nDimsForWork];
if (padMode != CONSTANT || (padMode == CONSTANT && padValue == 0)) {
params.lastDstDim *= params.sizeData;
params.shift *= params.sizeData;
}
for (size_t i = 0; i < params.srcDims.size(); ++i)
params.srcODims.push_back(padsBegin[i] + params.srcDims[i]);
if (padMode == REFLECT || padMode == SYMMETRIC) {
int shift = padMode == SYMMETRIC ? 1 : 0;
for (size_t i = 0; i < params.srcDims.size(); ++i)
params.srcDimsForReflectOrSymmetric.push_back(params.srcDims[i] + params.srcODims[i] - 2 + shift);
}
}
void MKLDNNPadNode::execute(mkldnn::stream strm) {
switch (padMode) {
case CONSTANT:
padConstant();
break;
case EDGE:
padEdge();
break;
case REFLECT:
padReflectOrSymmetric();
break;
case SYMMETRIC:
padReflectOrSymmetric(true);
break;
}
}
static inline size_t parallel_init(size_t start, size_t nDims, const SizeVector& dims, SizeVector& indexes) {
for (int j = nDims - 1; j >= 0; j--) {
indexes[j] = start % dims[j];
start = start / dims[j];
}
return start;
}
static inline void parallel_step(size_t nDims, const SizeVector& dims, SizeVector& indexes) {
for (int j = nDims - 1; j >= 0; j--) {
indexes[j] = (indexes[j] + 1) % dims[j];
if (indexes[j] != 0)
return;
}
}
void MKLDNNPadNode::padConstant() {
if (padValue == 0) {
padConstantZero();
return;
}
auto selectedPrimitiveDescriptor = getSelectedPrimitiveDescriptor();
if (!selectedPrimitiveDescriptor)
THROW_IE_EXCEPTION << "CPU Pad node with name '" << getName() << "' doesn't have primitive descriptors.";
InferenceEngine::Precision precision = selectedPrimitiveDescriptor->getConfig().inConfs[0].desc.getPrecision();
OV_SWITCH(MKLDNNPlugin, PadConstantEmitter, this, precision,
OV_CASE(InferenceEngine::Precision::FP32, float),
OV_CASE(InferenceEngine::Precision::I32, int32_t),
OV_CASE(InferenceEngine::Precision::BF16, bfloat16_t),
OV_CASE(InferenceEngine::Precision::I8, int8_t),
OV_CASE(InferenceEngine::Precision::U8, uint8_t));
}
template<typename T>
void MKLDNNPadNode::padConstantCommon() {
T* srcData = reinterpret_cast<T*>(this->getParentEdgeAt(0)->getMemoryPtr()->GetPtr());
T* dstData = reinterpret_cast<T*>(this->getChildEdgeAt(0)->getMemoryPtr()->GetPtr());
T value = static_cast<T>(padValue);
parallel_nt(0, [&](const int ithr, const int nthr) {
size_t start = 0, end = 0;
SizeVector indexes(params.nDimsForWork, 0);
splitter(params.workAmount, nthr, ithr, start, end);
parallel_init(start, params.nDimsForWork, params.dstDims, indexes);
size_t dstIdx = 0;
getDstIdx(indexes, dstIdx);
for (size_t iwork = start; iwork < end; ++iwork, dstIdx += params.lastDstDim) {
size_t j = 0;
for (; j < params.nDimsForWork; ++j) {
if (indexes[j] < padsBegin[j] || indexes[j] >= params.srcODims[j])
break;
}
if (j != params.nDimsForWork) {
std::fill_n(&dstData[dstIdx], params.lastDstDim, value);
parallel_step(params.nDimsForWork, params.dstDims, indexes);
continue;
}
size_t srcIdx = 0;
for (size_t idx = 0; idx < params.nDimsForWork; ++idx)
srcIdx += (indexes[idx] - padsBegin[idx]) * params.srcStrides[idx];
std::fill_n(&dstData[dstIdx], padsBegin[params.nDimsForWork] * params.shift, value);
cpu_memcpy(&dstData[dstIdx + padsBegin[params.nDimsForWork] * params.shift], &srcData[srcIdx],
params.srcDims[params.nDimsForWork] * params.shift * params.sizeData);
std::fill_n(&dstData[dstIdx + params.srcODims[params.nDimsForWork] * params.shift],
padsEnd[params.nDimsForWork] * params.shift, value);
parallel_step(params.nDimsForWork, params.dstDims, indexes);
}
});
}
void MKLDNNPadNode::padConstantZero() {
uint8_t* srcData = reinterpret_cast<uint8_t*>(this->getParentEdgeAt(0)->getMemoryPtr()->GetPtr());
uint8_t* dstData = reinterpret_cast<uint8_t*>(this->getChildEdgeAt(0)->getMemoryPtr()->GetPtr());
parallel_nt(0, [&](const int ithr, const int nthr) {
size_t start = 0, end = 0;
SizeVector indexes(params.nDimsForWork, 0);
splitter(params.workAmount, nthr, ithr, start, end);
parallel_init(start, params.nDimsForWork, params.dstDims, indexes);
size_t dstIdx = 0;
getDstIdx(indexes, dstIdx);
for (size_t iwork = start; iwork < end; ++iwork, dstIdx += params.lastDstDim) {
size_t j = 0;
for (; j < params.nDimsForWork; ++j) {
if (indexes[j] < padsBegin[j] || indexes[j] >= params.srcODims[j])
break;
}
if (j != params.nDimsForWork) {
memset(&dstData[dstIdx], 0, params.lastDstDim);
parallel_step(params.nDimsForWork, params.dstDims, indexes);
continue;
}
size_t srcIdx = 0;
for (size_t idx = 0; idx < params.nDimsForWork; ++idx)
srcIdx += (indexes[idx] - padsBegin[idx]) * params.srcStrides[idx];
srcIdx *= params.sizeData;
memset(&dstData[dstIdx], 0, padsBegin[params.nDimsForWork] * params.shift);
cpu_memcpy(&dstData[dstIdx + padsBegin[params.nDimsForWork] * params.shift], &srcData[srcIdx],
params.srcDims[params.nDimsForWork] * params.shift);
memset(&dstData[dstIdx + params.srcODims[params.nDimsForWork] * params.shift], 0, padsEnd[params.nDimsForWork] * params.shift);
parallel_step(params.nDimsForWork, params.dstDims, indexes);
}
});
}
void MKLDNNPadNode::padEdge() {
uint8_t* srcData = reinterpret_cast<uint8_t*>(this->getParentEdgeAt(0)->getMemoryPtr()->GetPtr());
uint8_t* dstData = reinterpret_cast<uint8_t*>(this->getChildEdgeAt(0)->getMemoryPtr()->GetPtr());
parallel_nt(0, [&](const int ithr, const int nthr) {
size_t start = 0, end = 0;
SizeVector indexes(params.nDimsForWork, 0);
splitter(params.workAmount, nthr, ithr, start, end);
parallel_init(start, params.nDimsForWork, params.dstDims, indexes);
size_t dstIdx = 0;
getDstIdx(indexes, dstIdx);
for (size_t iwork = start; iwork < end; ++iwork, dstIdx += params.lastDstDim) {
size_t srcIdx = 0;
for (size_t idx = 0; idx < params.nDimsForWork; ++idx) {
size_t shift = (indexes[idx] < padsBegin[idx]) ? 0 :
((indexes[idx] >= params.srcODims[idx]) ? (params.srcDims[idx] - 1) : (indexes[idx] - padsBegin[idx]));
srcIdx += shift * params.srcStrides[idx];
}
srcIdx *= params.sizeData;
for (size_t i = 0; i < padsBegin[params.nDimsForWork]; ++i)
cpu_memcpy(&dstData[dstIdx + i * params.shift], &srcData[srcIdx], params.shift);
cpu_memcpy(&dstData[dstIdx + padsBegin[params.nDimsForWork] * params.shift], &srcData[srcIdx],
params.srcDims[params.nDimsForWork] * params.shift);
for (size_t i = 0; i < padsEnd[params.nDimsForWork]; ++i)
cpu_memcpy(&dstData[dstIdx + params.srcODims[params.nDimsForWork] * params.shift + i * params.shift],
&srcData[srcIdx + (params.srcDims[params.nDimsForWork] - 1) * params.shift], params.shift);
parallel_step(params.nDimsForWork, params.dstDims, indexes);
}
});
}
void MKLDNNPadNode::padReflectOrSymmetric(const bool isSymmetric) {
uint8_t* srcData = reinterpret_cast<uint8_t*>(this->getParentEdgeAt(0)->getMemoryPtr()->GetPtr());
uint8_t* dstData = reinterpret_cast<uint8_t*>(this->getChildEdgeAt(0)->getMemoryPtr()->GetPtr());
size_t shift = isSymmetric ? 1 : 0;
parallel_nt(0, [&](const int ithr, const int nthr) {
size_t start = 0, end = 0;
SizeVector indexes(params.nDimsForWork, 0);
splitter(params.workAmount, nthr, ithr, start, end);
parallel_init(start, params.nDimsForWork, params.dstDims, indexes);
size_t dstIdx = 0;
getDstIdx(indexes, dstIdx);
for (size_t iwork = start; iwork < end; ++iwork, dstIdx += params.lastDstDim) {
size_t srcIdx = 0;
for (size_t i = 0; i < params.nDimsForWork; ++i) {
size_t idx = (indexes[i] < padsBegin[i]) ? (padsBegin[i] - indexes[i] - shift) :
((indexes[i] >= params.srcODims[i]) ? (params.srcDimsForReflectOrSymmetric[i] - indexes[i]) : (indexes[i] - padsBegin[i]));
srcIdx += idx * params.srcStrides[i];
}
srcIdx *= params.sizeData;
for (size_t i = 0; i < padsBegin[params.nDimsForWork]; ++i)
cpu_memcpy(&dstData[dstIdx + i * params.shift],
&srcData[srcIdx + (padsBegin[params.nDimsForWork] - shift - i) * params.shift], params.shift);
cpu_memcpy(&dstData[dstIdx + padsBegin[params.nDimsForWork] * params.shift], &srcData[srcIdx],
params.srcDims[params.nDimsForWork] * params.shift);
size_t srcShift = (params.srcDimsForReflectOrSymmetric[params.nDimsForWork] - params.srcODims[params.nDimsForWork]) * params.shift;
for (size_t i = 0; i < padsEnd[params.nDimsForWork]; ++i)
cpu_memcpy(&dstData[dstIdx + (params.srcODims[params.nDimsForWork] + i) * params.shift],
&srcData[srcIdx + srcShift - i * params.shift], params.shift);
parallel_step(params.nDimsForWork, params.dstDims, indexes);
}
});
}
inline void MKLDNNPadNode::getDstIdx(const InferenceEngine::SizeVector& indexes, size_t& dstIdx) const {
for (size_t i = 0; i < params.nDimsForWork; ++i)
dstIdx += indexes[i] * params.dstStrides[i];
dstIdx *= (padMode == CONSTANT && padValue != 0) ? 1 : params.sizeData;
}
bool MKLDNNPadNode::created() const {
return getType() == Pad;
}
REG_MKLDNN_PRIM_FOR(MKLDNNPadNode, Pad);
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "google/cloud/bigtable/examples/bigtable_examples_common.h"
#include "google/cloud/bigtable/table_admin.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/testing_util/crash_handler.h"
#include <fstream>
#include <sstream>
namespace {
using google::cloud::bigtable::examples::Usage;
void AccessToken(std::vector<std::string> const& argv) {
if (argv.size() != 3) {
throw Usage{"test-access-token: <project-id> <instance-id> <access-token>"};
}
// Create a namespace alias to make the code easier to read.
namespace cbt = google::cloud::bigtable;
using google::cloud::StatusOr;
//! [test access token]
[](std::string const& project_id, std::string const& instance_id,
std::string const& access_token) {
auto call_credentials = grpc::AccessTokenCredentials(access_token);
auto channel_credentials =
grpc::SslCredentials(grpc::SslCredentialsOptions());
auto credentials = grpc::CompositeChannelCredentials(channel_credentials,
call_credentials);
cbt::TableAdmin admin(cbt::CreateDefaultAdminClient(
project_id, cbt::ClientOptions(credentials)),
instance_id);
auto tables = admin.ListTables(cbt::TableAdmin::NAME_ONLY);
if (!tables) throw std::runtime_error(tables.status().message());
}
//! [test access token]
(argv.at(0), argv.at(1), argv.at(2));
}
void JWTAccessToken(std::vector<std::string> const& argv) {
if (argv.size() != 3) {
throw Usage{
"test-jwt-access-token <project-id> <instance-id> "
"<service_account_file_json>"};
}
// Create a namespace alias to make the code easier to read.
namespace cbt = google::cloud::bigtable;
using google::cloud::StatusOr;
//! [test jwt access token]
[](std::string const& project_id, std::string const& instance_id,
std::string const& service_account_file_json) {
std::ifstream stream(service_account_file_json);
if (!stream.is_open()) {
std::ostringstream os;
os << "JWTAccessToken(" << service_account_file_json
<< "): cannot open upload file source";
throw std::runtime_error(os.str());
}
std::string json_key(std::istreambuf_iterator<char>{stream}, {});
auto call_credentials =
grpc::ServiceAccountJWTAccessCredentials(json_key, 6000);
auto channel_credentials =
grpc::SslCredentials(grpc::SslCredentialsOptions());
auto credentials = grpc::CompositeChannelCredentials(channel_credentials,
call_credentials);
cbt::TableAdmin admin(cbt::CreateDefaultAdminClient(
project_id, cbt::ClientOptions(credentials)),
instance_id);
auto tables = admin.ListTables(cbt::TableAdmin::NAME_ONLY);
if (!tables) throw std::runtime_error(tables.status().message());
}
//! [test jwt access token]
(argv.at(0), argv.at(1), argv.at(2));
}
void GCECredentials(std::vector<std::string> const& argv) {
if (argv.size() != 2) {
throw Usage{"test-gce-credentials: <project-id> <instance-id>"};
}
// Create a namespace alias to make the code easier to read.
namespace cbt = google::cloud::bigtable;
using google::cloud::StatusOr;
//! [test gce credentials]
[](std::string const& project_id, std::string const& instance_id) {
auto call_credentials = grpc::GoogleComputeEngineCredentials();
auto channel_credentials =
grpc::SslCredentials(grpc::SslCredentialsOptions());
auto credentials = grpc::CompositeChannelCredentials(channel_credentials,
call_credentials);
cbt::TableAdmin admin(cbt::CreateDefaultAdminClient(
project_id, cbt::ClientOptions(credentials)),
instance_id);
auto tables = admin.ListTables(cbt::TableAdmin::NAME_ONLY);
if (!tables) throw std::runtime_error(tables.status().message());
}
//! [test gce credentials]
(argv.at(0), argv.at(1));
}
void RunAll(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::bigtable::examples;
if (!argv.empty()) throw Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_CPP_BIGTABLE_TEST_INSTANCE_ID",
"GOOGLE_CLOUD_CPP_BIGTABLE_TEST_ACCESS_TOKEN",
"GOOGLE_APPLICATION_CREDENTIALS",
});
auto const project_id =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto const instance_id = google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_BIGTABLE_TEST_INSTANCE_ID")
.value();
auto const access_token = google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_BIGTABLE_TEST_ACCESS_TOKEN")
.value();
auto const credentials_file =
google::cloud::internal::GetEnv("GOOGLE_APPLICATION_CREDENTIALS").value();
AccessToken({project_id, instance_id, access_token});
JWTAccessToken({project_id, instance_id, credentials_file});
}
} // anonymous namespace
int main(int argc, char* argv[]) {
google::cloud::testing_util::InstallCrashHandler(argv[0]);
google::cloud::bigtable::examples::Commands commands = {
{"test-access-token", AccessToken},
{"test-jwt-access-token", JWTAccessToken},
{"test-gce-credentials", GCECredentials},
{"auto", RunAll},
};
google::cloud::bigtable::examples::Example example(std::move(commands));
return example.Run(argc, argv);
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <unordered_set>
// class unordered_set
// insert(...)
// emplace(...)
// UNSUPPORTED: c++98, c++03
#include <unordered_set>
#include "test_macros.h"
#include "container_test_types.h"
#include "../../set_allocator_requirement_test_templates.h"
int main(int, char**)
{
testSetInsert<TCT::unordered_set<> >();
testSetEmplace<TCT::unordered_set<> >();
return 0;
}
|
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C ;
// const ll M = 1000000007;
int N;
ll L;
ll x[100010];
int main () {
cin >> N >> L;
for (auto i = 0; i < N; i++) {
cin >> x[i];
}
if (N == 1) {
cout << "YES" << endl;
return 0;
}
for (auto i = 1; i < N; i++) {
if (x[i] - x[i-1] == L) {
cout << "NO" << endl;
return 0;
}
}
int place = 0;
int left = 0;
for (auto right = 0; right < N-1; right++) {
if (x[right+1] - x[right] < L) {
// cerr << right << " and " << right+1 << endl;
continue;
} else {
if (x[right] - x[left] >= L) {
// cerr << right << " and " << left << " : " << x[right] - x[left] << endl;
cout << "NO" << endl;
return 0;
} else {
place = max(place + 2 * L, x[right] + L);
// cerr << "place = " << place << endl;
if (place >= x[right+1]) {
// cerr << "place >= " << "x[" << right+1 << "] = " << x[right+1] << endl;
cout << "NO" << endl;
return 0;
} else {
// cerr << "left = " << right << endl;
left = right+1;
}
}
}
}
if (x[N-1] - x[left] >= L) {
cout << "NO" << endl;
return 0;
}
cout << "YES" << endl;
}
|
/*
* Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <string>
#include <mraa/i2c.hpp>
#include <interfaces/iProximity.hpp>
#define ADDR 0x4A // device address
// registers address
#define ISR 0x00 // Interrupt Status Register
#define MCR 0x01 // Main Configuration Register
#define RCR 0x02 // Receive Configuration Register
#define TCR 0x03 // Transmit Configuration Register
#define ALSDATA_HIGH 0x04 // ambient sensor data high byte
#define ALSDATA_LOW 0x05 // ambient sensor data low byte
#define PRXDATA 0x15 // proximity sensor data
#define ALS_UP_THRESH_HIGH 0x06 // ALS Interrupt Threshold Registers High
#define ALS_UP_THRESH_LOW 0x07 // ALS Interrupt Threshold Registers Low
#define ALS_LO_THRESH_HIGH 0x08 // ALS Interrupt Threshold Registers High
#define ALS_LO_THRESH_LOW 0x09 // ALS Interrupt Threshold Registers Low
#define TPTR 0x0A // ALS/PROX Threshold Persist Timer Register
#define PROX_THRESH_IND 0x0B // Proximity Threshold Register
#define PROX_THRESH 0x0C // Proximity Threshold Register
#define TRIM_GAIN_GREEN 0x0F // Digital Gain Trim Register
#define TRIM_GAIN_IR 0x10 // Digital Gain Trim Register
#define HIGH 1
#define LOW 0
namespace upm {
/**
* @brief MAX44000 Proximity Sensor
* @defgroup max44000 libupm-max44000
* @ingroup maxim i2c light
*/
/**
* @library max44000
* @sensor max44000
* @comname Ambient and Infrared Proximity Sensor
* @type light
* @man maxim
* @con i2c
* @web https://www.maximintegrated.com/en/products/analog/sensors-and-sensor-interface/MAX44000.html
*
* @brief API for the MAX44000 Ambient and Infrared Proximity Sensor
*
* Maxim Integrated*
* [MAX44000](http://datasheets.maximintegrated.com/en/ds/MAX44000.pdf)
* is an ambient and infrared proximity sensor. This module was tested on the
* Maxim Integrated
* [MAX44000PMB1 PMOD module]
* (http://datasheets.maximintegrated.com/en/ds/MAX44000PMB1.pdf) from the
* analog PMOD kit.
*
* @snippet max44000.cxx Interesting
*/
class MAX44000 : virtual public iProximity {
public:
/**
* Instantiates an MAX44000 object
*
* @param bus Number of the used bus
* @param devAddr Address of the used I2C device
*/
MAX44000 (int bus, int devAddr=ADDR);
/**
* MAX44000 object destructor; basically, it closes the I2C connection.
* ~MAX44000 ();
* no need for the destructor - the I2c connection will be closed when
* m_i2cMaxControlCtx variable will be out of context
**/
/**
* Reads the proximity value from the sensor (based on ambient data).
*/
uint16_t getProximity ();
/**
* Reads the proximity value from the sensor.
*/
virtual float getValue ();
/**
* Reads the ambient value from the sensor (based on ambient data).
*/
uint16_t getAmbient ();
/**
* Returns the name of the component
*/
std::string name()
{
return m_name;
}
/**
* Reads a one-byte register
*
* @param reg Address of the register
*/
uint8_t i2cReadReg_8 (int reg);
/**
* Reads a two-byte register
*
* @param reg Address of the register
*/
uint16_t i2cReadReg_16 (int reg);
/**
* Writes to a one-byte register
*
* @param reg Address of the register
* @param value Byte to be written
*/
mraa::Result i2cWriteReg (uint8_t reg, uint8_t value);
private:
std::string m_name;
int m_maxControlAddr;
int m_bus;
mraa::I2c m_i2cMaxControlCtx;
};
}
|
/*************************************************************************/
/* project_manager.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "project_manager.h"
#include "core/io/config_file.h"
#include "core/io/resource_saver.h"
#include "core/io/stream_peer_ssl.h"
#include "core/io/zip_io.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/os/keyboard.h"
#include "core/os/os.h"
#include "core/translation.h"
#include "core/version.h"
#include "core/version_hash.gen.h"
#include "editor_scale.h"
#include "editor_settings.h"
#include "editor_themes.h"
#include "scene/gui/center_container.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/margin_container.h"
#include "scene/gui/panel_container.h"
#include "scene/gui/separator.h"
#include "scene/gui/texture_rect.h"
#include "scene/gui/tool_button.h"
static inline String get_project_key_from_path(const String &dir) {
return dir.replace("/", "::");
}
class ProjectDialog : public ConfirmationDialog {
GDCLASS(ProjectDialog, ConfirmationDialog);
public:
enum Mode {
MODE_NEW,
MODE_IMPORT,
MODE_INSTALL,
MODE_RENAME
};
private:
enum MessageType {
MESSAGE_ERROR,
MESSAGE_WARNING,
MESSAGE_SUCCESS
};
enum InputType {
PROJECT_PATH,
INSTALL_PATH
};
Mode mode;
Button *browse;
Button *install_browse;
Button *create_dir;
Container *name_container;
Container *path_container;
Container *install_path_container;
Container *rasterizer_container;
Ref<ButtonGroup> rasterizer_button_group;
Label *msg;
LineEdit *project_path;
LineEdit *project_name;
LineEdit *install_path;
TextureRect *status_rect;
TextureRect *install_status_rect;
FileDialog *fdialog;
FileDialog *fdialog_install;
String zip_path;
String zip_title;
AcceptDialog *dialog_error;
String fav_dir;
String created_folder_path;
void set_message(const String &p_msg, MessageType p_type = MESSAGE_SUCCESS, InputType input_type = PROJECT_PATH) {
msg->set_text(p_msg);
Ref<Texture> current_path_icon = status_rect->get_texture();
Ref<Texture> current_install_icon = install_status_rect->get_texture();
Ref<Texture> new_icon;
switch (p_type) {
case MESSAGE_ERROR: {
msg->add_color_override("font_color", get_color("error_color", "Editor"));
msg->set_modulate(Color(1, 1, 1, 1));
new_icon = get_icon("StatusError", "EditorIcons");
} break;
case MESSAGE_WARNING: {
msg->add_color_override("font_color", get_color("warning_color", "Editor"));
msg->set_modulate(Color(1, 1, 1, 1));
new_icon = get_icon("StatusWarning", "EditorIcons");
} break;
case MESSAGE_SUCCESS: {
msg->set_modulate(Color(1, 1, 1, 0));
new_icon = get_icon("StatusSuccess", "EditorIcons");
} break;
}
if (current_path_icon != new_icon && input_type == PROJECT_PATH) {
status_rect->set_texture(new_icon);
} else if (current_install_icon != new_icon && input_type == INSTALL_PATH) {
install_status_rect->set_texture(new_icon);
}
set_size(Size2(500, 0) * EDSCALE);
}
String _test_path() {
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
String valid_path, valid_install_path;
if (d->change_dir(project_path->get_text()) == OK) {
valid_path = project_path->get_text();
} else if (d->change_dir(project_path->get_text().strip_edges()) == OK) {
valid_path = project_path->get_text().strip_edges();
} else if (project_path->get_text().ends_with(".zip")) {
if (d->file_exists(project_path->get_text())) {
valid_path = project_path->get_text();
}
} else if (project_path->get_text().strip_edges().ends_with(".zip")) {
if (d->file_exists(project_path->get_text().strip_edges())) {
valid_path = project_path->get_text().strip_edges();
}
}
if (valid_path == "") {
set_message(TTR("The path does not exist."), MESSAGE_ERROR);
memdelete(d);
get_ok()->set_disabled(true);
return "";
}
if (mode == MODE_IMPORT && valid_path.ends_with(".zip")) {
if (d->change_dir(install_path->get_text()) == OK) {
valid_install_path = install_path->get_text();
} else if (d->change_dir(install_path->get_text().strip_edges()) == OK) {
valid_install_path = install_path->get_text().strip_edges();
}
if (valid_install_path == "") {
set_message(TTR("The path does not exist."), MESSAGE_ERROR, INSTALL_PATH);
memdelete(d);
get_ok()->set_disabled(true);
return "";
}
}
if (mode == MODE_IMPORT || mode == MODE_RENAME) {
if (valid_path != "" && !d->file_exists("project.godot")) {
if (valid_path.ends_with(".zip")) {
FileAccess *src_f = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
unzFile pkg = unzOpen2(valid_path.utf8().get_data(), &io);
if (!pkg) {
set_message(TTR("Error opening package file, not in ZIP format."), MESSAGE_ERROR);
memdelete(d);
get_ok()->set_disabled(true);
unzClose(pkg);
return "";
}
int ret = unzGoToFirstFile(pkg);
while (ret == UNZ_OK) {
unz_file_info info;
char fname[16384];
ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
if (String(fname).ends_with("project.godot")) {
break;
}
ret = unzGoToNextFile(pkg);
}
if (ret == UNZ_END_OF_LIST_OF_FILE) {
set_message(TTR("Invalid '.zip' project file, does not contain a 'project.godot' file."), MESSAGE_ERROR);
memdelete(d);
get_ok()->set_disabled(true);
unzClose(pkg);
return "";
}
unzClose(pkg);
// check if the specified install folder is empty, even though this is not an error, it is good to check here
d->list_dir_begin();
bool is_empty = true;
String n = d->get_next();
while (n != String()) {
if (n != "." && n != "..") {
is_empty = false;
break;
}
n = d->get_next();
}
d->list_dir_end();
if (!is_empty) {
set_message(TTR("Please choose an empty folder."), MESSAGE_WARNING, INSTALL_PATH);
memdelete(d);
get_ok()->set_disabled(true);
return "";
}
} else {
set_message(TTR("Please choose a 'project.godot' or '.zip' file."), MESSAGE_ERROR);
memdelete(d);
install_path_container->hide();
get_ok()->set_disabled(true);
return "";
}
} else if (valid_path.ends_with("zip")) {
set_message(TTR("Directory already contains a Godot project."), MESSAGE_ERROR, INSTALL_PATH);
memdelete(d);
get_ok()->set_disabled(true);
return "";
}
} else {
// check if the specified folder is empty, even though this is not an error, it is good to check here
d->list_dir_begin();
bool is_empty = true;
String n = d->get_next();
while (n != String()) {
if (n != "." && n != "..") { // i don't know if this is enough to guarantee an empty dir
is_empty = false;
break;
}
n = d->get_next();
}
d->list_dir_end();
if (!is_empty) {
set_message(TTR("Please choose an empty folder."), MESSAGE_ERROR);
memdelete(d);
get_ok()->set_disabled(true);
return "";
}
}
set_message("");
set_message("", MESSAGE_SUCCESS, INSTALL_PATH);
memdelete(d);
get_ok()->set_disabled(false);
return valid_path;
}
void _path_text_changed(const String &p_path) {
String sp = _test_path();
if (sp != "") {
// If the project name is empty or default, infer the project name from the selected folder name
if (project_name->get_text() == "" || project_name->get_text() == TTR("New Game Project")) {
sp = sp.replace("\\", "/");
int lidx = sp.find_last("/");
if (lidx != -1) {
sp = sp.substr(lidx + 1, sp.length()).capitalize();
}
if (sp == "" && mode == MODE_IMPORT)
sp = TTR("Imported Project");
project_name->set_text(sp);
_text_changed(sp);
}
}
if (created_folder_path != "" && created_folder_path != p_path) {
_remove_created_folder();
}
}
void _file_selected(const String &p_path) {
String p = p_path;
if (mode == MODE_IMPORT) {
if (p.ends_with("project.godot")) {
p = p.get_base_dir();
install_path_container->hide();
get_ok()->set_disabled(false);
} else if (p.ends_with(".zip")) {
install_path->set_text(p.get_base_dir());
install_path_container->show();
get_ok()->set_disabled(false);
} else {
set_message(TTR("Please choose a 'project.godot' or '.zip' file."), MESSAGE_ERROR);
get_ok()->set_disabled(true);
return;
}
}
String sp = p.simplify_path();
project_path->set_text(sp);
_path_text_changed(sp);
if (p.ends_with(".zip")) {
install_path->call_deferred("grab_focus");
} else {
get_ok()->call_deferred("grab_focus");
}
}
void _path_selected(const String &p_path) {
String p = p_path;
String sp = p.simplify_path();
project_path->set_text(sp);
_path_text_changed(sp);
get_ok()->call_deferred("grab_focus");
}
void _install_path_selected(const String &p_path) {
String p = p_path;
String sp = p.simplify_path();
install_path->set_text(sp);
_path_text_changed(sp);
get_ok()->call_deferred("grab_focus");
}
void _browse_path() {
fdialog->set_current_dir(project_path->get_text());
if (mode == MODE_IMPORT) {
fdialog->set_mode(FileDialog::MODE_OPEN_FILE);
fdialog->clear_filters();
fdialog->add_filter("project.godot ; " VERSION_NAME " Project");
fdialog->add_filter("*.zip ; Zip File");
} else {
fdialog->set_mode(FileDialog::MODE_OPEN_DIR);
}
fdialog->popup_centered_ratio();
}
void _browse_install_path() {
fdialog_install->set_current_dir(install_path->get_text());
fdialog_install->set_mode(FileDialog::MODE_OPEN_DIR);
fdialog_install->popup_centered_ratio();
}
void _create_folder() {
if (project_name->get_text() == "" || created_folder_path != "" || project_name->get_text().ends_with(".") || project_name->get_text().ends_with(" ")) {
set_message(TTR("Invalid Project Name."), MESSAGE_WARNING);
return;
}
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
if (d->change_dir(project_path->get_text()) == OK) {
if (!d->dir_exists(project_name->get_text())) {
if (d->make_dir(project_name->get_text()) == OK) {
d->change_dir(project_name->get_text());
String dir_str = d->get_current_dir();
project_path->set_text(dir_str);
_path_text_changed(dir_str);
created_folder_path = d->get_current_dir();
create_dir->set_disabled(true);
} else {
dialog_error->set_text(TTR("Couldn't create folder."));
dialog_error->popup_centered_minsize();
}
} else {
dialog_error->set_text(TTR("There is already a folder in this path with the specified name."));
dialog_error->popup_centered_minsize();
}
}
memdelete(d);
}
void _text_changed(const String &p_text) {
if (mode != MODE_NEW)
return;
_test_path();
if (p_text == "")
set_message(TTR("It would be a good idea to name your project."), MESSAGE_WARNING);
}
void ok_pressed() {
String dir = project_path->get_text();
if (mode == MODE_RENAME) {
String dir2 = _test_path();
if (dir2 == "") {
set_message(TTR("Invalid project path (changed anything?)."), MESSAGE_ERROR);
return;
}
ProjectSettings *current = memnew(ProjectSettings);
int err = current->setup(dir2, "");
if (err != OK) {
set_message(vformat(TTR("Couldn't load project.godot in project path (error %d). It may be missing or corrupted."), err), MESSAGE_ERROR);
} else {
ProjectSettings::CustomMap edited_settings;
edited_settings["application/config/name"] = project_name->get_text();
if (current->save_custom(dir2.plus_file("project.godot"), edited_settings, Vector<String>(), true) != OK) {
set_message(TTR("Couldn't edit project.godot in project path."), MESSAGE_ERROR);
}
}
hide();
emit_signal("projects_updated");
} else {
if (mode == MODE_IMPORT) {
if (project_path->get_text().ends_with(".zip")) {
mode = MODE_INSTALL;
ok_pressed();
return;
}
} else {
if (mode == MODE_NEW) {
ProjectSettings::CustomMap initial_settings;
if (rasterizer_button_group->get_pressed_button()->get_meta("driver_name") == "GLES3") {
initial_settings["rendering/quality/driver/driver_name"] = "GLES3";
} else {
initial_settings["rendering/quality/driver/driver_name"] = "GLES2";
initial_settings["rendering/vram_compression/import_etc2"] = false;
initial_settings["rendering/vram_compression/import_etc"] = true;
}
initial_settings["application/config/name"] = project_name->get_text();
initial_settings["application/config/icon"] = "res://icon.png";
initial_settings["rendering/environment/default_environment"] = "res://default_env.tres";
if (ProjectSettings::get_singleton()->save_custom(dir.plus_file("project.godot"), initial_settings, Vector<String>(), false) != OK) {
set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR);
} else {
ResourceSaver::save(dir.plus_file("icon.png"), get_icon("DefaultProjectIcon", "EditorIcons"));
FileAccess *f = FileAccess::open(dir.plus_file("default_env.tres"), FileAccess::WRITE);
if (!f) {
set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR);
} else {
f->store_line("[gd_resource type=\"Environment\" load_steps=2 format=2]");
f->store_line("[sub_resource type=\"ProceduralSky\" id=1]");
f->store_line("[resource]");
f->store_line("background_mode = 2");
f->store_line("background_sky = SubResource( 1 )");
memdelete(f);
}
}
} else if (mode == MODE_INSTALL) {
if (project_path->get_text().ends_with(".zip")) {
dir = install_path->get_text();
zip_path = project_path->get_text();
}
FileAccess *src_f = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io);
if (!pkg) {
dialog_error->set_text(TTR("Error opening package file, not in ZIP format."));
dialog_error->popup_centered_minsize();
return;
}
int ret = unzGoToFirstFile(pkg);
Vector<String> failed_files;
int idx = 0;
while (ret == UNZ_OK) {
//get filename
unz_file_info info;
char fname[16384];
ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
String path = fname;
int depth = 1; //stuff from github comes with tag
bool skip = false;
while (depth > 0) {
int pp = path.find("/");
if (pp == -1) {
skip = true;
break;
}
path = path.substr(pp + 1, path.length());
depth--;
}
if (skip || path == String()) {
//
} else if (path.ends_with("/")) { // a dir
path = path.substr(0, path.length() - 1);
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
da->make_dir(dir.plus_file(path));
memdelete(da);
} else {
Vector<uint8_t> data;
data.resize(info.uncompressed_size);
//read
unzOpenCurrentFile(pkg);
unzReadCurrentFile(pkg, data.ptrw(), data.size());
unzCloseCurrentFile(pkg);
FileAccess *f = FileAccess::open(dir.plus_file(path), FileAccess::WRITE);
if (f) {
f->store_buffer(data.ptr(), data.size());
memdelete(f);
} else {
failed_files.push_back(path);
}
}
idx++;
ret = unzGoToNextFile(pkg);
}
unzClose(pkg);
if (failed_files.size()) {
String msg = TTR("The following files failed extraction from package:") + "\n\n";
for (int i = 0; i < failed_files.size(); i++) {
if (i > 15) {
msg += "\nAnd " + itos(failed_files.size() - i) + " more files.";
break;
}
msg += failed_files[i] + "\n";
}
dialog_error->set_text(msg);
dialog_error->popup_centered_minsize();
} else if (!project_path->get_text().ends_with(".zip")) {
dialog_error->set_text(TTR("Package installed successfully!"));
dialog_error->popup_centered_minsize();
}
}
}
dir = dir.replace("\\", "/");
if (dir.ends_with("/"))
dir = dir.substr(0, dir.length() - 1);
String proj = get_project_key_from_path(dir);
EditorSettings::get_singleton()->set("projects/" + proj, dir);
EditorSettings::get_singleton()->save();
hide();
emit_signal("project_created", dir);
}
}
void _remove_created_folder() {
if (created_folder_path != "") {
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
d->remove(created_folder_path);
memdelete(d);
create_dir->set_disabled(false);
created_folder_path = "";
}
}
void cancel_pressed() {
_remove_created_folder();
project_path->clear();
_path_text_changed("");
project_name->clear();
_text_changed("");
if (status_rect->get_texture() == get_icon("StatusError", "EditorIcons"))
msg->show();
if (install_status_rect->get_texture() == get_icon("StatusError", "EditorIcons"))
msg->show();
}
void _notification(int p_what) {
if (p_what == MainLoop::NOTIFICATION_WM_QUIT_REQUEST)
_remove_created_folder();
}
protected:
static void _bind_methods() {
ClassDB::bind_method("_browse_path", &ProjectDialog::_browse_path);
ClassDB::bind_method("_create_folder", &ProjectDialog::_create_folder);
ClassDB::bind_method("_text_changed", &ProjectDialog::_text_changed);
ClassDB::bind_method("_path_text_changed", &ProjectDialog::_path_text_changed);
ClassDB::bind_method("_path_selected", &ProjectDialog::_path_selected);
ClassDB::bind_method("_file_selected", &ProjectDialog::_file_selected);
ClassDB::bind_method("_install_path_selected", &ProjectDialog::_install_path_selected);
ClassDB::bind_method("_browse_install_path", &ProjectDialog::_browse_install_path);
ADD_SIGNAL(MethodInfo("project_created"));
ADD_SIGNAL(MethodInfo("projects_updated"));
}
public:
void set_zip_path(const String &p_path) {
zip_path = p_path;
}
void set_zip_title(const String &p_title) {
zip_title = p_title;
}
void set_mode(Mode p_mode) {
mode = p_mode;
}
void set_project_path(const String &p_path) {
project_path->set_text(p_path);
}
void show_dialog() {
if (mode == MODE_RENAME) {
project_path->set_editable(false);
browse->hide();
install_browse->hide();
set_title(TTR("Rename Project"));
get_ok()->set_text(TTR("Rename"));
name_container->show();
status_rect->hide();
msg->hide();
install_path_container->hide();
install_status_rect->hide();
rasterizer_container->hide();
get_ok()->set_disabled(false);
ProjectSettings *current = memnew(ProjectSettings);
int err = current->setup(project_path->get_text(), "");
if (err != OK) {
set_message(vformat(TTR("Couldn't load project.godot in project path (error %d). It may be missing or corrupted."), err), MESSAGE_ERROR);
status_rect->show();
msg->show();
get_ok()->set_disabled(true);
} else if (current->has_setting("application/config/name")) {
String proj = current->get("application/config/name");
project_name->set_text(proj);
_text_changed(proj);
}
project_name->call_deferred("grab_focus");
create_dir->hide();
} else {
fav_dir = EditorSettings::get_singleton()->get("filesystem/directories/default_project_path");
if (fav_dir != "") {
project_path->set_text(fav_dir);
fdialog->set_current_dir(fav_dir);
} else {
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
project_path->set_text(d->get_current_dir());
fdialog->set_current_dir(d->get_current_dir());
memdelete(d);
}
String proj = TTR("New Game Project");
project_name->set_text(proj);
_text_changed(proj);
project_path->set_editable(true);
browse->set_disabled(false);
browse->show();
install_browse->set_disabled(false);
install_browse->show();
create_dir->show();
status_rect->show();
install_status_rect->show();
msg->show();
if (mode == MODE_IMPORT) {
set_title(TTR("Import Existing Project"));
get_ok()->set_text(TTR("Import & Edit"));
name_container->hide();
install_path_container->hide();
rasterizer_container->hide();
project_path->grab_focus();
} else if (mode == MODE_NEW) {
set_title(TTR("Create New Project"));
get_ok()->set_text(TTR("Create & Edit"));
name_container->show();
install_path_container->hide();
rasterizer_container->show();
project_name->call_deferred("grab_focus");
project_name->call_deferred("select_all");
} else if (mode == MODE_INSTALL) {
set_title(TTR("Install Project:") + " " + zip_title);
get_ok()->set_text(TTR("Install & Edit"));
project_name->set_text(zip_title);
name_container->show();
install_path_container->hide();
rasterizer_container->hide();
project_path->grab_focus();
}
_test_path();
}
popup_centered_minsize(Size2(500, 0) * EDSCALE);
}
ProjectDialog() {
VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
name_container = memnew(VBoxContainer);
vb->add_child(name_container);
Label *l = memnew(Label);
l->set_text(TTR("Project Name:"));
name_container->add_child(l);
HBoxContainer *pnhb = memnew(HBoxContainer);
name_container->add_child(pnhb);
project_name = memnew(LineEdit);
project_name->set_h_size_flags(SIZE_EXPAND_FILL);
pnhb->add_child(project_name);
create_dir = memnew(Button);
pnhb->add_child(create_dir);
create_dir->set_text(TTR("Create Folder"));
create_dir->connect("pressed", this, "_create_folder");
path_container = memnew(VBoxContainer);
vb->add_child(path_container);
l = memnew(Label);
l->set_text(TTR("Project Path:"));
path_container->add_child(l);
HBoxContainer *pphb = memnew(HBoxContainer);
path_container->add_child(pphb);
project_path = memnew(LineEdit);
project_path->set_h_size_flags(SIZE_EXPAND_FILL);
pphb->add_child(project_path);
install_path_container = memnew(VBoxContainer);
vb->add_child(install_path_container);
l = memnew(Label);
l->set_text(TTR("Project Installation Path:"));
install_path_container->add_child(l);
HBoxContainer *iphb = memnew(HBoxContainer);
install_path_container->add_child(iphb);
install_path = memnew(LineEdit);
install_path->set_h_size_flags(SIZE_EXPAND_FILL);
iphb->add_child(install_path);
// status icon
status_rect = memnew(TextureRect);
status_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
pphb->add_child(status_rect);
browse = memnew(Button);
browse->set_text(TTR("Browse"));
browse->connect("pressed", this, "_browse_path");
pphb->add_child(browse);
// install status icon
install_status_rect = memnew(TextureRect);
install_status_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
iphb->add_child(install_status_rect);
install_browse = memnew(Button);
install_browse->set_text(TTR("Browse"));
install_browse->connect("pressed", this, "_browse_install_path");
iphb->add_child(install_browse);
msg = memnew(Label);
msg->set_align(Label::ALIGN_CENTER);
vb->add_child(msg);
// rasterizer selection
rasterizer_container = memnew(VBoxContainer);
vb->add_child(rasterizer_container);
l = memnew(Label);
l->set_text(TTR("Renderer:"));
rasterizer_container->add_child(l);
Container *rshb = memnew(HBoxContainer);
rasterizer_container->add_child(rshb);
rasterizer_button_group.instance();
Container *rvb = memnew(VBoxContainer);
rvb->set_h_size_flags(SIZE_EXPAND_FILL);
rshb->add_child(rvb);
Button *rs_button = memnew(CheckBox);
rs_button->set_button_group(rasterizer_button_group);
rs_button->set_text(TTR("OpenGL ES 3.0"));
rs_button->set_meta("driver_name", "GLES3");
rs_button->set_pressed(true);
rvb->add_child(rs_button);
l = memnew(Label);
l->set_text(TTR("Higher visual quality\nAll features available\nIncompatible with older hardware\nNot recommended for web games"));
rvb->add_child(l);
rshb->add_child(memnew(VSeparator));
rvb = memnew(VBoxContainer);
rvb->set_h_size_flags(SIZE_EXPAND_FILL);
rshb->add_child(rvb);
rs_button = memnew(CheckBox);
rs_button->set_button_group(rasterizer_button_group);
rs_button->set_text(TTR("OpenGL ES 2.0"));
rs_button->set_meta("driver_name", "GLES2");
rvb->add_child(rs_button);
l = memnew(Label);
l->set_text(TTR("Lower visual quality\nSome features not available\nWorks on most hardware\nRecommended for web games"));
rvb->add_child(l);
l = memnew(Label);
l->set_text(TTR("Renderer can be changed later, but scenes may need to be adjusted."));
l->set_align(Label::ALIGN_CENTER);
rasterizer_container->add_child(l);
fdialog = memnew(FileDialog);
fdialog->set_access(FileDialog::ACCESS_FILESYSTEM);
fdialog_install = memnew(FileDialog);
fdialog_install->set_access(FileDialog::ACCESS_FILESYSTEM);
add_child(fdialog);
add_child(fdialog_install);
project_name->connect("text_changed", this, "_text_changed");
project_path->connect("text_changed", this, "_path_text_changed");
install_path->connect("text_changed", this, "_path_text_changed");
fdialog->connect("dir_selected", this, "_path_selected");
fdialog->connect("file_selected", this, "_file_selected");
fdialog_install->connect("dir_selected", this, "_install_path_selected");
fdialog_install->connect("file_selected", this, "_install_path_selected");
set_hide_on_ok(false);
mode = MODE_NEW;
dialog_error = memnew(AcceptDialog);
add_child(dialog_error);
}
};
class ProjectListItemControl : public HBoxContainer {
GDCLASS(ProjectListItemControl, HBoxContainer)
public:
TextureButton *favorite_button;
TextureRect *icon;
bool icon_needs_reload;
bool hover;
ProjectListItemControl() {
favorite_button = NULL;
icon = NULL;
icon_needs_reload = true;
hover = false;
}
void set_is_favorite(bool fav) {
favorite_button->set_modulate(fav ? Color(1, 1, 1, 1) : Color(1, 1, 1, 0.2));
}
void _notification(int p_what) {
switch (p_what) {
case NOTIFICATION_MOUSE_ENTER: {
hover = true;
update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
hover = false;
update();
} break;
case NOTIFICATION_DRAW: {
if (hover) {
draw_style_box(get_stylebox("hover", "Tree"), Rect2(Point2(), get_size() - Size2(10, 0) * EDSCALE));
}
} break;
}
}
};
class ProjectList : public ScrollContainer {
GDCLASS(ProjectList, ScrollContainer)
public:
static const char *SIGNAL_SELECTION_CHANGED;
static const char *SIGNAL_PROJECT_ASK_OPEN;
enum MenuOptions {
GLOBAL_NEW_WINDOW,
GLOBAL_OPEN_PROJECT
};
// Can often be passed by copy
struct Item {
String project_key;
String project_name;
String description;
String path;
String icon;
String main_scene;
uint64_t last_modified;
bool favorite;
bool grayed;
bool missing;
int version;
ProjectListItemControl *control;
Item() {}
Item(const String &p_project,
const String &p_name,
const String &p_description,
const String &p_path,
const String &p_icon,
const String &p_main_scene,
uint64_t p_last_modified,
bool p_favorite,
bool p_grayed,
bool p_missing,
int p_version) {
project_key = p_project;
project_name = p_name;
description = p_description;
path = p_path;
icon = p_icon;
main_scene = p_main_scene;
last_modified = p_last_modified;
favorite = p_favorite;
grayed = p_grayed;
missing = p_missing;
version = p_version;
control = NULL;
}
_FORCE_INLINE_ bool operator==(const Item &l) const {
return project_key == l.project_key;
}
};
ProjectList();
~ProjectList();
void load_projects();
void set_search_term(String p_search_term);
void set_order_option(ProjectListFilter::FilterOption p_option);
void sort_projects();
int get_project_count() const;
void select_project(int p_index);
void erase_selected_projects();
Vector<Item> get_selected_projects() const;
const Set<String> &get_selected_project_keys() const;
void ensure_project_visible(int p_index);
int get_single_selected_index() const;
bool is_any_project_missing() const;
void erase_missing_projects();
int refresh_project(const String &dir_path);
private:
static void _bind_methods();
void _notification(int p_what);
void _panel_draw(Node *p_hb);
void _panel_input(const Ref<InputEvent> &p_ev, Node *p_hb);
void _favorite_pressed(Node *p_hb);
void _show_project(const String &p_path);
void select_range(int p_begin, int p_end);
void toggle_select(int p_index);
void create_project_item_control(int p_index);
void remove_project(int p_index, bool p_update_settings);
void update_icons_async();
void load_project_icon(int p_index);
static void load_project_data(const String &p_property_key, Item &p_item, bool p_favorite);
String _search_term;
ProjectListFilter::FilterOption _order_option;
Set<String> _selected_project_keys;
String _last_clicked; // Project key
VBoxContainer *_scroll_children;
int _icon_load_index;
Vector<Item> _projects;
};
struct ProjectListComparator {
ProjectListFilter::FilterOption order_option;
// operator<
_FORCE_INLINE_ bool operator()(const ProjectList::Item &a, const ProjectList::Item &b) const {
if (a.favorite && !b.favorite) {
return true;
}
if (b.favorite && !a.favorite) {
return false;
}
switch (order_option) {
case ProjectListFilter::FILTER_PATH:
return a.project_key < b.project_key;
case ProjectListFilter::FILTER_MODIFIED:
return a.last_modified > b.last_modified;
default:
return a.project_name < b.project_name;
}
}
};
ProjectList::ProjectList() {
_order_option = ProjectListFilter::FILTER_MODIFIED;
_scroll_children = memnew(VBoxContainer);
_scroll_children->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(_scroll_children);
_icon_load_index = 0;
}
ProjectList::~ProjectList() {
}
void ProjectList::update_icons_async() {
_icon_load_index = 0;
set_process(true);
}
void ProjectList::_notification(int p_what) {
if (p_what == NOTIFICATION_PROCESS) {
// Load icons as a coroutine to speed up launch when you have hundreds of projects
if (_icon_load_index < _projects.size()) {
Item &item = _projects.write[_icon_load_index];
if (item.control->icon_needs_reload) {
load_project_icon(_icon_load_index);
}
_icon_load_index++;
} else {
set_process(false);
}
}
}
void ProjectList::load_project_icon(int p_index) {
Item &item = _projects.write[p_index];
Ref<Texture> default_icon = get_icon("DefaultProjectIcon", "EditorIcons");
Ref<Texture> icon;
if (item.icon != "") {
Ref<Image> img;
img.instance();
Error err = img->load(item.icon.replace_first("res://", item.path + "/"));
if (err == OK) {
img->resize(default_icon->get_width(), default_icon->get_height(), Image::INTERPOLATE_LANCZOS);
Ref<ImageTexture> it = memnew(ImageTexture);
it->create_from_image(img);
icon = it;
}
}
if (icon.is_null()) {
icon = default_icon;
}
item.control->icon->set_texture(icon);
item.control->icon_needs_reload = false;
}
void ProjectList::load_project_data(const String &p_property_key, Item &p_item, bool p_favorite) {
String path = EditorSettings::get_singleton()->get(p_property_key);
String conf = path.plus_file("project.godot");
bool grayed = false;
bool missing = false;
Ref<ConfigFile> cf = memnew(ConfigFile);
Error cf_err = cf->load(conf);
int config_version = 0;
String project_name = TTR("Unnamed Project");
if (cf_err == OK) {
String cf_project_name = static_cast<String>(cf->get_value("application", "config/name", ""));
if (cf_project_name != "")
project_name = cf_project_name.xml_unescape();
config_version = (int)cf->get_value("", "config_version", 0);
}
if (config_version > ProjectSettings::CONFIG_VERSION) {
// Comes from an incompatible (more recent) Godot version, grey it out
grayed = true;
}
String description = cf->get_value("application", "config/description", "");
String icon = cf->get_value("application", "config/icon", "");
String main_scene = cf->get_value("application", "run/main_scene", "");
uint64_t last_modified = 0;
if (FileAccess::exists(conf)) {
last_modified = FileAccess::get_modified_time(conf);
String fscache = path.plus_file(".fscache");
if (FileAccess::exists(fscache)) {
uint64_t cache_modified = FileAccess::get_modified_time(fscache);
if (cache_modified > last_modified)
last_modified = cache_modified;
}
} else {
grayed = true;
missing = true;
print_line("Project is missing: " + conf);
}
String project_key = p_property_key.get_slice("/", 1);
p_item = Item(project_key, project_name, description, path, icon, main_scene, last_modified, p_favorite, grayed, missing, config_version);
}
void ProjectList::load_projects() {
// This is a full, hard reload of the list. Don't call this unless really required, it's expensive.
// If you have 150 projects, it may read through 150 files on your disk at once + load 150 icons.
// Clear whole list
for (int i = 0; i < _projects.size(); ++i) {
Item &project = _projects.write[i];
CRASH_COND(project.control == NULL);
memdelete(project.control); // Why not queue_free()?
}
_projects.clear();
_last_clicked = "";
_selected_project_keys.clear();
OS::get_singleton()->global_menu_clear("_dock");
// Load data
// TODO Would be nice to change how projects and favourites are stored... it complicates things a bit.
// Use a dictionary associating project path to metadata (like is_favorite).
List<PropertyInfo> properties;
EditorSettings::get_singleton()->get_property_list(&properties);
Set<String> favorites;
// Find favourites...
for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
String property_key = E->get().name;
if (property_key.begins_with("favorite_projects/")) {
favorites.insert(property_key);
}
}
for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
// This is actually something like "projects/C:::Documents::Godot::Projects::MyGame"
String property_key = E->get().name;
if (!property_key.begins_with("projects/"))
continue;
String project_key = property_key.get_slice("/", 1);
bool favorite = favorites.has("favorite_projects/" + project_key);
Item item;
load_project_data(property_key, item, favorite);
_projects.push_back(item);
}
// Create controls
for (int i = 0; i < _projects.size(); ++i) {
create_project_item_control(i);
}
OS::get_singleton()->global_menu_add_separator("_dock");
OS::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), GLOBAL_NEW_WINDOW, Variant());
sort_projects();
set_v_scroll(0);
update_icons_async();
}
void ProjectList::create_project_item_control(int p_index) {
// Will be added last in the list, so make sure indexes match
ERR_FAIL_COND(p_index != _scroll_children->get_child_count());
Item &item = _projects.write[p_index];
ERR_FAIL_COND(item.control != NULL); // Already created
Ref<Texture> favorite_icon = get_icon("Favorites", "EditorIcons");
Color font_color = get_color("font_color", "Tree");
ProjectListItemControl *hb = memnew(ProjectListItemControl);
hb->connect("draw", this, "_panel_draw", varray(hb));
hb->connect("gui_input", this, "_panel_input", varray(hb));
hb->add_constant_override("separation", 10 * EDSCALE);
hb->set_tooltip(item.description);
VBoxContainer *favorite_box = memnew(VBoxContainer);
favorite_box->set_name("FavoriteBox");
TextureButton *favorite = memnew(TextureButton);
favorite->set_name("FavoriteButton");
favorite->set_normal_texture(favorite_icon);
// This makes the project's "hover" style display correctly when hovering the favorite icon
favorite->set_mouse_filter(MOUSE_FILTER_PASS);
favorite->connect("pressed", this, "_favorite_pressed", varray(hb));
favorite_box->add_child(favorite);
favorite_box->set_alignment(BoxContainer::ALIGN_CENTER);
hb->add_child(favorite_box);
hb->favorite_button = favorite;
hb->set_is_favorite(item.favorite);
TextureRect *tf = memnew(TextureRect);
tf->set_texture(get_icon("DefaultProjectIcon", "EditorIcons"));
if (item.missing) {
tf->set_modulate(Color(1, 1, 1, 0.5));
}
hb->add_child(tf);
hb->icon = tf;
VBoxContainer *vb = memnew(VBoxContainer);
if (item.grayed)
vb->set_modulate(Color(1, 1, 1, 0.5));
vb->set_h_size_flags(SIZE_EXPAND_FILL);
hb->add_child(vb);
Control *ec = memnew(Control);
ec->set_custom_minimum_size(Size2(0, 1));
ec->set_mouse_filter(MOUSE_FILTER_PASS);
vb->add_child(ec);
Label *title = memnew(Label(!item.missing ? item.project_name : TTR("Missing Project")));
title->add_font_override("font", get_font("title", "EditorFonts"));
title->add_color_override("font_color", font_color);
title->set_clip_text(true);
vb->add_child(title);
HBoxContainer *path_hb = memnew(HBoxContainer);
path_hb->set_h_size_flags(SIZE_EXPAND_FILL);
vb->add_child(path_hb);
Button *show = memnew(Button);
// Display a folder icon if the project directory can be opened, or a "broken file" icon if it can't
show->set_icon(get_icon(!item.missing ? "Load" : "FileBroken", "EditorIcons"));
show->set_flat(true);
if (!item.grayed) {
// Don't make the icon less prominent if the parent is already grayed out
show->set_modulate(Color(1, 1, 1, 0.5));
}
path_hb->add_child(show);
if (!item.missing) {
show->connect("pressed", this, "_show_project", varray(item.path));
show->set_tooltip(TTR("Show in File Manager"));
} else {
show->set_tooltip(TTR("Error: Project is missing on the filesystem."));
}
Label *fpath = memnew(Label(item.path));
path_hb->add_child(fpath);
fpath->set_h_size_flags(SIZE_EXPAND_FILL);
fpath->set_modulate(Color(1, 1, 1, 0.5));
fpath->add_color_override("font_color", font_color);
fpath->set_clip_text(true);
_scroll_children->add_child(hb);
OS::get_singleton()->global_menu_add_item("_dock", item.project_name + " ( " + item.path + " )", GLOBAL_OPEN_PROJECT, Variant(item.path.plus_file("project.godot")));
item.control = hb;
}
void ProjectList::set_search_term(String p_search_term) {
_search_term = p_search_term;
}
void ProjectList::set_order_option(ProjectListFilter::FilterOption p_option) {
if (_order_option != p_option) {
_order_option = p_option;
EditorSettings::get_singleton()->set("project_manager/sorting_order", (int)_order_option);
EditorSettings::get_singleton()->save();
}
}
void ProjectList::sort_projects() {
SortArray<Item, ProjectListComparator> sorter;
sorter.compare.order_option = _order_option;
sorter.sort(_projects.ptrw(), _projects.size());
for (int i = 0; i < _projects.size(); ++i) {
Item &item = _projects.write[i];
bool visible = true;
if (_search_term != "") {
String search_path;
if (_search_term.find("/") != -1) {
// Search path will match the whole path
search_path = item.path;
} else {
// Search path will only match the last path component to make searching more strict
search_path = item.path.get_file();
}
// When searching, display projects whose name or path contain the search term
visible = item.project_name.findn(_search_term) != -1 || search_path.findn(_search_term) != -1;
}
item.control->set_visible(visible);
}
for (int i = 0; i < _projects.size(); ++i) {
Item &item = _projects.write[i];
if (item.control->is_visible()) {
item.control->get_parent()->move_child(item.control, i);
}
}
// Rewind the coroutine because order of projects changed
update_icons_async();
}
const Set<String> &ProjectList::get_selected_project_keys() const {
// Faster if that's all you need
return _selected_project_keys;
}
Vector<ProjectList::Item> ProjectList::get_selected_projects() const {
Vector<Item> items;
if (_selected_project_keys.size() == 0) {
return items;
}
items.resize(_selected_project_keys.size());
int j = 0;
for (int i = 0; i < _projects.size(); ++i) {
const Item &item = _projects[i];
if (_selected_project_keys.has(item.project_key)) {
items.write[j++] = item;
}
}
ERR_FAIL_COND_V(j != items.size(), items);
return items;
}
void ProjectList::ensure_project_visible(int p_index) {
const Item &item = _projects[p_index];
int item_top = item.control->get_position().y;
int item_bottom = item.control->get_position().y + item.control->get_size().y;
if (item_top < get_v_scroll()) {
set_v_scroll(item_top);
} else if (item_bottom > get_v_scroll() + get_size().y) {
set_v_scroll(item_bottom - get_size().y);
}
}
int ProjectList::get_single_selected_index() const {
if (_selected_project_keys.size() == 0) {
// Default selection
return 0;
}
String key;
if (_selected_project_keys.size() == 1) {
// Only one selected
key = _selected_project_keys.front()->get();
} else {
// Multiple selected, consider the last clicked one as "main"
key = _last_clicked;
}
for (int i = 0; i < _projects.size(); ++i) {
if (_projects[i].project_key == key) {
return i;
}
}
return 0;
}
void ProjectList::remove_project(int p_index, bool p_update_settings) {
const Item item = _projects[p_index]; // Take a copy
_selected_project_keys.erase(item.project_key);
if (_last_clicked == item.project_key) {
_last_clicked = "";
}
memdelete(item.control);
_projects.remove(p_index);
if (p_update_settings) {
EditorSettings::get_singleton()->erase("projects/" + item.project_key);
EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key);
// Not actually saving the file, in case you are doing more changes to settings
}
}
bool ProjectList::is_any_project_missing() const {
for (int i = 0; i < _projects.size(); ++i) {
if (_projects[i].missing) {
return true;
}
}
return false;
}
void ProjectList::erase_missing_projects() {
if (_projects.empty()) {
return;
}
int deleted_count = 0;
int remaining_count = 0;
for (int i = 0; i < _projects.size(); ++i) {
const Item &item = _projects[i];
if (item.missing) {
remove_project(i, true);
--i;
++deleted_count;
} else {
++remaining_count;
}
}
print_line("Removed " + itos(deleted_count) + " projects from the list, remaining " + itos(remaining_count) + " projects");
EditorSettings::get_singleton()->save();
}
int ProjectList::refresh_project(const String &dir_path) {
// Reads editor settings and reloads information about a specific project.
// If it wasn't loaded and should be in the list, it is added (i.e new project).
// If it isn't in the list anymore, it is removed.
// If it is in the list but doesn't exist anymore, it is marked as missing.
String project_key = get_project_key_from_path(dir_path);
// Read project manager settings
bool is_favourite = false;
bool should_be_in_list = false;
String property_key = "projects/" + project_key;
{
List<PropertyInfo> properties;
EditorSettings::get_singleton()->get_property_list(&properties);
String favorite_property_key = "favorite_projects/" + project_key;
bool found = false;
for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
String prop = E->get().name;
if (!found && prop == property_key) {
found = true;
} else if (!is_favourite && prop == favorite_property_key) {
is_favourite = true;
}
}
should_be_in_list = found;
}
bool was_selected = _selected_project_keys.has(project_key);
// Remove item in any case
for (int i = 0; i < _projects.size(); ++i) {
const Item &existing_item = _projects[i];
if (existing_item.path == dir_path) {
remove_project(i, false);
break;
}
}
int index = -1;
if (should_be_in_list) {
// Recreate it with updated info
Item item;
load_project_data(property_key, item, is_favourite);
_projects.push_back(item);
create_project_item_control(_projects.size() - 1);
sort_projects();
for (int i = 0; i < _projects.size(); ++i) {
if (_projects[i].project_key == project_key) {
if (was_selected) {
select_project(i);
ensure_project_visible(i);
}
load_project_icon(i);
index = i;
break;
}
}
}
return index;
}
int ProjectList::get_project_count() const {
return _projects.size();
}
void ProjectList::select_project(int p_index) {
Vector<Item> previous_selected_items = get_selected_projects();
_selected_project_keys.clear();
for (int i = 0; i < previous_selected_items.size(); ++i) {
previous_selected_items[i].control->update();
}
toggle_select(p_index);
}
inline void sort(int &a, int &b) {
if (a > b) {
int temp = a;
a = b;
b = temp;
}
}
void ProjectList::select_range(int p_begin, int p_end) {
sort(p_begin, p_end);
select_project(p_begin);
for (int i = p_begin + 1; i <= p_end; ++i) {
toggle_select(i);
}
}
void ProjectList::toggle_select(int p_index) {
Item &item = _projects.write[p_index];
if (_selected_project_keys.has(item.project_key)) {
_selected_project_keys.erase(item.project_key);
} else {
_selected_project_keys.insert(item.project_key);
}
item.control->update();
}
void ProjectList::erase_selected_projects() {
if (_selected_project_keys.size() == 0) {
return;
}
for (int i = 0; i < _projects.size(); ++i) {
Item &item = _projects.write[i];
if (_selected_project_keys.has(item.project_key) && item.control->is_visible()) {
EditorSettings::get_singleton()->erase("projects/" + item.project_key);
EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key);
memdelete(item.control);
_projects.remove(i);
--i;
}
}
EditorSettings::get_singleton()->save();
_selected_project_keys.clear();
_last_clicked = "";
}
// Draws selected project highlight
void ProjectList::_panel_draw(Node *p_hb) {
Control *hb = Object::cast_to<Control>(p_hb);
hb->draw_line(Point2(0, hb->get_size().y + 1), Point2(hb->get_size().x - 10, hb->get_size().y + 1), get_color("guide_color", "Tree"));
String key = _projects[p_hb->get_index()].project_key;
if (_selected_project_keys.has(key)) {
hb->draw_style_box(get_stylebox("selected", "Tree"), Rect2(Point2(), hb->get_size() - Size2(10, 0) * EDSCALE));
}
}
// Input for each item in the list
void ProjectList::_panel_input(const Ref<InputEvent> &p_ev, Node *p_hb) {
Ref<InputEventMouseButton> mb = p_ev;
int clicked_index = p_hb->get_index();
const Item &clicked_project = _projects[clicked_index];
if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) {
if (mb->get_shift() && _selected_project_keys.size() > 0 && _last_clicked != "" && clicked_project.project_key != _last_clicked) {
int anchor_index = -1;
for (int i = 0; i < _projects.size(); ++i) {
const Item &p = _projects[i];
if (p.project_key == _last_clicked) {
anchor_index = p.control->get_index();
break;
}
}
CRASH_COND(anchor_index == -1);
select_range(anchor_index, clicked_index);
} else if (mb->get_control()) {
toggle_select(clicked_index);
} else {
_last_clicked = clicked_project.project_key;
select_project(clicked_index);
}
emit_signal(SIGNAL_SELECTION_CHANGED);
if (!mb->get_control() && mb->is_doubleclick()) {
emit_signal(SIGNAL_PROJECT_ASK_OPEN);
}
}
}
void ProjectList::_favorite_pressed(Node *p_hb) {
ProjectListItemControl *control = Object::cast_to<ProjectListItemControl>(p_hb);
int index = control->get_index();
Item item = _projects.write[index]; // Take copy
item.favorite = !item.favorite;
if (item.favorite) {
EditorSettings::get_singleton()->set("favorite_projects/" + item.project_key, item.path);
} else {
EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key);
}
EditorSettings::get_singleton()->save();
_projects.write[index] = item;
control->set_is_favorite(item.favorite);
sort_projects();
if (item.favorite) {
for (int i = 0; i < _projects.size(); ++i) {
if (_projects[i].project_key == item.project_key) {
ensure_project_visible(i);
break;
}
}
}
}
void ProjectList::_show_project(const String &p_path) {
OS::get_singleton()->shell_open(String("file://") + p_path);
}
const char *ProjectList::SIGNAL_SELECTION_CHANGED = "selection_changed";
const char *ProjectList::SIGNAL_PROJECT_ASK_OPEN = "project_ask_open";
void ProjectList::_bind_methods() {
ClassDB::bind_method("_panel_draw", &ProjectList::_panel_draw);
ClassDB::bind_method("_panel_input", &ProjectList::_panel_input);
ClassDB::bind_method("_favorite_pressed", &ProjectList::_favorite_pressed);
ClassDB::bind_method("_show_project", &ProjectList::_show_project);
ADD_SIGNAL(MethodInfo(SIGNAL_SELECTION_CHANGED));
ADD_SIGNAL(MethodInfo(SIGNAL_PROJECT_ASK_OPEN));
}
void ProjectManager::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
Engine::get_singleton()->set_editor_hint(false);
} break;
case NOTIFICATION_READY: {
if (_project_list->get_project_count() == 0 && StreamPeerSSL::is_available())
open_templates->popup_centered_minsize();
if (_project_list->get_project_count() >= 1) {
// Focus on the search box immediately to allow the user
// to search without having to reach for their mouse
project_filter->search_box->grab_focus();
}
} break;
case NOTIFICATION_VISIBILITY_CHANGED: {
set_process_unhandled_input(is_visible_in_tree());
} break;
case NOTIFICATION_WM_QUIT_REQUEST: {
_dim_window();
} break;
}
}
void ProjectManager::_dim_window() {
// This method must be called before calling `get_tree()->quit()`.
// Otherwise, its effect won't be visible
// Dim the project manager window while it's quitting to make it clearer that it's busy.
// No transition is applied, as the effect needs to be visible immediately
float c = 0.5f;
Color dim_color = Color(c, c, c);
gui_base->set_modulate(dim_color);
}
void ProjectManager::_update_project_buttons() {
Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects();
bool empty_selection = selected_projects.empty();
bool is_missing_project_selected = false;
for (int i = 0; i < selected_projects.size(); ++i) {
if (selected_projects[i].missing) {
is_missing_project_selected = true;
break;
}
}
erase_btn->set_disabled(empty_selection);
open_btn->set_disabled(empty_selection || is_missing_project_selected);
rename_btn->set_disabled(empty_selection || is_missing_project_selected);
run_btn->set_disabled(empty_selection || is_missing_project_selected);
erase_missing_btn->set_visible(_project_list->is_any_project_missing());
}
void ProjectManager::_unhandled_input(const Ref<InputEvent> &p_ev) {
Ref<InputEventKey> k = p_ev;
if (k.is_valid()) {
if (!k->is_pressed()) {
return;
}
// Pressing Command + Q quits the Project Manager
// This is handled by the platform implementation on macOS,
// so only define the shortcut on other platforms
#ifndef OSX_ENABLED
if (k->get_scancode_with_modifiers() == (KEY_MASK_CMD | KEY_Q)) {
_dim_window();
get_tree()->quit();
}
#endif
if (tabs->get_current_tab() != 0)
return;
bool scancode_handled = true;
switch (k->get_scancode()) {
case KEY_ENTER: {
_open_selected_projects_ask();
} break;
case KEY_DELETE: {
_erase_project();
} break;
case KEY_HOME: {
if (_project_list->get_project_count() > 0) {
_project_list->select_project(0);
_update_project_buttons();
}
} break;
case KEY_END: {
if (_project_list->get_project_count() > 0) {
_project_list->select_project(_project_list->get_project_count() - 1);
_update_project_buttons();
}
} break;
case KEY_UP: {
if (k->get_shift())
break;
int index = _project_list->get_single_selected_index();
if (index > 0) {
_project_list->select_project(index - 1);
_project_list->ensure_project_visible(index - 1);
_update_project_buttons();
}
break;
}
case KEY_DOWN: {
if (k->get_shift())
break;
int index = _project_list->get_single_selected_index();
if (index + 1 < _project_list->get_project_count()) {
_project_list->select_project(index + 1);
_project_list->ensure_project_visible(index + 1);
_update_project_buttons();
}
} break;
case KEY_F: {
if (k->get_command())
this->project_filter->search_box->grab_focus();
else
scancode_handled = false;
} break;
default: {
scancode_handled = false;
} break;
}
if (scancode_handled) {
accept_event();
}
}
}
void ProjectManager::_load_recent_projects() {
_project_list->set_order_option(project_order_filter->get_filter_option());
_project_list->set_search_term(project_filter->get_search_term());
_project_list->load_projects();
_update_project_buttons();
tabs->set_current_tab(0);
}
void ProjectManager::_on_projects_updated() {
Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects();
int index = 0;
for (int i = 0; i < selected_projects.size(); ++i) {
index = _project_list->refresh_project(selected_projects[i].path);
}
if (index != -1) {
_project_list->ensure_project_visible(index);
}
}
void ProjectManager::_on_project_created(const String &dir) {
project_filter->clear();
int i = _project_list->refresh_project(dir);
_project_list->select_project(i);
_project_list->ensure_project_visible(i);
_open_selected_projects_ask();
}
void ProjectManager::_confirm_update_settings() {
_open_selected_projects();
}
void ProjectManager::_global_menu_action(const Variant &p_id, const Variant &p_meta) {
int id = (int)p_id;
if (id == ProjectList::GLOBAL_NEW_WINDOW) {
List<String> args;
String exec = OS::get_singleton()->get_executable_path();
OS::ProcessID pid = 0;
OS::get_singleton()->execute(exec, args, false, &pid);
} else if (id == ProjectList::GLOBAL_OPEN_PROJECT) {
String conf = (String)p_meta;
if (conf != String()) {
List<String> args;
args.push_back(conf);
String exec = OS::get_singleton()->get_executable_path();
OS::ProcessID pid = 0;
OS::get_singleton()->execute(exec, args, false, &pid);
}
}
}
void ProjectManager::_open_selected_projects() {
const Set<String> &selected_list = _project_list->get_selected_project_keys();
for (const Set<String>::Element *E = selected_list.front(); E; E = E->next()) {
const String &selected = E->get();
String path = EditorSettings::get_singleton()->get("projects/" + selected);
String conf = path.plus_file("project.godot");
if (!FileAccess::exists(conf)) {
dialog_error->set_text(vformat(TTR("Can't open project at '%s'."), path));
dialog_error->popup_centered_minsize();
return;
}
print_line("Editing project: " + path + " (" + selected + ")");
List<String> args;
args.push_back("--path");
args.push_back(path);
args.push_back("--editor");
if (OS::get_singleton()->is_disable_crash_handler()) {
args.push_back("--disable-crash-handler");
}
String exec = OS::get_singleton()->get_executable_path();
OS::ProcessID pid = 0;
Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND(err);
}
_dim_window();
get_tree()->quit();
}
void ProjectManager::_open_selected_projects_ask() {
const Set<String> &selected_list = _project_list->get_selected_project_keys();
if (selected_list.size() < 1) {
return;
}
if (selected_list.size() > 1) {
multi_open_ask->set_text(TTR("Are you sure to open more than one project?"));
multi_open_ask->popup_centered_minsize();
return;
}
ProjectList::Item project = _project_list->get_selected_projects()[0];
if (project.missing) {
return;
}
// Update the project settings or don't open
String conf = project.path.plus_file("project.godot");
int config_version = project.version;
// Check if the config_version property was empty or 0
if (config_version == 0) {
ask_update_settings->set_text(vformat(TTR("The following project settings file does not specify the version of Godot through which it was created.\n\n%s\n\nIf you proceed with opening it, it will be converted to Godot's current configuration file format.\nWarning: You won't be able to open the project with previous versions of the engine anymore."), conf));
ask_update_settings->popup_centered_minsize();
return;
}
// Check if we need to convert project settings from an earlier engine version
if (config_version < ProjectSettings::CONFIG_VERSION) {
ask_update_settings->set_text(vformat(TTR("The following project settings file was generated by an older engine version, and needs to be converted for this version:\n\n%s\n\nDo you want to convert it?\nWarning: You won't be able to open the project with previous versions of the engine anymore."), conf));
ask_update_settings->popup_centered_minsize();
return;
}
// Check if the file was generated by a newer, incompatible engine version
if (config_version > ProjectSettings::CONFIG_VERSION) {
dialog_error->set_text(vformat(TTR("Can't open project at '%s'.") + "\n" + TTR("The project settings were created by a newer engine version, whose settings are not compatible with this version."), project.path));
dialog_error->popup_centered_minsize();
return;
}
// Open if the project is up-to-date
_open_selected_projects();
}
void ProjectManager::_run_project_confirm() {
Vector<ProjectList::Item> selected_list = _project_list->get_selected_projects();
for (int i = 0; i < selected_list.size(); ++i) {
const String &selected_main = selected_list[i].main_scene;
if (selected_main == "") {
run_error_diag->set_text(TTR("Can't run project: no main scene defined.\nPlease edit the project and set the main scene in the Project Settings under the \"Application\" category."));
run_error_diag->popup_centered();
return;
}
const String &selected = selected_list[i].project_key;
String path = EditorSettings::get_singleton()->get("projects/" + selected);
if (!DirAccess::exists(path + "/.import")) {
run_error_diag->set_text(TTR("Can't run project: Assets need to be imported.\nPlease edit the project to trigger the initial import."));
run_error_diag->popup_centered();
return;
}
print_line("Running project: " + path + " (" + selected + ")");
List<String> args;
args.push_back("--path");
args.push_back(path);
if (OS::get_singleton()->is_disable_crash_handler()) {
args.push_back("--disable-crash-handler");
}
String exec = OS::get_singleton()->get_executable_path();
OS::ProcessID pid = 0;
Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND(err);
}
}
// When you press the "Run" button
void ProjectManager::_run_project() {
const Set<String> &selected_list = _project_list->get_selected_project_keys();
if (selected_list.size() < 1) {
return;
}
if (selected_list.size() > 1) {
multi_run_ask->set_text(vformat(TTR("Are you sure to run %d projects at once?"), selected_list.size()));
multi_run_ask->popup_centered_minsize();
} else {
_run_project_confirm();
}
}
void ProjectManager::_scan_dir(const String &path, List<String> *r_projects) {
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
da->change_dir(path);
da->list_dir_begin();
String n = da->get_next();
while (n != String()) {
if (da->current_is_dir() && !n.begins_with(".")) {
_scan_dir(da->get_current_dir().plus_file(n), r_projects);
} else if (n == "project.godot") {
r_projects->push_back(da->get_current_dir());
}
n = da->get_next();
}
da->list_dir_end();
memdelete(da);
}
void ProjectManager::_scan_begin(const String &p_base) {
print_line("Scanning projects at: " + p_base);
List<String> projects;
_scan_dir(p_base, &projects);
print_line("Found " + itos(projects.size()) + " projects.");
for (List<String>::Element *E = projects.front(); E; E = E->next()) {
String proj = get_project_key_from_path(E->get());
EditorSettings::get_singleton()->set("projects/" + proj, E->get());
}
EditorSettings::get_singleton()->save();
_load_recent_projects();
}
void ProjectManager::_scan_projects() {
scan_dir->popup_centered_ratio();
}
void ProjectManager::_new_project() {
npdialog->set_mode(ProjectDialog::MODE_NEW);
npdialog->show_dialog();
}
void ProjectManager::_import_project() {
npdialog->set_mode(ProjectDialog::MODE_IMPORT);
npdialog->show_dialog();
}
void ProjectManager::_rename_project() {
const Set<String> &selected_list = _project_list->get_selected_project_keys();
if (selected_list.size() == 0) {
return;
}
for (Set<String>::Element *E = selected_list.front(); E; E = E->next()) {
const String &selected = E->get();
String path = EditorSettings::get_singleton()->get("projects/" + selected);
npdialog->set_project_path(path);
npdialog->set_mode(ProjectDialog::MODE_RENAME);
npdialog->show_dialog();
}
}
void ProjectManager::_erase_project_confirm() {
_project_list->erase_selected_projects();
_update_project_buttons();
}
void ProjectManager::_erase_missing_projects_confirm() {
_project_list->erase_missing_projects();
_update_project_buttons();
}
void ProjectManager::_erase_project() {
const Set<String> &selected_list = _project_list->get_selected_project_keys();
if (selected_list.size() == 0)
return;
String confirm_message;
if (selected_list.size() >= 2) {
confirm_message = vformat(TTR("Remove %d projects from the list?\nThe project folders' contents won't be modified."), selected_list.size());
} else {
confirm_message = TTR("Remove this project from the list?\nThe project folder's contents won't be modified.");
}
erase_ask->set_text(confirm_message);
erase_ask->popup_centered_minsize();
}
void ProjectManager::_erase_missing_projects() {
erase_missing_ask->set_text(TTR("Remove all missing projects from the list?\nThe project folders' contents won't be modified."));
erase_missing_ask->popup_centered_minsize();
}
void ProjectManager::_language_selected(int p_id) {
String lang = language_btn->get_item_metadata(p_id);
EditorSettings::get_singleton()->set("interface/editor/editor_language", lang);
language_btn->set_text(lang);
language_btn->set_icon(get_icon("Environment", "EditorIcons"));
language_restart_ask->set_text(TTR("Language changed.\nThe interface will update after restarting the editor or project manager."));
language_restart_ask->popup_centered();
}
void ProjectManager::_restart_confirm() {
List<String> args = OS::get_singleton()->get_cmdline_args();
String exec = OS::get_singleton()->get_executable_path();
OS::ProcessID pid = 0;
Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND(err);
_dim_window();
get_tree()->quit();
}
void ProjectManager::_exit_dialog() {
_dim_window();
get_tree()->quit();
}
void ProjectManager::_install_project(const String &p_zip_path, const String &p_title) {
npdialog->set_mode(ProjectDialog::MODE_INSTALL);
npdialog->set_zip_path(p_zip_path);
npdialog->set_zip_title(p_title);
npdialog->show_dialog();
}
void ProjectManager::_files_dropped(PoolStringArray p_files, int p_screen) {
Set<String> folders_set;
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
for (int i = 0; i < p_files.size(); i++) {
String file = p_files[i];
folders_set.insert(da->dir_exists(file) ? file : file.get_base_dir());
}
memdelete(da);
if (folders_set.size() > 0) {
PoolStringArray folders;
for (Set<String>::Element *E = folders_set.front(); E; E = E->next()) {
folders.append(E->get());
}
bool confirm = true;
if (folders.size() == 1) {
DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
if (dir->change_dir(folders[0]) == OK) {
dir->list_dir_begin();
String file = dir->get_next();
while (confirm && file != String()) {
if (!dir->current_is_dir() && file.ends_with("project.godot")) {
confirm = false;
}
file = dir->get_next();
}
dir->list_dir_end();
}
memdelete(dir);
}
if (confirm) {
multi_scan_ask->get_ok()->disconnect("pressed", this, "_scan_multiple_folders");
multi_scan_ask->get_ok()->connect("pressed", this, "_scan_multiple_folders", varray(folders));
multi_scan_ask->set_text(
vformat(TTR("Are you sure to scan %s folders for existing Godot projects?\nThis could take a while."), folders.size()));
multi_scan_ask->popup_centered_minsize();
} else {
_scan_multiple_folders(folders);
}
}
}
void ProjectManager::_scan_multiple_folders(PoolStringArray p_files) {
for (int i = 0; i < p_files.size(); i++) {
_scan_begin(p_files.get(i));
}
}
void ProjectManager::_on_order_option_changed() {
_project_list->set_order_option(project_order_filter->get_filter_option());
_project_list->sort_projects();
}
void ProjectManager::_on_filter_option_changed() {
_project_list->set_search_term(project_filter->get_search_term());
_project_list->sort_projects();
}
void ProjectManager::_bind_methods() {
ClassDB::bind_method("_open_selected_projects_ask", &ProjectManager::_open_selected_projects_ask);
ClassDB::bind_method("_open_selected_projects", &ProjectManager::_open_selected_projects);
ClassDB::bind_method(D_METHOD("_global_menu_action"), &ProjectManager::_global_menu_action, DEFVAL(Variant()));
ClassDB::bind_method("_run_project", &ProjectManager::_run_project);
ClassDB::bind_method("_run_project_confirm", &ProjectManager::_run_project_confirm);
ClassDB::bind_method("_scan_projects", &ProjectManager::_scan_projects);
ClassDB::bind_method("_scan_begin", &ProjectManager::_scan_begin);
ClassDB::bind_method("_import_project", &ProjectManager::_import_project);
ClassDB::bind_method("_new_project", &ProjectManager::_new_project);
ClassDB::bind_method("_rename_project", &ProjectManager::_rename_project);
ClassDB::bind_method("_erase_project", &ProjectManager::_erase_project);
ClassDB::bind_method("_erase_missing_projects", &ProjectManager::_erase_missing_projects);
ClassDB::bind_method("_erase_project_confirm", &ProjectManager::_erase_project_confirm);
ClassDB::bind_method("_erase_missing_projects_confirm", &ProjectManager::_erase_missing_projects_confirm);
ClassDB::bind_method("_language_selected", &ProjectManager::_language_selected);
ClassDB::bind_method("_restart_confirm", &ProjectManager::_restart_confirm);
ClassDB::bind_method("_exit_dialog", &ProjectManager::_exit_dialog);
ClassDB::bind_method("_on_order_option_changed", &ProjectManager::_on_order_option_changed);
ClassDB::bind_method("_on_filter_option_changed", &ProjectManager::_on_filter_option_changed);
ClassDB::bind_method("_on_projects_updated", &ProjectManager::_on_projects_updated);
ClassDB::bind_method("_on_project_created", &ProjectManager::_on_project_created);
ClassDB::bind_method("_unhandled_input", &ProjectManager::_unhandled_input);
ClassDB::bind_method("_install_project", &ProjectManager::_install_project);
ClassDB::bind_method("_files_dropped", &ProjectManager::_files_dropped);
ClassDB::bind_method("_open_asset_library", &ProjectManager::_open_asset_library);
ClassDB::bind_method("_confirm_update_settings", &ProjectManager::_confirm_update_settings);
ClassDB::bind_method("_update_project_buttons", &ProjectManager::_update_project_buttons);
ClassDB::bind_method(D_METHOD("_scan_multiple_folders", "files"), &ProjectManager::_scan_multiple_folders);
}
void ProjectManager::_open_asset_library() {
asset_library->disable_community_support();
tabs->set_current_tab(1);
}
ProjectManager::ProjectManager() {
// load settings
if (!EditorSettings::get_singleton())
EditorSettings::create();
EditorSettings::get_singleton()->set_optimize_save(false); //just write settings as they came
{
int display_scale = EditorSettings::get_singleton()->get("interface/editor/display_scale");
float custom_display_scale = EditorSettings::get_singleton()->get("interface/editor/custom_display_scale");
switch (display_scale) {
case 0: {
// Try applying a suitable display scale automatically
const int screen = OS::get_singleton()->get_current_screen();
editor_set_scale(OS::get_singleton()->get_screen_dpi(screen) >= 192 && OS::get_singleton()->get_screen_size(screen).x > 2000 ? 2.0 : 1.0);
} break;
case 1: editor_set_scale(0.75); break;
case 2: editor_set_scale(1.0); break;
case 3: editor_set_scale(1.25); break;
case 4: editor_set_scale(1.5); break;
case 5: editor_set_scale(1.75); break;
case 6: editor_set_scale(2.0); break;
default: {
editor_set_scale(custom_display_scale);
} break;
}
// Define a minimum window size to prevent UI elements from overlapping or being cut off
OS::get_singleton()->set_min_window_size(Size2(750, 420) * EDSCALE);
#ifndef OSX_ENABLED
// The macOS platform implementation uses its own hiDPI window resizing code
// TODO: Resize windows on hiDPI displays on Windows and Linux and remove the line below
OS::get_singleton()->set_window_size(OS::get_singleton()->get_window_size() * MAX(1, EDSCALE));
#endif
}
FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
set_anchors_and_margins_preset(Control::PRESET_WIDE);
set_theme(create_editor_theme());
gui_base = memnew(Control);
add_child(gui_base);
gui_base->set_anchors_and_margins_preset(Control::PRESET_WIDE);
gui_base->set_theme(create_custom_theme());
Panel *panel = memnew(Panel);
gui_base->add_child(panel);
panel->set_anchors_and_margins_preset(Control::PRESET_WIDE);
panel->add_style_override("panel", gui_base->get_stylebox("Background", "EditorStyles"));
VBoxContainer *vb = memnew(VBoxContainer);
panel->add_child(vb);
vb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 8 * EDSCALE);
String cp;
cp += 0xA9;
OS::get_singleton()->set_window_title(VERSION_NAME + String(" - ") + TTR("Project Manager") + " - " + cp + " 2007-2019 Juan Linietsky, Ariel Manzur & Godot Contributors");
Control *center_box = memnew(Control);
center_box->set_v_size_flags(SIZE_EXPAND_FILL);
vb->add_child(center_box);
tabs = memnew(TabContainer);
center_box->add_child(tabs);
tabs->set_anchors_and_margins_preset(Control::PRESET_WIDE);
tabs->set_tab_align(TabContainer::ALIGN_LEFT);
HBoxContainer *tree_hb = memnew(HBoxContainer);
projects_hb = tree_hb;
projects_hb->set_name(TTR("Projects"));
tabs->add_child(tree_hb);
VBoxContainer *search_tree_vb = memnew(VBoxContainer);
tree_hb->add_child(search_tree_vb);
search_tree_vb->set_h_size_flags(SIZE_EXPAND_FILL);
HBoxContainer *sort_filters = memnew(HBoxContainer);
Label *sort_label = memnew(Label);
sort_label->set_text(TTR("Sort:"));
sort_filters->add_child(sort_label);
Vector<String> sort_filter_titles;
sort_filter_titles.push_back("Name");
sort_filter_titles.push_back("Path");
sort_filter_titles.push_back("Last Modified");
project_order_filter = memnew(ProjectListFilter);
project_order_filter->add_filter_option();
project_order_filter->_setup_filters(sort_filter_titles);
project_order_filter->set_filter_size(150);
sort_filters->add_child(project_order_filter);
project_order_filter->connect("filter_changed", this, "_on_order_option_changed");
project_order_filter->set_custom_minimum_size(Size2(180, 10) * EDSCALE);
int projects_sorting_order = (int)EditorSettings::get_singleton()->get("project_manager/sorting_order");
project_order_filter->set_filter_option((ProjectListFilter::FilterOption)projects_sorting_order);
sort_filters->add_spacer(true);
project_filter = memnew(ProjectListFilter);
project_filter->add_search_box();
project_filter->connect("filter_changed", this, "_on_filter_option_changed");
project_filter->set_custom_minimum_size(Size2(280, 10) * EDSCALE);
sort_filters->add_child(project_filter);
search_tree_vb->add_child(sort_filters);
PanelContainer *pc = memnew(PanelContainer);
pc->add_style_override("panel", gui_base->get_stylebox("bg", "Tree"));
search_tree_vb->add_child(pc);
pc->set_v_size_flags(SIZE_EXPAND_FILL);
_project_list = memnew(ProjectList);
_project_list->connect(ProjectList::SIGNAL_SELECTION_CHANGED, this, "_update_project_buttons");
_project_list->connect(ProjectList::SIGNAL_PROJECT_ASK_OPEN, this, "_open_selected_projects_ask");
pc->add_child(_project_list);
_project_list->set_enable_h_scroll(false);
VBoxContainer *tree_vb = memnew(VBoxContainer);
tree_hb->add_child(tree_vb);
Button *open = memnew(Button);
open->set_text(TTR("Edit"));
tree_vb->add_child(open);
open->connect("pressed", this, "_open_selected_projects_ask");
open_btn = open;
Button *run = memnew(Button);
run->set_text(TTR("Run"));
tree_vb->add_child(run);
run->connect("pressed", this, "_run_project");
run_btn = run;
tree_vb->add_child(memnew(HSeparator));
Button *scan = memnew(Button);
scan->set_text(TTR("Scan"));
tree_vb->add_child(scan);
scan->connect("pressed", this, "_scan_projects");
tree_vb->add_child(memnew(HSeparator));
scan_dir = memnew(FileDialog);
scan_dir->set_access(FileDialog::ACCESS_FILESYSTEM);
scan_dir->set_mode(FileDialog::MODE_OPEN_DIR);
scan_dir->set_title(TTR("Select a Folder to Scan")); // must be after mode or it's overridden
scan_dir->set_current_dir(EditorSettings::get_singleton()->get("filesystem/directories/default_project_path"));
gui_base->add_child(scan_dir);
scan_dir->connect("dir_selected", this, "_scan_begin");
Button *create = memnew(Button);
create->set_text(TTR("New Project"));
tree_vb->add_child(create);
create->connect("pressed", this, "_new_project");
Button *import = memnew(Button);
import->set_text(TTR("Import"));
tree_vb->add_child(import);
import->connect("pressed", this, "_import_project");
Button *rename = memnew(Button);
rename->set_text(TTR("Rename"));
tree_vb->add_child(rename);
rename->connect("pressed", this, "_rename_project");
rename_btn = rename;
Button *erase = memnew(Button);
erase->set_text(TTR("Remove"));
tree_vb->add_child(erase);
erase->connect("pressed", this, "_erase_project");
erase_btn = erase;
Button *erase_missing = memnew(Button);
erase_missing->set_text(TTR("Remove Missing"));
tree_vb->add_child(erase_missing);
erase_missing->connect("pressed", this, "_erase_missing_projects");
erase_missing_btn = erase_missing;
tree_vb->add_spacer();
if (StreamPeerSSL::is_available()) {
asset_library = memnew(EditorAssetLibrary(true));
asset_library->set_name(TTR("Templates"));
tabs->add_child(asset_library);
asset_library->connect("install_asset", this, "_install_project");
} else {
WARN_PRINT("Asset Library not available, as it requires SSL to work.");
}
HBoxContainer *settings_hb = memnew(HBoxContainer);
settings_hb->set_alignment(BoxContainer::ALIGN_END);
settings_hb->set_h_grow_direction(Control::GROW_DIRECTION_BEGIN);
Label *version_label = memnew(Label);
String hash = String(VERSION_HASH);
if (hash.length() != 0) {
hash = "." + hash.left(9);
}
version_label->set_text("v" VERSION_FULL_BUILD "" + hash);
// Fade out the version label to be less prominent, but still readable
version_label->set_self_modulate(Color(1, 1, 1, 0.6));
version_label->set_align(Label::ALIGN_CENTER);
settings_hb->add_child(version_label);
language_btn = memnew(OptionButton);
language_btn->set_flat(true);
language_btn->set_focus_mode(Control::FOCUS_NONE);
Vector<String> editor_languages;
List<PropertyInfo> editor_settings_properties;
EditorSettings::get_singleton()->get_property_list(&editor_settings_properties);
for (List<PropertyInfo>::Element *E = editor_settings_properties.front(); E; E = E->next()) {
PropertyInfo &pi = E->get();
if (pi.name == "interface/editor/editor_language") {
editor_languages = pi.hint_string.split(",");
}
}
String current_lang = EditorSettings::get_singleton()->get("interface/editor/editor_language");
for (int i = 0; i < editor_languages.size(); i++) {
String lang = editor_languages[i];
String lang_name = TranslationServer::get_singleton()->get_locale_name(lang);
language_btn->add_item(lang_name + " [" + lang + "]", i);
language_btn->set_item_metadata(i, lang);
if (current_lang == lang) {
language_btn->select(i);
language_btn->set_text(lang);
}
}
language_btn->set_icon(get_icon("Environment", "EditorIcons"));
settings_hb->add_child(language_btn);
language_btn->connect("item_selected", this, "_language_selected");
center_box->add_child(settings_hb);
settings_hb->set_anchors_and_margins_preset(Control::PRESET_TOP_RIGHT);
//////////////////////////////////////////////////////////////
language_restart_ask = memnew(ConfirmationDialog);
language_restart_ask->get_ok()->set_text(TTR("Restart Now"));
language_restart_ask->get_ok()->connect("pressed", this, "_restart_confirm");
language_restart_ask->get_cancel()->set_text(TTR("Continue"));
gui_base->add_child(language_restart_ask);
erase_missing_ask = memnew(ConfirmationDialog);
erase_missing_ask->get_ok()->set_text(TTR("Remove All"));
erase_missing_ask->get_ok()->connect("pressed", this, "_erase_missing_projects_confirm");
gui_base->add_child(erase_missing_ask);
erase_ask = memnew(ConfirmationDialog);
erase_ask->get_ok()->set_text(TTR("Remove"));
erase_ask->get_ok()->connect("pressed", this, "_erase_project_confirm");
gui_base->add_child(erase_ask);
multi_open_ask = memnew(ConfirmationDialog);
multi_open_ask->get_ok()->set_text(TTR("Edit"));
multi_open_ask->get_ok()->connect("pressed", this, "_open_selected_projects");
gui_base->add_child(multi_open_ask);
multi_run_ask = memnew(ConfirmationDialog);
multi_run_ask->get_ok()->set_text(TTR("Run"));
multi_run_ask->get_ok()->connect("pressed", this, "_run_project_confirm");
gui_base->add_child(multi_run_ask);
multi_scan_ask = memnew(ConfirmationDialog);
multi_scan_ask->get_ok()->set_text(TTR("Scan"));
gui_base->add_child(multi_scan_ask);
ask_update_settings = memnew(ConfirmationDialog);
ask_update_settings->get_ok()->connect("pressed", this, "_confirm_update_settings");
gui_base->add_child(ask_update_settings);
OS::get_singleton()->set_low_processor_usage_mode(true);
npdialog = memnew(ProjectDialog);
gui_base->add_child(npdialog);
npdialog->connect("projects_updated", this, "_on_projects_updated");
npdialog->connect("project_created", this, "_on_project_created");
_load_recent_projects();
if (EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path")) {
_scan_begin(EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path"));
}
SceneTree::get_singleton()->connect("files_dropped", this, "_files_dropped");
SceneTree::get_singleton()->connect("global_menu_action", this, "_global_menu_action");
run_error_diag = memnew(AcceptDialog);
gui_base->add_child(run_error_diag);
run_error_diag->set_title(TTR("Can't run project"));
dialog_error = memnew(AcceptDialog);
gui_base->add_child(dialog_error);
open_templates = memnew(ConfirmationDialog);
open_templates->set_text(TTR("You currently don't have any projects.\nWould you like to explore official example projects in the Asset Library?"));
open_templates->get_ok()->set_text(TTR("Open Asset Library"));
open_templates->connect("confirmed", this, "_open_asset_library");
add_child(open_templates);
}
ProjectManager::~ProjectManager() {
if (EditorSettings::get_singleton())
EditorSettings::destroy();
}
void ProjectListFilter::_setup_filters(Vector<String> options) {
filter_option->clear();
for (int i = 0; i < options.size(); i++)
filter_option->add_item(TTR(options[i]));
}
void ProjectListFilter::_search_text_changed(const String &p_newtext) {
emit_signal("filter_changed");
}
String ProjectListFilter::get_search_term() {
return search_box->get_text().strip_edges();
}
ProjectListFilter::FilterOption ProjectListFilter::get_filter_option() {
return _current_filter;
}
void ProjectListFilter::set_filter_option(FilterOption option) {
filter_option->select((int)option);
_filter_option_selected(0);
}
void ProjectListFilter::_filter_option_selected(int p_idx) {
FilterOption selected = (FilterOption)(filter_option->get_selected());
if (_current_filter != selected) {
_current_filter = selected;
emit_signal("filter_changed");
}
}
void ProjectListFilter::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE && has_search_box) {
search_box->set_right_icon(get_icon("Search", "EditorIcons"));
search_box->set_clear_button_enabled(true);
}
}
void ProjectListFilter::_bind_methods() {
ClassDB::bind_method(D_METHOD("_search_text_changed"), &ProjectListFilter::_search_text_changed);
ClassDB::bind_method(D_METHOD("_filter_option_selected"), &ProjectListFilter::_filter_option_selected);
ADD_SIGNAL(MethodInfo("filter_changed"));
}
void ProjectListFilter::add_filter_option() {
filter_option = memnew(OptionButton);
filter_option->set_clip_text(true);
filter_option->connect("item_selected", this, "_filter_option_selected");
add_child(filter_option);
}
void ProjectListFilter::add_search_box() {
search_box = memnew(LineEdit);
search_box->set_placeholder(TTR("Search"));
search_box->connect("text_changed", this, "_search_text_changed");
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(search_box);
has_search_box = true;
}
void ProjectListFilter::set_filter_size(int h_size) {
filter_option->set_custom_minimum_size(Size2(h_size * EDSCALE, 10 * EDSCALE));
}
ProjectListFilter::ProjectListFilter() {
_current_filter = FILTER_NAME;
has_search_box = false;
}
void ProjectListFilter::clear() {
if (has_search_box) {
search_box->clear();
}
}
|
//------------------------------------//
// Author: Breno Cunha Queiroz //
// Date: 2020-11-18 //
// SCC0650 - Computação Gráfica (2020)//
//------------------------------------//
#ifndef KART_H
#define KART_H
#include <vector>
#include "mesh.hpp"
#include "texture.hpp"
#include "shader.hpp"
#include "nlohmann/json.hpp"
using namespace nlohmann;
class Kart
{
public:
Kart(Shader* shader);
~Kart();
void draw();
static Mesh* externMesh;
static Mesh* internMesh;
static Mesh* wheelMesh;
static std::vector<Texture*> externTextures;
static std::vector<Texture*> internTextures;
static std::vector<Texture*> wheelTextures;
//---------- Getters and Setters ----------//
void setName(std::string name) { _name=name; }
void setPosition(glm::vec3 pos) { _position=pos; }
glm::vec3 getPosition() const { return _position; }
glm::vec3 getFront();
glm::vec3 getFrontWheelVector();
void setAngle(float angle) { _angle=angle; }
void setInternTexIndex(int index) { _internTexIndex=index; }
int getInternTexIndex() const { return _internTexIndex; }
void setExternTexIndex(int index) { _externTexIndex=index; }
int getExternTexIndex() const { return _externTexIndex; }
void setWheelTexIndex(int index) { _wheelTexIndex=index; }
int getWheelTexIndex() const { return _wheelTexIndex; }
Shader* getShader() const { return _shader; }
json getKartJson();
void setKartJson(json state);
//---------- Callbacks ----------//
void updatePhysics(float dt);
void updateOnKey(int key, int scancode, int action, int mods);
private:
void rotateFrontWheel(float angle);
glm::vec3 calcTurnCenter();
Shader* _shader;
std::string _name;
// User control
bool _accelerate;
bool _brake;
int _steeringWheel;
// Physiscs
glm::vec3 _position;
glm::vec3 _velocity;
glm::vec3 _acceleration;
float _damping;
glm::vec3 _forceAccum;
float _inverseMass;
// Body
float _angle;
// Wheels
glm::vec3 _frontWheelPos;
glm::vec3 _rearWheelPos;
float _wheelAngularPosition;
float _wheelAngularVelocity;
float _frontWheelAngle;
float _frontWheelAngularVelocity;
float _frontWheelMaxAngle;
// Textures
int _internTexIndex;
int _externTexIndex;
int _wheelTexIndex;
};
#endif// KART_H
|
#include "Environment/ASTEvaluatePatternWithValueNode.hpp"
#include "Environment/ASTSourcePosition.hpp"
#include "Environment/ASTVisitor.hpp"
#include "Environment/BootstrapTypeRegistration.hpp"
namespace Sysmel
{
namespace Environment
{
static BootstrapTypeRegistration<ASTEvaluatePatternWithValueNode> ASTEvaluatePatternWithValueNodeTypeRegistration;
bool ASTEvaluatePatternWithValueNode::isASTEvaluatePatternWithValueNode() const
{
return true;
}
AnyValuePtr ASTEvaluatePatternWithValueNode::accept(const ASTVisitorPtr &visitor)
{
return visitor->visitEvaluatePatternWithValueNode(selfFromThis());
}
SExpression ASTEvaluatePatternWithValueNode::asSExpression() const
{
return SExpressionList{{SExpressionIdentifier{{"evaluatePatternWithValue"}},
sourcePosition->asSExpression(),
introduceNewLexicalScope,
patternNode ? patternNode->asSExpression() : nullptr,
valueNode ? valueNode->asSExpression() : nullptr,
patternEvaluationNode ? patternEvaluationNode->asSExpression() : nullptr,
successAction ? successAction->asSExpression() : nullptr,
failureAction ? failureAction->asSExpression() : nullptr,
}};
}
} // End of namespace Environment
} // End of namespace Sysmel
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid PyramidsCoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size())
{
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash())
{
CTxDestination address;
if (ExtractDestination(pk, address))
{
const CScriptID& hash = boost::get<const CScriptID&>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs)
{
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid PyramidsCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
vector<unsigned char> txData(ParseHexV(params[0], "argument"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.GetCoins(prevHash, coins); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
CCoins coins;
if (view.GetCoins(txid, coins)) {
if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
// what todo if txid is known, but the actual output isn't?
}
if ((unsigned int)nOut >= coins.vout.size())
coins.vout.resize(nOut+1);
coins.vout[nOut].scriptPubKey = scriptPubKey;
coins.vout[nOut].nValue = 0; // we don't know the actual output value
view.SetCoins(txid, coins);
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
CCoins coins;
if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
{
fComplete = false;
continue;
}
const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
// parse hex string from parameter
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
bool fHave = false;
CCoinsViewCache &view = *pcoinsTip;
CCoins existingCoins;
{
fHave = view.GetCoins(hashTx, existingCoins);
if (!fHave) {
// push to local node
CValidationState state;
if (!tx.AcceptToMemoryPool(state, true, false))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state
}
}
if (fHave) {
if (existingCoins.nHeight < 1000000000)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain");
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
} else {
SyncWithWallets(hashTx, tx, NULL, true);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
|
/*
* Copyright 2015, Andrea Del Prete, LAAS-CNRS
*
*/
#ifndef __sot_torque_control_trajectory_generator_H__
#define __sot_torque_control_trajectory_generator_H__
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined(WIN32)
#if defined(trajectory_generator_EXPORTS)
#define TRAJECTORYGENERATOR_EXPORT __declspec(dllexport)
#else
#define TRAJECTORYGENERATOR_EXPORT __declspec(dllimport)
#endif
#else
#define HRP2COMMON_EXPORT
#endif
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#include <iostream>
#include <map>
#include <fstream> /// to read text file
#include "boost/assign.hpp"
#include <dynamic-graph/signal-helper.h>
#include <sot/torque_control/utils/vector-conversions.hh>
namespace dynamicgraph {
namespace sot {
namespace torque_control {
#define MAXBUFSIZE ((int)1000000)
Eigen::MatrixXd readMatrixFromFile(const char* filename) {
int cols = 0, rows = 0;
double buff[MAXBUFSIZE];
// Read numbers from file into buffer.
std::ifstream infile;
infile.open(filename);
while (!infile.eof()) {
std::string line;
getline(infile, line);
// std::cout<<"Read line "<<rows<<"\n";
int temp_cols = 0;
std::stringstream stream(line);
while (!stream.eof()) stream >> buff[cols * rows + temp_cols++];
if (temp_cols == 0) continue;
if (cols == 0)
cols = temp_cols;
else if (temp_cols != cols && !infile.eof()) {
std::cout << "Error while reading matrix from file, line " << rows << " has " << temp_cols
<< " columnds, while preceding lines had " << cols << " columnds\n";
std::cout << line << "\n";
break;
}
rows++;
if ((rows + 1) * cols >= MAXBUFSIZE) {
std::cout << "Max buffer size exceeded (" << rows << " rows, " << cols << " cols)\n";
break;
}
}
infile.close();
rows--;
// Populate matrix with numbers.
Eigen::MatrixXd result(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) result(i, j) = buff[cols * i + j];
return result;
}
class AbstractTrajectoryGenerator {
protected:
Eigen::VectorXd m_x; /// current position
Eigen::VectorXd m_dx; /// current velocity
Eigen::VectorXd m_ddx; /// current acceleration
Eigen::VectorXd m_x_init; /// initial position
Eigen::VectorXd m_x_final; /// final position
double m_traj_time; /// time to go from x_init to x_final (sec)
double m_dt; /// control dt (sampling period of the trajectory)
double m_t; /// current time
Eigen::VectorXd::Index m_size;
virtual void resizeAllData(Eigen::VectorXd::Index size) {
m_size = size;
m_x.setZero(size);
m_dx.setZero(size);
m_ddx.setZero(size);
m_x_init.setZero(size);
m_x_final.setZero(size);
}
void sendMsg(const std::string& msg, MsgType t = MSG_TYPE_INFO, const char* file = "", int line = 0) {
sendMsg("[AbstrTrajGen] " + msg, t, file, line);
}
public:
AbstractTrajectoryGenerator(double dt, double traj_time, Eigen::VectorXd::Index size) {
m_t = 0.0;
m_dt = dt;
m_traj_time = traj_time;
resizeAllData(size);
}
AbstractTrajectoryGenerator(double dt, double traj_time, const Eigen::VectorXd& x_init,
const Eigen::VectorXd& x_final) {
assert(x_init.size() == x_final.size() && "Initial and final state must have the same size");
m_dt = dt;
m_traj_time = traj_time;
resizeAllData(x_init.size());
set_initial_point(x_init);
set_final_point(x_final);
}
virtual bool set_initial_point(const Eigen::VectorXd& x_init) {
if (x_init.size() != m_x_init.size()) return false;
m_x_init = x_init;
m_x = x_init;
m_dx.setZero();
m_t = 0.0;
return true;
}
virtual bool set_initial_point(const double& x_init) {
if (1 != m_x_init.size()) return false;
m_x_init(0) = x_init;
m_x(0) = x_init;
m_dx(0) = 0.0;
m_t = 0.0;
return true;
}
virtual bool set_final_point(const Eigen::VectorXd& x_final) {
if (x_final.size() != m_x_final.size()) return false;
m_x_final = x_final;
return true;
}
virtual bool set_final_point(const double& x_final) {
if (1 != m_x_final.size()) return false;
m_x_final(0) = x_final;
return true;
}
virtual bool set_trajectory_time(double traj_time) {
if (traj_time <= 0.0) return false;
m_traj_time = traj_time;
return true;
}
virtual const Eigen::VectorXd& compute_next_point() = 0;
virtual const Eigen::VectorXd& getPos() { return m_x; }
virtual const Eigen::VectorXd& getVel() { return m_dx; }
virtual const Eigen::VectorXd& getAcc() { return m_ddx; }
virtual const Eigen::VectorXd& get_initial_point() { return m_x_init; }
virtual const Eigen::VectorXd& get_final_point() { return m_x_final; }
virtual bool isTrajectoryEnded() { return m_t >= m_traj_time; }
};
/** Fake trajectory generator that actually generates no trajectory
* at all.
* */
class NoTrajectoryGenerator : public AbstractTrajectoryGenerator {
public:
NoTrajectoryGenerator(int size) : AbstractTrajectoryGenerator(0.001, 1.0, size) {}
virtual const Eigen::VectorXd& compute_next_point() {
m_t += m_dt;
return m_x;
}
virtual bool isTrajectoryEnded() { return false; }
};
/** Trajectory generator that reads the trajectory and its derivatives from a text file.
* */
class TextFileTrajectoryGenerator : public AbstractTrajectoryGenerator {
protected:
Eigen::MatrixXd m_posTraj;
Eigen::MatrixXd m_velTraj;
Eigen::MatrixXd m_accTraj;
public:
TextFileTrajectoryGenerator(double dt, Eigen::VectorXd::Index size) : AbstractTrajectoryGenerator(dt, 1.0, size) {}
virtual bool loadTextFile(const std::string& fileName) {
Eigen::MatrixXd data = readMatrixFromFile(fileName.c_str());
// std::cout<<"Read matrix with "<<data.rows()<<" rows and "<<data.cols()<<" cols from text file\n";
if (data.cols() != 3 * m_size) {
std::cout << "Unexpected number of columns (expected " << 3 * m_size << ", found " << data.cols() << ")\n";
return false;
}
m_traj_time = m_dt * (double)data.rows();
m_t = 0.0;
m_posTraj = data.leftCols(m_size);
m_velTraj = data.middleCols(m_size, m_size);
m_accTraj = data.rightCols(m_size);
m_x_init = m_posTraj.row(0);
return true;
}
virtual const Eigen::VectorXd& compute_next_point() {
Eigen::VectorXd::Index i = (Eigen::VectorXd::Index)std::floor(m_t / m_dt);
if (i < m_posTraj.rows()) {
m_x = m_posTraj.row(i);
m_dx = m_velTraj.row(i);
m_ddx = m_accTraj.row(i);
}
m_t += m_dt;
return m_x;
}
};
/** Point-to-point minimum-jerk trajectory generator. */
class MinimumJerkTrajectoryGenerator : public AbstractTrajectoryGenerator {
public:
MinimumJerkTrajectoryGenerator(double dt, double traj_time, int size)
: AbstractTrajectoryGenerator(dt, traj_time, size) {}
virtual const Eigen::VectorXd& compute_next_point() {
if (m_t <= m_traj_time) {
double td = m_t / m_traj_time;
double td2 = td * td;
double td3 = td2 * td;
double td4 = td3 * td;
double td5 = td4 * td;
double p = 10 * td3 - 15 * td4 + 6 * td5;
double dp = (30 * td2 - 60 * td3 + 30 * td4) / m_traj_time;
double ddp = (60 * td - 180 * td2 + 120 * td3) / (m_traj_time * m_traj_time);
m_x = m_x_init + (m_x_final - m_x_init) * p;
m_dx = (m_x_final - m_x_init) * dp;
m_ddx = (m_x_final - m_x_init) * ddp;
}
m_t += m_dt;
return m_x;
}
};
/** Endless sinusoidal trajectory generator.
* The sinusoid is actually a cosine so that it starts with zero velocity.
*/
class SinusoidTrajectoryGenerator : public AbstractTrajectoryGenerator {
public:
SinusoidTrajectoryGenerator(double dt, double traj_time, int size)
: AbstractTrajectoryGenerator(dt, traj_time, size) {}
const Eigen::VectorXd& compute_next_point() {
double f = 1.0 / (2.0 * m_traj_time);
double two_pi_f = 2 * M_PI * f;
double two_pi_f_t = two_pi_f * m_t;
double p = 0.5 * (1.0 - cos(two_pi_f_t));
double dp = 0.5 * two_pi_f * sin(two_pi_f_t);
double ddp = 0.5 * two_pi_f * two_pi_f * cos(two_pi_f_t);
m_x = m_x_init + (m_x_final - m_x_init) * p;
m_dx = (m_x_final - m_x_init) * dp;
m_ddx = (m_x_final - m_x_init) * ddp;
m_t += m_dt;
return m_x;
}
virtual bool isTrajectoryEnded() { return false; }
};
/** Endless triangular trajectory generator.
*/
class TriangleTrajectoryGenerator : public AbstractTrajectoryGenerator {
protected:
bool m_comingBack;
double m_Tacc;
public:
TriangleTrajectoryGenerator(double dt, double traj_time, int size)
: AbstractTrajectoryGenerator(dt, traj_time, size), m_comingBack(false) {
m_Tacc = 1.0;
}
bool set_acceleration_time(const double Tacc) {
if (Tacc < 0.0 || Tacc > 0.5 * m_traj_time) return false;
m_Tacc = Tacc;
return true;
}
const Eigen::VectorXd& compute_next_point() {
int way;
double t = m_t;
Eigen::VectorXd max_vel = (m_x_final - m_x_init) / (m_traj_time - m_Tacc);
if (m_t > m_traj_time) {
way = -1;
t = t - m_traj_time;
} else {
way = 1;
}
if (t < m_Tacc) {
m_ddx = way * max_vel / m_Tacc;
m_dx = t / m_Tacc * way * max_vel;
} else if (t > m_traj_time - m_Tacc) {
m_ddx = -way * max_vel / m_Tacc;
m_dx = (m_traj_time - t) / m_Tacc * way * max_vel;
} else {
m_ddx = 0.0 * max_vel;
m_dx = way * max_vel;
}
m_x += m_dt * m_dx;
m_t += m_dt;
if (m_t >= 2 * m_traj_time) m_t = m_t - 2 * m_traj_time;
return m_x;
}
virtual bool isTrajectoryEnded() { return false; }
};
/** Endless piece-wise constant acceleration trajectory generator.
*/
class ConstantAccelerationTrajectoryGenerator : public AbstractTrajectoryGenerator {
protected:
bool m_is_accelerating; // if true then apply ddx0, otherwise apply -ddx0
int m_counter; // counter to decide when to switch from ddx0 to -ddx0
int m_counter_max; // value of the counter at which to switch from ddx0 to -ddx0
Eigen::VectorXd m_ddx0; // acceleration to go halfway from x_init to x_final in half traj_time
public:
ConstantAccelerationTrajectoryGenerator(double dt, double traj_time, int size)
: AbstractTrajectoryGenerator(dt, traj_time, size), m_is_accelerating(true) {}
virtual bool set_trajectory_time(double traj_time) {
bool res = AbstractTrajectoryGenerator::set_trajectory_time(traj_time);
if (!res) return false;
m_counter_max = int(m_traj_time / m_dt);
m_counter = int(0.5 * m_counter_max);
m_is_accelerating = true;
return true;
}
const Eigen::VectorXd& compute_next_point() {
m_ddx0 = 4.0 * (m_x_final - m_x_init) / (m_traj_time * m_traj_time);
if (m_counter == m_counter_max) {
m_counter = 0;
m_is_accelerating = !m_is_accelerating;
}
m_counter += 1;
m_ddx = m_ddx0;
if (m_is_accelerating == false) m_ddx *= -1.0;
m_x += m_dt * m_dx + 0.5 * m_dt * m_dt * m_ddx;
m_dx += m_dt * m_ddx;
m_t += m_dt;
return m_x;
}
virtual bool isTrajectoryEnded() { return false; }
};
/** Linear chirp trajectory generator.
* A linear chirp is a sinusoid whose frequency is a linear function of time.
* In particular the frequency starts from a value f0 and it increases linearly
* up to a value f1. Then it goes back to f0 and the trajectory is ended.
*/
class LinearChirpTrajectoryGenerator : public AbstractTrajectoryGenerator {
protected:
Eigen::VectorXd m_f0; /// initial frequency
Eigen::VectorXd m_f1; /// final frequency
/// Variables for temporary results
Eigen::VectorXd m_k; /// frequency first derivative
Eigen::VectorXd m_f; /// current frequency (i.e. time derivative of the phase over 2*pi)
Eigen::VectorXd m_phi; /// current phase
Eigen::VectorXd m_phi_0; /// phase shift for second half of trajectory
Eigen::VectorXd m_p;
Eigen::VectorXd m_dp;
Eigen::VectorXd m_ddp;
public:
LinearChirpTrajectoryGenerator(double dt, double traj_time, int size)
: AbstractTrajectoryGenerator(dt, traj_time, size) {
m_f0.setZero(size);
m_f1.setZero(size);
m_k.setZero(size);
m_f.setZero(size);
m_phi.setZero(size);
m_phi_0.setZero(size);
m_p.setZero(size);
m_dp.setZero(size);
m_ddp.setZero(size);
}
virtual bool set_initial_frequency(const Eigen::VectorXd& f0) {
if (f0.size() != m_f0.size()) return false;
m_f0 = f0;
return true;
}
virtual bool set_initial_frequency(const double& f0) {
if (1 != m_f0.size()) return false;
m_f0[0] = f0;
return true;
}
virtual bool set_final_frequency(const Eigen::VectorXd& f1) {
if (f1.size() != m_f1.size()) return false;
m_f1 = f1;
return true;
}
virtual bool set_final_frequency(const double& f1) {
if (1 != m_f1.size()) return false;
m_f1[0] = f1;
return true;
}
const Eigen::VectorXd& compute_next_point() {
if (m_t == 0.0) {
m_k = 2.0 * (m_f1 - m_f0) / m_traj_time;
m_phi_0 = M_PI * m_traj_time * (m_f0 - m_f1);
}
if (m_t < 0.5 * m_traj_time) {
m_f = m_f0 + m_k * m_t;
m_phi = 2 * M_PI * m_t * (m_f0 + 0.5 * m_k * m_t);
} else {
m_f = m_f1 + m_k * (0.5 * m_traj_time - m_t);
m_phi = m_phi_0 + 2 * M_PI * m_t * (m_f1 + 0.5 * m_k * (m_traj_time - m_t));
}
m_p = 0.5 * (1.0 - m_phi.array().cos());
m_dp = M_PI * m_f.array() * m_phi.array().sin();
m_ddp = 2.0 * M_PI * M_PI * m_f.array() * m_f.array() * m_phi.array().cos();
m_x = m_x_init.array() + (m_x_final.array() - m_x_init.array()) * m_p.array();
m_dx = (m_x_final - m_x_init).array() * m_dp.array();
m_ddx = (m_x_final - m_x_init).array() * m_ddp.array();
m_t += m_dt;
return m_x;
}
};
} // namespace torque_control
} // namespace sot
} // namespace dynamicgraph
#endif // #ifndef __sot_torque_control_trajectory_generators_H__
|
#include "engine/assets/Texture.h"
#if ZE_WITH_EDITOR
#include "assetdatacache/AssetDatacache.h"
#include "assets/AssetCooker.h"
#endif
namespace ze
{
void TexturePlatformData::load(Texture* in_texture)
{
switch(in_texture->get_asset_format())
{
case Texture::TextureAssetFormat::TextureEditor:
#if ZE_WITH_EDITOR
size_t i = 0;
/** Check for missing mipmaps */
bool missing_mipmap = false;
for (auto& mip : mipmaps)
{
std::string key = uuids::to_string(in_texture->get_uuid()) + "_"
+ std::to_string(in_texture->get_compression_mode()) + "_"
+ std::to_string(in_texture->get_format()) + "_"
+ "Mip_" + std::to_string(i++) + "_"
+ std::to_string(mip.width) + "_"
+ std::to_string(mip.height) + "_"
+ std::to_string(mip.depth);
if (!assetdatacache::has_key(key))
{
missing_mipmap = true;
break;
}
}
/** Recompute the mipmaps if missing, this will save this to the assetdatacache */
if(missing_mipmap)
{
AssetCooker::cook_asset(in_texture);
}
i = 0;
for(auto& mip : mipmaps)
{
std::string key = uuids::to_string(in_texture->get_uuid()) + "_"
+ std::to_string(in_texture->get_compression_mode()) + "_"
+ std::to_string(in_texture->get_format()) + "_"
+ "Mip_" + std::to_string(i++) + "_"
+ std::to_string(mip.width) + "_"
+ std::to_string(mip.height) + "_"
+ std::to_string(mip.depth);
mip.data = assetdatacache::get_sync(key);
}
#endif
break;
}
}
}
|
/****************************************************************************
* Copyright (c) 2018-2019 by the Cabana authors *
* All rights reserved. *
* *
* This file is part of the Cabana library. Cabana is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Serial/TestSerial_Category.hpp>
#include <tstCommunicationPlan.hpp>
|
#include "graph.h"
#include "general_cascade.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
//#include <time.h>
#include <iostream>
int GeneralCascade::n = 0;
int GeneralCascade::m = 0;
int GeneralCascade::targetSize = 0;
int GeneralCascade::resultSize = 0;
int GeneralCascade::target[MAX_K]={0};
bool GeneralCascade::built = false;
void GeneralCascade::Build()
{
n = Graph::GetN();
m = Graph::GetM();
built = true;
}
void GeneralCascade::SetTarget(int size, int set[])
{
if (!built) Build();
targetSize = size;
for (int i=0; i<size; i++)
target[i] = set[i];
resultSize = 0;
}
double GeneralCascade::Run(int num_iter, int size, int set[])
{
SetTarget(size, set);
int h, t;
int *list = new int[n];
bool *active= new bool[n];
for (int it=0; it<num_iter; it++)
{
//printf("%d\n",it);
memset(active, 0, sizeof(bool)*n);
for (int i=0; i<targetSize; i++)
{
list[i] = target[i];
active[target[i]] = true;
}
resultSize += targetSize;
h = 0;
t = targetSize;
while (h<t)
{
int k = Graph::GetNeighbor(list[h]);
//printf("%d \n",k);
for (int i=0; i<k; i++)
{
Edge e = Graph::GetEdge(list[h], i);
//cout << '\t' << e.u << '\t' << e.v << '\t' << exp(-e.w1) << '\t' << exp(-e.w2) << endl;
if (active[e.v]) continue;
//printf("%d %d %lg %lg\n", e.u, e.v, exp(-e.w1), exp(-e.w2));
//for (int j=0; j< e.c; j++)
if (((double)rand()/(double)RAND_MAX) < exp(-e.w1))
{
list[t] = e.v;
active[e.v] = true;
t++;
resultSize++;
//break;
}
}
h++;
}
}
delete[] active;
delete[] list;
return (double)resultSize / (double)num_iter;
}
|
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include "originalVibe.h"
#include<iostream>
using namespace std;
using namespace cv;
int main(int, char*argv[])
{
/*视频流的输入*/
VideoCapture cap(argv[1]);
if(!cap.isOpened())
return -1;
/*视频帧图像*/
Mat frame;
/*前景-背景检测及显示窗口*/
Mat seg;
/*创建vibe背景建模的对象*/
OriginalVibe vibe(20,2,20,16,3,3);
Mat frameGray;
int number =0;
for(;;)
{
cap >> frame;
if(! frame.data)
break;
number++;
if(number == 1)
{
vibe.originalVibe_Init_BGR( frame );
continue;
}
else
{
vibe.originalVibe_ClassifyAndUpdate_BGR(frame,seg);
medianBlur(seg,seg,5);
imshow("segmentation", seg);
}
imshow("frame",frame);
if(waitKey(10) >= 0)
break;
}
return 0;
}
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Mikael Lagerkvist <lagerkvist@gecode.org>
*
* Contributing authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Mikael Lagerkvist, 2006
* Guido Tack, 2006
*
* Last modified:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
using namespace Gecode;
/** \brief Specification of one tile
*
* This structure can be used to specify a tile with specified width
* and height, number of such tiles (all with unique values), and a
* char-array tile showing the tile in row-major order.
*
* \relates Pentominoes
*/
class TileSpec {
public:
int width; ///< Width of tile
int height; ///< Height of tile
int amount; ///< Number of tiles
const char *tile; ///< Picture of tile
};
/** \brief Board specifications
*
* Each board specification repurposes the first two TileSpecs to
* record width and height of the board (TileSpec 0) as well as the
* number of tiles and whether the board is filled (TileSpec 1).
*
* \relates Pentominoes
*/
extern const TileSpec *examples[];
/** \brief Board specification sizes
*
* \relates Pentominoes
*/
extern const int examples_size[];
/** \brief Number of board specifications
*
* \relates Pentominoes
*/
extern const unsigned int n_examples;
namespace {
/** \name Symmetry functions
*
* These functions implement the 8 symmetries of 2D planes. The
* functions are templatized so that they can be used both for the
* pieces (defined using C-strings) and for arrays of variables.
*
* \relates Pentominoes
*/
//@{
/** Return index of (\a h, \a w) in the row-major layout of a matrix with
* width \a w1 and height \a h1.
*/
int pos(int h, int w, int h1, int w1);
/// Type for tile symmetry functions
typedef void (*tsymmfunc)(const char*, int, int, char*, int&, int&);
/// Type for board symmetry functions
typedef void (*bsymmfunc)(const IntVarArgs, int, int, IntVarArgs&, int&, int&);
/// Identity symmetry
template<class CArray, class Array>
void id(CArray t1, int w1, int h1, Array t2, int& w2, int&h2);
/// Rotate 90 degrees
template<class CArray, class Array>
void rot90(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
/// Rotate 180 degrees
template<class CArray, class Array>
void rot180(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
/// Rotate 270 degrees
template<class CArray, class Array>
void rot270(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
/// Flip x-wise
template<class CArray, class Array>
void flipx(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
/// Flip y-wise
template<class CArray, class Array>
void flipy(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
/// Flip diagonal 1
template<class CArray, class Array>
void flipd1(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
/// Flip diagonal 2
template<class CArray, class Array>
void flipd2(CArray t1, int w1, int h1, Array t2, int& w2, int& h2);
//@}
}
/**
* \brief %Example: %Pentominoes
*
* \section ScriptPentominoesProblem The Problem
*
* This example places pieces of a puzzle, where each piece is
* composed of a collection of squares, onto a grid. The pieces may
* all be rotated and flipped freely. The goal is to place all the
* pieces on the grid, without any overlaps. An example piece to be
* placed looks like
* \code
* XXX
* X
* XXX
* \endcode
* in one of its rotations.
*
* The most famous instance of such a puzzle is the Pentominoes
* puzzle, where the pieces are all pieces formed by 5 four-connected
* squares.
*
*
* \section ScriptPentominoesVariables The Variables
*
* The variables for the model is the grid of squares that the pieces
* are placed on, where each of the variables for the squares takes
* the value of the number of the piece which is placed overonto it.
*
*
* \section ScriptPentominoesOnePiece Placing one piece
*
* The constraint for each piece placement uses regular expressions
* (and consequently the extensional constraint) for expressing
* placement of (rotated) pieces on the grid. Consider the simple
* example of placing the piece
* \code
* XX
* X
* X
* \endcode
* onto the 4 by 4 board
* \code
* 0123
* 4567
* 89AB
* CDEF
* \endcode
*
* Let the variables 0-F be 0/1-variables indicating if the piece is
* placed on that position or not. First consider placing the piece on
* some location, say covering 1,2,6, and A. Then, writing the
* sequence of values for the variables 0-F out, we get the string
* 0110001000100000. This string and all other strings corresponding
* to placing the above piece in that particular rotation can be
* described using the regular expression \f$0^*11000100010^*\f$. The
* expression indicates that first comes some number of zeroes, then
* two ones in a row (covering places 1 and 2 in our example
* placement), then comes exactly three 0's (not covering places 3, 4,
* and 5), and so on. The variable number of 0's at the beginning and at the end
* makes the expression match any placement of the piece on the board.
*
* There is one problem with the above constraint, since it allows
* placing the piece covering places 3, 4, 8, and C. That is, the
* piece may wrap around the board. To prohibit this, we add a new
* dummy-column to the board, so that it looks like
* \code
* 0123G
* 4567H
* 89ABI
* CDEFJ
* \endcode
* The variables for places G to J are all set to zero initially, and the
* regular expression for the placement of the piece is modified to
* include the extra column, \f$0^*1100001000010^*\f$.
*
*
* \section ScriptPentominoesRotatingPiece Rotating pieces
*
* To handle rotations of the piece, we can use disjunctions of
* regular expressions for all the relevant rotations. Consider the
* rotated version of the above piece, depicted below.
* \code
* X
* XXX
* \endcode
* The corresponding regular expression for this piece is
* \f$0^*1001110^*\f$. To combine these two regular expressions, we
* can simply use disjunction of regular expressions, arriving at the
* expression \f$0^*1100001000010^*|0^*1001110^*\f$ for enforcing
* the placement of the piece in one of the above two rotations.
*
* There are 8 symmetries for the pieces in general. The 8 disjuncts
* for a particular piece might, however, contain less than 8 distinct
* expressions (for example, any square has only one distinct
* disjunct). This is removed when then automaton for the expression
* is computed, since it is minimized.
*
*
* \section ScriptPentominoesSeveral Placing several pieces
*
* To generalize the above model to several pieces, we let the
* variables range from 0 to n, where n is the number of pieces to
* place. Given that we place three pieces, and that the above shown
* piece is number one, we will replace each \f$0\f$-expression with
* the expression \f$(0|2|3)\f$. Thus, the second regular expression
* becomes \f$(0|2|3)^*1(0|2|3)(0|2|3)111(0|2|3)^*\f$. Additionaly,
* the end of line marker gets its own value.
*
* This generalization suffers from the fact that the automata become
* much more complex. This problem can be solved by instead
* projecting out each component, which gives a new board of
* 0/1-variables for each piece to place.
*
*
* \section ScriptPentominoesHeuristic The Branching
*
* This model does not use any advanced heuristic for the
* branching. The variables selection is simply in order, and the
* value selection is minimum value first.
*
* The static value selection allows us to order the pieces in the
* specification of the problem. The pieces are approximately ordered by
* largness or hardness to place.
*
*
* \section ScriptPentominoesSymmetries Removing board symmetries
*
* Especially when searching for all solutions of a puzzle instance,
* we might want to remove the symmetrical boards from the
* solutions-space. This is done using the same symmetry functions as
* for the piece symmetries and lexicographical order constraints.
*
*
* \ingroup Example
*
*/
class Pentominoes : public Script {
public:
/// Choice of propagators
enum {
PROPAGATION_INT, ///< Use integer propagators
PROPAGATION_BOOLEAN, ///< Use Boolean propagators
};
/// Choice of symmetry breaking
enum {
SYMMETRY_NONE, ///< Do not remove symmetric solutions
SYMMETRY_FULL, ///< Remove symmetric solutions
};
private:
/// Specification of the tiles to place.
const TileSpec *spec;
/// Width and height of the board
int width, height;
/// Whether the board is filled or not
bool filled;
/// Number of specifications of tiles to place
int nspecs;
/// Number of tiles to place
int ntiles;
/// The variables for the board.
IntVarArray board;
/// Compute number of tiles
int compute_number_of_tiles(const TileSpec* ts, int nspecs) {
int res = 0;
for (int i = nspecs; i--; ) {
res += ts[i].amount;
}
return res;
}
/// Returns the regular expression for placing a specific tile \a
/// tile in a specific rotation.
REG tile_reg(int twidth, int theight, const char* tile,
REG mark, REG other, REG eol) {
REG oe = other | eol;
REG res = *oe;
REG color[] = {other, mark};
for (int h = 0; h < theight; ++h) {
for (int w = 0; w < twidth; ++w) {
int which = tile[h*twidth + w] == 'X';
res += color[which];
}
if (h < theight-1) {
res += oe(width-twidth, width-twidth);
}
}
res += *oe + oe;
return res;
}
/// Returns the regular expression for placing tile number \a t in
/// any rotation.
REG get_constraint(int t, REG mark, REG other, REG eol) {
// This should be done for all rotations
REG res;
char *t2 = new char[width*height];
int w2, h2;
tsymmfunc syms[] = {id, flipx, flipy, flipd1, flipd2, rot90, rot180, rot270};
int symscnt = sizeof(syms)/sizeof(tsymmfunc);
for (int i = 0; i < symscnt; ++i) {
syms[i](spec[t].tile, spec[t].width, spec[t].height, t2, w2, h2);
res = res | tile_reg(w2, h2, t2, mark, other, eol);
}
delete [] t2;
return res;
}
public:
/// Construction of the model.
Pentominoes(const SizeOptions& opt)
: spec(examples[opt.size()]),
width(spec[0].width+1), // Add one for extra row at end.
height(spec[0].height),
filled(spec[0].amount),
nspecs(examples_size[opt.size()]-1),
ntiles(compute_number_of_tiles(spec+1, nspecs)),
board(*this, width*height, filled,ntiles+1) {
spec += 1; // No need for the specification-part any longer
// Set end-of-line markers
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width-1; ++w)
rel(*this, board[h*width + w], IRT_NQ, ntiles+1);
rel(*this, board[h*width + width - 1], IRT_EQ, ntiles+1);
}
// Post constraints
if (opt.propagation() == PROPAGATION_INT) {
int tile = 0;
for (int i = 0; i < nspecs; ++i) {
for (int j = 0; j < spec[i].amount; ++j) {
// Color
int col = tile+1;
// Expression for color col
REG mark(col);
// Build expression for complement to color col
REG other;
bool first = true;
for (int j = filled; j <= ntiles; ++j) {
if (j == col) continue;
if (first) {
other = REG(j);
first = false;
} else {
other |= REG(j);
}
}
// End of line marker
REG eol(ntiles+1);
extensional(*this, board, get_constraint(i, mark, other, eol));
++tile;
}
}
} else { // opt.propagation() == PROPAGATION_BOOLEAN
int ncolors = ntiles + 2;
// Boolean variables for channeling
BoolVarArgs p(*this,ncolors * board.size(),0,1);
// Post channel constraints
for (int i=board.size(); i--; ) {
BoolVarArgs c(ncolors);
for (int j=ncolors; j--; )
c[j]=p[i*ncolors+j];
channel(*this, c, board[i]);
}
// For placing tile i, we construct the expression over
// 0/1-variables and apply it to the projection of
// the board on the color for the tile.
REG other(0), mark(1);
int tile = 0;
for (int i = 0; i < nspecs; ++i) {
for (int j = 0; j < spec[i].amount; ++j) {
int col = tile+1;
// Projection for color col
BoolVarArgs c(board.size());
for (int k = board.size(); k--; ) {
c[k] = p[k*ncolors+col];
}
extensional(*this, c, get_constraint(i, mark, other, other));
++tile;
}
}
}
if (opt.symmetry() == SYMMETRY_FULL) {
// Remove symmetrical boards
IntVarArgs orig(board.size()-height), symm(board.size()-height);
int pos = 0;
for (int i = 0; i < board.size(); ++i) {
if ((i+1)%width==0) continue;
orig[pos++] = board[i];
}
int w2, h2;
bsymmfunc syms[] = {flipx, flipy, flipd1, flipd2, rot90, rot180, rot270};
int symscnt = sizeof(syms)/sizeof(bsymmfunc);
for (int i = 0; i < symscnt; ++i) {
syms[i](orig, width-1, height, symm, w2, h2);
if (width-1 == w2 && height == h2)
rel(*this, orig, IRT_LQ, symm);
}
}
// Install branching
branch(*this, board, INT_VAR_NONE(), INT_VAL_MIN());
}
/// Constructor for cloning \a s
Pentominoes(bool share, Pentominoes& s) :
Script(share,s), spec(s.spec), width(s.width), height(s.height),
filled(s.filled), nspecs(s.nspecs) {
board.update(*this, share, s.board);
}
/// Copy space during cloning
virtual Space*
copy(bool share) {
return new Pentominoes(share,*this);
}
/// Print solution
virtual void
print(std::ostream& os) const {
for (int h = 0; h < height; ++h) {
os << "\t";
for (int w = 0; w < width-1; ++w) {
int val = board[h*width + w].val();
char c = val < 10 ? '0'+val : 'A' + (val-10);
os << c;
}
os << std::endl;
}
os << std::endl;
}
};
/** \brief Main-function
* \relates Pentominoes
*/
int
main(int argc, char* argv[]) {
SizeOptions opt("Pentominoes");
opt.size(1);
opt.symmetry(Pentominoes::SYMMETRY_FULL);
opt.symmetry(Pentominoes::SYMMETRY_NONE,
"none", "do not remove symmetric solutions");
opt.symmetry(Pentominoes::SYMMETRY_FULL,
"full", "remove symmetric solutions");
opt.propagation(Pentominoes::PROPAGATION_BOOLEAN);
opt.propagation(Pentominoes::PROPAGATION_INT,
"int", "use integer propagators");
opt.propagation(Pentominoes::PROPAGATION_BOOLEAN,
"bool", "use Boolean propagators");
opt.parse(argc,argv);
if (opt.size() >= n_examples) {
std::cerr << "Error: size must be between 0 and "
<< n_examples-1 << std::endl;
return 1;
}
Script::run<Pentominoes,DFS,SizeOptions>(opt);
return 0;
}
/** \name Puzzle specifications
*
* \relates Pentominoes
*/
//@{
/// Small specification
static const TileSpec puzzle0[] =
{
// Width and height of board
{4, 4, true, ""},
{2, 3, 1,
"XX"
"X "
"X "},
{2, 1, 1,
"XX"},
{3, 3, 1,
" XX"
" X"
"XXX"},
{1, 1, 1,
"X"},
{3, 1, 1,
"XXX"}
};
/// Standard specification
static const TileSpec puzzle1[] =
{
// Width and height of board
{8, 8, true, ""},
{3, 3, 1,
"XXX"
"XXX"
"XX "},
{5, 3, 1,
" XXX"
" X "
"XXX "},
{3, 4, 1,
"XXX"
"XXX"
" X"
" X"},
{3, 4, 1,
"XXX"
" X"
" X"
" X"},
{2, 5, 1,
" X"
" X"
" X"
"XX"
"XX"},
{4, 2, 1,
"XX "
"XXXX"},
{3, 3, 1,
"XXX"
" X"
" X"},
{2, 3, 1,
"XX"
"X "
"X "},
{2, 4, 1,
"XX"
"XX"
"XX"
"XX"},
{3, 2, 1,
"XX "
"XXX"}
};
// Perfect square number 2 from examples/perfect-square.cc
static const TileSpec square2[] =
{
// Width and height of board
{10, 10, true, ""},
{6, 6, 1,
"XXXXXX"
"XXXXXX"
"XXXXXX"
"XXXXXX"
"XXXXXX"
"XXXXXX"
},
{4, 4, 3,
"XXXX"
"XXXX"
"XXXX"
"XXXX"},
{2, 2, 4,
"XX"
"XX"}
};
// Perfect square number 3 from examples/perfect-square.cc
static const TileSpec square3[] =
{
// Width and height of board
{20, 20, true, ""},
{9, 9, 1,
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
"XXXXXXXXX"
},
{8, 8, 2,
"XXXXXXXX"
"XXXXXXXX"
"XXXXXXXX"
"XXXXXXXX"
"XXXXXXXX"
"XXXXXXXX"
"XXXXXXXX"
"XXXXXXXX"
},
{7, 7, 1,
"XXXXXXX"
"XXXXXXX"
"XXXXXXX"
"XXXXXXX"
"XXXXXXX"
"XXXXXXX"
"XXXXXXX"
},
{5, 5, 1,
"XXXXX"
"XXXXX"
"XXXXX"
"XXXXX"
"XXXXX"
},
{4, 4, 5,
"XXXX"
"XXXX"
"XXXX"
"XXXX"},
{3, 3, 3,
"XXX"
"XXX"
"XXX"},
{2, 2, 2,
"XX"
"XX"},
{1, 1, 2,
"X"}
};
static const TileSpec pentomino6x10[] =
{
// Width and height of board
{10, 6, true, ""},
{2, 4, 1,
"X "
"X "
"X "
"XX"},
{3,3, 1,
"XX "
" XX"
" X "},
{3,3, 1,
"XXX"
" X "
" X "},
{3,3, 1,
" X"
" XX"
"XX "},
{2,4, 1,
" X"
"XX"
" X"
" X"},
{5,1, 1,
"XXXXX"},
{3,3, 1,
"X "
"XXX"
" X"},
{4,2, 1,
" XXX"
"XX "},
{2,3, 1,
"XX"
"XX"
" X"},
{3,2, 1,
"X X"
"XXX"},
{3,3, 1,
" X "
"XXX"
" X "},
{3,3, 1,
" X"
" X"
"XXX"}
};
static const TileSpec pentomino5x12[] =
{
// Width and height of board
{12, 5, true, ""},
{2, 4, 1,
"X "
"X "
"X "
"XX"},
{3,3, 1,
"XX "
" XX"
" X "},
{3,3, 1,
"XXX"
" X "
" X "},
{3,3, 1,
" X"
" XX"
"XX "},
{2,4, 1,
" X"
"XX"
" X"
" X"},
{5,1, 1,
"XXXXX"},
{3,3, 1,
"X "
"XXX"
" X"},
{4,2, 1,
" XXX"
"XX "},
{2,3, 1,
"XX"
"XX"
" X"},
{3,2, 1,
"X X"
"XXX"},
{3,3, 1,
" X "
"XXX"
" X "},
{3,3, 1,
" X"
" X"
"XXX"}
};
static const TileSpec pentomino4x15[] =
{
// Width and height of board
{15, 4, true, ""},
{2, 4, 1,
"X "
"X "
"X "
"XX"},
{3,3, 1,
"XX "
" XX"
" X "},
{3,3, 1,
"XXX"
" X "
" X "},
{3,3, 1,
" X"
" XX"
"XX "},
{2,4, 1,
" X"
"XX"
" X"
" X"},
{5,1, 1,
"XXXXX"},
{3,3, 1,
"X "
"XXX"
" X"},
{4,2, 1,
" XXX"
"XX "},
{2,3, 1,
"XX"
"XX"
" X"},
{3,2, 1,
"X X"
"XXX"},
{3,3, 1,
" X "
"XXX"
" X "},
{3,3, 1,
" X"
" X"
"XXX"}
};
static const TileSpec pentomino3x20[] =
{
// Width and height of board
{20, 3, true, ""},
{2, 4, 1,
"X "
"X "
"X "
"XX"},
{3,3, 1,
"XX "
" XX"
" X "},
{3,3, 1,
"XXX"
" X "
" X "},
{3,3, 1,
" X"
" XX"
"XX "},
{2,4, 1,
" X"
"XX"
" X"
" X"},
{5,1, 1,
"XXXXX"},
{3,3, 1,
"X "
"XXX"
" X"},
{4,2, 1,
" XXX"
"XX "},
{2,3, 1,
"XX"
"XX"
" X"},
{3,2, 1,
"X X"
"XXX"},
{3,3, 1,
" X "
"XXX"
" X "},
{3,3, 1,
" X"
" X"
"XXX"}
};
/// List of specifications
const TileSpec *examples[] = {puzzle0, puzzle1, square2, square3,
pentomino6x10,pentomino5x12,
pentomino4x15,pentomino3x20};
const int examples_size[] = {sizeof(puzzle0)/sizeof(TileSpec),
sizeof(puzzle1)/sizeof(TileSpec),
sizeof(square2)/sizeof(TileSpec),
sizeof(square3)/sizeof(TileSpec),
sizeof(pentomino6x10)/sizeof(TileSpec),
sizeof(pentomino5x12)/sizeof(TileSpec),
sizeof(pentomino4x15)/sizeof(TileSpec),
sizeof(pentomino3x20)/sizeof(TileSpec)};
/// Number of specifications
const unsigned n_examples = sizeof(examples)/sizeof(TileSpec*);
//@}
// Symmetry functions
namespace {
int pos(int h, int w, int h1, int w1) {
if (!(0 <= h && h < h1) ||
!(0 <= w && w < w1)) {
std::cerr << "Cannot place (" << h << "," << w
<< ") on board of size " << h1 << "x" << w1 << std::endl;
}
return h * w1 + w;
}
template<class CArray, class Array>
void id(CArray t1, int w1, int h1, Array t2, int& w2, int&h2) {
w2 = w1; h2 = h1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(h, w, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void rot90(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = h1; h2 = w1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(w, w2-h-1, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void rot180(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = w1; h2 = h1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(h2-h-1, w2-w-1, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void rot270(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = h1; h2 = w1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(h2-w-1, h, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void flipx(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = w1; h2 = h1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(h, w2-w-1, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void flipy(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = w1; h2 = h1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(h2-h-1, w, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void flipd1(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = h1; h2 = w1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(w, h, h2, w2)] = t1[pos(h, w, h1, w1)];
}
template<class CArray, class Array>
void flipd2(CArray t1, int w1, int h1, Array t2, int& w2, int& h2) {
w2 = h1; h2 = w1;
for (int h = 0; h < h1; ++h)
for (int w = 0; w < w1; ++w)
t2[pos(h2-w-1, w2-h-1, h2, w2)] = t1[pos(h, w, h1, w1)];
}
}
// STATISTICS: example-any
|
#ifndef I_APPLICATION_LISTENER_HPP
#define I_APPLICATION_LISTENER_HPP
namespace wgt
{
class IApplicationListener
{
public:
virtual void applicationStarted() = 0;
virtual void applicationStopped() = 0;
};
} // end namespace wgt
#endif // I_APPLICATION_LISTENER_HPP
|
/*
Copyright 2013, 2015 Rogier van Dalen.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/** \file
Implement the polymorphic interface for actual ranges underlying any_range.
This file follows the same structure as interface.hpp.
Some of the class names are even the same, but then in a different namespace.
Before reading this file, it is probably easiest to read and understand
interface.hpp.
The same idea of linear inheritance is used in this file, but here each
combination of direction and operation gets its own class, and the
implementation linearly inherits from all of them.
*/
#ifndef RANGE_ANY_RANGE_IMPLEMENTATION_HPP_INCLUDED
#define RANGE_ANY_RANGE_IMPLEMENTATION_HPP_INCLUDED
#include <utility>
#include <stdexcept>
#include <boost/mpl/placeholders.hpp>
#include "utility/unique_ptr.hpp"
#include "meta/range.hpp"
#include "meta/fold.hpp"
#include "range/core.hpp"
#include "capability.hpp"
#include "interface.hpp"
namespace range { namespace any_range_implementation {
/** \brief
Implement the interface in ./interface.hpp for \a Capabilities, for all
operations that \a Underlying supports.
Operations that are not supported by \a Underlying lead to undefined
behaviour when called.
*/
template <class Element, class CapabilityKeys, class Underlying>
class implementation;
template <class Element, class CapabilityKeys, class Underlying>
class base
: public any_range_interface::interface <Element, CapabilityKeys,
typename capability::detect_default_direction <Underlying>::type>
{
static_assert (capability::is_capability_keys <CapabilityKeys>::value,
"");
Underlying underlying_;
public:
typedef Underlying underlying_type;
typedef implementation <Element, CapabilityKeys, Underlying>
implementation_type;
template <class OtherUnderlying> struct implementation_for {
typedef implementation <Element, CapabilityKeys, OtherUnderlying>
type;
};
template <class Argument> base (Argument && argument)
: underlying_ (std::forward <Argument> (argument)) {}
base (base const & other) : underlying_ (other.underlying_) {}
base (base && other) : underlying_ (std::move (other.underlying_)) {}
Underlying & underlying() { return underlying_; }
Underlying const & underlying() const { return underlying_; }
};
/** Implement the losing of a capability. */
template <class Element, class CapabilityKeys, class KeyToRemove,
class Base, class Enable = void>
struct implement_lose_capability;
// Without copy construction: can not be implemented.
template <class Element, class CapabilityKeys, class KeyToRemove,
class Base>
struct implement_lose_capability <Element, CapabilityKeys, KeyToRemove,
Base, typename boost::disable_if <
meta::has_key <capability::copy_construct, CapabilityKeys>
>::type>
: Base
{
static_assert (capability::is_capability_keys <CapabilityKeys>::value,
"");
template <class Argument> implement_lose_capability (
Argument && argument)
: Base (std::forward <Argument> (argument)) {}
};
// With copy construction: can be implemented.
template <class Element, class CapabilityKeys, class KeyToRemove,
class Base>
struct implement_lose_capability <Element, CapabilityKeys, KeyToRemove,
Base, typename boost::enable_if <
meta::has_key <capability::copy_construct, CapabilityKeys>
>::type>
: Base
{
static_assert (capability::is_capability_keys <CapabilityKeys>::value,
"");
template <class Argument> implement_lose_capability (
Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::lose_capability;
virtual typename Base::template
interface_ptr_without <KeyToRemove>::type
lose_capability (capability::type <KeyToRemove>) const
{
typedef typename meta::remove <KeyToRemove, CapabilityKeys>::type
new_capability_keys;
typedef implementation <Element, new_capability_keys,
typename Base::underlying_type> new_implementation_type;
return utility::make_unique <new_implementation_type> (
this->underlying());
}
};
/* Implement capabilities. */
template <class Element, class Capability, class Base, class Enable = void>
struct implement;
template <class Element, class Base>
struct implement <Element,
meta::map_element <capability::copy_construct, void>,
Base>
: Base
{
template <class Argument> implement (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
virtual typename Base::interface_ptr copy() const {
return utility::make_unique <typename Base::implementation_type> (
this->underlying());
}
};
// default_direction
template <class Element, class Direction, class Base>
struct implement <Element,
meta::map_element <capability::default_direction, Direction>,
Base>
: Base
{
template <class Argument> implement (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
// Sometimes this overrides something, but if the default direction
// is default-constructible, the method is not virtual in the interface.
virtual Direction default_direction() const
{ throw std::logic_error ("Bug in any_range."); }
};
template <class Element, class Capability, class Direction, class Base>
struct implement_capability;
// Farm out to implement_capability for each capability.
template <class Element, class Direction, class Capabilities, class Base>
struct implement <Element,
meta::map_element <Direction, Capabilities>, Base>
: meta::fold <implement_capability <
Element, boost::mpl::_2, Direction, boost::mpl::_1>,
Base, Capabilities>::type
{
typedef typename meta::fold <implement_capability <
Element, boost::mpl::_2, Direction, boost::mpl::_1>,
Base, Capabilities>::type base_type;
template <class Argument> implement (Argument && argument)
: base_type (std::forward <Argument> (argument)) {}
};
// empty.
template <class Element, class Direction, class Base>
struct implement_capability <Element,
capability::empty, Direction, Base>
: Base
{
template <class Argument> implement_capability (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::empty;
virtual bool empty (Direction const & direction) const
{ return range::empty (this->underlying(), direction); }
};
// size.
template <class Element, class Direction, class Base>
struct implement_capability <Element,
capability::size, Direction, Base>
: Base
{
template <class Argument> implement_capability (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::size;
virtual std::size_t size (Direction const & direction) const
{ return range::size (this->underlying(), direction); }
};
// first.
template <class Element, class Direction, class Base>
struct implement_capability <Element,
capability::first, Direction, Base>
: Base
{
template <class Argument> implement_capability (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::first;
private:
Element implementation (
Direction const & direction, rime::false_type) const
{ return range::first (this->underlying(), direction); }
Element implementation (Direction const &, rime::true_type) const
{ throw std::logic_error ("first() not implemented for empty range."); }
public:
virtual Element first (Direction const & direction) const {
return implementation (direction,
always_empty <typename Base::underlying_type, Direction>());
}
};
// drop_one.
template <class Element, class Direction, class Base>
struct implement_capability <Element,
capability::drop_one, Direction, Base>
: Base
{
template <class Argument> implement_capability (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::drop_one;
typedef typename Base::interface_ptr interface_ptr;
private:
interface_ptr implementation (
Direction const & direction, rime::false_type) const
{
typedef typename Base::underlying_type underlying_type;
// If the range is heterogeneous, the new underlying type will be
// different.
// It is assumed it has the same capabilities.
typedef typename result_of <callable::drop (
underlying_type, Direction)>::type new_underlying_type;
typedef typename Base::template implementation_for <
new_underlying_type>::type new_implementation_type;
return utility::make_unique <new_implementation_type> (
range::drop (this->underlying(), direction));
}
interface_ptr implementation (Direction const &, rime::true_type) const
{ throw std::logic_error ("drop() not implemented for empty range."); }
public:
virtual interface_ptr drop_one (
Direction const & direction) const
{
return implementation (direction,
always_empty <typename Base::underlying_type, Direction>());
}
};
// drop_n.
template <class Element, class Direction, class Base>
struct implement_capability <Element,
capability::drop_n, Direction, Base>
: Base
{
template <class Argument> implement_capability (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::drop_n;
typedef typename Base::interface_ptr interface_ptr;
private:
// Not always empty.
interface_ptr implementation (std::size_t increment,
Direction const & direction, rime::false_type) const
{
typedef typename Base::underlying_type underlying_type;
typedef typename result_of <callable::drop (
underlying_type, std::size_t, Direction)>::type
new_underlying_type;
typedef typename Base::template implementation_for <
new_underlying_type>::type new_implementation_type;
return utility::make_unique <new_implementation_type> (
range::drop (this->underlying(), increment, direction));
}
// Always empty.
interface_ptr implementation (
std::size_t, Direction const &, rime::true_type) const
{ throw std::logic_error ("drop() not implemented for empty range."); }
public:
virtual interface_ptr drop_n (
std::size_t increment, Direction const & direction) const
{
return implementation (increment, direction,
always_empty <typename Base::underlying_type, Direction>());
}
};
template <class Element, class Direction, class Base>
struct implement_capability <Element,
capability::chop_destructive, Direction, Base>
: Base
{
template <class Argument> implement_capability (Argument && argument)
: Base (std::forward <Argument> (argument)) {}
using Base::chop_destructive;
typedef typename Base::interface_ptr interface_ptr;
public:
// Don't hide this type from subclasses.
typedef typename Base::underlying_type underlying_type;
private:
typedef any_range_interface::chopped <Element, interface_ptr>
chop_destructive_result;
// Dispatch based on: has <chop_in_place>, always_empty.
chop_destructive_result implementation (
Direction const & direction, interface_ptr & this_,
rime::true_type, rime::false_type)
{
return chop_destructive_result (
range::chop_in_place (this->underlying(), direction),
interface_ptr());
}
chop_destructive_result implementation (
Direction const & direction, interface_ptr & this_,
rime::false_type, rime::false_type)
{
auto c = range::chop (std::move (this->underlying()), direction);
typedef typename std::decay <decltype (c.forward_rest())>::type
new_underlying_type;
typedef typename Base::template implementation_for <
new_underlying_type>::type new_implementation_type;
interface_ptr discardable = std::move (this_);
this_ =
utility::make_unique <new_implementation_type> (c.move_rest());
return chop_destructive_result (
c.move_first(), std::move (discardable));
}
template <class Bool>
chop_destructive_result implementation (
Direction const &, interface_ptr &, Bool, rime::true_type)
{ throw std::logic_error ("chop() not implemented for empty range."); }
public:
virtual chop_destructive_result chop_destructive (
Direction const & direction, interface_ptr & this_)
{
return implementation (direction, this_,
has <callable::chop_in_place (underlying_type &, Direction)>(),
always_empty <typename Base::underlying_type, Direction>());
}
};
// Types for implementation class.
template <class Element, class CapabilityKeys, class Underlying>
struct implementation_types
{
typedef typename capability::detect_capabilities <
Underlying, CapabilityKeys>::type capabilities;
typedef typename meta::fold <
implement_lose_capability <Element, CapabilityKeys,
boost::mpl::_2, boost::mpl::_1>,
base <Element, CapabilityKeys, Underlying>,
CapabilityKeys>::type lose_capabilities_type;
typedef typename meta::fold <
implement <Element, boost::mpl::_2, boost::mpl::_1>,
lose_capabilities_type,
capabilities>::type base_type;
};
/* Main implementation class. */
template <class Element, class CapabilityKeys, class Underlying>
class implementation
: public implementation_types <
Element, CapabilityKeys, Underlying>::base_type
{
typedef implementation_types <Element, CapabilityKeys, Underlying>
types;
public:
typedef typename types::capabilities capabilities;
private:
typedef typename types::base_type base_type;
public:
template <class Argument> implementation (Argument && argument)
: base_type (std::forward <Argument> (argument)) {}
};
}} // namespace range::any_range_implementation
#endif // RANGE_ANY_RANGE_IMPLEMENTATION_HPP_INCLUDED
|
/* Copyright (c) 2012-2013 Stanislaw Halik <sthalik@misaki.pl>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*/
/*
* this file appeared originally in facetracknoir, was rewritten completely
* following opentrack fork.
*
* originally written by Wim Vriend.
*/
#include "tracker.h"
#include <cmath>
#include <algorithm>
#if defined(_WIN32)
# include <windows.h>
#endif
Tracker::Tracker(main_settings& s, Mappings &m, SelectedLibraries &libs) :
s(s),
m(m),
centerp(s.center_at_startup),
enabledp(true),
zero_(false),
should_quit(false),
libs(libs),
r_b(dmat<3,3>::eye()),
t_b {0,0,0}
{
}
Tracker::~Tracker()
{
should_quit = true;
wait();
}
double Tracker::map(double pos, Mapping& axis)
{
bool altp = (pos < 0) && axis.opts.altp;
axis.curve.setTrackingActive( !altp );
axis.curveAlt.setTrackingActive( altp );
auto& fc = altp ? axis.curveAlt : axis.curve;
return fc.getValue(pos) + axis.opts.zero;
}
void Tracker::t_compensate(const rmat& rmat, const double* xyz, double* output, bool rz)
{
// TY is really yaw axis. need swapping accordingly.
dmat<3, 1> tvec({ xyz[2], -xyz[0], -xyz[1] });
const dmat<3, 1> ret = rmat * tvec;
if (!rz)
output[2] = ret(0, 0);
else
output[2] = xyz[2];
output[1] = -ret(2, 0);
output[0] = -ret(1, 0);
}
void Tracker::logic()
{
bool inverts[6] = {
m(0).opts.invert,
m(1).opts.invert,
m(2).opts.invert,
m(3).opts.invert,
m(4).opts.invert,
m(5).opts.invert,
};
static constexpr double pi = 3.141592653;
static constexpr double r2d = 180. / pi;
Pose value, raw;
if (!zero_)
for (int i = 0; i < 6; i++)
{
value(i) = newpose[i];
raw(i) = newpose[i];
}
else
{
auto mat = rmat::rmat_to_euler(r_b);
for (int i = 0; i < 3; i++)
{
raw(i+3) = value(i+3) = mat(i, 0) * r2d;
raw(i) = value(i) = t_b[i];
}
}
const double off[] = {
s.camera_yaw,
s.camera_pitch,
0.
};
const rmat cam = rmat::euler_to_rmat(off);
rmat r = rmat::euler_to_rmat(&value[Yaw]);
dmat<3, 1> t { value(0), value(1), value(2) };
r = cam * r;
t = cam * t;
bool can_center = false;
if (centerp)
{
for (int i = 0; i < 6; i++)
if (fabs(newpose[i]) != 0)
{
can_center = true;
break;
}
}
if (can_center)
{
centerp = false;
for (int i = 0; i < 3; i++)
t_b[i] = t(i, 0);
r_b = r;
}
{
double tmp[3] = { t(0, 0) - t_b[0], t(1, 0) - t_b[1], t(2, 0) - t_b[2] };
t_compensate(cam, tmp, tmp, false);
const rmat m_ = r * r_b.t();
const dmat<3, 1> euler = rmat::rmat_to_euler(m_);
for (int i = 0; i < 3; i++)
{
value(i) = tmp[i];
value(i+3) = euler(i, 0) * r2d;
}
}
for (int i = 3; i < 6; i++)
value(i) = map(value(i), m(i));
{
Pose tmp = value;
if (libs.pFilter)
libs.pFilter->filter(tmp, value);
}
if (s.tcomp_p)
t_compensate(rmat::euler_to_rmat(&value[Yaw]),
value,
value,
s.tcomp_tz);
for (int i = 0; i < 3; i++)
value(i) = map(value(i), m(i));
for (int i = 0; i < 6; i++)
value[i] *= inverts[i] ? -1. : 1.;
Pose output_pose_;
for (int i = 0; i < 6; i++)
{
auto& axis = m(i);
int k = axis.opts.src;
if (k < 0 || k >= 6)
output_pose_(i) = 0;
else
output_pose_(i) = value(k);
}
libs.pProtocol->pose(output_pose_);
QMutexLocker foo(&mtx);
output_pose = output_pose_;
raw_6dof = raw;
}
void Tracker::run() {
const int sleep_ms = 3;
#if defined(_WIN32)
(void) timeBeginPeriod(1);
#endif
while (!should_quit)
{
t.start();
double tmp[6] {0,0,0, 0,0,0};
libs.pTracker->data(tmp);
if (enabledp)
for (int i = 0; i < 6; i++)
newpose[i] = tmp[i];
logic();
long q = sleep_ms * 1000L - t.elapsed()/1000L;
usleep(std::max(1L, q));
}
{
// do one last pass with origin pose
for (int i = 0; i < 6; i++)
newpose[i] = 0;
logic();
// filter may inhibit exact origin
Pose p;
libs.pProtocol->pose(p);
}
#if defined(_WIN32)
(void) timeEndPeriod(1);
#endif
for (int i = 0; i < 6; i++)
{
m(i).curve.setTrackingActive(false);
m(i).curveAlt.setTrackingActive(false);
}
}
void Tracker::get_raw_and_mapped_poses(double* mapped, double* raw) const {
QMutexLocker foo(&const_cast<Tracker&>(*this).mtx);
for (int i = 0; i < 6; i++)
{
raw[i] = raw_6dof(i);
mapped[i] = output_pose(i);
}
}
|
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Function.h>
#include <AK/String.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Accessor.h>
#include <LibJS/Runtime/BooleanObject.h>
#include <LibJS/Runtime/Date.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/NumberObject.h>
#include <LibJS/Runtime/ObjectPrototype.h>
#include <LibJS/Runtime/RegExpObject.h>
#include <LibJS/Runtime/StringObject.h>
#include <LibJS/Runtime/Value.h>
namespace JS {
ObjectPrototype::ObjectPrototype(GlobalObject& global_object)
: Object(Object::ConstructWithoutPrototypeTag::Tag, global_object)
{
}
void ObjectPrototype::initialize(GlobalObject& global_object)
{
auto& vm = this->vm();
Object::initialize(global_object);
// This must be called after the constructor has returned, so that the below code
// can find the ObjectPrototype through normal paths.
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(vm.names.hasOwnProperty, has_own_property, 1, attr);
define_native_function(vm.names.toString, to_string, 0, attr);
define_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
define_native_function(vm.names.valueOf, value_of, 0, attr);
define_native_function(vm.names.propertyIsEnumerable, property_is_enumerable, 1, attr);
define_native_function(vm.names.isPrototypeOf, is_prototype_of, 1, attr);
// Annex B
define_native_function(vm.names.__defineGetter__, define_getter, 2, attr);
define_native_function(vm.names.__defineSetter__, define_setter, 2, attr);
define_native_function(vm.names.__lookupGetter__, lookup_getter, 1, attr);
define_native_function(vm.names.__lookupSetter__, lookup_setter, 1, attr);
define_native_accessor(vm.names.__proto__, proto_getter, proto_setter, Attribute::Configurable);
}
ObjectPrototype::~ObjectPrototype()
{
}
// 10.4.7.1 [[SetPrototypeOf]] ( V ), https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects-setprototypeof-v
bool ObjectPrototype::internal_set_prototype_of(Object* prototype)
{
return set_immutable_prototype(prototype);
}
// 20.1.3.2 Object.prototype.hasOwnProperty ( V ), https://tc39.es/ecma262/#sec-object.prototype.hasownproperty
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::has_own_property)
{
auto property_key = vm.argument(0).to_property_key(global_object);
if (vm.exception())
return {};
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return {};
return Value(this_object->has_own_property(property_key));
}
// 20.1.3.6 Object.prototype.toString ( ), https://tc39.es/ecma262/#sec-object.prototype.tostring
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_string)
{
auto this_value = vm.this_value(global_object);
// 1. If the this value is undefined, return "[object Undefined]".
if (this_value.is_undefined())
return js_string(vm, "[object Undefined]");
// 2. If the this value is null, return "[object Null]".
if (this_value.is_null())
return js_string(vm, "[object Null]");
// 3. Let O be ! ToObject(this value).
auto* object = this_value.to_object(global_object);
VERIFY(object);
// 4. Let isArray be ? IsArray(O).
auto is_array = Value(object).is_array(global_object);
if (vm.exception())
return {};
String builtin_tag;
// 5. If isArray is true, let builtinTag be "Array".
if (is_array)
builtin_tag = "Array";
// 6. Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
else if (object->has_parameter_map())
builtin_tag = "Arguments";
// 7. Else if O has a [[Call]] internal method, let builtinTag be "Function".
else if (object->is_function())
builtin_tag = "Function";
// 8. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
else if (is<Error>(object))
builtin_tag = "Error";
// 9. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
else if (is<BooleanObject>(object))
builtin_tag = "Boolean";
// 10. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
else if (is<NumberObject>(object))
builtin_tag = "Number";
// 11. Else if O has a [[StringData]] internal slot, let builtinTag be "String".
else if (is<StringObject>(object))
builtin_tag = "String";
// 12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
else if (is<Date>(object))
builtin_tag = "Date";
// 13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
else if (is<RegExpObject>(object))
builtin_tag = "RegExp";
// 14. Else, let builtinTag be "Object".
else
builtin_tag = "Object";
// 15. Let tag be ? Get(O, @@toStringTag).
auto to_string_tag = object->get(*vm.well_known_symbol_to_string_tag());
if (vm.exception())
return {};
// Optimization: Instead of creating another PrimitiveString from builtin_tag, we separate tag and to_string_tag and add an additional branch to step 16.
String tag;
// 16. If Type(tag) is not String, set tag to builtinTag.
if (!to_string_tag.is_string())
tag = move(builtin_tag);
else
tag = to_string_tag.as_string().string();
// 17. Return the string-concatenation of "[object ", tag, and "]".
return js_string(vm, String::formatted("[object {}]", tag));
}
// 20.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] ), https://tc39.es/ecma262/#sec-object.prototype.tolocalestring
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_locale_string)
{
auto this_value = vm.this_value(global_object);
return this_value.invoke(global_object, vm.names.toString);
}
// 20.1.3.7 Object.prototype.valueOf ( ), https://tc39.es/ecma262/#sec-object.prototype.valueof
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::value_of)
{
return vm.this_value(global_object).to_object(global_object);
}
// 20.1.3.4 Object.prototype.propertyIsEnumerable ( V ), https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::property_is_enumerable)
{
// 1. Let P be ? ToPropertyKey(V).
auto property_key = vm.argument(0).to_property_key(global_object);
if (vm.exception())
return {};
// 2. Let O be ? ToObject(this value).
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return {};
// 3. Let desc be ? O.[[GetOwnProperty]](P).
auto property_descriptor = this_object->internal_get_own_property(property_key);
if (vm.exception())
return {};
// 4. If desc is undefined, return false.
if (!property_descriptor.has_value())
return Value(false);
// 5. Return desc.[[Enumerable]].
return Value(*property_descriptor->enumerable);
}
// 20.1.3.3 Object.prototype.isPrototypeOf ( V ), https://tc39.es/ecma262/#sec-object.prototype.isprototypeof
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::is_prototype_of)
{
auto object_argument = vm.argument(0);
if (!object_argument.is_object())
return Value(false);
auto* object = &object_argument.as_object();
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return {};
for (;;) {
object = object->internal_get_prototype_of();
if (!object)
return Value(false);
if (same_value(this_object, object))
return Value(true);
}
}
// B.2.2.2 Object.prototype.__defineGetter__ ( P, getter ), https://tc39.es/ecma262/#sec-object.prototype.__defineGetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_getter)
{
auto object = vm.this_value(global_object).to_object(global_object);
if (vm.exception())
return {};
auto getter = vm.argument(1);
if (!getter.is_function()) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, getter.to_string_without_side_effects());
return {};
}
auto descriptor = PropertyDescriptor { .get = &getter.as_function(), .enumerable = true, .configurable = true };
auto key = vm.argument(0).to_property_key(global_object);
if (vm.exception())
return {};
object->define_property_or_throw(key, descriptor);
if (vm.exception())
return {};
return js_undefined();
}
// B.2.2.3 Object.prototype.__defineSetter__ ( P, getter ), https://tc39.es/ecma262/#sec-object.prototype.__defineSetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::define_setter)
{
auto object = vm.this_value(global_object).to_object(global_object);
if (vm.exception())
return {};
auto setter = vm.argument(1);
if (!setter.is_function()) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, setter.to_string_without_side_effects());
return {};
}
auto descriptor = PropertyDescriptor { .set = &setter.as_function(), .enumerable = true, .configurable = true };
auto key = vm.argument(0).to_property_key(global_object);
if (vm.exception())
return {};
object->define_property_or_throw(key, descriptor);
if (vm.exception())
return {};
return js_undefined();
}
// B.2.2.4 Object.prototype.__lookupGetter__ ( P ), https://tc39.es/ecma262/#sec-object.prototype.__lookupGetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_getter)
{
auto object = vm.this_value(global_object).to_object(global_object);
if (vm.exception())
return {};
auto key = vm.argument(0).to_property_key(global_object);
if (vm.exception())
return {};
while (object) {
auto desc = object->internal_get_own_property(key);
if (vm.exception())
return {};
if (desc.has_value()) {
if (desc->is_accessor_descriptor())
return *desc->get ?: js_undefined();
return js_undefined();
}
object = object->internal_get_prototype_of();
if (vm.exception())
return {};
}
return js_undefined();
}
// B.2.2.5 Object.prototype.__lookupSetter__ ( P ), https://tc39.es/ecma262/#sec-object.prototype.__lookupSetter__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::lookup_setter)
{
auto* object = vm.this_value(global_object).to_object(global_object);
if (vm.exception())
return {};
auto key = vm.argument(0).to_property_key(global_object);
if (vm.exception())
return {};
while (object) {
auto desc = object->internal_get_own_property(key);
if (vm.exception())
return {};
if (desc.has_value()) {
if (desc->is_accessor_descriptor())
return *desc->set ?: js_undefined();
return js_undefined();
}
object = object->internal_get_prototype_of();
if (vm.exception())
return {};
}
return js_undefined();
}
// B.2.2.1.1 get Object.prototype.__proto__, https://tc39.es/ecma262/#sec-get-object.prototype.__proto__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::proto_getter)
{
auto object = vm.this_value(global_object).to_object(global_object);
if (vm.exception())
return {};
auto proto = object->internal_get_prototype_of();
if (vm.exception())
return {};
return proto;
}
// B.2.2.1.2 set Object.prototype.__proto__, https://tc39.es/ecma262/#sec-set-object.prototype.__proto__
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::proto_setter)
{
auto object = TRY_OR_DISCARD(require_object_coercible(global_object, vm.this_value(global_object)));
auto proto = vm.argument(0);
if (!proto.is_object() && !proto.is_null())
return js_undefined();
if (!object.is_object())
return js_undefined();
auto status = object.as_object().internal_set_prototype_of(proto.is_object() ? &proto.as_object() : nullptr);
if (vm.exception())
return {};
if (!status) {
// FIXME: Improve/contextualize error message
vm.throw_exception<TypeError>(global_object, ErrorType::ObjectSetPrototypeOfReturnedFalse);
return {};
}
return js_undefined();
}
}
|
//
// Created by vito on 31.10.20.
//
#include "game_guess_num_console_app/assets_loader.h"
#include "game_guess_num/g_number_assets.h"
#include "game_guess_num/g_number_logic.h"
#include "game_guess_num/g_number_metainfo.h"
void AssetsLoader::LoadStaticAssetsForGuessNumber(Culture::Language lang) {
Game::Language = lang;
Game::DescriptionInfo = &GuessNumber::gdi;
Game::DescriptionStrings = &GuessNumber::game_description_strings;
Game::StringAssets = &GuessNumber::Assets::game_assets_strings;
Game::GlobalVariableDeclarations =
&GuessNumber::Logic::GlobalVariables::declaration;
Game::Levels = &GuessNumber::Logic::guess_number_levels;
#ifdef PEP_DEBUG
Terminal::ReportErr(GuessNumber::gdi.project_work_name);
Terminal::ReportErr(Game::DescriptionInfo->project_work_name);
Terminal::ReportErr((void *)Game::DescriptionInfo);
Terminal::ReportErr((void *)Game::DescriptionStrings);
Terminal::ReportErr((void *)Game::StringAssets);
Terminal::ReportErr((void *)Game::GlobalVariableDeclarations);
Terminal::ReportErr((void *)Game::Levels);
#endif
}
|
/**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand
#include "mongo/platform/basic.h"
#include "mongo/db/catalog/capped_utils.h"
#include "mongo/base/error_codes.h"
#include "mongo/db/background.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/collection_catalog_entry.h"
#include "mongo/db/catalog/create_collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/catalog/drop_collection.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/catalog/rename_collection.h"
#include "mongo/db/client.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/curop.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/index_builder.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/query/plan_yield_policy.h"
#include "mongo/db/repl/replication_coordinator_global.h"
#include "mongo/db/service_context.h"
#include "mongo/db/views/view.h"
#include "mongo/util/scopeguard.h"
mongo::Status mongo::emptyCapped(OperationContext* opCtx, const NamespaceString& collectionName) {
AutoGetDb autoDb(opCtx, collectionName.db(), MODE_X);
bool userInitiatedWritesAndNotPrimary = opCtx->writesAreReplicated() &&
!repl::getGlobalReplicationCoordinator()->canAcceptWritesFor(opCtx, collectionName);
if (userInitiatedWritesAndNotPrimary) {
return Status(ErrorCodes::NotMaster,
str::stream() << "Not primary while truncating collection: "
<< collectionName.ns());
}
Database* db = autoDb.getDb();
massert(13429, "no such database", db);
Collection* collection = db->getCollection(opCtx, collectionName);
uassert(ErrorCodes::CommandNotSupportedOnView,
str::stream() << "emptycapped not supported on view: " << collectionName.ns(),
collection || !db->getViewCatalog()->lookup(opCtx, collectionName.ns()));
massert(28584, "no such collection", collection);
if (collectionName.isSystem() && !collectionName.isSystemDotProfile()) {
return Status(ErrorCodes::IllegalOperation,
str::stream() << "Cannot truncate a system collection: "
<< collectionName.ns());
}
if (NamespaceString::virtualized(collectionName.ns())) {
return Status(ErrorCodes::IllegalOperation,
str::stream() << "Cannot truncate a virtual collection: "
<< collectionName.ns());
}
if ((repl::getGlobalReplicationCoordinator()->getReplicationMode() !=
repl::ReplicationCoordinator::modeNone) &&
collectionName.isOplog()) {
return Status(ErrorCodes::OplogOperationUnsupported,
str::stream() << "Cannot truncate a live oplog while replicating: "
<< collectionName.ns());
}
BackgroundOperation::assertNoBgOpInProgForNs(collectionName.ns());
WriteUnitOfWork wuow(opCtx);
Status status = collection->truncate(opCtx);
if (!status.isOK()) {
return status;
}
getGlobalServiceContext()->getOpObserver()->onEmptyCapped(
opCtx, collection->ns(), collection->uuid());
wuow.commit();
return Status::OK();
}
mongo::Status mongo::cloneCollectionAsCapped(OperationContext* opCtx,
Database* db,
const std::string& shortFrom,
const std::string& shortTo,
double size,
bool temp) {
NamespaceString fromNss(db->name(), shortFrom);
NamespaceString toNss(db->name(), shortTo);
Collection* fromCollection = db->getCollection(opCtx, fromNss);
if (!fromCollection) {
if (db->getViewCatalog()->lookup(opCtx, fromNss.ns())) {
return Status(ErrorCodes::CommandNotSupportedOnView,
str::stream() << "cloneCollectionAsCapped not supported for views: "
<< fromNss.ns());
}
return Status(ErrorCodes::NamespaceNotFound,
str::stream() << "source collection " << fromNss.ns() << " does not exist");
}
if (db->getCollection(opCtx, toNss)) {
return Status(ErrorCodes::NamespaceExists,
str::stream() << "cloneCollectionAsCapped failed - destination collection "
<< toNss.ns()
<< " already exists. source collection: "
<< fromNss.ns());
}
// create new collection
{
auto options = fromCollection->getCatalogEntry()->getCollectionOptions(opCtx);
// The capped collection will get its own new unique id, as the conversion isn't reversible,
// so it can't be rolled back.
options.uuid.reset();
options.capped = true;
options.cappedSize = size;
if (temp)
options.temp = true;
BSONObjBuilder cmd;
cmd.append("create", toNss.coll());
cmd.appendElements(options.toBSON());
Status status = createCollection(opCtx, toNss.db().toString(), cmd.done());
if (!status.isOK())
return status;
}
Collection* toCollection = db->getCollection(opCtx, toNss);
invariant(toCollection); // we created above
// how much data to ignore because it won't fit anyway
// datasize and extentSize can't be compared exactly, so add some padding to 'size'
long long allocatedSpaceGuess =
std::max(static_cast<long long>(size * 2),
static_cast<long long>(toCollection->getRecordStore()->storageSize(opCtx) * 2));
long long excessSize = fromCollection->dataSize(opCtx) - allocatedSpaceGuess;
auto exec = InternalPlanner::collectionScan(opCtx,
fromNss.ns(),
fromCollection,
PlanExecutor::WRITE_CONFLICT_RETRY_ONLY,
InternalPlanner::FORWARD);
Snapshotted<BSONObj> objToClone;
RecordId loc;
PlanExecutor::ExecState state = PlanExecutor::FAILURE; // suppress uninitialized warnings
DisableDocumentValidation validationDisabler(opCtx);
int retries = 0; // non-zero when retrying our last document.
while (true) {
if (!retries) {
state = exec->getNextSnapshotted(&objToClone, &loc);
}
switch (state) {
case PlanExecutor::IS_EOF:
return Status::OK();
case PlanExecutor::ADVANCED: {
if (excessSize > 0) {
// 4x is for padding, power of 2, etc...
excessSize -= (4 * objToClone.value().objsize());
continue;
}
break;
}
default:
// Unreachable as:
// 1) We require a read lock (at a minimum) on the "from" collection
// and won't yield, preventing collection drop and PlanExecutor::DEAD
// 2) PlanExecutor::FAILURE is only returned on PlanStage::FAILURE. The
// CollectionScan PlanStage does not have a FAILURE scenario.
// 3) All other PlanExecutor states are handled above
invariant(false);
}
try {
// Make sure we are working with the latest version of the document.
if (objToClone.snapshotId() != opCtx->recoveryUnit()->getSnapshotId() &&
!fromCollection->findDoc(opCtx, loc, &objToClone)) {
// doc was deleted so don't clone it.
retries = 0;
continue;
}
WriteUnitOfWork wunit(opCtx);
OpDebug* const nullOpDebug = nullptr;
uassertStatusOK(toCollection->insertDocument(
opCtx, InsertStatement(objToClone.value()), nullOpDebug, true));
wunit.commit();
// Go to the next document
retries = 0;
} catch (const WriteConflictException& wce) {
CurOp::get(opCtx)->debug().writeConflicts++;
retries++; // logAndBackoff expects this to be 1 on first call.
wce.logAndBackoff(retries, "cloneCollectionAsCapped", fromNss.ns());
// Can't use writeConflictRetry since we need to save/restore exec around call to
// abandonSnapshot.
exec->saveState();
opCtx->recoveryUnit()->abandonSnapshot();
auto restoreStatus = exec->restoreState(); // Handles any WCEs internally.
if (!restoreStatus.isOK()) {
return restoreStatus;
}
}
}
invariant(false); // unreachable
}
mongo::Status mongo::convertToCapped(OperationContext* opCtx,
const NamespaceString& collectionName,
double size) {
StringData dbname = collectionName.db();
StringData shortSource = collectionName.coll();
AutoGetDb autoDb(opCtx, collectionName.db(), MODE_X);
bool userInitiatedWritesAndNotPrimary = opCtx->writesAreReplicated() &&
!repl::getGlobalReplicationCoordinator()->canAcceptWritesFor(opCtx, collectionName);
if (userInitiatedWritesAndNotPrimary) {
return Status(ErrorCodes::NotMaster,
str::stream() << "Not primary while converting " << collectionName.ns()
<< " to a capped collection");
}
Database* const db = autoDb.getDb();
if (!db) {
return Status(ErrorCodes::NamespaceNotFound,
str::stream() << "database " << dbname << " not found");
}
BackgroundOperation::assertNoBgOpInProgForDb(dbname);
// Generate a temporary collection name that will not collide with any existing collections.
auto tmpNameResult =
db->makeUniqueCollectionNamespace(opCtx, "tmp%%%%%.convertToCapped." + shortSource);
if (!tmpNameResult.isOK()) {
return Status(tmpNameResult.getStatus().code(),
str::stream() << "Cannot generate temporary collection namespace to convert "
<< collectionName.ns()
<< " to a capped collection: "
<< tmpNameResult.getStatus().reason());
}
const auto& longTmpName = tmpNameResult.getValue();
const auto shortTmpName = longTmpName.coll().toString();
{
Status status =
cloneCollectionAsCapped(opCtx, db, shortSource.toString(), shortTmpName, size, true);
if (!status.isOK())
return status;
}
RenameCollectionOptions options;
options.dropTarget = true;
options.stayTemp = false;
return renameCollection(opCtx, longTmpName, collectionName, options);
}
|
/**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
int A[5];
int go(int k, int u) {
if (k == 5) return u == 23;
int ret = 0;
if (!ret) ret |= go(k+1, u+A[k]);
if (!ret) ret |= go(k+1, u-A[k]);
if (!ret) ret |= go(k+1, u*A[k]);
return ret;
}
int main() {
while (1) {
int t = 0;
for (int i = 0; i < 5; i++) scanf("%d", A+i), t |= A[i];
if (!t) break;
sort(A, A+5);
int ret = 0;
do ret = go(1,A[0]); while (!ret && next_permutation(A, A+5));
if (ret) puts("Possible");
else puts("Impossible");
}
return 0;
}
|
/*************************************************************************/
/* shader_compiler_rd.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "shader_compiler_rd.h"
#include "core/os/os.h"
#include "core/project_settings.h"
#include "rasterizer_storage_rd.h"
#include "servers/rendering_server.h"
#define SL ShaderLanguage
static String _mktab(int p_level) {
String tb;
for (int i = 0; i < p_level; i++) {
tb += "\t";
}
return tb;
}
static String _typestr(SL::DataType p_type) {
String type = ShaderLanguage::get_datatype_name(p_type);
if (ShaderLanguage::is_sampler_type(p_type)) {
type = type.replace("sampler", "texture"); //we use textures instead of samplers
}
return type;
}
static int _get_datatype_size(SL::DataType p_type) {
switch (p_type) {
case SL::TYPE_VOID:
return 0;
case SL::TYPE_BOOL:
return 4;
case SL::TYPE_BVEC2:
return 8;
case SL::TYPE_BVEC3:
return 12;
case SL::TYPE_BVEC4:
return 16;
case SL::TYPE_INT:
return 4;
case SL::TYPE_IVEC2:
return 8;
case SL::TYPE_IVEC3:
return 12;
case SL::TYPE_IVEC4:
return 16;
case SL::TYPE_UINT:
return 4;
case SL::TYPE_UVEC2:
return 8;
case SL::TYPE_UVEC3:
return 12;
case SL::TYPE_UVEC4:
return 16;
case SL::TYPE_FLOAT:
return 4;
case SL::TYPE_VEC2:
return 8;
case SL::TYPE_VEC3:
return 12;
case SL::TYPE_VEC4:
return 16;
case SL::TYPE_MAT2:
return 32; //4 * 4 + 4 * 4
case SL::TYPE_MAT3:
return 48; // 4 * 4 + 4 * 4 + 4 * 4
case SL::TYPE_MAT4:
return 64;
case SL::TYPE_SAMPLER2D:
return 16;
case SL::TYPE_ISAMPLER2D:
return 16;
case SL::TYPE_USAMPLER2D:
return 16;
case SL::TYPE_SAMPLER2DARRAY:
return 16;
case SL::TYPE_ISAMPLER2DARRAY:
return 16;
case SL::TYPE_USAMPLER2DARRAY:
return 16;
case SL::TYPE_SAMPLER3D:
return 16;
case SL::TYPE_ISAMPLER3D:
return 16;
case SL::TYPE_USAMPLER3D:
return 16;
case SL::TYPE_SAMPLERCUBE:
return 16;
case SL::TYPE_SAMPLERCUBEARRAY:
return 16;
case SL::TYPE_STRUCT:
return 0;
case SL::TYPE_MAX: {
ERR_FAIL_V(0);
};
}
ERR_FAIL_V(0);
}
static int _get_datatype_alignment(SL::DataType p_type) {
switch (p_type) {
case SL::TYPE_VOID:
return 0;
case SL::TYPE_BOOL:
return 4;
case SL::TYPE_BVEC2:
return 8;
case SL::TYPE_BVEC3:
return 16;
case SL::TYPE_BVEC4:
return 16;
case SL::TYPE_INT:
return 4;
case SL::TYPE_IVEC2:
return 8;
case SL::TYPE_IVEC3:
return 16;
case SL::TYPE_IVEC4:
return 16;
case SL::TYPE_UINT:
return 4;
case SL::TYPE_UVEC2:
return 8;
case SL::TYPE_UVEC3:
return 16;
case SL::TYPE_UVEC4:
return 16;
case SL::TYPE_FLOAT:
return 4;
case SL::TYPE_VEC2:
return 8;
case SL::TYPE_VEC3:
return 16;
case SL::TYPE_VEC4:
return 16;
case SL::TYPE_MAT2:
return 16;
case SL::TYPE_MAT3:
return 16;
case SL::TYPE_MAT4:
return 16;
case SL::TYPE_SAMPLER2D:
return 16;
case SL::TYPE_ISAMPLER2D:
return 16;
case SL::TYPE_USAMPLER2D:
return 16;
case SL::TYPE_SAMPLER2DARRAY:
return 16;
case SL::TYPE_ISAMPLER2DARRAY:
return 16;
case SL::TYPE_USAMPLER2DARRAY:
return 16;
case SL::TYPE_SAMPLER3D:
return 16;
case SL::TYPE_ISAMPLER3D:
return 16;
case SL::TYPE_USAMPLER3D:
return 16;
case SL::TYPE_SAMPLERCUBE:
return 16;
case SL::TYPE_SAMPLERCUBEARRAY:
return 16;
case SL::TYPE_STRUCT:
return 0;
case SL::TYPE_MAX: {
ERR_FAIL_V(0);
}
}
ERR_FAIL_V(0);
}
static String _interpstr(SL::DataInterpolation p_interp) {
switch (p_interp) {
case SL::INTERPOLATION_FLAT:
return "flat ";
case SL::INTERPOLATION_SMOOTH:
return "";
}
return "";
}
static String _prestr(SL::DataPrecision p_pres) {
switch (p_pres) {
case SL::PRECISION_LOWP:
return "lowp ";
case SL::PRECISION_MEDIUMP:
return "mediump ";
case SL::PRECISION_HIGHP:
return "highp ";
case SL::PRECISION_DEFAULT:
return "";
}
return "";
}
static String _qualstr(SL::ArgumentQualifier p_qual) {
switch (p_qual) {
case SL::ARGUMENT_QUALIFIER_IN:
return "";
case SL::ARGUMENT_QUALIFIER_OUT:
return "out ";
case SL::ARGUMENT_QUALIFIER_INOUT:
return "inout ";
}
return "";
}
static String _opstr(SL::Operator p_op) {
return SL::get_operator_text(p_op);
}
static String _mkid(const String &p_id) {
String id = "m_" + p_id.replace("__", "_dus_");
return id.replace("__", "_dus_"); //doubleunderscore is reserved in glsl
}
static String f2sp0(float p_float) {
String num = rtoss(p_float);
if (num.find(".") == -1 && num.find("e") == -1) {
num += ".0";
}
return num;
}
static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value> &p_values) {
switch (p_type) {
case SL::TYPE_BOOL:
return p_values[0].boolean ? "true" : "false";
case SL::TYPE_BVEC2:
case SL::TYPE_BVEC3:
case SL::TYPE_BVEC4: {
String text = "bvec" + itos(p_type - SL::TYPE_BOOL + 1) + "(";
for (int i = 0; i < p_values.size(); i++) {
if (i > 0) {
text += ",";
}
text += p_values[i].boolean ? "true" : "false";
}
text += ")";
return text;
}
case SL::TYPE_INT:
return itos(p_values[0].sint);
case SL::TYPE_IVEC2:
case SL::TYPE_IVEC3:
case SL::TYPE_IVEC4: {
String text = "ivec" + itos(p_type - SL::TYPE_INT + 1) + "(";
for (int i = 0; i < p_values.size(); i++) {
if (i > 0) {
text += ",";
}
text += itos(p_values[i].sint);
}
text += ")";
return text;
} break;
case SL::TYPE_UINT:
return itos(p_values[0].uint) + "u";
case SL::TYPE_UVEC2:
case SL::TYPE_UVEC3:
case SL::TYPE_UVEC4: {
String text = "uvec" + itos(p_type - SL::TYPE_UINT + 1) + "(";
for (int i = 0; i < p_values.size(); i++) {
if (i > 0) {
text += ",";
}
text += itos(p_values[i].uint) + "u";
}
text += ")";
return text;
} break;
case SL::TYPE_FLOAT:
return f2sp0(p_values[0].real);
case SL::TYPE_VEC2:
case SL::TYPE_VEC3:
case SL::TYPE_VEC4: {
String text = "vec" + itos(p_type - SL::TYPE_FLOAT + 1) + "(";
for (int i = 0; i < p_values.size(); i++) {
if (i > 0) {
text += ",";
}
text += f2sp0(p_values[i].real);
}
text += ")";
return text;
} break;
case SL::TYPE_MAT2:
case SL::TYPE_MAT3:
case SL::TYPE_MAT4: {
String text = "mat" + itos(p_type - SL::TYPE_MAT2 + 2) + "(";
for (int i = 0; i < p_values.size(); i++) {
if (i > 0) {
text += ",";
}
text += f2sp0(p_values[i].real);
}
text += ")";
return text;
} break;
default:
ERR_FAIL_V(String());
}
}
String ShaderCompilerRD::_get_sampler_name(ShaderLanguage::TextureFilter p_filter, ShaderLanguage::TextureRepeat p_repeat) {
if (p_filter == ShaderLanguage::FILTER_DEFAULT) {
ERR_FAIL_COND_V(actions.default_filter == ShaderLanguage::FILTER_DEFAULT, String());
p_filter = actions.default_filter;
}
if (p_repeat == ShaderLanguage::REPEAT_DEFAULT) {
ERR_FAIL_COND_V(actions.default_repeat == ShaderLanguage::REPEAT_DEFAULT, String());
p_repeat = actions.default_repeat;
}
return actions.sampler_array_name + "[" + itos(p_filter + (p_repeat == ShaderLanguage::REPEAT_ENABLE ? ShaderLanguage::FILTER_DEFAULT : 0)) + "]";
}
void ShaderCompilerRD::_dump_function_deps(const SL::ShaderNode *p_node, const StringName &p_for_func, const Map<StringName, String> &p_func_code, String &r_to_add, Set<StringName> &added) {
int fidx = -1;
for (int i = 0; i < p_node->functions.size(); i++) {
if (p_node->functions[i].name == p_for_func) {
fidx = i;
break;
}
}
ERR_FAIL_COND(fidx == -1);
for (Set<StringName>::Element *E = p_node->functions[fidx].uses_function.front(); E; E = E->next()) {
if (added.has(E->get())) {
continue; //was added already
}
_dump_function_deps(p_node, E->get(), p_func_code, r_to_add, added);
SL::FunctionNode *fnode = nullptr;
for (int i = 0; i < p_node->functions.size(); i++) {
if (p_node->functions[i].name == E->get()) {
fnode = p_node->functions[i].function;
break;
}
}
ERR_FAIL_COND(!fnode);
r_to_add += "\n";
String header;
if (fnode->return_type == SL::TYPE_STRUCT) {
header = _mkid(fnode->return_struct_name) + " " + _mkid(fnode->name) + "(";
} else {
header = _typestr(fnode->return_type) + " " + _mkid(fnode->name) + "(";
}
for (int i = 0; i < fnode->arguments.size(); i++) {
if (i > 0) {
header += ", ";
}
if (fnode->arguments[i].is_const) {
header += "const ";
}
if (fnode->arguments[i].type == SL::TYPE_STRUCT) {
header += _qualstr(fnode->arguments[i].qualifier) + _mkid(fnode->arguments[i].type_str) + " " + _mkid(fnode->arguments[i].name);
} else {
header += _qualstr(fnode->arguments[i].qualifier) + _prestr(fnode->arguments[i].precision) + _typestr(fnode->arguments[i].type) + " " + _mkid(fnode->arguments[i].name);
}
}
header += ")\n";
r_to_add += header;
r_to_add += p_func_code[E->get()];
added.insert(E->get());
}
}
static String _get_global_variable_from_type_and_index(const String &p_buffer, const String &p_index, ShaderLanguage::DataType p_type) {
switch (p_type) {
case ShaderLanguage::TYPE_BOOL: {
return "(" + p_buffer + "[" + p_index + "].x != 0.0)";
}
case ShaderLanguage::TYPE_BVEC2: {
return "(" + p_buffer + "[" + p_index + "].xy != vec2(0.0))";
}
case ShaderLanguage::TYPE_BVEC3: {
return "(" + p_buffer + "[" + p_index + "].xyz != vec3(0.0))";
}
case ShaderLanguage::TYPE_BVEC4: {
return "(" + p_buffer + "[" + p_index + "].xyzw != vec4(0.0))";
}
case ShaderLanguage::TYPE_INT: {
return "floatBitsToInt(" + p_buffer + "[" + p_index + "].x)";
}
case ShaderLanguage::TYPE_IVEC2: {
return "floatBitsToInt(" + p_buffer + "[" + p_index + "].xy)";
}
case ShaderLanguage::TYPE_IVEC3: {
return "floatBitsToInt(" + p_buffer + "[" + p_index + "].xyz)";
}
case ShaderLanguage::TYPE_IVEC4: {
return "floatBitsToInt(" + p_buffer + "[" + p_index + "].xyzw)";
}
case ShaderLanguage::TYPE_UINT: {
return "floatBitsToUInt(" + p_buffer + "[" + p_index + "].x)";
}
case ShaderLanguage::TYPE_UVEC2: {
return "floatBitsToUInt(" + p_buffer + "[" + p_index + "].xy)";
}
case ShaderLanguage::TYPE_UVEC3: {
return "floatBitsToUInt(" + p_buffer + "[" + p_index + "].xyz)";
}
case ShaderLanguage::TYPE_UVEC4: {
return "floatBitsToUInt(" + p_buffer + "[" + p_index + "].xyzw)";
}
case ShaderLanguage::TYPE_FLOAT: {
return "(" + p_buffer + "[" + p_index + "].x)";
}
case ShaderLanguage::TYPE_VEC2: {
return "(" + p_buffer + "[" + p_index + "].xy)";
}
case ShaderLanguage::TYPE_VEC3: {
return "(" + p_buffer + "[" + p_index + "].xyz)";
}
case ShaderLanguage::TYPE_VEC4: {
return "(" + p_buffer + "[" + p_index + "].xyzw)";
}
case ShaderLanguage::TYPE_MAT2: {
return "mat2(" + p_buffer + "[" + p_index + "].xy," + p_buffer + "[" + p_index + "+1].xy)";
}
case ShaderLanguage::TYPE_MAT3: {
return "mat3(" + p_buffer + "[" + p_index + "].xyz," + p_buffer + "[" + p_index + "+1].xyz," + p_buffer + "[" + p_index + "+2].xyz)";
}
case ShaderLanguage::TYPE_MAT4: {
return "mat4(" + p_buffer + "[" + p_index + "].xyzw," + p_buffer + "[" + p_index + "+1].xyzw," + p_buffer + "[" + p_index + "+2].xyzw," + p_buffer + "[" + p_index + "+3].xyzw)";
}
default: {
ERR_FAIL_V("void");
}
}
}
String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions, bool p_assigning, bool p_use_scope) {
String code;
switch (p_node->type) {
case SL::Node::TYPE_SHADER: {
SL::ShaderNode *pnode = (SL::ShaderNode *)p_node;
for (int i = 0; i < pnode->render_modes.size(); i++) {
if (p_default_actions.render_mode_defines.has(pnode->render_modes[i]) && !used_rmode_defines.has(pnode->render_modes[i])) {
r_gen_code.defines.push_back(p_default_actions.render_mode_defines[pnode->render_modes[i]]);
used_rmode_defines.insert(pnode->render_modes[i]);
}
if (p_actions.render_mode_flags.has(pnode->render_modes[i])) {
*p_actions.render_mode_flags[pnode->render_modes[i]] = true;
}
if (p_actions.render_mode_values.has(pnode->render_modes[i])) {
Pair<int *, int> &p = p_actions.render_mode_values[pnode->render_modes[i]];
*p.first = p.second;
}
}
// structs
for (int i = 0; i < pnode->vstructs.size(); i++) {
SL::StructNode *st = pnode->vstructs[i].shader_struct;
String struct_code;
struct_code += "struct ";
struct_code += _mkid(pnode->vstructs[i].name);
struct_code += " ";
struct_code += "{\n";
for (int j = 0; j < st->members.size(); j++) {
SL::MemberNode *m = st->members[j];
if (m->datatype == SL::TYPE_STRUCT) {
struct_code += _mkid(m->struct_name);
} else {
struct_code += _prestr(m->precision);
struct_code += _typestr(m->datatype);
}
struct_code += " ";
struct_code += m->name;
if (m->array_size > 0) {
struct_code += "[";
struct_code += itos(m->array_size);
struct_code += "]";
}
struct_code += ";\n";
}
struct_code += "}";
struct_code += ";\n";
r_gen_code.vertex_global += struct_code;
r_gen_code.fragment_global += struct_code;
r_gen_code.compute_global += struct_code;
}
int max_texture_uniforms = 0;
int max_uniforms = 0;
for (Map<StringName, SL::ShaderNode::Uniform>::Element *E = pnode->uniforms.front(); E; E = E->next()) {
if (SL::is_sampler_type(E->get().type)) {
max_texture_uniforms++;
} else {
if (E->get().scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) {
continue; //instances are indexed directly, dont need index uniforms
}
max_uniforms++;
}
}
r_gen_code.texture_uniforms.resize(max_texture_uniforms);
Vector<int> uniform_sizes;
Vector<int> uniform_alignments;
Vector<StringName> uniform_defines;
uniform_sizes.resize(max_uniforms);
uniform_alignments.resize(max_uniforms);
uniform_defines.resize(max_uniforms);
bool uses_uniforms = false;
for (Map<StringName, SL::ShaderNode::Uniform>::Element *E = pnode->uniforms.front(); E; E = E->next()) {
String ucode;
if (E->get().scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) {
//insert, but don't generate any code.
p_actions.uniforms->insert(E->key(), E->get());
continue; //instances are indexed directly, dont need index uniforms
}
if (SL::is_sampler_type(E->get().type)) {
ucode = "layout(set = " + itos(actions.texture_layout_set) + ", binding = " + itos(actions.base_texture_binding_index + E->get().texture_order) + ") uniform ";
}
bool is_buffer_global = !SL::is_sampler_type(E->get().type) && E->get().scope == SL::ShaderNode::Uniform::SCOPE_GLOBAL;
if (is_buffer_global) {
//this is an integer to index the global table
ucode += _typestr(ShaderLanguage::TYPE_UINT);
} else {
ucode += _prestr(E->get().precision);
ucode += _typestr(E->get().type);
}
ucode += " " + _mkid(E->key());
ucode += ";\n";
if (SL::is_sampler_type(E->get().type)) {
r_gen_code.vertex_global += ucode;
r_gen_code.fragment_global += ucode;
r_gen_code.compute_global += ucode;
GeneratedCode::Texture texture;
texture.name = E->key();
texture.hint = E->get().hint;
texture.type = E->get().type;
texture.filter = E->get().filter;
texture.repeat = E->get().repeat;
texture.global = E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL;
if (texture.global) {
r_gen_code.uses_global_textures = true;
}
r_gen_code.texture_uniforms.write[E->get().texture_order] = texture;
} else {
if (!uses_uniforms) {
r_gen_code.defines.push_back(String("#define USE_MATERIAL_UNIFORMS\n"));
uses_uniforms = true;
}
uniform_defines.write[E->get().order] = ucode;
if (is_buffer_global) {
//globals are indices into the global table
uniform_sizes.write[E->get().order] = _get_datatype_size(ShaderLanguage::TYPE_UINT);
uniform_alignments.write[E->get().order] = _get_datatype_alignment(ShaderLanguage::TYPE_UINT);
} else {
uniform_sizes.write[E->get().order] = _get_datatype_size(E->get().type);
uniform_alignments.write[E->get().order] = _get_datatype_alignment(E->get().type);
}
}
p_actions.uniforms->insert(E->key(), E->get());
}
for (int i = 0; i < max_uniforms; i++) {
r_gen_code.uniforms += uniform_defines[i];
}
#if 1
// add up
int offset = 0;
for (int i = 0; i < uniform_sizes.size(); i++) {
int align = offset % uniform_alignments[i];
if (align != 0) {
offset += uniform_alignments[i] - align;
}
r_gen_code.uniform_offsets.push_back(offset);
offset += uniform_sizes[i];
}
r_gen_code.uniform_total_size = offset;
if (r_gen_code.uniform_total_size % 16 != 0) { //UBO sizes must be multiples of 16
r_gen_code.uniform_total_size += 16 - (r_gen_code.uniform_total_size % 16);
}
#else
// add up
for (int i = 0; i < uniform_sizes.size(); i++) {
if (i > 0) {
int align = uniform_sizes[i - 1] % uniform_alignments[i];
if (align != 0) {
uniform_sizes[i - 1] += uniform_alignments[i] - align;
}
uniform_sizes[i] = uniform_sizes[i] + uniform_sizes[i - 1];
}
}
//offset
r_gen_code.uniform_offsets.resize(uniform_sizes.size());
for (int i = 0; i < uniform_sizes.size(); i++) {
if (i > 0)
r_gen_code.uniform_offsets[i] = uniform_sizes[i - 1];
else
r_gen_code.uniform_offsets[i] = 0;
}
/*
for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) {
if (SL::is_sampler_type(E->get().type)) {
continue;
}
}
*/
if (uniform_sizes.size()) {
r_gen_code.uniform_total_size = uniform_sizes[uniform_sizes.size() - 1];
} else {
r_gen_code.uniform_total_size = 0;
}
#endif
uint32_t index = p_default_actions.base_varying_index;
for (Map<StringName, SL::ShaderNode::Varying>::Element *E = pnode->varyings.front(); E; E = E->next()) {
String vcode;
String interp_mode = _interpstr(E->get().interpolation);
vcode += _prestr(E->get().precision);
vcode += _typestr(E->get().type);
vcode += " " + _mkid(E->key());
if (E->get().array_size > 0) {
vcode += "[";
vcode += itos(E->get().array_size);
vcode += "]";
}
vcode += ";\n";
r_gen_code.vertex_global += "layout(location=" + itos(index) + ") " + interp_mode + "out " + vcode;
r_gen_code.fragment_global += "layout(location=" + itos(index) + ") " + interp_mode + "in " + vcode;
r_gen_code.compute_global += "layout(location=" + itos(index) + ") " + interp_mode + "out " + vcode;
index++;
}
for (int i = 0; i < pnode->vconstants.size(); i++) {
const SL::ShaderNode::Constant &cnode = pnode->vconstants[i];
String gcode;
gcode += "const ";
gcode += _prestr(cnode.precision);
if (cnode.type == SL::TYPE_STRUCT) {
gcode += _mkid(cnode.type_str);
} else {
gcode += _typestr(cnode.type);
}
gcode += " " + _mkid(String(cnode.name));
if (cnode.array_size > 0) {
gcode += "[";
gcode += itos(cnode.array_size);
gcode += "]";
}
gcode += "=";
gcode += _dump_node_code(cnode.initializer, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
gcode += ";\n";
r_gen_code.vertex_global += gcode;
r_gen_code.fragment_global += gcode;
r_gen_code.compute_global += gcode;
}
Map<StringName, String> function_code;
//code for functions
for (int i = 0; i < pnode->functions.size(); i++) {
SL::FunctionNode *fnode = pnode->functions[i].function;
function = fnode;
current_func_name = fnode->name;
function_code[fnode->name] = _dump_node_code(fnode->body, p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
function = nullptr;
}
//place functions in actual code
Set<StringName> added_vtx;
Set<StringName> added_fragment; //share for light
Set<StringName> added_compute; //share for light
for (int i = 0; i < pnode->functions.size(); i++) {
SL::FunctionNode *fnode = pnode->functions[i].function;
function = fnode;
current_func_name = fnode->name;
if (fnode->name == vertex_name) {
_dump_function_deps(pnode, fnode->name, function_code, r_gen_code.vertex_global, added_vtx);
r_gen_code.vertex = function_code[vertex_name];
}
if (fnode->name == fragment_name) {
_dump_function_deps(pnode, fnode->name, function_code, r_gen_code.fragment_global, added_fragment);
r_gen_code.fragment = function_code[fragment_name];
}
if (fnode->name == light_name) {
_dump_function_deps(pnode, fnode->name, function_code, r_gen_code.fragment_global, added_fragment);
r_gen_code.light = function_code[light_name];
}
if (fnode->name == compute_name) {
_dump_function_deps(pnode, fnode->name, function_code, r_gen_code.compute_global, added_compute);
r_gen_code.compute = function_code[compute_name];
}
function = nullptr;
}
//code+=dump_node_code(pnode->body,p_level);
} break;
case SL::Node::TYPE_STRUCT: {
} break;
case SL::Node::TYPE_FUNCTION: {
} break;
case SL::Node::TYPE_BLOCK: {
SL::BlockNode *bnode = (SL::BlockNode *)p_node;
//variables
if (!bnode->single_statement) {
code += _mktab(p_level - 1) + "{\n";
}
for (int i = 0; i < bnode->statements.size(); i++) {
String scode = _dump_node_code(bnode->statements[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
if (bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW || bnode->single_statement) {
code += scode; //use directly
} else {
code += _mktab(p_level) + scode + ";\n";
}
}
if (!bnode->single_statement) {
code += _mktab(p_level - 1) + "}\n";
}
} break;
case SL::Node::TYPE_VARIABLE_DECLARATION: {
SL::VariableDeclarationNode *vdnode = (SL::VariableDeclarationNode *)p_node;
String declaration;
if (vdnode->is_const) {
declaration += "const ";
}
if (vdnode->datatype == SL::TYPE_STRUCT) {
declaration += _mkid(vdnode->struct_name);
} else {
declaration += _prestr(vdnode->precision) + _typestr(vdnode->datatype);
}
for (int i = 0; i < vdnode->declarations.size(); i++) {
if (i > 0) {
declaration += ",";
} else {
declaration += " ";
}
declaration += _mkid(vdnode->declarations[i].name);
if (vdnode->declarations[i].initializer) {
declaration += "=";
declaration += _dump_node_code(vdnode->declarations[i].initializer, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
}
}
code += declaration;
} break;
case SL::Node::TYPE_VARIABLE: {
SL::VariableNode *vnode = (SL::VariableNode *)p_node;
if (p_assigning && p_actions.write_flag_pointers.has(vnode->name)) {
*p_actions.write_flag_pointers[vnode->name] = true;
}
if (p_default_actions.usage_defines.has(vnode->name) && !used_name_defines.has(vnode->name)) {
String define = p_default_actions.usage_defines[vnode->name];
if (define.begins_with("@")) {
define = p_default_actions.usage_defines[define.substr(1, define.length())];
}
r_gen_code.defines.push_back(define);
used_name_defines.insert(vnode->name);
}
if (p_actions.usage_flag_pointers.has(vnode->name) && !used_flag_pointers.has(vnode->name)) {
*p_actions.usage_flag_pointers[vnode->name] = true;
used_flag_pointers.insert(vnode->name);
}
if (p_default_actions.renames.has(vnode->name)) {
code = p_default_actions.renames[vnode->name];
} else {
if (shader->uniforms.has(vnode->name)) {
//its a uniform!
const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[vnode->name];
if (u.texture_order >= 0) {
code = _mkid(vnode->name); //texture, use as is
} else {
//a scalar or vector
if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {
code = actions.base_uniform_string + _mkid(vnode->name); //texture, use as is
//global variable, this means the code points to an index to the global table
code = _get_global_variable_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type);
} else if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
//instance variable, index it as such
code = "(" + p_default_actions.instance_uniform_index_variable + "+" + itos(u.instance_index) + ")";
code = _get_global_variable_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type);
} else {
//regular uniform, index from UBO
code = actions.base_uniform_string + _mkid(vnode->name);
}
}
} else {
code = _mkid(vnode->name); //its something else (local var most likely) use as is
}
}
if (vnode->name == time_name) {
if (current_func_name == vertex_name) {
r_gen_code.uses_vertex_time = true;
}
if (current_func_name == fragment_name || current_func_name == light_name) {
r_gen_code.uses_fragment_time = true;
}
}
} break;
case SL::Node::TYPE_ARRAY_CONSTRUCT: {
SL::ArrayConstructNode *acnode = (SL::ArrayConstructNode *)p_node;
int sz = acnode->initializer.size();
if (acnode->datatype == SL::TYPE_STRUCT) {
code += _mkid(acnode->struct_name);
} else {
code += _typestr(acnode->datatype);
}
code += "[";
code += itos(acnode->initializer.size());
code += "]";
code += "(";
for (int i = 0; i < sz; i++) {
code += _dump_node_code(acnode->initializer[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
if (i != sz - 1) {
code += ", ";
}
}
code += ")";
} break;
case SL::Node::TYPE_ARRAY_DECLARATION: {
SL::ArrayDeclarationNode *adnode = (SL::ArrayDeclarationNode *)p_node;
String declaration;
if (adnode->is_const) {
declaration += "const ";
}
if (adnode->datatype == SL::TYPE_STRUCT) {
declaration += _mkid(adnode->struct_name);
} else {
declaration = _prestr(adnode->precision) + _typestr(adnode->datatype);
}
for (int i = 0; i < adnode->declarations.size(); i++) {
if (i > 0) {
declaration += ",";
} else {
declaration += " ";
}
declaration += _mkid(adnode->declarations[i].name);
declaration += "[";
declaration += itos(adnode->declarations[i].size);
declaration += "]";
int sz = adnode->declarations[i].initializer.size();
if (sz > 0) {
declaration += "=";
if (adnode->datatype == SL::TYPE_STRUCT) {
declaration += _mkid(adnode->struct_name);
} else {
declaration += _typestr(adnode->datatype);
}
declaration += "[";
declaration += itos(sz);
declaration += "]";
declaration += "(";
for (int j = 0; j < sz; j++) {
declaration += _dump_node_code(adnode->declarations[i].initializer[j], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
if (j != sz - 1) {
declaration += ", ";
}
}
declaration += ")";
}
}
code += declaration;
} break;
case SL::Node::TYPE_ARRAY: {
SL::ArrayNode *anode = (SL::ArrayNode *)p_node;
if (p_assigning && p_actions.write_flag_pointers.has(anode->name)) {
*p_actions.write_flag_pointers[anode->name] = true;
}
if (p_default_actions.usage_defines.has(anode->name) && !used_name_defines.has(anode->name)) {
String define = p_default_actions.usage_defines[anode->name];
if (define.begins_with("@")) {
define = p_default_actions.usage_defines[define.substr(1, define.length())];
}
r_gen_code.defines.push_back(define);
used_name_defines.insert(anode->name);
}
if (p_actions.usage_flag_pointers.has(anode->name) && !used_flag_pointers.has(anode->name)) {
*p_actions.usage_flag_pointers[anode->name] = true;
used_flag_pointers.insert(anode->name);
}
if (p_default_actions.renames.has(anode->name)) {
code = p_default_actions.renames[anode->name];
} else {
code = _mkid(anode->name);
}
if (anode->call_expression != nullptr) {
code += ".";
code += _dump_node_code(anode->call_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning, false);
}
if (anode->index_expression != nullptr) {
code += "[";
code += _dump_node_code(anode->index_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += "]";
}
if (anode->name == time_name) {
if (current_func_name == vertex_name) {
r_gen_code.uses_vertex_time = true;
}
if (current_func_name == fragment_name || current_func_name == light_name) {
r_gen_code.uses_fragment_time = true;
}
}
} break;
case SL::Node::TYPE_CONSTANT: {
SL::ConstantNode *cnode = (SL::ConstantNode *)p_node;
if (cnode->array_size == 0) {
return get_constant_text(cnode->datatype, cnode->values);
} else {
if (cnode->get_datatype() == SL::TYPE_STRUCT) {
code += _mkid(cnode->struct_name);
} else {
code += _typestr(cnode->datatype);
}
code += "[";
code += itos(cnode->array_size);
code += "]";
code += "(";
for (int i = 0; i < cnode->array_size; i++) {
if (i > 0) {
code += ",";
} else {
code += "";
}
code += _dump_node_code(cnode->array_declarations[0].initializer[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
}
code += ")";
}
} break;
case SL::Node::TYPE_OPERATOR: {
SL::OperatorNode *onode = (SL::OperatorNode *)p_node;
switch (onode->op) {
case SL::OP_ASSIGN:
case SL::OP_ASSIGN_ADD:
case SL::OP_ASSIGN_SUB:
case SL::OP_ASSIGN_MUL:
case SL::OP_ASSIGN_DIV:
case SL::OP_ASSIGN_SHIFT_LEFT:
case SL::OP_ASSIGN_SHIFT_RIGHT:
case SL::OP_ASSIGN_MOD:
case SL::OP_ASSIGN_BIT_AND:
case SL::OP_ASSIGN_BIT_OR:
case SL::OP_ASSIGN_BIT_XOR:
code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, true) + _opstr(onode->op) + _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
break;
case SL::OP_BIT_INVERT:
case SL::OP_NEGATE:
case SL::OP_NOT:
case SL::OP_DECREMENT:
case SL::OP_INCREMENT:
code = _opstr(onode->op) + _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
break;
case SL::OP_POST_DECREMENT:
case SL::OP_POST_INCREMENT:
code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + _opstr(onode->op);
break;
case SL::OP_CALL:
case SL::OP_STRUCT:
case SL::OP_CONSTRUCT: {
ERR_FAIL_COND_V(onode->arguments[0]->type != SL::Node::TYPE_VARIABLE, String());
SL::VariableNode *vnode = (SL::VariableNode *)onode->arguments[0];
bool is_texture_func = false;
if (onode->op == SL::OP_STRUCT) {
code += _mkid(vnode->name);
} else if (onode->op == SL::OP_CONSTRUCT) {
code += String(vnode->name);
} else {
if (internal_functions.has(vnode->name)) {
code += vnode->name;
is_texture_func = texture_functions.has(vnode->name);
} else if (p_default_actions.renames.has(vnode->name)) {
code += p_default_actions.renames[vnode->name];
} else {
code += _mkid(vnode->name);
}
}
code += "(";
for (int i = 1; i < onode->arguments.size(); i++) {
if (i > 1) {
code += ", ";
}
String node_code = _dump_node_code(onode->arguments[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
if (is_texture_func && i == 1 && onode->arguments[i]->type == SL::Node::TYPE_VARIABLE) {
//need to map from texture to sampler in order to sample
const SL::VariableNode *varnode = static_cast<const SL::VariableNode *>(onode->arguments[i]);
StringName texture_uniform = varnode->name;
String sampler_name;
if (actions.custom_samplers.has(texture_uniform)) {
sampler_name = actions.custom_samplers[texture_uniform];
} else {
if (shader->uniforms.has(texture_uniform)) {
sampler_name = _get_sampler_name(shader->uniforms[texture_uniform].filter, shader->uniforms[texture_uniform].repeat);
} else {
bool found = false;
for (int j = 0; j < function->arguments.size(); j++) {
if (function->arguments[j].name == texture_uniform) {
if (function->arguments[j].tex_builtin_check) {
ERR_CONTINUE(!actions.custom_samplers.has(function->arguments[j].tex_builtin));
sampler_name = actions.custom_samplers[function->arguments[j].tex_builtin];
found = true;
break;
}
if (function->arguments[j].tex_argument_check) {
sampler_name = _get_sampler_name(function->arguments[j].tex_argument_filter, function->arguments[j].tex_argument_repeat);
found = true;
break;
}
}
}
if (!found) {
//function was most likely unused, so use anything (compiler will remove it anyway)
sampler_name = _get_sampler_name(ShaderLanguage::FILTER_DEFAULT, ShaderLanguage::REPEAT_DEFAULT);
}
}
}
code += ShaderLanguage::get_datatype_name(onode->arguments[i]->get_datatype()) + "(" + node_code + ", " + sampler_name + ")";
} else {
code += node_code;
}
}
code += ")";
} break;
case SL::OP_INDEX: {
code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += "[";
code += _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += "]";
} break;
case SL::OP_SELECT_IF: {
code += "(";
code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += "?";
code += _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += ":";
code += _dump_node_code(onode->arguments[2], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += ")";
} break;
default: {
if (p_use_scope) {
code += "(";
}
code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + _opstr(onode->op) + _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
if (p_use_scope) {
code += ")";
}
break;
}
}
} break;
case SL::Node::TYPE_CONTROL_FLOW: {
SL::ControlFlowNode *cfnode = (SL::ControlFlowNode *)p_node;
if (cfnode->flow_op == SL::FLOW_OP_IF) {
code += _mktab(p_level) + "if (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
if (cfnode->blocks.size() == 2) {
code += _mktab(p_level) + "else\n";
code += _dump_node_code(cfnode->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
}
} else if (cfnode->flow_op == SL::FLOW_OP_SWITCH) {
code += _mktab(p_level) + "switch (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cfnode->flow_op == SL::FLOW_OP_CASE) {
code += _mktab(p_level) + "case " + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ":\n";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cfnode->flow_op == SL::FLOW_OP_DEFAULT) {
code += _mktab(p_level) + "default:\n";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cfnode->flow_op == SL::FLOW_OP_DO) {
code += _mktab(p_level) + "do";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
code += _mktab(p_level) + "while (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ");";
} else if (cfnode->flow_op == SL::FLOW_OP_WHILE) {
code += _mktab(p_level) + "while (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cfnode->flow_op == SL::FLOW_OP_FOR) {
String left = _dump_node_code(cfnode->blocks[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
String middle = _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
String right = _dump_node_code(cfnode->expressions[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += _mktab(p_level) + "for (" + left + ";" + middle + ";" + right + ")\n";
code += _dump_node_code(cfnode->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cfnode->flow_op == SL::FLOW_OP_RETURN) {
if (cfnode->expressions.size()) {
code = "return " + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ";";
} else {
code = "return;";
}
} else if (cfnode->flow_op == SL::FLOW_OP_DISCARD) {
if (p_actions.usage_flag_pointers.has("DISCARD") && !used_flag_pointers.has("DISCARD")) {
*p_actions.usage_flag_pointers["DISCARD"] = true;
used_flag_pointers.insert("DISCARD");
}
code = "discard;";
} else if (cfnode->flow_op == SL::FLOW_OP_CONTINUE) {
code = "continue;";
} else if (cfnode->flow_op == SL::FLOW_OP_BREAK) {
code = "break;";
}
} break;
case SL::Node::TYPE_MEMBER: {
SL::MemberNode *mnode = (SL::MemberNode *)p_node;
code = _dump_node_code(mnode->owner, p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + "." + mnode->name;
if (mnode->index_expression != nullptr) {
code += "[";
code += _dump_node_code(mnode->index_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += "]";
}
} break;
}
return code;
}
ShaderLanguage::DataType ShaderCompilerRD::_get_variable_type(const StringName &p_type) {
RS::GlobalVariableType gvt = ((RasterizerStorageRD *)(RasterizerStorage::base_singleton))->global_variable_get_type_internal(p_type);
return RS::global_variable_type_get_shader_datatype(gvt);
}
Error ShaderCompilerRD::compile(RS::ShaderMode p_mode, const String &p_code, IdentifierActions *p_actions, const String &p_path, GeneratedCode &r_gen_code) {
Error err = parser.compile(p_code, ShaderTypes::get_singleton()->get_functions(p_mode), ShaderTypes::get_singleton()->get_modes(p_mode), ShaderTypes::get_singleton()->get_types(), _get_variable_type);
if (err != OK) {
Vector<String> shader = p_code.split("\n");
for (int i = 0; i < shader.size(); i++) {
print_line(itos(i + 1) + " " + shader[i]);
}
_err_print_error(nullptr, p_path.utf8().get_data(), parser.get_error_line(), parser.get_error_text().utf8().get_data(), ERR_HANDLER_SHADER);
return err;
}
r_gen_code.defines.clear();
r_gen_code.vertex = String();
r_gen_code.vertex_global = String();
r_gen_code.fragment = String();
r_gen_code.fragment_global = String();
r_gen_code.compute = String();
r_gen_code.compute_global = String();
r_gen_code.light = String();
r_gen_code.uses_fragment_time = false;
r_gen_code.uses_vertex_time = false;
r_gen_code.uses_global_textures = false;
used_name_defines.clear();
used_rmode_defines.clear();
used_flag_pointers.clear();
shader = parser.get_shader();
function = nullptr;
_dump_node_code(shader, 1, r_gen_code, *p_actions, actions, false);
return OK;
}
void ShaderCompilerRD::initialize(DefaultIdentifierActions p_actions) {
actions = p_actions;
vertex_name = "vertex";
fragment_name = "fragment";
compute_name = "compute";
light_name = "light";
time_name = "TIME";
List<String> func_list;
ShaderLanguage::get_builtin_funcs(&func_list);
for (List<String>::Element *E = func_list.front(); E; E = E->next()) {
internal_functions.insert(E->get());
}
texture_functions.insert("texture");
texture_functions.insert("textureProj");
texture_functions.insert("textureLod");
texture_functions.insert("textureProjLod");
texture_functions.insert("textureGrad");
}
ShaderCompilerRD::ShaderCompilerRD() {
#if 0
/** SPATIAL SHADER **/
actions[RS::SHADER_SPATIAL].renames["WORLD_MATRIX"] = "world_transform";
actions[RS::SHADER_SPATIAL].renames["INV_CAMERA_MATRIX"] = "camera_inverse_matrix";
actions[RS::SHADER_SPATIAL].renames["CAMERA_MATRIX"] = "camera_matrix";
actions[RS::SHADER_SPATIAL].renames["PROJECTION_MATRIX"] = "projection_matrix";
actions[RS::SHADER_SPATIAL].renames["INV_PROJECTION_MATRIX"] = "inv_projection_matrix";
actions[RS::SHADER_SPATIAL].renames["MODELVIEW_MATRIX"] = "modelview";
actions[RS::SHADER_SPATIAL].renames["VERTEX"] = "vertex.xyz";
actions[RS::SHADER_SPATIAL].renames["NORMAL"] = "normal";
actions[RS::SHADER_SPATIAL].renames["TANGENT"] = "tangent";
actions[RS::SHADER_SPATIAL].renames["BINORMAL"] = "binormal";
actions[RS::SHADER_SPATIAL].renames["POSITION"] = "position";
actions[RS::SHADER_SPATIAL].renames["UV"] = "uv_interp";
actions[RS::SHADER_SPATIAL].renames["UV2"] = "uv2_interp";
actions[RS::SHADER_SPATIAL].renames["COLOR"] = "color_interp";
actions[RS::SHADER_SPATIAL].renames["POINT_SIZE"] = "gl_PointSize";
actions[RS::SHADER_SPATIAL].renames["INSTANCE_ID"] = "gl_InstanceID";
//builtins
actions[RS::SHADER_SPATIAL].renames["TIME"] = "time";
actions[RS::SHADER_SPATIAL].renames["VIEWPORT_SIZE"] = "viewport_size";
actions[RS::SHADER_SPATIAL].renames["FRAGCOORD"] = "gl_FragCoord";
actions[RS::SHADER_SPATIAL].renames["FRONT_FACING"] = "gl_FrontFacing";
actions[RS::SHADER_SPATIAL].renames["NORMALMAP"] = "normalmap";
actions[RS::SHADER_SPATIAL].renames["NORMALMAP_DEPTH"] = "normaldepth";
actions[RS::SHADER_SPATIAL].renames["ALBEDO"] = "albedo";
actions[RS::SHADER_SPATIAL].renames["ALPHA"] = "alpha";
actions[RS::SHADER_SPATIAL].renames["METALLIC"] = "metallic";
actions[RS::SHADER_SPATIAL].renames["SPECULAR"] = "specular";
actions[RS::SHADER_SPATIAL].renames["ROUGHNESS"] = "roughness";
actions[RS::SHADER_SPATIAL].renames["RIM"] = "rim";
actions[RS::SHADER_SPATIAL].renames["RIM_TINT"] = "rim_tint";
actions[RS::SHADER_SPATIAL].renames["CLEARCOAT"] = "clearcoat";
actions[RS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"] = "clearcoat_gloss";
actions[RS::SHADER_SPATIAL].renames["ANISOTROPY"] = "anisotropy";
actions[RS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"] = "anisotropy_flow";
actions[RS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength";
actions[RS::SHADER_SPATIAL].renames["TRANSMISSION"] = "transmission";
actions[RS::SHADER_SPATIAL].renames["AO"] = "ao";
actions[RS::SHADER_SPATIAL].renames["AO_LIGHT_AFFECT"] = "ao_light_affect";
actions[RS::SHADER_SPATIAL].renames["EMISSION"] = "emission";
actions[RS::SHADER_SPATIAL].renames["POINT_COORD"] = "gl_PointCoord";
actions[RS::SHADER_SPATIAL].renames["INSTANCE_CUSTOM"] = "instance_custom";
actions[RS::SHADER_SPATIAL].renames["SCREEN_UV"] = "screen_uv";
actions[RS::SHADER_SPATIAL].renames["SCREEN_TEXTURE"] = "screen_texture";
actions[RS::SHADER_SPATIAL].renames["DEPTH_TEXTURE"] = "depth_buffer";
actions[RS::SHADER_SPATIAL].renames["DEPTH"] = "gl_FragDepth";
actions[RS::SHADER_SPATIAL].renames["ALPHA_SCISSOR"] = "alpha_scissor";
actions[RS::SHADER_SPATIAL].renames["OUTPUT_IS_SRGB"] = "SHADER_IS_SRGB";
//for light
actions[RS::SHADER_SPATIAL].renames["VIEW"] = "view";
actions[RS::SHADER_SPATIAL].renames["LIGHT_COLOR"] = "light_color";
actions[RS::SHADER_SPATIAL].renames["LIGHT"] = "light";
actions[RS::SHADER_SPATIAL].renames["ATTENUATION"] = "attenuation";
actions[RS::SHADER_SPATIAL].renames["DIFFUSE_LIGHT"] = "diffuse_light";
actions[RS::SHADER_SPATIAL].renames["SPECULAR_LIGHT"] = "specular_light";
actions[RS::SHADER_SPATIAL].usage_defines["TANGENT"] = "#define ENABLE_TANGENT_INTERP\n";
actions[RS::SHADER_SPATIAL].usage_defines["BINORMAL"] = "@TANGENT";
actions[RS::SHADER_SPATIAL].usage_defines["RIM"] = "#define LIGHT_USE_RIM\n";
actions[RS::SHADER_SPATIAL].usage_defines["RIM_TINT"] = "@RIM";
actions[RS::SHADER_SPATIAL].usage_defines["CLEARCOAT"] = "#define LIGHT_USE_CLEARCOAT\n";
actions[RS::SHADER_SPATIAL].usage_defines["CLEARCOAT_GLOSS"] = "@CLEARCOAT";
actions[RS::SHADER_SPATIAL].usage_defines["ANISOTROPY"] = "#define LIGHT_USE_ANISOTROPY\n";
actions[RS::SHADER_SPATIAL].usage_defines["ANISOTROPY_FLOW"] = "@ANISOTROPY";
actions[RS::SHADER_SPATIAL].usage_defines["AO"] = "#define ENABLE_AO\n";
actions[RS::SHADER_SPATIAL].usage_defines["AO_LIGHT_AFFECT"] = "#define ENABLE_AO\n";
actions[RS::SHADER_SPATIAL].usage_defines["UV"] = "#define ENABLE_UV_INTERP\n";
actions[RS::SHADER_SPATIAL].usage_defines["UV2"] = "#define ENABLE_UV2_INTERP\n";
actions[RS::SHADER_SPATIAL].usage_defines["NORMALMAP"] = "#define ENABLE_NORMALMAP\n";
actions[RS::SHADER_SPATIAL].usage_defines["NORMALMAP_DEPTH"] = "@NORMALMAP";
actions[RS::SHADER_SPATIAL].usage_defines["COLOR"] = "#define ENABLE_COLOR_INTERP\n";
actions[RS::SHADER_SPATIAL].usage_defines["INSTANCE_CUSTOM"] = "#define ENABLE_INSTANCE_CUSTOM\n";
actions[RS::SHADER_SPATIAL].usage_defines["ALPHA_SCISSOR"] = "#define ALPHA_SCISSOR_USED\n";
actions[RS::SHADER_SPATIAL].usage_defines["POSITION"] = "#define OVERRIDE_POSITION\n";
actions[RS::SHADER_SPATIAL].usage_defines["SSS_STRENGTH"] = "#define ENABLE_SSS\n";
actions[RS::SHADER_SPATIAL].usage_defines["TRANSMISSION"] = "#define TRANSMISSION_USED\n";
actions[RS::SHADER_SPATIAL].usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n";
actions[RS::SHADER_SPATIAL].usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
actions[RS::SHADER_SPATIAL].usage_defines["DIFFUSE_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n";
actions[RS::SHADER_SPATIAL].usage_defines["SPECULAR_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["world_vertex_coords"] = "#define VERTEX_WORLD_COORDS_USED\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["ensure_correct_normals"] = "#define ENSURE_CORRECT_NORMALS\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["cull_front"] = "#define DO_SIDE_CHECK\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["cull_disabled"] = "#define DO_SIDE_CHECK\n";
bool force_lambert = GLOBAL_GET("rendering/quality/shading/force_lambert_over_burley");
if (!force_lambert) {
actions[RS::SHADER_SPATIAL].render_mode_defines["diffuse_burley"] = "#define DIFFUSE_BURLEY\n";
}
actions[RS::SHADER_SPATIAL].render_mode_defines["diffuse_oren_nayar"] = "#define DIFFUSE_OREN_NAYAR\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["diffuse_lambert_wrap"] = "#define DIFFUSE_LAMBERT_WRAP\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["diffuse_toon"] = "#define DIFFUSE_TOON\n";
bool force_blinn = GLOBAL_GET("rendering/quality/shading/force_blinn_over_ggx");
if (!force_blinn) {
actions[RS::SHADER_SPATIAL].render_mode_defines["specular_schlick_ggx"] = "#define SPECULAR_SCHLICK_GGX\n";
} else {
actions[RS::SHADER_SPATIAL].render_mode_defines["specular_schlick_ggx"] = "#define SPECULAR_BLINN\n";
}
actions[RS::SHADER_SPATIAL].render_mode_defines["specular_blinn"] = "#define SPECULAR_BLINN\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["specular_phong"] = "#define SPECULAR_PHONG\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["specular_toon"] = "#define SPECULAR_TOON\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["specular_disabled"] = "#define SPECULAR_DISABLED\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["shadows_disabled"] = "#define SHADOWS_DISABLED\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["ambient_light_disabled"] = "#define AMBIENT_LIGHT_DISABLED\n";
actions[RS::SHADER_SPATIAL].render_mode_defines["shadow_to_opacity"] = "#define USE_SHADOW_TO_OPACITY\n";
/* PARTICLES SHADER */
actions[RS::SHADER_PARTICLES].renames["COLOR"] = "out_color";
actions[RS::SHADER_PARTICLES].renames["VELOCITY"] = "out_velocity_active.xyz";
actions[RS::SHADER_PARTICLES].renames["MASS"] = "mass";
actions[RS::SHADER_PARTICLES].renames["ACTIVE"] = "shader_active";
actions[RS::SHADER_PARTICLES].renames["RESTART"] = "restart";
actions[RS::SHADER_PARTICLES].renames["CUSTOM"] = "out_custom";
actions[RS::SHADER_PARTICLES].renames["TRANSFORM"] = "xform";
actions[RS::SHADER_PARTICLES].renames["TIME"] = "time";
actions[RS::SHADER_PARTICLES].renames["LIFETIME"] = "lifetime";
actions[RS::SHADER_PARTICLES].renames["DELTA"] = "local_delta";
actions[RS::SHADER_PARTICLES].renames["NUMBER"] = "particle_number";
actions[RS::SHADER_PARTICLES].renames["INDEX"] = "index";
actions[RS::SHADER_PARTICLES].renames["GRAVITY"] = "current_gravity";
actions[RS::SHADER_PARTICLES].renames["EMISSION_TRANSFORM"] = "emission_transform";
actions[RS::SHADER_PARTICLES].renames["RANDOM_SEED"] = "random_seed";
actions[RS::SHADER_PARTICLES].render_mode_defines["disable_force"] = "#define DISABLE_FORCE\n";
actions[RS::SHADER_PARTICLES].render_mode_defines["disable_velocity"] = "#define DISABLE_VELOCITY\n";
actions[RS::SHADER_PARTICLES].render_mode_defines["keep_data"] = "#define ENABLE_KEEP_DATA\n";
#endif
}
|
// Copyright (c) 2011-2013 The VirtaCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "overviewpage.h"
#include "ui_overviewpage.h"
#include "virtacoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 64
#define NUM_ITEMS 3
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(): QAbstractItemDelegate(), unit(VirtaCoinUnits::VTA)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(value.canConvert<QBrush>())
{
QBrush brush = qvariant_cast<QBrush>(value);
foreground = brush.color();
}
painter->setPen(foreground);
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = VirtaCoinUnits::formatWithUnit(unit, amount, true);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
clientModel(0),
walletModel(0),
currentBalance(-1),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
txdelegate(new TxViewDelegate()),
filter(0)
{
ui->setupUi(this);
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
emit transactionClicked(filter->mapToSource(index));
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
int unit = walletModel->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
ui->labelBalance->setText(VirtaCoinUnits::formatWithUnit(unit, balance));
ui->labelUnconfirmed->setText(VirtaCoinUnits::formatWithUnit(unit, unconfirmedBalance));
ui->labelImmature->setText(VirtaCoinUnits::formatWithUnit(unit, immatureBalance));
ui->labelTotal->setText(VirtaCoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool showImmature = immatureBalance != 0;
ui->labelImmature->setVisible(showImmature);
ui->labelImmatureText->setVisible(showImmature);
}
void OverviewPage::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Show warning if this is a prerelease version
connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
updateAlerts(model->getStatusBarWarnings());
}
}
void OverviewPage::setWalletModel(WalletModel *model)
{
this->walletModel = model;
if(model && model->getOptionsModel())
{
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
// update the display unit, to not use the default ("VTA")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if(walletModel && walletModel->getOptionsModel())
{
if(currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
}
void OverviewPage::updateAlerts(const QString &warnings)
{
this->ui->labelAlerts->setVisible(!warnings.isEmpty());
this->ui->labelAlerts->setText(warnings);
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
|
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, George Kouros.
* 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 the the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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: George Kouros
*********************************************************************/
#include <tf/tf.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/Path.h>
#include "reeds_shepp_paths_ros/reeds_shepp_paths_ros.h"
#include <math.h>
class StartGoalUpdater
{
public:
StartGoalUpdater(
ros::NodeHandle* nh,
geometry_msgs::PoseStamped* start,
geometry_msgs::PoseStamped* goal)
: nh_(nh), start_(start), goal_(goal),
receivedStart_(false), receivedGoal_(false)
{
startSub_ = nh_->subscribe(
"/initialpose", 1, &StartGoalUpdater::startCallback, this);
goalSub_ = nh_->subscribe(
"/move_base_simple/goal", 1, &StartGoalUpdater::goalCallback, this);
}
void startCallback(const geometry_msgs::PoseWithCovarianceStamped& msg)
{
if (!receivedStart_)
receivedStart_ = true;
start_->header = msg.header;
start_->pose = msg.pose.pose;
}
void goalCallback(const geometry_msgs::PoseStamped& msg)
{
if (!receivedGoal_)
receivedGoal_ = true;
*goal_ = msg;
}
bool receivedStart() {return receivedStart_;}
bool receivedGoal() {return receivedGoal_;}
bool receivedStartAndGoal() {return (receivedStart_ && receivedGoal_);}
private:
ros::NodeHandle* nh_;
ros::Subscriber startSub_;
ros::Subscriber goalSub_;
geometry_msgs::PoseStamped* start_;
geometry_msgs::PoseStamped* goal_;
bool receivedStart_;
bool receivedGoal_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "reeds_shepp_paths_ros_demo");
ros::NodeHandle nh("~");
// create path publisher
ros::Publisher pathPub = nh.advertise<nav_msgs::Path>("path", 1);
ros::Publisher startPosePub = nh.advertise<geometry_msgs::PoseStamped>("start_pose", 1);
ros::Publisher goalPosePub = nh.advertise<geometry_msgs::PoseStamped>("goal_pose", 1);
geometry_msgs::PoseStamped start, goal;
start.header.frame_id = goal.header.frame_id = "map";
StartGoalUpdater sgu(&nh, &start, &goal);
// initialize ReedsSheppPathsROS
reeds_shepp::RSPathsROS RSPlanner("demo", NULL, NULL);
while (ros::ok())
{
if (sgu.receivedStart())
startPosePub.publish(start);
if (sgu.receivedGoal())
goalPosePub.publish(goal);
if (sgu.receivedStartAndGoal())
{
// plan path from start to goal pose
std::vector<geometry_msgs::PoseStamped> pathPoses;
RSPlanner.planPath(start, goal, pathPoses);
std_msgs::Header header =
(start.header.stamp > goal.header.stamp) ? start.header : goal.header;
// create path msg from path states
nav_msgs::Path path;
path.header = header;
path.poses = pathPoses;
// publish path
pathPub.publish(path);
}
else
{
ROS_INFO("Waiting for start and goal poses...");
}
ros::spinOnce();
ros::Duration(1.0).sleep();
}
return 0;
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/test/browsing_data_remover_test_util.h"
#include "base/bind.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/threading/thread_task_runner_handle.h"
namespace content {
BrowsingDataRemoverCompletionObserver::BrowsingDataRemoverCompletionObserver(
BrowsingDataRemover* remover)
: observer_(this),
origin_task_runner_(base::ThreadTaskRunnerHandle::Get()) {
observer_.Add(remover);
}
BrowsingDataRemoverCompletionObserver::
~BrowsingDataRemoverCompletionObserver() {}
void BrowsingDataRemoverCompletionObserver::BlockUntilCompletion() {
base::ThreadPoolInstance::Get()->FlushAsyncForTesting(base::BindOnce(
&BrowsingDataRemoverCompletionObserver::FlushForTestingComplete,
base::Unretained(this)));
run_loop_.Run();
}
void BrowsingDataRemoverCompletionObserver::OnBrowsingDataRemoverDone(
uint64_t failed_data_types) {
browsing_data_remover_done_ = true;
failed_data_types_ = failed_data_types;
observer_.RemoveAll();
QuitRunLoopWhenTasksComplete();
}
void BrowsingDataRemoverCompletionObserver::FlushForTestingComplete() {
if (origin_task_runner_->RunsTasksInCurrentSequence()) {
flush_for_testing_complete_ = true;
QuitRunLoopWhenTasksComplete();
return;
}
origin_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&BrowsingDataRemoverCompletionObserver::FlushForTestingComplete,
base::Unretained(this)));
}
void BrowsingDataRemoverCompletionObserver::QuitRunLoopWhenTasksComplete() {
if (!flush_for_testing_complete_ || !browsing_data_remover_done_)
return;
run_loop_.QuitWhenIdle();
}
BrowsingDataRemoverCompletionInhibitor::BrowsingDataRemoverCompletionInhibitor(
BrowsingDataRemover* remover)
: remover_(remover),
run_loop_(new base::RunLoop),
origin_task_runner_(base::ThreadTaskRunnerHandle::Get()) {
DCHECK(remover);
remover_->SetWouldCompleteCallbackForTesting(
base::BindRepeating(&BrowsingDataRemoverCompletionInhibitor::
OnBrowsingDataRemoverWouldComplete,
base::Unretained(this)));
}
BrowsingDataRemoverCompletionInhibitor::
~BrowsingDataRemoverCompletionInhibitor() {
Reset();
}
void BrowsingDataRemoverCompletionInhibitor::Reset() {
if (!remover_)
return;
remover_->SetWouldCompleteCallbackForTesting(
base::RepeatingCallback<void(base::OnceClosure)>());
remover_ = nullptr;
}
void BrowsingDataRemoverCompletionInhibitor::BlockUntilNearCompletion() {
base::ThreadPoolInstance::Get()->FlushAsyncForTesting(base::BindOnce(
&BrowsingDataRemoverCompletionInhibitor::FlushForTestingComplete,
base::Unretained(this)));
run_loop_->Run();
run_loop_ = std::make_unique<base::RunLoop>();
flush_for_testing_complete_ = false;
browsing_data_remover_would_complete_done_ = false;
}
void BrowsingDataRemoverCompletionInhibitor::ContinueToCompletion() {
DCHECK(!continue_to_completion_callback_.is_null());
std::move(continue_to_completion_callback_).Run();
}
void BrowsingDataRemoverCompletionInhibitor::OnBrowsingDataRemoverWouldComplete(
base::OnceClosure continue_to_completion) {
DCHECK(continue_to_completion_callback_.is_null());
continue_to_completion_callback_ = std::move(continue_to_completion);
browsing_data_remover_would_complete_done_ = true;
QuitRunLoopWhenTasksComplete();
}
void BrowsingDataRemoverCompletionInhibitor::FlushForTestingComplete() {
if (origin_task_runner_->RunsTasksInCurrentSequence()) {
flush_for_testing_complete_ = true;
QuitRunLoopWhenTasksComplete();
return;
}
origin_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&BrowsingDataRemoverCompletionInhibitor::FlushForTestingComplete,
base::Unretained(this)));
}
void BrowsingDataRemoverCompletionInhibitor::QuitRunLoopWhenTasksComplete() {
if (!flush_for_testing_complete_ ||
!browsing_data_remover_would_complete_done_) {
return;
}
run_loop_->QuitWhenIdle();
}
} // namespace content
|
#include <JLHE.h>
#include <JLHE/Core/EntryPoint.h>
#include <Platform/OpenGL/OpenGLShader.h>
#include <imgui/imgui.h>
#include "Sandbox2D.h"
// TEMPORARY
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class ExampleLayer : public JLHE::Layer {
public:
ExampleLayer()
: Layer("Example"), m_CameraController(1280.0f / 720.0f, true), m_TrianglePosition(0.0f) {
m_VertexArray = JLHE::VertexArray::Create();
float vertices[3 * 7] = {
-0.5f, -0.5f, 0.0f, 0.8f, 0.2f, 0.8f, 1.0f,
0.5f, -0.5f, 0.0f, 0.2f, 0.3f, 0.8f, 1.0f,
0.0f, 0.5f, 0.0f, 0.8f, 0.8f, 0.2f, 1.0f
};
JLHE::Ref<JLHE::VertexBuffer> vertexBuffer;
vertexBuffer = JLHE::VertexBuffer::Create(vertices, sizeof(vertices));
JLHE::BufferLayout layout = {
{ JLHE::ShaderDataType::Float3, "a_Position" },
{ JLHE::ShaderDataType::Float4, "a_Color" }
};
vertexBuffer->SetLayout(layout);
m_VertexArray->AddVertexBuffer(vertexBuffer);
uint32_t indices[3] = { 0, 1, 2 };
JLHE::Ref<JLHE::IndexBuffer> indexBuffer;
indexBuffer = JLHE::IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32_t));
m_VertexArray->SetIndexBuffer(indexBuffer);
std::string vertexSrc = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec4 a_Color;
uniform mat4 u_ViewProjectionMatrix;
uniform mat4 u_Transform;
out vec3 v_Position;
out vec4 v_Color;
void main() {
v_Position = a_Position;
v_Color = a_Color;
gl_Position = u_ViewProjectionMatrix * u_Transform * vec4(a_Position, 1.0);
}
)";
std::string fragmentSrc = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec3 v_Position;
in vec4 v_Color;
void main() {
color = vec4(v_Position * 0.5 + 0.5, 1.0);
color = v_Color;
}
)";
m_Shader = JLHE::Shader::Create("Triangle", vertexSrc, fragmentSrc);
//----------------------------------------------------------
m_SquareVA = JLHE::VertexArray::Create();
float squareVertices[4 * 5] = {
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f
};
JLHE::Ref<JLHE::VertexBuffer> squareVertexBuffer;
squareVertexBuffer = JLHE::VertexBuffer::Create(squareVertices, sizeof(squareVertices));
squareVertexBuffer->SetLayout({
{ JLHE::ShaderDataType::Float3, "a_Position" },
{ JLHE::ShaderDataType::Float2, "a_TexCoord" }
});
m_SquareVA->AddVertexBuffer(squareVertexBuffer);
uint32_t squareIndices[6] = { 0, 1, 2, 2, 3, 0 };
JLHE::Ref<JLHE::IndexBuffer> squareIndexBuffer;
squareIndexBuffer = JLHE::IndexBuffer::Create(squareIndices, sizeof(squareIndices) / sizeof(uint32_t));
m_SquareVA->SetIndexBuffer(squareIndexBuffer);
//m_TextureShader = JLHE::Shader::Create("Assets/Shaders/Texture.glsl");
auto textureShader = m_ShaderLibrary.Load("Assets/Shaders/Texture.glsl");
m_Texture = JLHE::Texture2D::Create("Assets/Textures/Checkerboard.png");
std::dynamic_pointer_cast<JLHE::OpenGLShader>(textureShader)->Bind();
std::dynamic_pointer_cast<JLHE::OpenGLShader>(textureShader)->UploadUniformInt("u_Texture", 0);
}
void OnUpdate(JLHE::Timestep timestep) override {
m_CameraController.OnUpdate(timestep);
JLHE::RenderCommand::SetClearColour({ m_ClearColour.r, m_ClearColour.g, m_ClearColour.b, 255 });
JLHE::RenderCommand::Clear();
auto textureShader = m_ShaderLibrary.Get("Texture");
JLHE::Renderer::BeginScene(m_CameraController.GetCamera()); {
m_Texture->Bind();
JLHE::Renderer::Submit(m_SquareVA, textureShader, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));
JLHE::Renderer::Submit(m_VertexArray, m_Shader, glm::translate(glm::mat4(1.0f), m_TrianglePosition) * glm::scale(glm::mat4(1.0f), glm::vec3(0.1f)));
JLHE::Renderer::EndScene();
}
}
virtual void OnImGuiRender() override {
ImGui::Begin("Settings");
ImGui::ColorEdit3("Clear Colour", glm::value_ptr(m_ClearColour));
ImGui::End();
}
virtual void OnEvent(JLHE::Event& e) override {
m_CameraController.OnEvent(e);
}
private:
JLHE::Ref<JLHE::VertexArray> m_VertexArray, m_SquareVA;
JLHE::Ref<JLHE::Shader> m_Shader;
JLHE::OrthographicCameraController m_CameraController;
JLHE::Ref<JLHE::Texture2D> m_Texture;
glm::vec3 m_CameraPosition;
glm::vec3 m_TrianglePosition;
float m_TriangleMoveSpeed = 0.5f;
JLHE::ShaderLibrary m_ShaderLibrary;
glm::vec3 m_ClearColour = { 30, 30, 30 };
};
class Sandbox : public JLHE::Application {
public:
Sandbox() {
//PushLayer(new ExampleLayer());
PushLayer(new Sandbox2D());
}
~Sandbox() {
}
};
JLHE::Application* JLHE::CreateApplication() {
return new Sandbox();
}
|
/**
* @cond doxygenLibsbmlInternal
*
* @file QualIdentifierConsistencyValidator.cpp
* @brief Checks an SBML model for structural consistency
* @author Sarah Keating
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2014 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution and
* also available online as http://sbml.org/software/libsbml/license.html
* ---------------------------------------------------------------------- -->*/
#ifndef doxygen_ignore
#include <sbml/packages/qual/validator/QualIdentifierConsistencyValidator.h>
/*
* Compile ConsistencyConstraints
*/
#include "constraints/QualIdentifierConsistencyConstraints.cpp"
LIBSBML_CPP_NAMESPACE_BEGIN
/*
* Initializes this Validator with a set of Constraints.
*/
void
QualIdentifierConsistencyValidator::init ()
{
#define AddingConstraintsToValidator 1
#include "constraints/QualIdentifierConsistencyConstraints.cpp"
}
LIBSBML_CPP_NAMESPACE_END
#endif
/** @endcond */
|
//===-- RegisterContextPOSIX_ppc64le.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <cerrno>
#include <cstdint>
#include <cstring>
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/RegisterValue.h"
#include "lldb/Utility/Scalar.h"
#include "llvm/Support/Compiler.h"
#include "RegisterContextPOSIX_ppc64le.h"
using namespace lldb_private;
using namespace lldb;
static const uint32_t g_gpr_regnums[] = {
gpr_r0_ppc64le, gpr_r1_ppc64le, gpr_r2_ppc64le, gpr_r3_ppc64le,
gpr_r4_ppc64le, gpr_r5_ppc64le, gpr_r6_ppc64le, gpr_r7_ppc64le,
gpr_r8_ppc64le, gpr_r9_ppc64le, gpr_r10_ppc64le, gpr_r11_ppc64le,
gpr_r12_ppc64le, gpr_r13_ppc64le, gpr_r14_ppc64le, gpr_r15_ppc64le,
gpr_r16_ppc64le, gpr_r17_ppc64le, gpr_r18_ppc64le, gpr_r19_ppc64le,
gpr_r20_ppc64le, gpr_r21_ppc64le, gpr_r22_ppc64le, gpr_r23_ppc64le,
gpr_r24_ppc64le, gpr_r25_ppc64le, gpr_r26_ppc64le, gpr_r27_ppc64le,
gpr_r28_ppc64le, gpr_r29_ppc64le, gpr_r30_ppc64le, gpr_r31_ppc64le,
gpr_pc_ppc64le, gpr_msr_ppc64le, gpr_origr3_ppc64le, gpr_ctr_ppc64le,
gpr_lr_ppc64le, gpr_xer_ppc64le, gpr_cr_ppc64le, gpr_softe_ppc64le,
gpr_trap_ppc64le,
};
static const uint32_t g_fpr_regnums[] = {
fpr_f0_ppc64le, fpr_f1_ppc64le, fpr_f2_ppc64le, fpr_f3_ppc64le,
fpr_f4_ppc64le, fpr_f5_ppc64le, fpr_f6_ppc64le, fpr_f7_ppc64le,
fpr_f8_ppc64le, fpr_f9_ppc64le, fpr_f10_ppc64le, fpr_f11_ppc64le,
fpr_f12_ppc64le, fpr_f13_ppc64le, fpr_f14_ppc64le, fpr_f15_ppc64le,
fpr_f16_ppc64le, fpr_f17_ppc64le, fpr_f18_ppc64le, fpr_f19_ppc64le,
fpr_f20_ppc64le, fpr_f21_ppc64le, fpr_f22_ppc64le, fpr_f23_ppc64le,
fpr_f24_ppc64le, fpr_f25_ppc64le, fpr_f26_ppc64le, fpr_f27_ppc64le,
fpr_f28_ppc64le, fpr_f29_ppc64le, fpr_f30_ppc64le, fpr_f31_ppc64le,
fpr_fpscr_ppc64le,
};
static const uint32_t g_vmx_regnums[] = {
vmx_vr0_ppc64le, vmx_vr1_ppc64le, vmx_vr2_ppc64le, vmx_vr3_ppc64le,
vmx_vr4_ppc64le, vmx_vr5_ppc64le, vmx_vr6_ppc64le, vmx_vr7_ppc64le,
vmx_vr8_ppc64le, vmx_vr9_ppc64le, vmx_vr10_ppc64le, vmx_vr11_ppc64le,
vmx_vr12_ppc64le, vmx_vr13_ppc64le, vmx_vr14_ppc64le, vmx_vr15_ppc64le,
vmx_vr16_ppc64le, vmx_vr17_ppc64le, vmx_vr18_ppc64le, vmx_vr19_ppc64le,
vmx_vr20_ppc64le, vmx_vr21_ppc64le, vmx_vr22_ppc64le, vmx_vr23_ppc64le,
vmx_vr24_ppc64le, vmx_vr25_ppc64le, vmx_vr26_ppc64le, vmx_vr27_ppc64le,
vmx_vr28_ppc64le, vmx_vr29_ppc64le, vmx_vr30_ppc64le, vmx_vr31_ppc64le,
vmx_vscr_ppc64le, vmx_vrsave_ppc64le,
};
static const uint32_t g_vsx_regnums[] = {
vsx_vs0_ppc64le, vsx_vs1_ppc64le, vsx_vs2_ppc64le, vsx_vs3_ppc64le,
vsx_vs4_ppc64le, vsx_vs5_ppc64le, vsx_vs6_ppc64le, vsx_vs7_ppc64le,
vsx_vs8_ppc64le, vsx_vs9_ppc64le, vsx_vs10_ppc64le, vsx_vs11_ppc64le,
vsx_vs12_ppc64le, vsx_vs13_ppc64le, vsx_vs14_ppc64le, vsx_vs15_ppc64le,
vsx_vs16_ppc64le, vsx_vs17_ppc64le, vsx_vs18_ppc64le, vsx_vs19_ppc64le,
vsx_vs20_ppc64le, vsx_vs21_ppc64le, vsx_vs22_ppc64le, vsx_vs23_ppc64le,
vsx_vs24_ppc64le, vsx_vs25_ppc64le, vsx_vs26_ppc64le, vsx_vs27_ppc64le,
vsx_vs28_ppc64le, vsx_vs29_ppc64le, vsx_vs30_ppc64le, vsx_vs31_ppc64le,
vsx_vs32_ppc64le, vsx_vs33_ppc64le, vsx_vs34_ppc64le, vsx_vs35_ppc64le,
vsx_vs36_ppc64le, vsx_vs37_ppc64le, vsx_vs38_ppc64le, vsx_vs39_ppc64le,
vsx_vs40_ppc64le, vsx_vs41_ppc64le, vsx_vs42_ppc64le, vsx_vs43_ppc64le,
vsx_vs44_ppc64le, vsx_vs45_ppc64le, vsx_vs46_ppc64le, vsx_vs47_ppc64le,
vsx_vs48_ppc64le, vsx_vs49_ppc64le, vsx_vs50_ppc64le, vsx_vs51_ppc64le,
vsx_vs52_ppc64le, vsx_vs53_ppc64le, vsx_vs54_ppc64le, vsx_vs55_ppc64le,
vsx_vs56_ppc64le, vsx_vs57_ppc64le, vsx_vs58_ppc64le, vsx_vs59_ppc64le,
vsx_vs60_ppc64le, vsx_vs61_ppc64le, vsx_vs62_ppc64le, vsx_vs63_ppc64le,
};
// Number of register sets provided by this context.
enum { k_num_register_sets = 4 };
static const RegisterSet g_reg_sets_ppc64le[k_num_register_sets] = {
{"General Purpose Registers", "gpr", k_num_gpr_registers_ppc64le,
g_gpr_regnums},
{"Floating Point Registers", "fpr", k_num_fpr_registers_ppc64le,
g_fpr_regnums},
{"Altivec/VMX Registers", "vmx", k_num_vmx_registers_ppc64le,
g_vmx_regnums},
{"VSX Registers", "vsx", k_num_vsx_registers_ppc64le, g_vsx_regnums},
};
bool RegisterContextPOSIX_ppc64le::IsGPR(unsigned reg) {
return (reg <= k_last_gpr_ppc64le); // GPR's come first.
}
bool RegisterContextPOSIX_ppc64le::IsFPR(unsigned reg) {
return (reg >= k_first_fpr_ppc64le) && (reg <= k_last_fpr_ppc64le);
}
bool RegisterContextPOSIX_ppc64le::IsVMX(unsigned reg) {
return (reg >= k_first_vmx_ppc64le) && (reg <= k_last_vmx_ppc64le);
}
bool RegisterContextPOSIX_ppc64le::IsVSX(unsigned reg) {
return (reg >= k_first_vsx_ppc64le) && (reg <= k_last_vsx_ppc64le);
}
RegisterContextPOSIX_ppc64le::RegisterContextPOSIX_ppc64le(
Thread &thread, uint32_t concrete_frame_idx,
RegisterInfoInterface *register_info)
: RegisterContext(thread, concrete_frame_idx) {
m_register_info_up.reset(register_info);
}
void RegisterContextPOSIX_ppc64le::InvalidateAllRegisters() {}
unsigned RegisterContextPOSIX_ppc64le::GetRegisterOffset(unsigned reg) {
assert(reg < k_num_registers_ppc64le && "Invalid register number.");
return GetRegisterInfo()[reg].byte_offset;
}
unsigned RegisterContextPOSIX_ppc64le::GetRegisterSize(unsigned reg) {
assert(reg < k_num_registers_ppc64le && "Invalid register number.");
return GetRegisterInfo()[reg].byte_size;
}
size_t RegisterContextPOSIX_ppc64le::GetRegisterCount() {
size_t num_registers = k_num_registers_ppc64le;
return num_registers;
}
size_t RegisterContextPOSIX_ppc64le::GetGPRSize() {
return m_register_info_up->GetGPRSize();
}
const RegisterInfo *RegisterContextPOSIX_ppc64le::GetRegisterInfo() {
// Commonly, this method is overridden and g_register_infos is copied and
// specialized. So, use GetRegisterInfo() rather than g_register_infos in
// this scope.
return m_register_info_up->GetRegisterInfo();
}
const RegisterInfo *
RegisterContextPOSIX_ppc64le::GetRegisterInfoAtIndex(size_t reg) {
if (reg < k_num_registers_ppc64le)
return &GetRegisterInfo()[reg];
else
return nullptr;
}
size_t RegisterContextPOSIX_ppc64le::GetRegisterSetCount() {
size_t sets = 0;
for (size_t set = 0; set < k_num_register_sets; ++set) {
if (IsRegisterSetAvailable(set))
++sets;
}
return sets;
}
const RegisterSet *RegisterContextPOSIX_ppc64le::GetRegisterSet(size_t set) {
if (IsRegisterSetAvailable(set))
return &g_reg_sets_ppc64le[set];
else
return nullptr;
}
const char *RegisterContextPOSIX_ppc64le::GetRegisterName(unsigned reg) {
assert(reg < k_num_registers_ppc64le && "Invalid register offset.");
return GetRegisterInfo()[reg].name;
}
bool RegisterContextPOSIX_ppc64le::IsRegisterSetAvailable(size_t set_index) {
size_t num_sets = k_num_register_sets;
return (set_index < num_sets);
}
|
#include "../include/robot_hmi/qrviz.hpp"
#include <QDebug>
#include <QException>
qrviz::qrviz(QVBoxLayout* layout)
{
//创建rviz panel
render_panel_=new rviz::RenderPanel();
//向layout添加
layout->addWidget(render_panel_);
//创建rviz控制对象
manager_=new rviz::VisualizationManager(render_panel_);
tool_manager_=manager_->getToolManager();
ROS_ASSERT(manager_!=NULL);
//初始化render_panel 实现放大缩小等操作
render_panel_->initialize(manager_->getSceneManager(),manager_);
manager_->setFixedFrame("map");
//初始化rviz控制对象
manager_->initialize();
manager_->startUpdate();
manager_->removeAllDisplays();
}
void qrviz::Display_Local_Map(QString map_topic,QString map_color,QString planner_topic,QColor planner_color,bool enable)
{
if(Local_Map_!=NULL||Local_Planner_!=NULL)
{
delete Local_Map_;
delete Local_Planner_;
Local_Map_=NULL;
Local_Planner_=NULL;
}
Local_Map_=manager_->createDisplay("rviz/Map","LocalMap",enable);
ROS_ASSERT(Local_Map_!=NULL);
Local_Planner_=manager_->createDisplay("rviz/Path","LocalPlanner",enable);
ROS_ASSERT(Local_Planner_!=NULL);
Local_Map_->subProp("Topic")->setValue(map_topic);
Local_Map_->subProp("Color Scheme")->setValue(map_color);
// Local_Planner_->subProp("Topic")->setValue(planner_topic);
// Local_Planner_->subProp("Color")->setValue(planner_color);
}
void qrviz::Display_Global_Map(QString map_topic,QString map_color,QString planner_topic,QColor planner_color,bool enable)
{
if(Global_Map_!=NULL||Global_Planner_!=NULL)
{
delete Global_Map_;
delete Global_Planner_;
Global_Map_=NULL;
Global_Planner_=NULL;
}
Global_Map_=manager_->createDisplay("rviz/Map","GlobalMap",enable);
ROS_ASSERT(Global_Map_!=NULL);
Global_Planner_=manager_->createDisplay("rviz/Path","GlobalPlanner",enable);
ROS_ASSERT(Global_Planner_!=NULL);
Global_Map_->subProp("Topic")->setValue(map_topic);
Global_Map_->subProp("Color Scheme")->setValue(map_color);
// Global_Planner_->subProp("Topic")->setValue(planner_topic);
// Global_Planner_->subProp("Color")->setValue(planner_color);
}
void qrviz::Set_Start_Pose()
{
rviz::Tool* current_tool_=tool_manager_->addTool("rviz/SetInitialPose");
//设置当前使用的工具
tool_manager_->setCurrentTool(current_tool_);
}
void qrviz::Set_Goal_Pose()
{
rviz::Tool* current_tool_=tool_manager_->addTool("rviz/SetGoal");
//获取属性容器
rviz::Property* pro=current_tool_->getPropertyContainer();
//设置发布导航目标点的topic
pro->subProp("Topic")->setValue("/move_base_simple/goal");
//设置当前使用的工具
tool_manager_->setCurrentTool(current_tool_);
}
void qrviz::Set_FixedFrame(QString Frame_name)
{
manager_->setFixedFrame(Frame_name);
qDebug()<<manager_->getFixedFrame();
}
void qrviz::Display_Grid(int Cell_Count,QColor color,bool enable)
{
if(Grid_!=NULL)
{
delete Grid_;
Grid_=NULL;
}
Grid_=manager_->createDisplay("rviz/Grid","myGrid",enable);
//设置cell Count
Grid_->subProp("Plane Cell Count")->setValue(Cell_Count);
//设置颜色
Grid_->subProp("Color")->setValue(color);
ROS_ASSERT(Grid_!=NULL);
}
void qrviz::Display_TF(bool enable)
{
if(TF_!=NULL)
{
delete TF_;
TF_=NULL;
}
TF_=manager_->createDisplay("rviz/TF","myTF",enable);
ROS_ASSERT(TF_!=NULL);
}
void qrviz::Display_LaserScan(QString laser_topic,bool enable)
{
if(LaserScan_!=NULL)
{
delete LaserScan_;
LaserScan_=NULL;
}
LaserScan_=manager_->createDisplay("rviz/LaserScan","myLaser",enable);
LaserScan_->subProp("Topic")->setValue(laser_topic);
ROS_ASSERT(LaserScan_!=NULL);
}
void qrviz::Display_RobotModel(bool enable)
{
if(RobotModel_!=NULL)
{
delete RobotModel_;
RobotModel_=NULL;
}
RobotModel_=manager_->createDisplay("rviz/RobotModel","myRobotModel",enable);
ROS_ASSERT(RobotModel_!=NULL);
}
void qrviz::Display_Map(QString topic,QString color_scheme,bool enable)
{
if(Map_!=NULL)
{
delete Map_;
Map_=NULL;
}
Map_=manager_->createDisplay("rviz/Map","myMap",enable);
ROS_ASSERT(Map_!=NULL);
Map_->subProp("Topic")->setValue(topic);
Map_->subProp("Color Scheme")->setValue(color_scheme);
}
void qrviz::Display_Path(QString topic,QColor color,bool enable)
{
if(Path_!=NULL)
{
delete Path_;
Path_=NULL;
}
Path_=manager_->createDisplay("rviz/Path","myPath",enable);
ROS_ASSERT(Path_!=NULL);
Path_->subProp("Topic")->setValue(topic);
Path_->subProp("Color")->setValue(color);
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/macie2/model/TagResourceResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
TagResourceResult::TagResourceResult()
{
}
TagResourceResult::TagResourceResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
TagResourceResult& TagResourceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
AWS_UNREFERENCED_PARAM(result);
return *this;
}
|
#include <mm/pmm.hpp>
#include <debug.hpp>
namespace pmm {
class mem_chunk {
public:
mem_chunk(size_t base, size_t page_cnt);
mem_chunk() = default;
mem_chunk *append_chunk(mem_chunk &&chunk);
size_t alloc(size_t cnt, size_t align);
void free(size_t base, size_t cnt);
size_t base;
size_t page_cnt;
mem_chunk *next;
mem_chunk *last;
static size_t buffer;
static void *chunk_alloc(size_t cnt);
private:
size_t bitmap_size;
size_t bitmap_cnt;
size_t last_free;
uint8_t *bitmap;
};
static mem_chunk *root = NULL;
static size_t pmm_lock = 0;
size_t mem_chunk::buffer = 0;
void init(stivale *stivale) {
stivale_mmap *mmap = reinterpret_cast<stivale_mmap*>(stivale->mmap_addr + vmm::high_vma);
auto max_size = [&]() {
size_t buffer_size = 0;
for(size_t i = 0; i < stivale->mmap_cnt; i++) {
if(mmap[i].type == 1)
buffer_size += sizeof(mem_chunk) + (mmap[i].len / vmm::page_size / 8);
total_mem += mmap[i].len;
}
return buffer_size;
}();
for(size_t i = 0; i < stivale->mmap_cnt; i++) {
print("[{x}] -> [{x}] length {x}\n", mmap[i].addr, mmap[i].addr + mmap[i].len, mmap[i].len);
}
print("Total memory: {x}\n", total_mem);
size_t i;
for(i = 0; i < stivale->mmap_cnt; i++) {
if(mmap[i].type == 1 && mmap[i].len >= max_size) {
mem_chunk::buffer = mmap[i].addr + vmm::high_vma;
mmap[i].addr += max_size;
mmap[i].len -= max_size;
break;
}
}
for(; i < stivale->mmap_cnt; i++) {
if(mmap[i].type == 1 && mmap[i].len) {
size_t save = mmap[i].addr;
mmap[i].addr = align_up(mmap[i].addr, vmm::page_size);
mmap[i].len -= mmap[i].addr - save;
if(root) {
root->append_chunk(mem_chunk(mmap[i].addr, mmap[i].len / vmm::page_size));
} else {
root = (mem_chunk*)mem_chunk::chunk_alloc(sizeof(mem_chunk));
*root = mem_chunk(mmap[i].addr, mmap[i].len / vmm::page_size);
}
}
}
}
mem_chunk *mem_chunk::append_chunk(mem_chunk &&chunk) {
mem_chunk *node = this;
while(node->next != NULL)
node = node->next;
node->next = reinterpret_cast<mem_chunk*>(buffer);
buffer += sizeof(mem_chunk);
*node->next = chunk;
return node->next;
}
mem_chunk::mem_chunk(size_t base, size_t page_cnt) : base(base), page_cnt(page_cnt) {
bitmap_size = div_roundup(page_cnt, 8);
bitmap = (uint8_t*)chunk_alloc(bitmap_size);
memset8(bitmap, 0, bitmap_size);
}
size_t mem_chunk::alloc(size_t cnt, size_t align) {
spin_lock(&pmm_lock);
size_t alloc_base = align_up(base + (last_free * vmm::page_size), align * vmm::page_size);
size_t bit_base = (alloc_base - base) / vmm::page_size;
auto find_next_free = [&, this](size_t current_index) -> void {
for(size_t i = current_index; i < page_cnt; i++) {
if(!bm_test(bitmap, i)) {
last_free = i;
return;
}
}
};
for(size_t i = bit_base; i < page_cnt; i += align) {
for(size_t j = i, count = 0; j < i + cnt; j++) {
if(bm_test(bitmap, j)) {
alloc_base += align * vmm::page_size;
break;
}
if(++count == cnt) {
for(size_t z = 0; z < count; z++)
bm_set(bitmap, i + z);
spin_release(&pmm_lock);
total_used_mem += cnt * vmm::page_size;
find_next_free(j);
return alloc_base;
}
}
}
spin_release(&pmm_lock);
return -1;
}
void mem_chunk::free(size_t base, size_t cnt) {
spin_lock(&pmm_lock);
for(size_t i = div_roundup(base, vmm::page_size); i < div_roundup(base, vmm::page_size) + cnt; i++) {
total_used_mem -= vmm::page_size;
bm_clear(bitmap, i);
}
spin_release(&pmm_lock);
}
void *mem_chunk::chunk_alloc(size_t cnt) {
void *ret = reinterpret_cast<void*>(buffer);
buffer += cnt;
return ret;
}
size_t alloc(size_t cnt, size_t align) {
mem_chunk *chunk = root;
do {
size_t alloc = chunk->alloc(cnt, align);
if(alloc == -1ull)
chunk = chunk->next;
else
return alloc;
} while(chunk != NULL);
print("PMM: out of memory\n");
return -1;
}
size_t calloc(size_t cnt, size_t align) {
size_t allocation = alloc(cnt, align);
memset64((uint64_t*)(allocation + vmm::high_vma), 0, (cnt * vmm::page_size) / 8);
return allocation;
}
void free(size_t base, size_t cnt) {
mem_chunk *chunk = root;
do {
if(base >= chunk->base && (base + cnt * vmm::page_size) <= (chunk->base + chunk->page_cnt * vmm::page_size)) {
return chunk->free(base - chunk->base, cnt);
}
chunk = chunk->next;
} while(chunk != NULL);
}
}
|
// C:\diabpsx\PSXSRC\MAIN.CPP
#include "types.h"
// address: 0x8007BA14
// line start: 133
// line end: 220
void AppMain() {
{
// register: 16
register int option_file;
{
{
// register: 16
register int option_file;
}
}
}
}
// address: 0x8007A2B8
// line start: 129
// line end: 200
void AppMain_addr_8007A2B8() {
}
// address: 0x80082F98
// line start: 354
// line end: 429
void GameTask__FP4TASK(struct TASK *T) {
{
{
{
}
}
}
}
// address: 0x8007A38C
// line start: 217
// line end: 241
void GameTask__FP4TASK_addr_8007A38C(struct TASK *T) {
}
// address: 0x8007A424
// line start: 254
// line end: 269
void MAIN_MainLoop__Fv() {
}
// address: 0x8007A360
// line start: 208
// line end: 209
void MAIN_RestartGameTask__Fv() {
}
// address: 0x8007A280
// line start: 110
// line end: 119
void Remove96__Fv() {
}
|
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a YardSaleCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
|
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <memory>
#include "ngraph/node.hpp"
#include "ngraph/op/op.hpp"
#include "ngraph/runtime/cpu/cpu_backend_visibility.h"
#include "ngraph/util.hpp"
namespace ngraph
{
namespace op
{
class BatchNormTrainingRelu : public Op
{
public:
static constexpr NodeTypeInfo type_info{"BatchNormTrainingRelu", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
CPU_BACKEND_API BatchNormTrainingRelu(double eps,
const Output<Node>& gamma,
const Output<Node>& beta,
const Output<Node>& input);
double get_eps_value() const { return m_epsilon; }
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
protected:
enum
{
GAMMA,
BETA,
INPUT,
MEAN,
VARIANCE,
DELTA
};
private:
double m_epsilon;
};
class BatchNormInferenceRelu : public Op
{
public:
static constexpr NodeTypeInfo type_info{"BatchNormInferenceRelu", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
BatchNormInferenceRelu(double eps,
const Output<ngraph::Node>& gamma,
const Output<ngraph::Node>& beta,
const Output<ngraph::Node>& input,
const Output<ngraph::Node>& mean,
const Output<ngraph::Node>& variance);
double get_eps_value() const { return m_epsilon; }
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
protected:
enum
{
GAMMA,
BETA,
INPUT,
MEAN,
VARIANCE,
DELTA
};
private:
double m_epsilon;
};
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: otherCoordinate.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME
// .SECTION Description
// this program tests vtkCoordinate
#include "vtkCamera.h"
#include "vtkCoordinate.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include <sstream>
#include "vtkDebugLeaks.h"
void ToAll(ostream& strm, vtkCoordinate* c1, vtkViewport* ren1, double* from)
{
double* value;
int* ivalue;
const char* whichCoord = c1->GetCoordinateSystemAsString();
c1->SetValue(from);
strm << endl << "========" << endl;
strm << *c1;
value = c1->GetComputedWorldValue(ren1);
strm << whichCoord << "(" << from[0] << ", " << from[1] << ", " << from[2] << ") -> World("
<< value[0] << ", " << value[1] << ", " << value[2] << ")" << endl;
ivalue = c1->GetComputedDisplayValue(ren1);
strm << whichCoord << "(" << from[0] << ", " << from[1] << ", " << from[2] << ") -> Display("
<< ivalue[0] << ", " << ivalue[1] << ")" << endl;
ivalue = c1->GetComputedLocalDisplayValue(ren1);
strm << whichCoord << "(" << from[0] << ", " << from[1] << ", " << from[2] << ") -> LocalDisplay("
<< ivalue[0] << ", " << ivalue[1] << ")" << endl;
ivalue = c1->GetComputedViewportValue(ren1);
strm << whichCoord << "(" << from[0] << ", " << from[1] << ", " << from[2] << ") -> Viewport("
<< ivalue[0] << ", " << ivalue[1] << ")" << endl;
}
int Test(ostream& strm)
{
// actual test
strm << "Testing vtkCoordinate" << endl;
vtkCoordinate* c1 = vtkCoordinate::New();
vtkCoordinate* c2 = vtkCoordinate::New();
vtkRenderWindow* renWin = vtkRenderWindow::New();
vtkRenderer* ren1 = vtkRenderer::New();
vtkCamera* camera = vtkCamera::New();
double from[3];
ren1->SetActiveCamera(camera);
renWin->AddRenderer(ren1);
renWin->SetSize(100, 100);
strm << "Origin: (" << ren1->GetOrigin()[0] << ", " << ren1->GetOrigin()[1] << ")" << endl;
strm << "Center: (" << ren1->GetCenter()[0] << ", " << ren1->GetOrigin()[1] << ")" << endl;
strm << endl << "********** A NULL Viewport **********" << endl;
c1->SetCoordinateSystemToWorld();
from[0] = 0.0;
from[1] = 0.0;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToDisplay();
from[0] = 50;
from[1] = 50;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToNormalizedDisplay();
from[0] = .5;
from[1] = .5;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToViewport();
from[0] = 50;
from[1] = 50;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToNormalizedViewport();
from[0] = .5;
from[1] = .5;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToView();
from[0] = 0.0;
from[1] = 0.0;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
strm << endl << "********** A specified Viewport **********" << endl;
c1->SetViewport(ren1);
c1->SetCoordinateSystemToWorld();
from[0] = 0.0;
from[1] = 0.0;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToDisplay();
from[0] = 50;
from[1] = 50;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToNormalizedDisplay();
from[0] = .5;
from[1] = .5;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToViewport();
from[0] = 50;
from[1] = 50;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToNormalizedViewport();
from[0] = .5;
from[1] = .5;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToView();
from[0] = 0.0;
from[1] = 0.0;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
strm << endl << "********** With a Reference Coordinate **********" << endl;
c2->SetCoordinateSystemToNormalizedDisplay();
c2->SetCoordinateSystemToWorld();
c2->SetValue(0.0, 0.0, 0.0);
c1->SetReferenceCoordinate(c2);
strm << *c2;
c1->SetCoordinateSystemToWorld();
from[0] = 0.0;
from[1] = 0.0;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToDisplay();
from[0] = 50;
from[1] = 50;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToNormalizedDisplay();
from[0] = .5;
from[1] = .5;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToViewport();
from[0] = 50;
from[1] = 50;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToNormalizedViewport();
from[0] = .5;
from[1] = .5;
from[2] = 0;
ToAll(strm, c1, ren1, from);
c1->SetCoordinateSystemToView();
from[0] = 0.0;
from[1] = 0.0;
from[2] = 0.0;
ToAll(strm, c1, ren1, from);
c1->Delete();
c2->Delete();
renWin->Delete();
ren1->Delete();
camera->Delete();
strm << "Testing completed" << endl;
return 0;
}
int otherCoordinate(int, char*[])
{
std::ostringstream vtkmsg_with_warning_C4701;
return Test(vtkmsg_with_warning_C4701);
}
|
// Copyright (c) 2017-2021 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include "BlkRawTest.h"
#include <2out/NamedTest.h>
#include <goost/kuznyechik/BlkRaw.h>
#include "TestBlockEqual.h"
using namespace std;
using namespace oout;
using namespace goost::kuznyechik;
using namespace kuznyechik;
BlkRawTest::BlkRawTest()
: tests(
make_unique<NamedTest>(
__func__,
make_shared<const NamedTest>(
"ByteOrder",
make_shared<TestBlockEqual>(
make_unique<BlkRaw>(1),
"00000000000000000000000000000001"
)
)
)
)
{
}
unique_ptr<const Result> BlkRawTest::result() const
{
return tests->result();
}
|
// Boost.Signals library
//
// Copyright (C) 2001-2002 Doug Gregor (gregod@cs.rpi.edu)
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modified code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modified is included with the copyright notice.
//
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// For more information, see http://www.boost.org
#define BOOST_INCLUDE_MAIN
#include <boost/test/test_tools.hpp>
#include <boost/signal.hpp>
#include <boost/bind.hpp>
typedef boost::signal1<int, int> sig_type;
class with_constant : public boost::signals::trackable {
public:
with_constant(int c) : constant(c) {}
int add(int i) { return i + constant; }
private:
int constant;
};
void do_delayed_connect(with_constant* wc,
sig_type& sig,
sig_type::slot_type slot)
{
// Should invalidate the slot, so that we cannot connect to it
delete wc;
boost::signals::connection c = sig.connect(slot);
BOOST_TEST(!c.connected());
}
int test_main(int, char*[])
{
sig_type s1;
with_constant* wc1 = new with_constant(7);
do_delayed_connect(wc1, s1, boost::bind(&with_constant::add, wc1, _1));
return 0;
}
|
/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(ossrs)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_LIB_RTMP_HPP
#define SRS_LIB_RTMP_HPP
/*
#include <srs_librtmp.h>
*/
/**
* srs-librtmp is a librtmp like library,
* used to play/publish rtmp stream from/to rtmp server.
* socket: use sync and block socket to connect/recv/send data with server.
* depends: no need other libraries; depends on ssl if use srs_complex_handshake.
* thread-safe: no
*/
/*************************************************************
**************************************************************
* Windows SRS-LIBRTMP pre-declare
**************************************************************
*************************************************************/
// for srs-librtmp, @see https://github.com/ossrs/srs/issues/213
#ifdef _WIN32
// include windows first.
#include <windows.h>
// the type used by this header for windows.
typedef unsigned long long u_int64_t;
typedef long long int64_t;
typedef unsigned int u_int32_t;
typedef u_int32_t uint32_t;
typedef int int32_t;
typedef unsigned char u_int8_t;
typedef char int8_t;
typedef unsigned short u_int16_t;
typedef short int16_t;
typedef int64_t ssize_t;
struct iovec {
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */
};
#endif
#include <sys/types.h>
#ifdef __cplusplus
extern "C"{
#endif
// typedefs
typedef int srs_bool;
/*************************************************************
**************************************************************
* srs-librtmp version
**************************************************************
*************************************************************/
extern int srs_version_major();
extern int srs_version_minor();
extern int srs_version_revision();
/*************************************************************
**************************************************************
* RTMP protocol context
**************************************************************
*************************************************************/
// the RTMP handler.
typedef void* srs_rtmp_t;
typedef void* srs_amf0_t;
/**
* create/destroy a rtmp protocol stack.
* @url rtmp url, for example:
* rtmp://localhost/live/livestream
* @remark default timeout to 30s if not set by srs_rtmp_set_timeout.
*
* @return a rtmp handler, or NULL if error occured.
*/
extern srs_rtmp_t srs_rtmp_create(const char* url);
/**
* create rtmp with url, used for connection specified application.
* @param url the tcUrl, for exmple:
* rtmp://localhost/live
* @remark this is used to create application connection-oriented,
* for example, the bandwidth client used this, no stream specified.
* @remark default timeout to 30s if not set by srs_rtmp_set_timeout.
*
* @return a rtmp handler, or NULL if error occured.
*/
extern srs_rtmp_t srs_rtmp_create2(const char* url);
/**
* set socket timeout
* @param recv_timeout_ms the timeout for receiving messages in ms.
* @param send_timeout_ms the timeout for sending message in ms.
* @remark user can set timeout once srs_rtmp_create/srs_rtmp_create2,
* or before srs_rtmp_handshake or srs_rtmp_dns_resolve to connect to server.
* @remark default timeout to 30s if not set by srs_rtmp_set_timeout.
*
* @return 0, success; otherswise, failed.
*/
extern int srs_rtmp_set_timeout(srs_rtmp_t rtmp, int recv_timeout_ms, int send_timeout_ms);
/**
* close and destroy the rtmp stack.
* @remark, user should never use the rtmp again.
*/
extern void srs_rtmp_destroy(srs_rtmp_t rtmp);
/*************************************************************
**************************************************************
* RTMP protocol stack
**************************************************************
*************************************************************/
/**
* connect and handshake with server
* category: publish/play
* previous: rtmp-create
* next: connect-app
*
* @return 0, success; otherswise, failed.
*/
/**
* simple handshake specifies in rtmp 1.0,
* not depends on ssl.
*/
/**
* srs_rtmp_handshake equals to invoke:
* srs_rtmp_dns_resolve()
* srs_rtmp_connect_server()
* srs_rtmp_do_simple_handshake()
* user can use these functions if needed.
*/
extern int srs_rtmp_handshake(srs_rtmp_t rtmp);
// parse uri, create socket, resolve host
extern int srs_rtmp_dns_resolve(srs_rtmp_t rtmp);
// connect socket to server
extern int srs_rtmp_connect_server(srs_rtmp_t rtmp);
// do simple handshake over socket.
extern int srs_rtmp_do_simple_handshake(srs_rtmp_t rtmp);
// do complex handshake over socket.
extern int srs_rtmp_do_complex_handshake(srs_rtmp_t rtmp);
/**
* set the args of connect packet for rtmp.
* @param args, the extra amf0 object args.
* @remark, all params can be NULL to ignore.
* @remark, user should never free the args for we directly use it.
*/
extern int srs_rtmp_set_connect_args(srs_rtmp_t rtmp,
const char* tcUrl, const char* swfUrl, const char* pageUrl, srs_amf0_t args
);
/**
* connect to rtmp vhost/app
* category: publish/play
* previous: handshake
* next: publish or play
*
* @return 0, success; otherswise, failed.
*/
extern int srs_rtmp_connect_app(srs_rtmp_t rtmp);
/**
* connect to server, get the debug srs info.
*
* SRS debug info:
* @param srs_server_ip, 128bytes, debug info, server ip client connected at.
* @param srs_server, 128bytes, server info.
* @param srs_primary, 128bytes, primary authors.
* @param srs_authors, 128bytes, authors.
* @param srs_version, 32bytes, server version.
* @param srs_id, int, debug info, client id in server log.
* @param srs_pid, int, debug info, server pid in log.
*
* @return 0, success; otherswise, failed.
*/
extern int srs_rtmp_connect_app2(srs_rtmp_t rtmp,
char srs_server_ip[128], char srs_server[128],
char srs_primary[128], char srs_authors[128],
char srs_version[32], int* srs_id, int* srs_pid
);
/**
* play a live/vod stream.
* category: play
* previous: connect-app
* next: destroy
* @return 0, success; otherwise, failed.
*/
extern int srs_rtmp_play_stream(srs_rtmp_t rtmp);
/**
* publish a live stream.
* category: publish
* previous: connect-app
* next: destroy
* @return 0, success; otherwise, failed.
*/
extern int srs_rtmp_publish_stream(srs_rtmp_t rtmp);
/**
* do bandwidth check with srs server.
*
* bandwidth info:
* @param start_time, output the start time, in ms.
* @param end_time, output the end time, in ms.
* @param play_kbps, output the play/download kbps.
* @param publish_kbps, output the publish/upload kbps.
* @param play_bytes, output the play/download bytes.
* @param publish_bytes, output the publish/upload bytes.
* @param play_duration, output the play/download test duration, in ms.
* @param publish_duration, output the publish/upload test duration, in ms.
*
* @return 0, success; otherswise, failed.
*/
extern int srs_rtmp_bandwidth_check(srs_rtmp_t rtmp,
int64_t* start_time, int64_t* end_time,
int* play_kbps, int* publish_kbps,
int* play_bytes, int* publish_bytes,
int* play_duration, int* publish_duration
);
/**
* E.4.1 FLV Tag, page 75
*/
// 8 = audio
#define SRS_RTMP_TYPE_AUDIO 8
// 9 = video
#define SRS_RTMP_TYPE_VIDEO 9
// 18 = script data
#define SRS_RTMP_TYPE_SCRIPT 18
/**
* read a audio/video/script-data packet from rtmp stream.
* @param type, output the packet type, macros:
* SRS_RTMP_TYPE_AUDIO, FlvTagAudio
* SRS_RTMP_TYPE_VIDEO, FlvTagVideo
* SRS_RTMP_TYPE_SCRIPT, FlvTagScript
* otherswise, invalid type.
* @param timestamp, in ms, overflow in 50days
* @param data, the packet data, according to type:
* FlvTagAudio, @see "E.4.2.1 AUDIODATA"
* FlvTagVideo, @see "E.4.3.1 VIDEODATA"
* FlvTagScript, @see "E.4.4.1 SCRIPTDATA"
* @param size, size of packet.
* @return the error code. 0 for success; otherwise, error.
*
* @remark: for read, user must free the data.
* @remark: for write, user should never free the data, even if error.
* @example /trunk/research/librtmp/srs_play.c
* @example /trunk/research/librtmp/srs_publish.c
*
* @return 0, success; otherswise, failed.
*/
extern int srs_rtmp_read_packet(srs_rtmp_t rtmp,
char* type, u_int32_t* timestamp, char** data, int* size
);
extern int srs_rtmp_write_packet(srs_rtmp_t rtmp,
char type, u_int32_t timestamp, char* data, int size
);
/**
* whether type is script data and the data is onMetaData.
*/
extern srs_bool srs_rtmp_is_onMetaData(char type, char* data, int size);
/*************************************************************
**************************************************************
* audio raw codec
**************************************************************
*************************************************************/
/**
* write an audio raw frame to srs.
* not similar to h.264 video, the audio never aggregated, always
* encoded one frame by one, so this api is used to write a frame.
*
* @param sound_format Format of SoundData. The following values are defined:
* 0 = Linear PCM, platform endian
* 1 = ADPCM
* 2 = MP3
* 3 = Linear PCM, little endian
* 4 = Nellymoser 16 kHz mono
* 5 = Nellymoser 8 kHz mono
* 6 = Nellymoser
* 7 = G.711 A-law logarithmic PCM
* 8 = G.711 mu-law logarithmic PCM
* 9 = reserved
* 10 = AAC
* 11 = Speex
* 14 = MP3 8 kHz
* 15 = Device-specific sound
* Formats 7, 8, 14, and 15 are reserved.
* AAC is supported in Flash Player 9,0,115,0 and higher.
* Speex is supported in Flash Player 10 and higher.
* @param sound_rate Sampling rate. The following values are defined:
* 0 = 5.5 kHz
* 1 = 11 kHz
* 2 = 22 kHz
* 3 = 44 kHz
* @param sound_size Size of each audio sample. This parameter only pertains to
* uncompressed formats. Compressed formats always decode
* to 16 bits internally.
* 0 = 8-bit samples
* 1 = 16-bit samples
* @param sound_type Mono or stereo sound
* 0 = Mono sound
* 1 = Stereo sound
* @param timestamp The timestamp of audio.
*
* @example /trunk/research/librtmp/srs_aac_raw_publish.c
* @example /trunk/research/librtmp/srs_audio_raw_publish.c
*
* @remark for aac, the frame must be in ADTS format.
* @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 75, 1.A.2.2 ADTS
* @remark for aac, only support profile 1-4, AAC main/LC/SSR/LTP,
* @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23, 1.5.1.1 Audio object type
*
* @see https://github.com/ossrs/srs/issues/212
* @see E.4.2.1 AUDIODATA of video_file_format_spec_v10_1.pdf
*
* @return 0, success; otherswise, failed.
*/
extern int srs_audio_write_raw_frame(srs_rtmp_t rtmp,
char sound_format, char sound_rate, char sound_size, char sound_type,
char* frame, int frame_size, u_int32_t timestamp
);
/**
* whether aac raw data is in adts format,
* which bytes sequence matches '1111 1111 1111'B, that is 0xFFF.
* @param aac_raw_data the input aac raw data, a encoded aac frame data.
* @param ac_raw_size the size of aac raw data.
*
* @reamrk used to check whether current frame is in adts format.
* @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 75, 1.A.2.2 ADTS
* @example /trunk/research/librtmp/srs_aac_raw_publish.c
*
* @return 0 false; otherwise, true.
*/
extern srs_bool srs_aac_is_adts(char* aac_raw_data, int ac_raw_size);
/**
* parse the adts header to get the frame size,
* which bytes sequence matches '1111 1111 1111'B, that is 0xFFF.
* @param aac_raw_data the input aac raw data, a encoded aac frame data.
* @param ac_raw_size the size of aac raw data.
*
* @return failed when <=0 failed; otherwise, ok.
*/
extern int srs_aac_adts_frame_size(char* aac_raw_data, int ac_raw_size);
/*************************************************************
**************************************************************
* h264 raw codec
**************************************************************
*************************************************************/
/**
* write h.264 raw frame over RTMP to rtmp server.
* @param frames the input h264 raw data, encoded h.264 I/P/B frames data.
* frames can be one or more than one frame,
* each frame prefixed h.264 annexb header, by N[00] 00 00 01, where N>=0,
* for instance, frame = header(00 00 00 01) + payload(67 42 80 29 95 A0 14 01 6E 40)
* about annexb, @see H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
* @param frames_size the size of h264 raw data.
* assert frames_size > 0, at least has 1 bytes header.
* @param dts the dts of h.264 raw data.
* @param pts the pts of h.264 raw data.
*
* @remark, user should free the frames.
* @remark, the tbn of dts/pts is 1/1000 for RTMP, that is, in ms.
* @remark, cts = pts - dts
* @remark, use srs_h264_startswith_annexb to check whether frame is annexb format.
* @example /trunk/research/librtmp/srs_h264_raw_publish.c
* @see https://github.com/ossrs/srs/issues/66
*
* @return 0, success; otherswise, failed.
* for dvbsp error, @see srs_h264_is_dvbsp_error().
* for duplictated sps error, @see srs_h264_is_duplicated_sps_error().
* for duplictated pps error, @see srs_h264_is_duplicated_pps_error().
*/
/**
For the example file:
http://winlinvip.github.io/srs.release/3rdparty/720p.h264.raw
The data sequence is:
// SPS
000000016742802995A014016E40
// PPS
0000000168CE3880
// IFrame
0000000165B8041014C038008B0D0D3A071.....
// PFrame
0000000141E02041F8CDDC562BBDEFAD2F.....
User can send the SPS+PPS, then each frame:
// SPS+PPS
srs_h264_write_raw_frames('000000016742802995A014016E400000000168CE3880', size, dts, pts)
// IFrame
srs_h264_write_raw_frames('0000000165B8041014C038008B0D0D3A071......', size, dts, pts)
// PFrame
srs_h264_write_raw_frames('0000000141E02041F8CDDC562BBDEFAD2F......', size, dts, pts)
User also can send one by one:
// SPS
srs_h264_write_raw_frames('000000016742802995A014016E4', size, dts, pts)
// PPS
srs_h264_write_raw_frames('00000000168CE3880', size, dts, pts)
// IFrame
srs_h264_write_raw_frames('0000000165B8041014C038008B0D0D3A071......', size, dts, pts)
// PFrame
srs_h264_write_raw_frames('0000000141E02041F8CDDC562BBDEFAD2F......', size, dts, pts)
*/
extern int srs_h264_write_raw_frames(srs_rtmp_t rtmp,
char* frames, int frames_size, u_int32_t dts, u_int32_t pts
);
/**
* whether error_code is dvbsp(drop video before sps/pps/sequence-header) error.
*
* @see https://github.com/ossrs/srs/issues/203
* @example /trunk/research/librtmp/srs_h264_raw_publish.c
* @remark why drop video?
* some encoder, for example, ipcamera, will send sps/pps before each IFrame,
* so, when error and reconnect the rtmp, the first video is not sps/pps(sequence header),
* this will cause SRS server to disable HLS.
*/
extern srs_bool srs_h264_is_dvbsp_error(int error_code);
/**
* whether error_code is duplicated sps error.
*
* @see https://github.com/ossrs/srs/issues/204
* @example /trunk/research/librtmp/srs_h264_raw_publish.c
*/
extern srs_bool srs_h264_is_duplicated_sps_error(int error_code);
/**
* whether error_code is duplicated pps error.
*
* @see https://github.com/ossrs/srs/issues/204
* @example /trunk/research/librtmp/srs_h264_raw_publish.c
*/
extern srs_bool srs_h264_is_duplicated_pps_error(int error_code);
/**
* whether h264 raw data starts with the annexb,
* which bytes sequence matches N[00] 00 00 01, where N>=0.
* @param h264_raw_data the input h264 raw data, a encoded h.264 I/P/B frame data.
* @paam h264_raw_size the size of h264 raw data.
* @param pnb_start_code output the size of start code, must >=3.
* NULL to ignore.
*
* @reamrk used to check whether current frame is in annexb format.
* @example /trunk/research/librtmp/srs_h264_raw_publish.c
*
* @return 0 false; otherwise, true.
*/
extern srs_bool srs_h264_startswith_annexb(
char* h264_raw_data, int h264_raw_size,
int* pnb_start_code
);
/*************************************************************
**************************************************************
* flv codec
* @example /trunk/research/librtmp/srs_flv_injecter.c
* @example /trunk/research/librtmp/srs_flv_parser.c
* @example /trunk/research/librtmp/srs_ingest_flv.c
* @example /trunk/research/librtmp/srs_ingest_rtmp.c
**************************************************************
*************************************************************/
typedef void* srs_flv_t;
/* open flv file for both read/write. */
extern srs_flv_t srs_flv_open_read(const char* file);
extern srs_flv_t srs_flv_open_write(const char* file);
extern void srs_flv_close(srs_flv_t flv);
/**
* read the flv header. 9bytes header.
* @param header, @see E.2 The FLV header, flv_v10_1.pdf in SRS doc.
* 3bytes, signature, "FLV",
* 1bytes, version, 0x01,
* 1bytes, flags, UB[5] 0, UB[1] audio present, UB[1] 0, UB[1] video present.
* 4bytes, dataoffset, 0x09, The length of this header in bytes
*
* @return 0, success; otherswise, failed.
* @remark, drop the 4bytes zero previous tag size.
*/
extern int srs_flv_read_header(srs_flv_t flv, char header[9]);
/**
* read the flv tag header, 1bytes tag, 3bytes data_size,
* 4bytes time, 3bytes stream id.
* @param ptype, output the type of tag, macros:
* SRS_RTMP_TYPE_AUDIO, FlvTagAudio
* SRS_RTMP_TYPE_VIDEO, FlvTagVideo
* SRS_RTMP_TYPE_SCRIPT, FlvTagScript
* @param pdata_size, output the size of tag data.
* @param ptime, output the time of tag, the dts in ms.
*
* @return 0, success; otherswise, failed.
* @remark, user must ensure the next is a tag, srs never check it.
*/
extern int srs_flv_read_tag_header(srs_flv_t flv,
char* ptype, int32_t* pdata_size, u_int32_t* ptime
);
/**
* read the tag data. drop the 4bytes previous tag size
* @param data, the data to read, user alloc and free it.
* @param size, the size of data to read, get by srs_flv_read_tag_header().
* @remark, srs will ignore and drop the 4bytes previous tag size.
*/
extern int srs_flv_read_tag_data(srs_flv_t flv, char* data, int32_t size);
/**
* write the flv header. 9bytes header.
* @param header, @see E.2 The FLV header, flv_v10_1.pdf in SRS doc.
* 3bytes, signature, "FLV",
* 1bytes, version, 0x01,
* 1bytes, flags, UB[5] 0, UB[1] audio present, UB[1] 0, UB[1] video present.
* 4bytes, dataoffset, 0x09, The length of this header in bytes
*
* @return 0, success; otherswise, failed.
* @remark, auto write the 4bytes zero previous tag size.
*/
extern int srs_flv_write_header(srs_flv_t flv, char header[9]);
/**
* write the flv tag to file.
*
* @return 0, success; otherswise, failed.
* @remark, auto write the 4bytes zero previous tag size.
*/
/* write flv tag to file, auto write the 4bytes previous tag size */
extern int srs_flv_write_tag(srs_flv_t flv,
char type, int32_t time, char* data, int size
);
/**
* get the tag size, for flv injecter to adjust offset,
* size = tag_header(11B) + data_size + previous_tag(4B)
* @return the size of tag.
*/
extern int srs_flv_size_tag(int data_size);
/* file stream */
/* file stream tellg to get offset */
extern int64_t srs_flv_tellg(srs_flv_t flv);
/* seek file stream, offset is form the start of file */
extern void srs_flv_lseek(srs_flv_t flv, int64_t offset);
/* error code */
/* whether the error code indicates EOF */
extern srs_bool srs_flv_is_eof(int error_code);
/* media codec */
/**
* whether the video body is sequence header
* @param data, the data of tag, read by srs_flv_read_tag_data().
* @param size, the size of tag, read by srs_flv_read_tag_data().
*/
extern srs_bool srs_flv_is_sequence_header(char* data, int32_t size);
/**
* whether the video body is keyframe
* @param data, the data of tag, read by srs_flv_read_tag_data().
* @param size, the size of tag, read by srs_flv_read_tag_data().
*/
extern srs_bool srs_flv_is_keyframe(char* data, int32_t size);
/*************************************************************
**************************************************************
* amf0 codec
* @example /trunk/research/librtmp/srs_ingest_flv.c
* @example /trunk/research/librtmp/srs_ingest_rtmp.c
**************************************************************
*************************************************************/
/* the output handler. */
typedef double srs_amf0_number;
/**
* parse amf0 from data.
* @param nparsed, the parsed size, NULL to ignore.
* @return the parsed amf0 object. NULL for error.
* @remark user must free the parsed or created object by srs_amf0_free.
*/
extern srs_amf0_t srs_amf0_parse(char* data, int size, int* nparsed);
extern srs_amf0_t srs_amf0_create_string(const char* value);
extern srs_amf0_t srs_amf0_create_number(srs_amf0_number value);
extern srs_amf0_t srs_amf0_create_ecma_array();
extern srs_amf0_t srs_amf0_create_strict_array();
extern srs_amf0_t srs_amf0_create_object();
extern srs_amf0_t srs_amf0_ecma_array_to_object(srs_amf0_t ecma_arr);
extern void srs_amf0_free(srs_amf0_t amf0);
/* size and to bytes */
extern int srs_amf0_size(srs_amf0_t amf0);
extern int srs_amf0_serialize(srs_amf0_t amf0, char* data, int size);
/* type detecter */
extern srs_bool srs_amf0_is_string(srs_amf0_t amf0);
extern srs_bool srs_amf0_is_boolean(srs_amf0_t amf0);
extern srs_bool srs_amf0_is_number(srs_amf0_t amf0);
extern srs_bool srs_amf0_is_null(srs_amf0_t amf0);
extern srs_bool srs_amf0_is_object(srs_amf0_t amf0);
extern srs_bool srs_amf0_is_ecma_array(srs_amf0_t amf0);
extern srs_bool srs_amf0_is_strict_array(srs_amf0_t amf0);
/* value converter */
extern const char* srs_amf0_to_string(srs_amf0_t amf0);
extern srs_bool srs_amf0_to_boolean(srs_amf0_t amf0);
extern srs_amf0_number srs_amf0_to_number(srs_amf0_t amf0);
/* value setter */
extern void srs_amf0_set_number(srs_amf0_t amf0, srs_amf0_number value);
/* object value converter */
extern int srs_amf0_object_property_count(srs_amf0_t amf0);
extern const char* srs_amf0_object_property_name_at(srs_amf0_t amf0, int index);
extern srs_amf0_t srs_amf0_object_property_value_at(srs_amf0_t amf0, int index);
extern srs_amf0_t srs_amf0_object_property(srs_amf0_t amf0, const char* name);
extern void srs_amf0_object_property_set(srs_amf0_t amf0, const char* name, srs_amf0_t value);
extern void srs_amf0_object_clear(srs_amf0_t amf0);
/* ecma array value converter */
extern int srs_amf0_ecma_array_property_count(srs_amf0_t amf0);
extern const char* srs_amf0_ecma_array_property_name_at(srs_amf0_t amf0, int index);
extern srs_amf0_t srs_amf0_ecma_array_property_value_at(srs_amf0_t amf0, int index);
extern srs_amf0_t srs_amf0_ecma_array_property(srs_amf0_t amf0, const char* name);
extern void srs_amf0_ecma_array_property_set(srs_amf0_t amf0, const char* name, srs_amf0_t value);
/* strict array value converter */
extern int srs_amf0_strict_array_property_count(srs_amf0_t amf0);
extern srs_amf0_t srs_amf0_strict_array_property_at(srs_amf0_t amf0, int index);
extern void srs_amf0_strict_array_append(srs_amf0_t amf0, srs_amf0_t value);
/*************************************************************
**************************************************************
* utilities
**************************************************************
*************************************************************/
/**
* get the current system time in ms.
* use gettimeofday() to get system time.
*/
extern int64_t srs_utils_time_ms();
/**
* get the send bytes.
*/
extern int64_t srs_utils_send_bytes(srs_rtmp_t rtmp);
/**
* get the recv bytes.
*/
extern int64_t srs_utils_recv_bytes(srs_rtmp_t rtmp);
/**
* parse the dts and pts by time in header and data in tag,
* or to parse the RTMP packet by srs_rtmp_read_packet().
*
* @param time, the timestamp of tag, read by srs_flv_read_tag_header().
* @param type, the type of tag, read by srs_flv_read_tag_header().
* @param data, the data of tag, read by srs_flv_read_tag_data().
* @param size, the size of tag, read by srs_flv_read_tag_header().
* @param ppts, output the pts in ms,
*
* @return 0, success; otherswise, failed.
* @remark, the dts always equals to @param time.
* @remark, the pts=dts for audio or data.
* @remark, video only support h.264.
*/
extern int srs_utils_parse_timestamp(
u_int32_t time, char type, char* data, int size,
u_int32_t* ppts
);
/**
* whether the flv tag specified by param type is ok.
* @return true when tag is video/audio/script-data; otherwise, false.
*/
extern srs_bool srs_utils_flv_tag_is_ok(char type);
extern srs_bool srs_utils_flv_tag_is_audio(char type);
extern srs_bool srs_utils_flv_tag_is_video(char type);
extern srs_bool srs_utils_flv_tag_is_av(char type);
/**
* get the CodecID of video tag.
* Codec Identifier. The following values are defined:
* 2 = Sorenson H.263
* 3 = Screen video
* 4 = On2 VP6
* 5 = On2 VP6 with alpha channel
* 6 = Screen video version 2
* 7 = AVC
* @return the code id. 0 for error.
*/
extern char srs_utils_flv_video_codec_id(char* data, int size);
/**
* get the AVCPacketType of video tag.
* The following values are defined:
* 0 = AVC sequence header
* 1 = AVC NALU
* 2 = AVC end of sequence (lower level NALU sequence ender is
* not required or supported)
* @return the avc packet type. -1(0xff) for error.
*/
extern char srs_utils_flv_video_avc_packet_type(char* data, int size);
/**
* get the FrameType of video tag.
* Type of video frame. The following values are defined:
* 1 = key frame (for AVC, a seekable frame)
* 2 = inter frame (for AVC, a non-seekable frame)
* 3 = disposable inter frame (H.263 only)
* 4 = generated key frame (reserved for server use only)
* 5 = video info/command frame
* @return the frame type. 0 for error.
*/
extern char srs_utils_flv_video_frame_type(char* data, int size);
/**
* get the SoundFormat of audio tag.
* Format of SoundData. The following values are defined:
* 0 = Linear PCM, platform endian
* 1 = ADPCM
* 2 = MP3
* 3 = Linear PCM, little endian
* 4 = Nellymoser 16 kHz mono
* 5 = Nellymoser 8 kHz mono
* 6 = Nellymoser
* 7 = G.711 A-law logarithmic PCM
* 8 = G.711 mu-law logarithmic PCM
* 9 = reserved
* 10 = AAC
* 11 = Speex
* 14 = MP3 8 kHz
* 15 = Device-specific sound
* Formats 7, 8, 14, and 15 are reserved.
* AAC is supported in Flash Player 9,0,115,0 and higher.
* Speex is supported in Flash Player 10 and higher.
* @return the sound format. -1(0xff) for error.
*/
extern char srs_utils_flv_audio_sound_format(char* data, int size);
/**
* get the SoundRate of audio tag.
* Sampling rate. The following values are defined:
* 0 = 5.5 kHz
* 1 = 11 kHz
* 2 = 22 kHz
* 3 = 44 kHz
* @return the sound rate. -1(0xff) for error.
*/
extern char srs_utils_flv_audio_sound_rate(char* data, int size);
/**
* get the SoundSize of audio tag.
* Size of each audio sample. This parameter only pertains to
* uncompressed formats. Compressed formats always decode
* to 16 bits internally.
* 0 = 8-bit samples
* 1 = 16-bit samples
* @return the sound size. -1(0xff) for error.
*/
extern char srs_utils_flv_audio_sound_size(char* data, int size);
/**
* get the SoundType of audio tag.
* Mono or stereo sound
* 0 = Mono sound
* 1 = Stereo sound
* @return the sound type. -1(0xff) for error.
*/
extern char srs_utils_flv_audio_sound_type(char* data, int size);
/**
* get the AACPacketType of audio tag.
* The following values are defined:
* 0 = AAC sequence header
* 1 = AAC raw
* @return the aac packet type. -1(0xff) for error.
*/
extern char srs_utils_flv_audio_aac_packet_type(char* data, int size);
/*************************************************************
**************************************************************
* human readable print.
**************************************************************
*************************************************************/
/**
* human readable print
* @param pdata, output the heap data, NULL to ignore.
* user must use srs_amf0_free_bytes to free it.
* @return return the *pdata for print. NULL to ignore.
*/
extern char* srs_human_amf0_print(srs_amf0_t amf0, char** pdata, int* psize);
/**
* convert the flv tag type to string.
* SRS_RTMP_TYPE_AUDIO to "Audio"
* SRS_RTMP_TYPE_VIDEO to "Video"
* SRS_RTMP_TYPE_SCRIPT to "Data"
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_tag_type2string(char type);
/**
* get the codec id string.
* H.263 = Sorenson H.263
* Screen = Screen video
* VP6 = On2 VP6
* VP6Alpha = On2 VP6 with alpha channel
* Screen2 = Screen video version 2
* H.264 = AVC
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_video_codec_id2string(char codec_id);
/**
* get the avc packet type string.
* SH = AVC sequence header
* Nalu = AVC NALU
* SpsPpsEnd = AVC end of sequence
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_video_avc_packet_type2string(char avc_packet_type);
/**
* get the frame type string.
* I = key frame (for AVC, a seekable frame)
* P/B = inter frame (for AVC, a non-seekable frame)
* DI = disposable inter frame (H.263 only)
* GI = generated key frame (reserved for server use only)
* VI = video info/command frame
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_video_frame_type2string(char frame_type);
/**
* get the SoundFormat string.
* Format of SoundData. The following values are defined:
* LinearPCM = Linear PCM, platform endian
* ADPCM = ADPCM
* MP3 = MP3
* LinearPCMLe = Linear PCM, little endian
* NellymoserKHz16 = Nellymoser 16 kHz mono
* NellymoserKHz8 = Nellymoser 8 kHz mono
* Nellymoser = Nellymoser
* G711APCM = G.711 A-law logarithmic PCM
* G711MuPCM = G.711 mu-law logarithmic PCM
* Reserved = reserved
* AAC = AAC
* Speex = Speex
* MP3KHz8 = MP3 8 kHz
* DeviceSpecific = Device-specific sound
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_audio_sound_format2string(char sound_format);
/**
* get the SoundRate of audio tag.
* Sampling rate. The following values are defined:
* 5.5KHz = 5.5 kHz
* 11KHz = 11 kHz
* 22KHz = 22 kHz
* 44KHz = 44 kHz
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_audio_sound_rate2string(char sound_rate);
/**
* get the SoundSize of audio tag.
* Size of each audio sample. This parameter only pertains to
* uncompressed formats. Compressed formats always decode
* to 16 bits internally.
* 8bit = 8-bit samples
* 16bit = 16-bit samples
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_audio_sound_size2string(char sound_size);
/**
* get the SoundType of audio tag.
* Mono or stereo sound
* Mono = Mono sound
* Stereo = Stereo sound
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_audio_sound_type2string(char sound_type);
/**
* get the AACPacketType of audio tag.
* The following values are defined:
* SH = AAC sequence header
* Raw = AAC raw
* otherwise, "Unknown"
* @remark user never free the return char*,
* it's static shared const string.
*/
extern const char* srs_human_flv_audio_aac_packet_type2string(char aac_packet_type);
/**
* print the rtmp packet, use srs_human_trace/srs_human_verbose for packet,
* and use srs_human_raw for script data body.
* @return an error code for parse the timetstamp to dts and pts.
*/
extern int srs_human_print_rtmp_packet(char type, u_int32_t timestamp, char* data, int size);
/**
* @param pre_timestamp the previous timestamp in ms to calc the diff.
*/
extern int srs_human_print_rtmp_packet2(char type, u_int32_t timestamp, char* data, int size, u_int32_t pre_timestamp);
/**
* @param pre_now the previous system time in ms to calc the ndiff.
*/
extern int srs_human_print_rtmp_packet3(char type, u_int32_t timestamp, char* data, int size, u_int32_t pre_timestamp, int64_t pre_now);
/**
* @param starttime the rtmpdump starttime in ms.
* @param nb_packets the number of packets received, to calc the packets interval in ms.
*/
extern int srs_human_print_rtmp_packet4(char type, u_int32_t timestamp, char* data, int size, u_int32_t pre_timestamp, int64_t pre_now, int64_t starttime, int64_t nb_packets);
// log to console, for use srs-librtmp application.
extern const char* srs_human_format_time();
// when disabled log, donot compile it.
#ifdef SRS_DISABLE_LOG
#define srs_human_trace(msg, ...) (void)0
#define srs_human_verbose(msg, ...) (void)0
#define srs_human_raw(msg, ...) (void)0
#else
#define srs_human_trace(msg, ...) printf("[%s] ", srs_human_format_time());printf(msg, ##__VA_ARGS__);printf("\n")
#define srs_human_verbose(msg, ...) printf("[%s] ", srs_human_format_time());printf(msg, ##__VA_ARGS__);printf("\n")
#define srs_human_raw(msg, ...) printf(msg, ##__VA_ARGS__)
#endif
/*************************************************************
**************************************************************
* IO hijack, use your specified io functions.
**************************************************************
*************************************************************/
// the void* will convert to your handler for io hijack.
typedef void* srs_hijack_io_t;
#ifdef SRS_HIJACK_IO
#ifndef _WIN32
// for iovec.
#include <sys/uio.h>
#endif
/**
* get the hijack io object in rtmp protocol sdk.
* @remark, user should never provides this method, srs-librtmp provides it.
*/
extern srs_hijack_io_t srs_hijack_io_get(srs_rtmp_t rtmp);
#endif
// define the following macro and functions in your module to hijack the io.
// the example @see https://github.com/winlinvip/st-load
// which use librtmp but use its own io(use st also).
#ifdef SRS_HIJACK_IO
/**
* create hijack.
* @return NULL for error; otherwise, ok.
*/
extern srs_hijack_io_t srs_hijack_io_create();
/**
* destroy the context, user must close the socket.
*/
extern void srs_hijack_io_destroy(srs_hijack_io_t ctx);
/**
* create socket, not connect yet.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_create_socket(srs_hijack_io_t ctx);
/**
* connect socket at server_ip:port.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_connect(srs_hijack_io_t ctx, const char* server_ip, int port);
/**
* read from socket.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_read(srs_hijack_io_t ctx, void* buf, size_t size, ssize_t* nread);
/**
* set the socket recv timeout.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_set_recv_timeout(srs_hijack_io_t ctx, int64_t timeout_us);
/**
* get the socket recv timeout.
* @return 0, success; otherswise, failed.
*/
extern int64_t srs_hijack_io_get_recv_timeout(srs_hijack_io_t ctx);
/**
* get the socket recv bytes.
* @return 0, success; otherswise, failed.
*/
extern int64_t srs_hijack_io_get_recv_bytes(srs_hijack_io_t ctx);
/**
* set the socket send timeout.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_set_send_timeout(srs_hijack_io_t ctx, int64_t timeout_us);
/**
* get the socket send timeout.
* @return 0, success; otherswise, failed.
*/
extern int64_t srs_hijack_io_get_send_timeout(srs_hijack_io_t ctx);
/**
* get the socket send bytes.
* @return 0, success; otherswise, failed.
*/
extern int64_t srs_hijack_io_get_send_bytes(srs_hijack_io_t ctx);
/**
* writev of socket.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_writev(srs_hijack_io_t ctx, const iovec *iov, int iov_size, ssize_t* nwrite);
/**
* whether the timeout is never timeout.
* @return 0, success; otherswise, failed.
*/
extern bool srs_hijack_io_is_never_timeout(srs_hijack_io_t ctx, int64_t timeout_us);
/**
* read fully, fill the buf exactly size bytes.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_read_fully(srs_hijack_io_t ctx, void* buf, size_t size, ssize_t* nread);
/**
* write bytes to socket.
* @return 0, success; otherswise, failed.
*/
extern int srs_hijack_io_write(srs_hijack_io_t ctx, void* buf, size_t size, ssize_t* nwrite);
#endif
/*************************************************************
**************************************************************
* Windows SRS-LIBRTMP solution
**************************************************************
*************************************************************/
// for srs-librtmp, @see https://github.com/ossrs/srs/issues/213
#ifdef _WIN32
// for time.
#define _CRT_SECURE_NO_WARNINGS
#include <time.h>
int gettimeofday(struct timeval* tv, struct timezone* tz);
#define PRId64 "lld"
// for inet helpers.
typedef int socklen_t;
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
// for mkdir().
#include<direct.h>
// for open().
typedef int mode_t;
#define S_IRUSR 0
#define S_IWUSR 0
#define S_IXUSR 0
#define S_IRGRP 0
#define S_IWGRP 0
#define S_IXGRP 0
#define S_IROTH 0
#define S_IXOTH 0
// for file seek.
#include <io.h>
#include <fcntl.h>
#define open _open
#define close _close
#define lseek _lseek
#define write _write
#define read _read
// for pid.
typedef int pid_t;
pid_t getpid(void);
// for socket.
ssize_t writev(int fd, const struct iovec *iov, int iovcnt);
typedef int64_t useconds_t;
int usleep(useconds_t usec);
int socket_setup();
int socket_cleanup();
// others.
#define snprintf _snprintf
#endif
#ifdef __cplusplus
}
#endif
#endif
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "Semester.h"
// this function recieves the mode search and prints the result
void Semester:: search(char mode){
string search_term, term2;
// identifies the "type" then loops inside the vector of that type to find the result
switch(mode){
case 'n':
cout << "Enter class type and class number (ex: CSCI 112):";
cin >> search_term>> term2;
if(search_term == "CSCI"){
for(Csci cc: cs){
if(term2 == cc.Cnum())cout << cc.Type()<<"-"<<cc.Ctitle()<<"-"<<cc.Cnum()<<"-"<<cc.Proname()<<"\n";
}
}
else if(search_term == "EGEN"){
for(Egen cc: eg){
if(term2 == cc.Cnum())cout << cc.Type()<<"-"<<cc.Proname()<<"-"<<cc.Ctitle()<<"-"<<cc.Cnum()<<"\n";
}
}
else if(search_term == "BIOB"){
for(Biology cc: bio){
if(term2 == cc.Cnum())cout << cc.Type()<<"-"<<cc.Cnum()<<"-"<<cc.Ctitle()<<"-"<<cc.Proname()<<"\n";
}
}
else{cout<<"wrong entry! try again.";}
break;
case 't':
cout << "Enter type (CSCI, EGEN, or BIOB):";
cin >> search_term;
if(search_term == "BIOB"){
for (Biology uc: bio){uc.Print();}
}
else if(search_term == "CSCI"){
for (Csci cc: cs){cc.Print();}
}
else if(search_term == "EGEN"){
for (Egen ec: eg){ec.Print();}
}
else cout <<"Wrong entry!\n";
break;
}
}
// reads input and puts in to vector of classes based on its type
void Semester::Read(ifstream& ifs){
string line;
while(getline(ifs, line)){
uclass one_class;
one_class.SetFromCsvLine(line);
if(one_class.type == "EGEN"){
eg.push_back(one_class);}
else if(one_class.type == "BIOB"){
bio.push_back(one_class);}
else if(one_class.type == "CSCI"){
cs.push_back(one_class); }
}
}
void Semester::Print(){}
|
/*
* Copyright (c) 2016 Jason Lowe-Power
* 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 the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Jason Lowe-Power
*/
#ifndef __LEARNING_GEM5_HELLO_OBJECT_HH__
#define __LEARNING_GEM5_HELLO_OBJECT_HH__
#include <string>
#include "learning_gem5/goodbye_object.hh"
#include "params/HelloObject.hh"
#include "sim/sim_object.hh"
class HelloObject : public SimObject
{
private:
void processEvent();
EventWrapper<HelloObject, &HelloObject::processEvent> event;
/// Pointer to the corresponding GoodbyeObject. Set via Python
GoodbyeObject* goodbye;
/// The name of this object in the Python config file
std::string myName;
/// Latency between calling the event (in ticks)
Tick latency;
/// Number of times left to fire the event before goodbye
int timesLeft;
public:
HelloObject(HelloObjectParams *p);
void startup();
};
#endif // __LEARNING_GEM5_HELLO_OBJECT_HH__
|
/*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "It_vfs_fat.h"
static UINT32 TestCase(VOID)
{
INT32 ret;
CHAR pathname1[FAT_STANDARD_NAME_LENGTH] = FAT_DEV_PATH;
CHAR pathname2[FAT_STANDARD_NAME_LENGTH] = FAT_PATH_NAME;
ret = mkdir(pathname2, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT);
ret = format(pathname1, 0XFFFC, FAT_FILE_SYSTEMTYPE_AUTO);
ICUNIT_GOTO_EQUAL(ret, FAT_IS_ERROR, ret, EXIT);
ICUNIT_GOTO_EQUAL(errno, EINVAL, errno, EXIT);
ret = access(pathname2, F_OK);
ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT);
ret = remove(pathname2);
ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT);
return FAT_NO_ERROR;
EXIT:
rmdir(pathname2);
return FAT_NO_ERROR;
}
VOID ItFsFat518(VOID)
{
TEST_ADD_CASE("IT_FS_FAT_518", TestCase, TEST_VFS, TEST_VFAT, TEST_LEVEL2, TEST_FUNCTION);
}
|
//=================================================================================================
/*!
// \file src/mathtest/dvecdvecsub/VDaV5a.cpp
// \brief Source file for the VDaV5a dense vector/dense vector subtraction math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecdvecsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VDaV5a'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Vector type definitions
typedef blaze::DynamicVector<TypeA> VDa;
typedef blaze::StaticVector<TypeA,5UL> V5a;
// Creator type definitions
typedef blazetest::Creator<VDa> CVDa;
typedef blazetest::Creator<V5a> CV5a;
// Running the tests
RUN_DVECDVECSUB_OPERATION_TEST( CVDa( 5UL ), CV5a() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.