text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ResponseCorrelator.h"
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::transport::filters;
using namespace activemq::exceptions;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
////////////////////////////////////////////////////////////////////////////////
ResponseCorrelator::ResponseCorrelator( Transport* next, bool own )
:
TransportFilter( next, own ) {
//nextCommandId = 0;
nextCommandId.set(1);
// Start in the closed state.
closed = true;
}
////////////////////////////////////////////////////////////////////////////////
ResponseCorrelator::~ResponseCorrelator(){
// Close the transport and destroy it.
close();
// Don't do anything with the future responses -
// they should be cleaned up by each requester.
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::oneway( Command* command )
throw( CommandIOException, decaf::lang::exceptions::UnsupportedOperationException ) {
try{
command->setCommandId( nextCommandId.getAndIncrement() );
command->setResponseRequired( false );
if( closed || next == NULL ){
throw CommandIOException( __FILE__, __LINE__,
"transport already closed" );
}
next->oneway( command );
}
AMQ_CATCH_RETHROW( UnsupportedOperationException )
AMQ_CATCH_RETHROW( CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, CommandIOException )
AMQ_CATCHALL_THROW( CommandIOException )
}
////////////////////////////////////////////////////////////////////////////////
Response* ResponseCorrelator::request( Command* command )
throw( CommandIOException, decaf::lang::exceptions::UnsupportedOperationException ) {
try{
command->setCommandId( nextCommandId.getAndIncrement() );
command->setResponseRequired( true );
// Add a future response object to the map indexed by this
// command id.
// TODO = This might not get deleted if an exception is thrown.
FutureResponse* futureResponse = new FutureResponse();
synchronized( &mapMutex ){
requestMap[command->getCommandId()] = futureResponse;
}
// Wait to be notified of the response via the futureResponse
// object.
Response* response = NULL;
// Send the request.
next->oneway( command );
// Get the response.
response = futureResponse->getResponse();
// Perform cleanup on the map.
synchronized( &mapMutex ){
// We've done our waiting - get this thing out
// of the map.
requestMap.erase( command->getCommandId() );
// Destroy the futureResponse. It is safe to
// do this now because the other thread only
// accesses the futureResponse within a lock on
// the map.
delete futureResponse;
futureResponse = NULL;
}
if( response == NULL ){
throw CommandIOException( __FILE__, __LINE__,
"No valid response received for command: %s, check broker.",
command->toString().c_str() );
}
return response;
}
AMQ_CATCH_RETHROW( UnsupportedOperationException )
AMQ_CATCH_RETHROW( CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, CommandIOException )
AMQ_CATCHALL_THROW( CommandIOException )
}
////////////////////////////////////////////////////////////////////////////////
Response* ResponseCorrelator::request( Command* command, unsigned int timeout )
throw( CommandIOException, decaf::lang::exceptions::UnsupportedOperationException ) {
try{
command->setCommandId( nextCommandId.getAndIncrement() );
command->setResponseRequired( true );
// Add a future response object to the map indexed by this
// command id.
// TODO = This might not get deleted if an exception is thrown.
FutureResponse* futureResponse = new FutureResponse();
synchronized( &mapMutex ){
requestMap[command->getCommandId()] = futureResponse;
}
// Wait to be notified of the response via the futureResponse
// object.
Response* response = NULL;
// Send the request.
next->oneway( command );
// Get the response.
response = futureResponse->getResponse( timeout );
// Perform cleanup on the map.
synchronized( &mapMutex ){
// We've done our waiting - get this thing out
// of the map.
requestMap.erase( command->getCommandId() );
// Destroy the futureResponse. It is safe to
// do this now because the other thread only
// accesses the futureResponse within a lock on
// the map.
delete futureResponse;
futureResponse = NULL;
}
if( response == NULL ){
throw CommandIOException( __FILE__, __LINE__,
"No valid response received for command: %s, check broker.",
command->toString().c_str() );
}
return response;
}
AMQ_CATCH_RETHROW( UnsupportedOperationException )
AMQ_CATCH_RETHROW( CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, CommandIOException )
AMQ_CATCHALL_THROW( CommandIOException )
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::onCommand( Command* command ) {
// Let's see if the incoming command is a response.
Response* response = dynamic_cast<Response*>( command );
if( response == NULL ){
// It's a non-response - just notify the listener.
fire( command );
return;
}
// It is a response - let's correlate ...
synchronized( &mapMutex ){
// Look the future request up based on the correlation id.
std::map<unsigned int, FutureResponse*>::iterator iter =
requestMap.find( response->getCorrelationId() );
if( iter == requestMap.end() ){
// This is not terrible - just log it.
//printf("ResponseCorrelator::onCommand() - received unknown response for request: %d\n",
// response->getCorrelationId() );
return;
}
// Get the future response (if it's in the map, it's not NULL).
FutureResponse* futureResponse = NULL;
futureResponse = iter->second;
// Set the response property in the future response.
futureResponse->setResponse( response );
}
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::start() throw( cms::CMSException ) {
try{
/**
* We're already started.
*/
if( !closed ){
return;
}
if( commandlistener == NULL ){
throw exceptions::ActiveMQException( __FILE__, __LINE__,
"commandListener is invalid" );
}
if( exceptionListener == NULL ){
throw exceptions::ActiveMQException( __FILE__, __LINE__,
"exceptionListener is invalid" );
}
if( next == NULL ){
throw exceptions::ActiveMQException( __FILE__, __LINE__,
"next transport is NULL" );
}
// Start the delegate transport object.
next->start();
// Mark it as open.
closed = false;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::close() throw( cms::CMSException ){
try{
// Wake-up any outstanding requests.
synchronized( &mapMutex ){
std::map<unsigned int, FutureResponse*>::iterator iter = requestMap.begin();
for( ; iter != requestMap.end(); ++iter ){
iter->second->setResponse( NULL );
}
}
if( !closed && next != NULL ){
next->close();
}
closed = true;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::onTransportException(
Transport* source AMQCPP_UNUSED,
const decaf::lang::Exception& ex ) {
// Trigger each outstanding request to complete so that we don't hang
// forever waiting for one that has been sent without timeout.
synchronized( &mapMutex ){
std::map<unsigned int, FutureResponse*>::iterator iter = requestMap.begin();
for( ; iter != requestMap.end(); ++iter ){
iter->second->setResponse( NULL );
}
}
fire( ex );
}
<commit_msg><commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ResponseCorrelator.h"
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::transport::filters;
using namespace activemq::exceptions;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
////////////////////////////////////////////////////////////////////////////////
ResponseCorrelator::ResponseCorrelator( Transport* next, bool own )
: TransportFilter( next, own ) {
nextCommandId.set(1);
// Start in the closed state.
closed = true;
}
////////////////////////////////////////////////////////////////////////////////
ResponseCorrelator::~ResponseCorrelator(){
// Close the transport and destroy it.
close();
// Don't do anything with the future responses -
// they should be cleaned up by each requester.
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::oneway( Command* command )
throw( CommandIOException, decaf::lang::exceptions::UnsupportedOperationException ) {
try{
command->setCommandId( nextCommandId.getAndIncrement() );
command->setResponseRequired( false );
if( closed || next == NULL ){
throw CommandIOException( __FILE__, __LINE__,
"transport already closed" );
}
next->oneway( command );
}
AMQ_CATCH_RETHROW( UnsupportedOperationException )
AMQ_CATCH_RETHROW( CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, CommandIOException )
AMQ_CATCHALL_THROW( CommandIOException )
}
////////////////////////////////////////////////////////////////////////////////
Response* ResponseCorrelator::request( Command* command )
throw( CommandIOException, decaf::lang::exceptions::UnsupportedOperationException ) {
try{
command->setCommandId( nextCommandId.getAndIncrement() );
command->setResponseRequired( true );
// Add a future response object to the map indexed by this
// command id.
// TODO = This might not get deleted if an exception is thrown.
FutureResponse* futureResponse = new FutureResponse();
synchronized( &mapMutex ){
requestMap[command->getCommandId()] = futureResponse;
}
// Wait to be notified of the response via the futureResponse
// object.
Response* response = NULL;
// Send the request.
next->oneway( command );
// Get the response.
response = futureResponse->getResponse();
// Perform cleanup on the map.
synchronized( &mapMutex ){
// We've done our waiting - get this thing out
// of the map.
requestMap.erase( command->getCommandId() );
// Destroy the futureResponse. It is safe to
// do this now because the other thread only
// accesses the futureResponse within a lock on
// the map.
delete futureResponse;
futureResponse = NULL;
}
if( response == NULL ){
throw CommandIOException( __FILE__, __LINE__,
"No valid response received for command: %s, check broker.",
command->toString().c_str() );
}
return response;
}
AMQ_CATCH_RETHROW( UnsupportedOperationException )
AMQ_CATCH_RETHROW( CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, CommandIOException )
AMQ_CATCHALL_THROW( CommandIOException )
}
////////////////////////////////////////////////////////////////////////////////
Response* ResponseCorrelator::request( Command* command, unsigned int timeout )
throw( CommandIOException, decaf::lang::exceptions::UnsupportedOperationException ) {
try{
command->setCommandId( nextCommandId.getAndIncrement() );
command->setResponseRequired( true );
// Add a future response object to the map indexed by this
// command id.
// TODO = This might not get deleted if an exception is thrown.
FutureResponse* futureResponse = new FutureResponse();
synchronized( &mapMutex ){
requestMap[command->getCommandId()] = futureResponse;
}
// Wait to be notified of the response via the futureResponse
// object.
Response* response = NULL;
// Send the request.
next->oneway( command );
// Get the response.
response = futureResponse->getResponse( timeout );
// Perform cleanup on the map.
synchronized( &mapMutex ){
// We've done our waiting - get this thing out
// of the map.
requestMap.erase( command->getCommandId() );
// Destroy the futureResponse. It is safe to
// do this now because the other thread only
// accesses the futureResponse within a lock on
// the map.
delete futureResponse;
futureResponse = NULL;
}
if( response == NULL ){
throw CommandIOException( __FILE__, __LINE__,
"No valid response received for command: %s, check broker.",
command->toString().c_str() );
}
return response;
}
AMQ_CATCH_RETHROW( UnsupportedOperationException )
AMQ_CATCH_RETHROW( CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, CommandIOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, CommandIOException )
AMQ_CATCHALL_THROW( CommandIOException )
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::onCommand( Command* command ) {
// Let's see if the incoming command is a response.
Response* response = dynamic_cast<Response*>( command );
if( response == NULL ){
// It's a non-response - just notify the listener.
fire( command );
return;
}
// It is a response - let's correlate ...
synchronized( &mapMutex ){
// Look the future request up based on the correlation id.
std::map<unsigned int, FutureResponse*>::iterator iter =
requestMap.find( response->getCorrelationId() );
if( iter == requestMap.end() ){
// This is not terrible - just log it.
//printf("ResponseCorrelator::onCommand() - received unknown response for request: %d\n",
// response->getCorrelationId() );
return;
}
// Get the future response (if it's in the map, it's not NULL).
FutureResponse* futureResponse = NULL;
futureResponse = iter->second;
// Set the response property in the future response.
futureResponse->setResponse( response );
}
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::start() throw( cms::CMSException ) {
try{
/**
* We're already started.
*/
if( !closed ){
return;
}
if( commandlistener == NULL ){
throw exceptions::ActiveMQException( __FILE__, __LINE__,
"commandListener is invalid" );
}
if( exceptionListener == NULL ){
throw exceptions::ActiveMQException( __FILE__, __LINE__,
"exceptionListener is invalid" );
}
if( next == NULL ){
throw exceptions::ActiveMQException( __FILE__, __LINE__,
"next transport is NULL" );
}
// Start the delegate transport object.
next->start();
// Mark it as open.
closed = false;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::close() throw( cms::CMSException ){
try{
// Wake-up any outstanding requests.
synchronized( &mapMutex ){
std::map<unsigned int, FutureResponse*>::iterator iter = requestMap.begin();
for( ; iter != requestMap.end(); ++iter ){
iter->second->setResponse( NULL );
}
}
if( !closed && next != NULL ){
next->close();
}
closed = true;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
void ResponseCorrelator::onTransportException(
Transport* source AMQCPP_UNUSED,
const decaf::lang::Exception& ex ) {
// Trigger each outstanding request to complete so that we don't hang
// forever waiting for one that has been sent without timeout.
synchronized( &mapMutex ){
std::map<unsigned int, FutureResponse*>::iterator iter = requestMap.begin();
for( ; iter != requestMap.end(); ++iter ){
iter->second->setResponse( NULL );
}
}
fire( ex );
}
<|endoftext|> |
<commit_before>// fhircpp - C++ Library for FHIR
//
// Copyright (C) 2017 David Mooney
//
// 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 "primitive.hpp"
#include "gtest/gtest.h"
TEST(fhircpp_test, primitive_boolean) {
fhir::boolean b;
ASSERT_EQ(b.value(), false);
fhir::boolean b2(true);
ASSERT_EQ(b2.value(), true);
fhir::boolean b3(b2);
ASSERT_EQ(b3.value(), true);
}
<commit_msg>Updated unit tests to use ASSERT_TRUE<commit_after>// fhircpp - C++ Library for FHIR
//
// Copyright (C) 2017 David Mooney
//
// 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 "primitive.hpp"
#include "gtest/gtest.h"
TEST(fhircpp_test, primitive_boolean) {
fhir::boolean b;
ASSERT_FALSE(b.value());
ASSERT_TRUE(b.valid());
fhir::boolean b2(true);
ASSERT_TRUE(b2.value());
ASSERT_TRUE(b2.valid());
fhir::boolean b3(b2);
ASSERT_TRUE(b3.value());
ASSERT_TRUE(b3.valid());
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_port.H
/// @brief Code to support ports
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef __MSS_EXP_PORT_H_
#define __MSS_EXP_PORT_H_
#include <fapi2.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/shared/exp_consts.H>
#include <lib/dimm/exp_rank.H>
#include <generic/memory/lib/utils/mc/gen_mss_port.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <mss_generic_attribute_getters.H>
#include <mss_explorer_attribute_getters.H>
namespace mss
{
//////////////////////////////////////////////////////////////
// Traits values for EXPLORER
//////////////////////////////////////////////////////////////
///
/// @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP
///
template<>
class portTraits< mss::mc_type::EXPLORER >
{
public:
// PORT_TYPE
static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT;
// scom register definition
static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q;
static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q;
static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q;
static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q;
static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q;
static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q;
static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q;
static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q;
static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR;
static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q;
static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0;
static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q;
static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q;
static constexpr uint64_t MAGIC_NUMBER_SIM = 765;
static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605;
// scom register field definition
enum
{
CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE,
CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE,
CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN,
CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL,
CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE,
CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE,
REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE,
CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR,
ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT,
ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT,
ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH,
PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE,
DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START,
RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY,
RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW,
RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION,
RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION,
RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN,
DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY,
DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN,
DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY,
DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN,
FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME,
FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN,
FWMS0_MARK = EXPLR_RDF_FWMS0_MARK,
FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN,
FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1,
RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE,
WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE,
};
};
///
/// @brief ATTR_MSS_MEM_MVPD_FWMS getter
/// @param[in] const ref to the TARGET_TYPE_OCMB_CHIP
/// @param[out] uint32_t&[] array reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Mark store records from OCMB VPD. The array dimension is [port][mark]. Explorer
/// only has one port so only [0][mark] is used in explorer.
///
template<>
inline fapi2::ReturnCode mvpd_fwms< mss::mc_type::EXPLORER >(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint32_t (&o_array)[mss::MARK_STORE_COUNT])
{
return mss::attr::get_mvpd_fwms(i_target, o_array);
}
/// @brief Get the attributes for the reorder queue setting
/// @param[in] const ref to the mc target
/// @param[out] uint8_t& reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Contains the settings for write/read reorder
/// queue
///
template< >
inline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint8_t& o_value)
{
return mss::attr::get_reorder_queue_setting(i_target, o_value);
}
///
/// @brief Change the state of the force_str bit - mc_type::EXPLORER specialization
/// @tparam MC the memory controller type
/// @param[in] i_target the target
/// @param[in] i_state the state
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< >
inline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const states i_state )
{
using TT = portTraits<mss::mc_type::EXPLORER>;
fapi2::buffer<uint64_t> l_data;
FAPI_DBG("Change force_str to %s %s", (i_state == HIGH ? "high" : "low"), mss::c_str(i_target));
FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) );
l_data.writeBit<TT::CFG_FORCE_STR>(i_state);
FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
}// mss
#endif
<commit_msg>Final monolithic snapshot of mss p10 FW<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_port.H
/// @brief Code to support ports
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef __MSS_EXP_PORT_H_
#define __MSS_EXP_PORT_H_
#include <fapi2.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/utils/mss_exp_conversions.H>
#include <mss_explorer_attribute_getters.H>
#include <lib/shared/exp_consts.H>
#include <lib/dimm/exp_rank.H>
#include <generic/memory/lib/utils/mc/gen_mss_port.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <mss_generic_attribute_getters.H>
namespace mss
{
//////////////////////////////////////////////////////////////
// Traits values for EXPLORER
//////////////////////////////////////////////////////////////
///
/// @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP
///
template<>
class portTraits< mss::mc_type::EXPLORER >
{
public:
// PORT_TYPE
static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT;
// scom register definition
static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q;
static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q;
static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q;
static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q;
static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q;
static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q;
static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q;
static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q;
static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR;
static constexpr uint64_t CTCR_REG = EXPLR_RDF_CTCR;
static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q;
static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0;
static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q;
static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q;
static constexpr uint64_t MAGIC_NUMBER_SIM = 765;
static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605;
// scom register field definition
enum
{
CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE,
CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE,
CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN,
CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL,
CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE,
CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE,
REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE,
CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR,
ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT,
ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT,
ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH,
PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE,
DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START,
RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY,
BW_WINDOW_SIZE = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE,
BW_WINDOW_SIZE_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE_LEN,
BW_SNAPSHOT = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT,
BW_SNAPSHOT_LEN = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT_LEN,
RECR_ENABLE_MPE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_MPE_NOISE_WINDOW,
RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW,
RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION,
RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION,
RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN,
RECR_RETRY_UNMARKED_ERRORS = EXPLR_RDF_RECR_RETRY_UNMARKED_ERRORS,
RECR_CFG_MAINT_USE_TIMERS = EXPLR_RDF_RECR_CFG_MAINT_USE_TIMERS,
RECR_MBSECCQ_MAINT_NO_RETRY_UE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_UE,
RECR_MBSECCQ_MAINT_NO_RETRY_MPE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_MPE,
CFG_CTRLUPD_AFTER_ERR = EXPLR_SRQ_MBA_FARB9Q_CFG_CTRLUPD_AFTER_ERR,
CFG_MC_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_ENABLE,
CFG_MC_PER_CAL_INTERVAL_TB = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB,
CFG_MC_PER_CAL_INTERVAL_TB_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB_LEN,
CFG_MC_PER_CAL_INTERVAL = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL,
CFG_MC_PER_CAL_INTERVAL_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_LEN,
CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN,
CFG_MC_PER_CAL_RUN_LENGTH = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH,
CFG_MC_PER_CAL_RUN_LENGTH_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH_LEN,
CFG_MC_PER_CAL_CTRLUPD_MIN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN,
CFG_MC_PER_CAL_CTRLUPD_MIN_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN_LEN,
CTCR_MPE_TIMER = EXPLR_RDF_CTCR_MPE_TIMER,
CTCR_MPE_TIMER_LEN = EXPLR_RDF_CTCR_MPE_TIMER_LEN,
CTCR_MPE_TIMEBASE = EXPLR_RDF_CTCR_MPE_TIMEBASE,
CTCR_MPE_TIMEBASE_LEN = EXPLR_RDF_CTCR_MPE_TIMEBASE_LEN,
CTCR_UE_TIMER = EXPLR_RDF_CTCR_UE_TIMER,
CTCR_UE_TIMER_LEN = EXPLR_RDF_CTCR_UE_TIMER_LEN,
CTCR_UE_TIMEBASE = EXPLR_RDF_CTCR_UE_TIMEBASE,
CTCR_UE_TIMEBASE_LEN = EXPLR_RDF_CTCR_UE_TIMEBASE_LEN,
CTCR_UE_LOCKOUT_ENABLE = EXPLR_RDF_CTCR_UE_LOCKOUT_ENABLE,
DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY,
DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN,
DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY,
DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN,
FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME,
FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN,
FWMS0_MARK = EXPLR_RDF_FWMS0_MARK,
FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN,
FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1,
RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE,
WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE,
};
};
///
/// @brief ATTR_MSS_MEM_MVPD_FWMS getter
/// @param[in] const ref to the TARGET_TYPE_OCMB_CHIP
/// @param[out] uint32_t&[] array reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Mark store records from OCMB VPD. The array dimension is [port][mark]. Explorer
/// only has one port so only [0][mark] is used in explorer.
///
template<>
inline fapi2::ReturnCode mvpd_fwms< mss::mc_type::EXPLORER >(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint32_t (&o_array)[mss::MARK_STORE_COUNT])
{
return mss::attr::get_mvpd_fwms(i_target, o_array);
}
/// @brief Get the attributes for the reorder queue setting
/// @param[in] const ref to the mc target
/// @param[out] uint8_t& reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Contains the settings for write/read reorder
/// queue
///
template< >
inline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint8_t& o_value)
{
return mss::attr::get_reorder_queue_setting(i_target, o_value);
}
///
/// @brief ATTR_MEM_EFF_DIMM_SPARE getter
/// @param[in] const ref to the TARGET_TYPE_DIMM
/// @param[out] uint32_t&[] array reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Spare DRAM availability. Used in various locations and is computed in mss_eff_cnfg.
/// Array indexes are [DIMM][RANK]
///
template<>
inline fapi2::ReturnCode dimm_spare< mss::mc_type::EXPLORER >(
const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint8_t (&o_array)[mss::MAX_RANK_PER_DIMM_ATTR])
{
return mss::attr::get_dimm_spare(i_target, o_array);
}
///
/// @brief Change the state of the force_str bit - mc_type::EXPLORER specialization
/// @tparam MC the memory controller type
/// @param[in] i_target the target
/// @param[in] i_state the state
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< >
inline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const states i_state )
{
using TT = portTraits<mss::mc_type::EXPLORER>;
fapi2::buffer<uint64_t> l_data;
FAPI_DBG("Change force_str to %s %s", (i_state == HIGH ? "high" : "low"), mss::c_str(i_target));
FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) );
l_data.writeBit<TT::CFG_FORCE_STR>(i_state);
FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
}// mss
#endif
<|endoftext|> |
<commit_before>#include <PCU.h>
#include "phOutput.h"
#include "phLinks.h"
#include "phAdjacent.h"
#include "phBubble.h"
#include "phAxisymmetry.h"
namespace ph {
static void getCounts(Output& o)
{
for (int i = 0; i < 4; ++i)
o.nGlobalEntities[i] = apf::countOwned(o.mesh, i);
PCU_Add_Ints(o.nGlobalEntities, 4);
o.nOwnedNodes = apf::countOwned(o.mesh, 0);
o.nOverlapNodes = o.mesh->count(0);
o.nGlobalNodes = o.nGlobalEntities[0];
}
static void getCoordinates(Output& o)
{
apf::Mesh* m = o.mesh;
int n = m->count(0);
double* x = new double[n * 3];
apf::MeshEntity* v;
int i = 0;
apf::MeshIterator* it = m->begin(0);
while ((v = m->iterate(it))) {
apf::Vector3 p;
m->getPoint(v, 0, p);
for (int j = 0; j < 3; ++j)
x[j * n + i] = p[j]; /* FORTRAN indexing */
++i;
}
m->end(it);
assert(i == n);
o.arrays.coordinates = x;
}
/* so apparently old phParAdapt just used EN_id,
and the id generator from pumi would do things
like this. I guess PHASTA is ok with a unique
number for each copy, regardless of part boundary
sharing...
update: Michel says these global numbers are ignored
by phasta. get rid of them when you can.
*/
static void getGlobal(Output& o)
{
apf::Mesh* m = o.mesh;
int n = m->count(0);
int self = PCU_Comm_Self();
int peers = PCU_Comm_Peers();
int id = self + 1;
o.arrays.globalNodeNumbers = new int[n];
for (int i = 0; i < n; ++i) {
o.arrays.globalNodeNumbers[i] = id;
id += peers;
}
}
static void getVertexLinks(Output& o, apf::Numbering* n)
{
Links links;
getLinks(o.mesh, 0, links);
encodeILWORK(n, links, o.nlwork, o.arrays.ilwork);
}
static void getInterior(Output& o, apf::Numbering* n)
{
apf::Mesh* m = o.mesh;
Blocks& bs = o.blocks.interior;
int*** ien = new int**[bs.getSize()];
apf::NewArray<int> js(bs.getSize());
for (int i = 0; i < bs.getSize(); ++i) {
ien[i] = new int*[bs.nElements[i]];
js[i] = 0;
}
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(m->getDimension());
while ((e = m->iterate(it))) {
BlockKey k;
getInteriorBlockKey(m, e, k);
int nv = k.nElementVertices;
assert(bs.keyToIndex.count(k));
int i = bs.keyToIndex[k];
int j = js[i];
ien[i][j] = new int[nv];
apf::Downward v;
getVertices(m, e, v);
for (int k = 0; k < nv; ++k)
ien[i][j][k] = apf::getNumber(n, v[k], 0, 0);
++js[i];
}
m->end(it);
for (int i = 0; i < bs.getSize(); ++i)
assert(js[i] == bs.nElements[i]);
o.arrays.ien = ien;
}
static void getBoundary(Output& o, BCs& bcs, apf::Numbering* n)
{
apf::Mesh* m = o.mesh;
gmi_model* gm = m->getModel();
int nbc = countNaturalBCs(*o.in);
Blocks& bs = o.blocks.boundary;
int*** ienb = new int**[bs.getSize()];
int*** ibcb = new int**[bs.getSize()];
double*** bcb = new double**[bs.getSize()];
apf::NewArray<int> js(bs.getSize());
for (int i = 0; i < bs.getSize(); ++i) {
ienb[i] = new int*[bs.nElements[i]];
ibcb[i] = new int*[bs.nElements[i]];
bcb[i] = new double*[bs.nElements[i]];
js[i] = 0;
}
int boundaryDim = m->getDimension() - 1;
apf::MeshEntity* f;
apf::MeshIterator* it = m->begin(boundaryDim);
while ((f = m->iterate(it))) {
apf::ModelEntity* me = m->toModel(f);
if (m->getModelType(me) != boundaryDim)
continue;
gmi_ent* gf = (gmi_ent*)me;
apf::MeshEntity* e = m->getUpward(f, 0);
BlockKey k;
getBoundaryBlockKey(m, e, f, k);
assert(bs.keyToIndex.count(k));
int i = bs.keyToIndex[k];
int j = js[i];
int nv = k.nElementVertices;
apf::Downward v;
getBoundaryVertices(m, e, f, v);
ienb[i][j] = new int[nv];
for (int k = 0; k < nv; ++k)
ienb[i][j][k] = apf::getNumber(n, v[k], 0, 0);
bcb[i][j] = new double[nbc]();
ibcb[i][j] = new int[2](); /* <- parens initialize to zero */
apf::Vector3 x = apf::getLinearCentroid(m, f);
applyNaturalBCs(gm, gf, bcs, x, bcb[i][j], ibcb[i][j]);
++js[i];
}
m->end(it);
for (int i = 0; i < bs.getSize(); ++i)
assert(js[i] == bs.nElements[i]);
o.arrays.ienb = ienb;
o.arrays.ibcb = ibcb;
o.arrays.bcb = bcb;
}
static void getBoundaryElements(Output& o)
{
Blocks& bs = o.blocks.boundary;
int n = 0;
for (int i = 0; i < bs.getSize(); ++i)
n += bs.nElements[i];
o.nBoundaryElements = n;
}
static void getMaxElementNodes(Output& o)
{
int n = 0;
Blocks& ibs = o.blocks.interior;
for (int i = 0; i < ibs.getSize(); ++i)
n = std::max(n, ibs.keys[i].nElementVertices);
Blocks& bbs = o.blocks.boundary;
for (int i = 0; i < bbs.getSize(); ++i)
n = std::max(n, bbs.keys[i].nElementVertices);
o.nMaxElementNodes = n;
}
/* returns the global periodic master iff it is on this
part, otherwise returns e */
static apf::MeshEntity* getLocalPeriodicMaster(apf::MatchedSharing* sh,
apf::MeshEntity* e)
{
if ( ! sh)
return e;
apf::Copy globalMaster = sh->getOwner(e);
if (globalMaster.peer == PCU_Comm_Self())
return globalMaster.entity;
else
return e;
}
static void getLocalPeriodicMasters(Output& o, apf::Numbering* n)
{
apf::Mesh* m = o.mesh;
int* iper = new int[m->count(0)];
apf::MeshIterator* it = m->begin(0);
apf::MeshEntity* e;
apf::MatchedSharing* sh = m->hasMatching() ? new apf::MatchedSharing(m) : 0;
int i = 0;
while ((e = m->iterate(it))) {
apf::MeshEntity* master = getLocalPeriodicMaster(sh, e);
if (master == e)
iper[i] = 0;
else
iper[i] = apf::getNumber(n, master, 0, 0) + 1;
++i;
}
m->end(it);
o.arrays.iper = iper;
delete sh;
}
static bool isMatchingSlave(apf::MatchedSharing* ms, apf::MeshEntity* v)
{
if (!ms)
return false;
apf::Matches matches;
ms->mesh->getMatches(v, matches);
if (!matches.getSize())
return false;
return !ms->isOwned(v);
}
static void getEssentialBCs(BCs& bcs, Output& o)
{
Input& in = *o.in;
apf::Mesh* m = o.mesh;
apf::MeshTag* angles = 0;
apf::MatchedSharing* ms = 0;
if (m->hasMatching())
ms = new apf::MatchedSharing(m);
if (in.axisymmetry)
angles = tagAngles(m, bcs, ms);
int nv = m->count(0);
o.arrays.nbc = new int[nv];
for (int i = 0; i < nv; ++i)
o.arrays.nbc[i] = 0;
o.arrays.ibc = new int[nv]();
o.arrays.bc = new double*[nv];
o.nEssentialBCNodes = 0;
int ibc;
int nec = countEssentialBCs(in);
double* bc = new double[nec]();
gmi_model* gm = m->getModel();
int i = 0;
int& ei = o.nEssentialBCNodes;
apf::MeshEntity* v;
apf::MeshIterator* it = m->begin(0);
while ((v = m->iterate(it))) {
gmi_ent* ge = (gmi_ent*) m->toModel(v);
apf::Vector3 x;
m->getPoint(v, 0, x);
ibc = 0;
for (int j = 0; j < nec; ++j)
bc[j] = 0;
bool hasBC = applyEssentialBCs(gm, ge, bcs, x, bc, &ibc);
/* matching introduces an iper bit */
/* which is set for all slaves */
if (isMatchingSlave(ms, v)) {
hasBC = true;
ibc |= (1<<10);
/* axisymmetric theta for some slaves */
if (in.axisymmetry && m->hasTag(v, angles))
m->getDoubleTag(v, angles, &bc[11]);
}
if (hasBC) {
o.arrays.nbc[i] = ei + 1;
o.arrays.ibc[ei] = ibc;
double* bc_ei = new double[nec];
for (int j = 0; j < nec; ++j)
bc_ei[j] = bc[j];
o.arrays.bc[ei] = bc_ei;
++ei;
}
++i;
}
m->end(it);
delete [] bc;
if (in.axisymmetry)
m->destroyTag(angles);
delete ms;
}
static void getInitialConditions(BCs& bcs, Output& o)
{
Input& in = *o.in;
apf::Mesh* m = o.mesh;
apf::MeshEntity* v;
apf::NewArray<double> s(in.ensa_dof);
apf::Field* f = m->findField("solution");
apf::MeshIterator* it = m->begin(0);
gmi_model* gm = m->getModel();
while ((v = m->iterate(it))) {
gmi_ent* ge = (gmi_ent*)m->toModel(v);
apf::getComponents(f, v, 0, &s[0]);
apf::Vector3 x;
m->getPoint(v, 0, x);
applySolutionBCs(gm, ge, bcs, x, &s[0]);
apf::setComponents(f, v, 0, &s[0]);
}
m->end(it);
}
static void getElementGraph(Output& o)
{
if (o.in->formElementGraph) {
apf::Numbering* n = apf::numberElements(o.mesh, "ph::getElementGraph");
o.arrays.ienneigh = formIENNEIGH(n);
Links links;
getLinks(o.mesh, o.mesh->getDimension() - 1, links);
encodeILWORKF(n, links, o.nlworkf, o.arrays.ilworkf);
} else {
o.arrays.ilworkf = 0;
o.arrays.ienneigh = 0;
}
}
Output::~Output()
{
delete [] arrays.coordinates;
delete [] arrays.ilwork;
delete [] arrays.ilworkf;
delete [] arrays.iper;
delete [] arrays.globalNodeNumbers;
Blocks& ibs = blocks.interior;
for (int i = 0; i < ibs.getSize(); ++i) {
for (int j = 0; j < ibs.nElements[i]; ++j)
delete [] arrays.ien[i][j];
delete [] arrays.ien[i];
}
delete [] arrays.ien;
Blocks& bbs = blocks.boundary;
for (int i = 0; i < bbs.getSize(); ++i) {
for (int j = 0; j < bbs.nElements[i]; ++j) {
delete [] arrays.ienb[i][j];
delete [] arrays.ibcb[i][j];
delete [] arrays.bcb[i][j];
}
delete [] arrays.ienb[i];
delete [] arrays.ibcb[i];
delete [] arrays.bcb[i];
}
delete [] arrays.ienb;
delete [] arrays.ibcb;
delete [] arrays.bcb;
delete [] arrays.nbc;
delete [] arrays.ibc;
for (int i = 0; i < nEssentialBCNodes; ++i)
delete [] arrays.bc[i];
delete [] arrays.bc;
delete [] arrays.ienneigh;
}
void generateOutput(Input& in, BCs& bcs, apf::Mesh* mesh, Output& o)
{
double t0 = PCU_Time();
o.in = ∈
o.mesh = mesh;
getCounts(o);
getCoordinates(o);
getGlobal(o);
getAllBlocks(o.mesh, o.blocks);
apf::Numbering* n = apf::numberOverlapNodes(mesh, "ph_local");
getVertexLinks(o, n);
getInterior(o, n);
getBoundary(o, bcs, n);
getLocalPeriodicMasters(o, n);
apf::destroyNumbering(n);
getBoundaryElements(o);
getMaxElementNodes(o);
getEssentialBCs(bcs, o);
getInitialConditions(bcs, o);
getElementGraph(o);
if (in.initBubbles)
initBubbles(o.mesh, in);
double t1 = PCU_Time();
if (!PCU_Comm_Self())
printf("generated output structs in %f seconds\n",t1 - t0);
}
}
<commit_msg>changing Chef IC loop to use element classif.<commit_after>#include <PCU.h>
#include "phOutput.h"
#include "phLinks.h"
#include "phAdjacent.h"
#include "phBubble.h"
#include "phAxisymmetry.h"
namespace ph {
static void getCounts(Output& o)
{
for (int i = 0; i < 4; ++i)
o.nGlobalEntities[i] = apf::countOwned(o.mesh, i);
PCU_Add_Ints(o.nGlobalEntities, 4);
o.nOwnedNodes = apf::countOwned(o.mesh, 0);
o.nOverlapNodes = o.mesh->count(0);
o.nGlobalNodes = o.nGlobalEntities[0];
}
static void getCoordinates(Output& o)
{
apf::Mesh* m = o.mesh;
int n = m->count(0);
double* x = new double[n * 3];
apf::MeshEntity* v;
int i = 0;
apf::MeshIterator* it = m->begin(0);
while ((v = m->iterate(it))) {
apf::Vector3 p;
m->getPoint(v, 0, p);
for (int j = 0; j < 3; ++j)
x[j * n + i] = p[j]; /* FORTRAN indexing */
++i;
}
m->end(it);
assert(i == n);
o.arrays.coordinates = x;
}
/* so apparently old phParAdapt just used EN_id,
and the id generator from pumi would do things
like this. I guess PHASTA is ok with a unique
number for each copy, regardless of part boundary
sharing...
update: Michel says these global numbers are ignored
by phasta. get rid of them when you can.
*/
static void getGlobal(Output& o)
{
apf::Mesh* m = o.mesh;
int n = m->count(0);
int self = PCU_Comm_Self();
int peers = PCU_Comm_Peers();
int id = self + 1;
o.arrays.globalNodeNumbers = new int[n];
for (int i = 0; i < n; ++i) {
o.arrays.globalNodeNumbers[i] = id;
id += peers;
}
}
static void getVertexLinks(Output& o, apf::Numbering* n)
{
Links links;
getLinks(o.mesh, 0, links);
encodeILWORK(n, links, o.nlwork, o.arrays.ilwork);
}
static void getInterior(Output& o, apf::Numbering* n)
{
apf::Mesh* m = o.mesh;
Blocks& bs = o.blocks.interior;
int*** ien = new int**[bs.getSize()];
apf::NewArray<int> js(bs.getSize());
for (int i = 0; i < bs.getSize(); ++i) {
ien[i] = new int*[bs.nElements[i]];
js[i] = 0;
}
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(m->getDimension());
while ((e = m->iterate(it))) {
BlockKey k;
getInteriorBlockKey(m, e, k);
int nv = k.nElementVertices;
assert(bs.keyToIndex.count(k));
int i = bs.keyToIndex[k];
int j = js[i];
ien[i][j] = new int[nv];
apf::Downward v;
getVertices(m, e, v);
for (int k = 0; k < nv; ++k)
ien[i][j][k] = apf::getNumber(n, v[k], 0, 0);
++js[i];
}
m->end(it);
for (int i = 0; i < bs.getSize(); ++i)
assert(js[i] == bs.nElements[i]);
o.arrays.ien = ien;
}
static void getBoundary(Output& o, BCs& bcs, apf::Numbering* n)
{
apf::Mesh* m = o.mesh;
gmi_model* gm = m->getModel();
int nbc = countNaturalBCs(*o.in);
Blocks& bs = o.blocks.boundary;
int*** ienb = new int**[bs.getSize()];
int*** ibcb = new int**[bs.getSize()];
double*** bcb = new double**[bs.getSize()];
apf::NewArray<int> js(bs.getSize());
for (int i = 0; i < bs.getSize(); ++i) {
ienb[i] = new int*[bs.nElements[i]];
ibcb[i] = new int*[bs.nElements[i]];
bcb[i] = new double*[bs.nElements[i]];
js[i] = 0;
}
int boundaryDim = m->getDimension() - 1;
apf::MeshEntity* f;
apf::MeshIterator* it = m->begin(boundaryDim);
while ((f = m->iterate(it))) {
apf::ModelEntity* me = m->toModel(f);
if (m->getModelType(me) != boundaryDim)
continue;
gmi_ent* gf = (gmi_ent*)me;
apf::MeshEntity* e = m->getUpward(f, 0);
BlockKey k;
getBoundaryBlockKey(m, e, f, k);
assert(bs.keyToIndex.count(k));
int i = bs.keyToIndex[k];
int j = js[i];
int nv = k.nElementVertices;
apf::Downward v;
getBoundaryVertices(m, e, f, v);
ienb[i][j] = new int[nv];
for (int k = 0; k < nv; ++k)
ienb[i][j][k] = apf::getNumber(n, v[k], 0, 0);
bcb[i][j] = new double[nbc]();
ibcb[i][j] = new int[2](); /* <- parens initialize to zero */
apf::Vector3 x = apf::getLinearCentroid(m, f);
applyNaturalBCs(gm, gf, bcs, x, bcb[i][j], ibcb[i][j]);
++js[i];
}
m->end(it);
for (int i = 0; i < bs.getSize(); ++i)
assert(js[i] == bs.nElements[i]);
o.arrays.ienb = ienb;
o.arrays.ibcb = ibcb;
o.arrays.bcb = bcb;
}
static void getBoundaryElements(Output& o)
{
Blocks& bs = o.blocks.boundary;
int n = 0;
for (int i = 0; i < bs.getSize(); ++i)
n += bs.nElements[i];
o.nBoundaryElements = n;
}
static void getMaxElementNodes(Output& o)
{
int n = 0;
Blocks& ibs = o.blocks.interior;
for (int i = 0; i < ibs.getSize(); ++i)
n = std::max(n, ibs.keys[i].nElementVertices);
Blocks& bbs = o.blocks.boundary;
for (int i = 0; i < bbs.getSize(); ++i)
n = std::max(n, bbs.keys[i].nElementVertices);
o.nMaxElementNodes = n;
}
/* returns the global periodic master iff it is on this
part, otherwise returns e */
static apf::MeshEntity* getLocalPeriodicMaster(apf::MatchedSharing* sh,
apf::MeshEntity* e)
{
if ( ! sh)
return e;
apf::Copy globalMaster = sh->getOwner(e);
if (globalMaster.peer == PCU_Comm_Self())
return globalMaster.entity;
else
return e;
}
static void getLocalPeriodicMasters(Output& o, apf::Numbering* n)
{
apf::Mesh* m = o.mesh;
int* iper = new int[m->count(0)];
apf::MeshIterator* it = m->begin(0);
apf::MeshEntity* e;
apf::MatchedSharing* sh = m->hasMatching() ? new apf::MatchedSharing(m) : 0;
int i = 0;
while ((e = m->iterate(it))) {
apf::MeshEntity* master = getLocalPeriodicMaster(sh, e);
if (master == e)
iper[i] = 0;
else
iper[i] = apf::getNumber(n, master, 0, 0) + 1;
++i;
}
m->end(it);
o.arrays.iper = iper;
delete sh;
}
static bool isMatchingSlave(apf::MatchedSharing* ms, apf::MeshEntity* v)
{
if (!ms)
return false;
apf::Matches matches;
ms->mesh->getMatches(v, matches);
if (!matches.getSize())
return false;
return !ms->isOwned(v);
}
static void getEssentialBCs(BCs& bcs, Output& o)
{
Input& in = *o.in;
apf::Mesh* m = o.mesh;
apf::MeshTag* angles = 0;
apf::MatchedSharing* ms = 0;
if (m->hasMatching())
ms = new apf::MatchedSharing(m);
if (in.axisymmetry)
angles = tagAngles(m, bcs, ms);
int nv = m->count(0);
o.arrays.nbc = new int[nv];
for (int i = 0; i < nv; ++i)
o.arrays.nbc[i] = 0;
o.arrays.ibc = new int[nv]();
o.arrays.bc = new double*[nv];
o.nEssentialBCNodes = 0;
int ibc;
int nec = countEssentialBCs(in);
double* bc = new double[nec]();
gmi_model* gm = m->getModel();
int i = 0;
int& ei = o.nEssentialBCNodes;
apf::MeshEntity* v;
apf::MeshIterator* it = m->begin(0);
while ((v = m->iterate(it))) {
gmi_ent* ge = (gmi_ent*) m->toModel(v);
apf::Vector3 x;
m->getPoint(v, 0, x);
ibc = 0;
for (int j = 0; j < nec; ++j)
bc[j] = 0;
bool hasBC = applyEssentialBCs(gm, ge, bcs, x, bc, &ibc);
/* matching introduces an iper bit */
/* which is set for all slaves */
if (isMatchingSlave(ms, v)) {
hasBC = true;
ibc |= (1<<10);
/* axisymmetric theta for some slaves */
if (in.axisymmetry && m->hasTag(v, angles))
m->getDoubleTag(v, angles, &bc[11]);
}
if (hasBC) {
o.arrays.nbc[i] = ei + 1;
o.arrays.ibc[ei] = ibc;
double* bc_ei = new double[nec];
for (int j = 0; j < nec; ++j)
bc_ei[j] = bc[j];
o.arrays.bc[ei] = bc_ei;
++ei;
}
++i;
}
m->end(it);
delete [] bc;
if (in.axisymmetry)
m->destroyTag(angles);
delete ms;
}
static void getInitialConditions(BCs& bcs, Output& o)
{
Input& in = *o.in;
apf::Mesh* m = o.mesh;
apf::NewArray<double> s(in.ensa_dof);
apf::Field* f = m->findField("solution");
apf::MeshIterator* it = m->begin(3);
apf::MeshEntity* e;
gmi_model* gm = m->getModel();
while ((e = m->iterate(it))) {
gmi_ent* ge = (gmi_ent*)m->toModel(e);
apf::Downward v;
int nv = m->getDownward(e, 0, v);
for (int i = 0; i < nv; ++i) {
apf::getComponents(f, v[i], 0, &s[0]);
apf::Vector3 x;
m->getPoint(v[i], 0, x);
applySolutionBCs(gm, ge, bcs, x, &s[0]);
apf::setComponents(f, v[i], 0, &s[0]);
}
}
m->end(it);
}
static void getElementGraph(Output& o)
{
if (o.in->formElementGraph) {
apf::Numbering* n = apf::numberElements(o.mesh, "ph::getElementGraph");
o.arrays.ienneigh = formIENNEIGH(n);
Links links;
getLinks(o.mesh, o.mesh->getDimension() - 1, links);
encodeILWORKF(n, links, o.nlworkf, o.arrays.ilworkf);
} else {
o.arrays.ilworkf = 0;
o.arrays.ienneigh = 0;
}
}
Output::~Output()
{
delete [] arrays.coordinates;
delete [] arrays.ilwork;
delete [] arrays.ilworkf;
delete [] arrays.iper;
delete [] arrays.globalNodeNumbers;
Blocks& ibs = blocks.interior;
for (int i = 0; i < ibs.getSize(); ++i) {
for (int j = 0; j < ibs.nElements[i]; ++j)
delete [] arrays.ien[i][j];
delete [] arrays.ien[i];
}
delete [] arrays.ien;
Blocks& bbs = blocks.boundary;
for (int i = 0; i < bbs.getSize(); ++i) {
for (int j = 0; j < bbs.nElements[i]; ++j) {
delete [] arrays.ienb[i][j];
delete [] arrays.ibcb[i][j];
delete [] arrays.bcb[i][j];
}
delete [] arrays.ienb[i];
delete [] arrays.ibcb[i];
delete [] arrays.bcb[i];
}
delete [] arrays.ienb;
delete [] arrays.ibcb;
delete [] arrays.bcb;
delete [] arrays.nbc;
delete [] arrays.ibc;
for (int i = 0; i < nEssentialBCNodes; ++i)
delete [] arrays.bc[i];
delete [] arrays.bc;
delete [] arrays.ienneigh;
}
void generateOutput(Input& in, BCs& bcs, apf::Mesh* mesh, Output& o)
{
double t0 = PCU_Time();
o.in = ∈
o.mesh = mesh;
getCounts(o);
getCoordinates(o);
getGlobal(o);
getAllBlocks(o.mesh, o.blocks);
apf::Numbering* n = apf::numberOverlapNodes(mesh, "ph_local");
getVertexLinks(o, n);
getInterior(o, n);
getBoundary(o, bcs, n);
getLocalPeriodicMasters(o, n);
apf::destroyNumbering(n);
getBoundaryElements(o);
getMaxElementNodes(o);
getEssentialBCs(bcs, o);
getInitialConditions(bcs, o);
getElementGraph(o);
if (in.initBubbles)
initBubbles(o.mesh, in);
double t1 = PCU_Time();
if (!PCU_Comm_Self())
printf("generated output structs in %f seconds\n",t1 - t0);
}
}
<|endoftext|> |
<commit_before>#include "FlagEditor.h"
#include <iostream>
#include <locale>
FlagEditor::FlagEditor(Connector& connection, std::map<std::string, int>& local,
std::map<std::string, int>& global, sf::Vector2f availableSize,
const sf::Font& font, const sf::Texture& buttonTexture)
:conn(connection),
localFlags(local),
globalFlags(global),
rect(sf::RectangleShape(availableSize)),
fnt(font)
//scrollbox(30,30,920,660,NULL)
{
sf::Vector2f textSpawn = sf::Vector2f(50, 50);
sf::Vector2f padding = sf::Vector2f(20, 0);
rect.setPosition(0, 0);
rect.setFillColor(sf::Color(29,29,29));
//rect.setFillColor(sf::Color::Blue);
float textHeight = 0.f;
float textLength = 0.f;
clickedButton = -1;
breakTexts[LOCAL] = sf::Text("Initial Local Flags:", font, charSize);
breakTexts[GLOBAL] = sf::Text("Initial Global Flags:", font, charSize);
breakTexts[REQUIRED] = sf::Text("Required Flags:", font, charSize);
breakTexts[TRIGGERED] = sf::Text("Triggered Flags:", font, charSize);
scrollbox = ScrollableRegion(30,30,920,660,NULL);
scrollbox.setAnchor(&breakTexts[TRIGGERED]);
inStrings[0] = "";
inStrings[1] = "";
breakTexts[LOCAL].setPosition(40, 40);
for (auto i : localFlags)
{
localTexts.push_back(sf::Text(i.first, font, charSize));
localTexts.back().setPosition(textSpawn);
textHeight = localTexts.back().getGlobalBounds().height;
textLength = localTexts.back().getGlobalBounds().width;
localTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
localTexts.back().setPosition(textSpawn + padding);
localTexts.back().move(textLength, 0);
// Moving the spawn
textSpawn.y += padding.x + textHeight;
}
textSpawn.y += padding.x * 2;
breakTexts[GLOBAL].setPosition(textSpawn);
breakTexts[GLOBAL].move(-10, 0);
textHeight = breakTexts[1].getGlobalBounds().height;
textSpawn.y += padding.x + textHeight;
for (auto i : globalFlags)
{
globalTexts.push_back(sf::Text(i.first, font, charSize));
globalTexts.back().setPosition(textSpawn);
textLength = globalTexts.back().getGlobalBounds().width;
globalTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
globalTexts.back().setPosition(textSpawn + padding);
globalTexts.back().move(textLength, 0);
textSpawn.y += padding.x + textHeight;
}
textSpawn.y += padding.x * 2;
breakTexts[REQUIRED].setPosition(textSpawn);
breakTexts[REQUIRED].move(-10, 0);
textHeight = breakTexts[2].getGlobalBounds().height;
textSpawn.y += padding.x + textHeight;
for (auto i : conn.getFlags())
{
requiredTexts.push_back(sf::Text(i.first, font, charSize));
requiredTexts.back().setPosition(textSpawn);
textLength = requiredTexts.back().getGlobalBounds().width;
requiredTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
requiredTexts.back().setPosition(textSpawn + padding);
requiredTexts.back().move(textLength, 0);
textSpawn.y += padding.x + textHeight;
}
breakTexts[TRIGGERED].setPosition(textSpawn);
breakTexts[TRIGGERED].move(-10, 0);
textHeight = breakTexts[3].getGlobalBounds().height;
textSpawn.y += padding.x + textHeight;
for (auto i : conn.getTriggers())
{
triggeredTexts.push_back(sf::Text(i.first, font, charSize));
triggeredTexts.back().setPosition(textSpawn);
textLength = triggeredTexts.back().getGlobalBounds().width;
triggeredTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
triggeredTexts.back().setPosition(textSpawn + padding);
triggeredTexts.back().move(textLength, 0);
textSpawn.y += padding.x + textHeight;
// Updating the scrollbox anchor
scrollbox.setAnchor(&triggeredTexts.back());
}
for(int i = 0; i < 4; ++i)
scrollbox.addElement(&breakTexts[i]);
for (int i = 0; i < 4; ++i)
{
buttons[i] = new Button(buttonTexture);
buttons[i]->setPosition(breakTexts[i].getPosition());
buttons[i]->move(sf::Vector2f(500, 0));
}
}
void FlagEditor::moveTextBlock(TextBlocks block, float moveVal)
{
switch (block)
{
case LOCAL:
breakTexts[LOCAL].move(0, moveVal);
for (auto &i : localTexts)
i.move(0, moveVal);
buttons[LOCAL]->move(0, moveVal);
case GLOBAL:
breakTexts[GLOBAL].move(0, moveVal);
for (auto &i : globalTexts)
i.move(0, moveVal);
buttons[GLOBAL]->move(0, moveVal);
case REQUIRED:
breakTexts[REQUIRED].move(0, moveVal);
for (auto &i : requiredTexts)
i.move(0, moveVal);
buttons[REQUIRED]->move(0, moveVal);
case TRIGGERED:
breakTexts[TRIGGERED].move(0, moveVal);
for (auto &i : triggeredTexts)
i.move(0, moveVal);
buttons[TRIGGERED]->move(0, moveVal);
}
}
// Returns true if a button was pressed, false otherwise
bool FlagEditor::checkButtons(InputManager* inputManager)
{
clickedButton = -1;
for (int i = 0; i < 4; ++i)
{
buttons[i]->update(inputManager);
if (buttons[i]->isPressed())
clickedButton = i;
}
return (clickedButton > -1 && clickedButton <= 3);
}
void FlagEditor::incrementFlags(const sf::Vector2f& mousePos)
{
increment(mousePos, requiredTexts, conn.getFlags());
increment(mousePos, triggeredTexts, conn.getTriggers(), false);
}
void FlagEditor::decrementFlags(const sf::Vector2f& mousePos)
{
decrement(mousePos, requiredTexts, conn.getFlags());
decrement(mousePos, triggeredTexts, conn.getTriggers(), false);
//decrement(mousePos, globalTexts, globalFlags);
//decrement(mousePos, localTexts, localFlags);
}
void FlagEditor::removeFlags(const sf::Vector2f& mousePos)
{
remove(mousePos, requiredTexts, conn.getFlags());
remove(mousePos, triggeredTexts, conn.getTriggers());
remove(mousePos, globalTexts, globalFlags);
remove(mousePos, localTexts, localFlags);
}
void FlagEditor::decrement(const sf::Vector2f& mousePos, std::vector<sf::Text>& vec,
std::map<std::string, int>& map, bool set)
{
if (map.size() == 0)
return;
auto mapItr = map.begin();
int vecItr = 0;
bool found = false;
for (; vecItr < vec.size(); ++vecItr)
{
if (vec[vecItr].getGlobalBounds().contains(mousePos))
{
found = true;
break;
}
if (vecItr % 2 == 0 && vecItr != 0)
mapItr++;
}
if (found)
{
// Decrementing the flag
mapItr->second--;
if (vecItr % 2 == 0)
vecItr++;
// Updating the string
if(set)
vec[vecItr].setString(std::to_string(mapItr->second));
else
{
std::string sign = "";
if (mapItr->second > 0)
sign = "+";
vec[vecItr].setString(sign + std::to_string(mapItr->second));
}
}
}
void FlagEditor::remove(const sf::Vector2f& mousePos, std::vector<sf::Text>& vec,
std::map<std::string, int>& map)
{
int vecSel = -1;
auto mapItr = map.begin();
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i].getGlobalBounds().contains(mousePos))
{
vecSel = i;
if (i % 2 == 1) // Clicked on the value of the flag
vecSel--;
}
if (i % 2 == 0 && i != 0)
mapItr++;
}
// If there was a match
if (vecSel != -1)
{
map.erase(mapItr);
vec.erase(vec.begin() + vecSel, vec.begin() + vecSel + 2);
}
}
void FlagEditor::increment(const sf::Vector2f& mousePos, std::vector<sf::Text>& vec,
std::map<std::string, int>& map, bool set)
{
int vecSel = -1;
auto mapItr = map.begin();
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i].getGlobalBounds().contains(mousePos))
{
vecSel = i;
if (i % 2 == 0) // Clicked on the name of the flag
vecSel = i + 1;
break;
}
if (i % 2 == 0 && i != 0)
mapItr++;
}
if (vecSel != -1)
{
mapItr->second++;
if(set)
vec[vecSel].setString(std::to_string(mapItr->second));
else
{
std::string sign = "";
if (mapItr->second > 0)
sign = "+";
vec[vecSel].setString(sign + std::to_string(mapItr->second));
}
}
}
void FlagEditor::inputString(std::string str)
{
int flagVal;
if (inStrings[0] == "")
{
inStrings[0] = str;
return;
}
else
{
inStrings[1] = str;
/*std::transform(str.begin(), str.end(), str.begin(), ::tolower);
if (str == "false")
{
inStrings[1] = str;
flagVal = false;
}
else if (str == "true")
{
inStrings[1] = str;
flagVal = true;
}
else
{
inStrings[0] = "";
inStrings[1] = "";
return;
}*/
try
{
flagVal = std::stoi(inStrings[1]);
}
catch (std::exception& e)
{
inStrings[0] = "";
inStrings[1] = "";
return;
}
}
// Both inStrings populated with valid values
switch ((TextBlocks)clickedButton)
{
case REQUIRED:
addText(requiredTexts);
conn.addFlag(inStrings[0], flagVal);
break;
case TRIGGERED:
addText(triggeredTexts);
scrollbox.setAnchor(&triggeredTexts.back());
conn.addTrigger(inStrings[0], flagVal);
break;
case GLOBAL:
addText(globalTexts);
globalFlags[inStrings[0]] = flagVal;
break;
case LOCAL:
addText(localTexts);
localFlags[inStrings[0]] = flagVal;
break;
}
moveTextBlock((TextBlocks)(clickedButton + 1), 50.f);
inStrings[0] = "";
inStrings[1] = "";
}
void FlagEditor::addText(std::vector<sf::Text>& vec)
{
auto ref = breakTexts[clickedButton];
int count = vec.size();
int widthPadding = 20;
vec.push_back(sf::Text(inStrings[0], fnt, charSize));
if (count != 0)
{
vec.back().setPosition(vec[count - 2].getPosition());
vec.back().move(0, vec[count-2].getGlobalBounds().height + 20);
}
else
{
vec.back().setPosition(ref.getPosition());
vec.back().move(10, ref.getGlobalBounds().height + 20);
}
auto keyItr = vec.back();
sf::Vector2f keyTextSize(keyItr.getGlobalBounds().width, keyItr.getGlobalBounds().height);
vec.push_back(sf::Text(inStrings[1], fnt, charSize));
if (count != 0)
{
vec.back().setPosition(vec[count - 2].getPosition());
vec.back().move(0 + widthPadding + keyTextSize.x, vec[count-2].getGlobalBounds().height + 20);
}
else
{
vec.back().setPosition(ref.getPosition());
vec.back().move(10 + widthPadding + keyTextSize.x, ref.getGlobalBounds().height + 20);
}
// Adding the text to our scrollbox
scrollbox.addElement(&vec.back());
}
void FlagEditor::render(sf::RenderWindow& window)
{
window.draw(rect);
window.draw(scrollbox.getVisBounds());
for (auto i : localTexts)
window.draw(i);
for (auto i : globalTexts)
window.draw(i);
for (auto i : requiredTexts)
window.draw(i);
for (auto i : triggeredTexts)
window.draw(i);
for (auto i : breakTexts)
window.draw(i);
for (auto i : buttons)
i->draw(&window);
}
void FlagEditor::checkScroll(float delta) { scrollbox.scroll(delta); }
FlagEditor::~FlagEditor()
{
for (int i = 0; i < 4; ++i)
{
delete buttons[i];
buttons[i] = NULL;
}
}
<commit_msg>fixed small bug where newly added flag keys wern't scrolling<commit_after>#include "FlagEditor.h"
#include <iostream>
#include <locale>
FlagEditor::FlagEditor(Connector& connection, std::map<std::string, int>& local,
std::map<std::string, int>& global, sf::Vector2f availableSize,
const sf::Font& font, const sf::Texture& buttonTexture)
:conn(connection),
localFlags(local),
globalFlags(global),
rect(sf::RectangleShape(availableSize)),
fnt(font)
//scrollbox(30,30,920,660,NULL)
{
sf::Vector2f textSpawn = sf::Vector2f(50, 50);
sf::Vector2f padding = sf::Vector2f(20, 0);
rect.setPosition(0, 0);
rect.setFillColor(sf::Color(29,29,29));
//rect.setFillColor(sf::Color::Blue);
float textHeight = 0.f;
float textLength = 0.f;
clickedButton = -1;
breakTexts[LOCAL] = sf::Text("Initial Local Flags:", font, charSize);
breakTexts[GLOBAL] = sf::Text("Initial Global Flags:", font, charSize);
breakTexts[REQUIRED] = sf::Text("Required Flags:", font, charSize);
breakTexts[TRIGGERED] = sf::Text("Triggered Flags:", font, charSize);
scrollbox = ScrollableRegion(30,30,920,160,NULL);
scrollbox.setAnchor(&breakTexts[TRIGGERED]);
inStrings[0] = "";
inStrings[1] = "";
breakTexts[LOCAL].setPosition(40, 40);
for (auto i : localFlags)
{
localTexts.push_back(sf::Text(i.first, font, charSize));
localTexts.back().setPosition(textSpawn);
textHeight = localTexts.back().getGlobalBounds().height;
textLength = localTexts.back().getGlobalBounds().width;
localTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
localTexts.back().setPosition(textSpawn + padding);
localTexts.back().move(textLength, 0);
// Moving the spawn
textSpawn.y += padding.x + textHeight;
}
textSpawn.y += padding.x * 2;
breakTexts[GLOBAL].setPosition(textSpawn);
breakTexts[GLOBAL].move(-10, 0);
textHeight = breakTexts[1].getGlobalBounds().height;
textSpawn.y += padding.x + textHeight;
for (auto i : globalFlags)
{
globalTexts.push_back(sf::Text(i.first, font, charSize));
globalTexts.back().setPosition(textSpawn);
textLength = globalTexts.back().getGlobalBounds().width;
globalTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
globalTexts.back().setPosition(textSpawn + padding);
globalTexts.back().move(textLength, 0);
textSpawn.y += padding.x + textHeight;
}
textSpawn.y += padding.x * 2;
breakTexts[REQUIRED].setPosition(textSpawn);
breakTexts[REQUIRED].move(-10, 0);
textHeight = breakTexts[2].getGlobalBounds().height;
textSpawn.y += padding.x + textHeight;
for (auto i : conn.getFlags())
{
requiredTexts.push_back(sf::Text(i.first, font, charSize));
requiredTexts.back().setPosition(textSpawn);
textLength = requiredTexts.back().getGlobalBounds().width;
requiredTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
requiredTexts.back().setPosition(textSpawn + padding);
requiredTexts.back().move(textLength, 0);
textSpawn.y += padding.x + textHeight;
}
breakTexts[TRIGGERED].setPosition(textSpawn);
breakTexts[TRIGGERED].move(-10, 0);
textHeight = breakTexts[3].getGlobalBounds().height;
textSpawn.y += padding.x + textHeight;
for (auto i : conn.getTriggers())
{
triggeredTexts.push_back(sf::Text(i.first, font, charSize));
triggeredTexts.back().setPosition(textSpawn);
textLength = triggeredTexts.back().getGlobalBounds().width;
triggeredTexts.push_back(sf::Text(std::to_string(i.second), font, charSize));
triggeredTexts.back().setPosition(textSpawn + padding);
triggeredTexts.back().move(textLength, 0);
textSpawn.y += padding.x + textHeight;
// Updating the scrollbox anchor
scrollbox.setAnchor(&triggeredTexts.back());
}
for(int i = 0; i < 4; ++i)
scrollbox.addElement(&breakTexts[i]);
for (int i = 0; i < 4; ++i)
{
buttons[i] = new Button(buttonTexture);
buttons[i]->setPosition(breakTexts[i].getPosition());
buttons[i]->move(sf::Vector2f(500, 0));
}
}
void FlagEditor::moveTextBlock(TextBlocks block, float moveVal)
{
switch (block)
{
case LOCAL:
breakTexts[LOCAL].move(0, moveVal);
for (auto &i : localTexts)
i.move(0, moveVal);
buttons[LOCAL]->move(0, moveVal);
case GLOBAL:
breakTexts[GLOBAL].move(0, moveVal);
for (auto &i : globalTexts)
i.move(0, moveVal);
buttons[GLOBAL]->move(0, moveVal);
case REQUIRED:
breakTexts[REQUIRED].move(0, moveVal);
for (auto &i : requiredTexts)
i.move(0, moveVal);
buttons[REQUIRED]->move(0, moveVal);
case TRIGGERED:
breakTexts[TRIGGERED].move(0, moveVal);
for (auto &i : triggeredTexts)
i.move(0, moveVal);
buttons[TRIGGERED]->move(0, moveVal);
}
}
// Returns true if a button was pressed, false otherwise
bool FlagEditor::checkButtons(InputManager* inputManager)
{
clickedButton = -1;
for (int i = 0; i < 4; ++i)
{
buttons[i]->update(inputManager);
if (buttons[i]->isPressed())
clickedButton = i;
}
return (clickedButton > -1 && clickedButton <= 3);
}
void FlagEditor::incrementFlags(const sf::Vector2f& mousePos)
{
increment(mousePos, requiredTexts, conn.getFlags());
increment(mousePos, triggeredTexts, conn.getTriggers(), false);
}
void FlagEditor::decrementFlags(const sf::Vector2f& mousePos)
{
decrement(mousePos, requiredTexts, conn.getFlags());
decrement(mousePos, triggeredTexts, conn.getTriggers(), false);
//decrement(mousePos, globalTexts, globalFlags);
//decrement(mousePos, localTexts, localFlags);
}
void FlagEditor::removeFlags(const sf::Vector2f& mousePos)
{
remove(mousePos, requiredTexts, conn.getFlags());
remove(mousePos, triggeredTexts, conn.getTriggers());
remove(mousePos, globalTexts, globalFlags);
remove(mousePos, localTexts, localFlags);
}
void FlagEditor::decrement(const sf::Vector2f& mousePos, std::vector<sf::Text>& vec,
std::map<std::string, int>& map, bool set)
{
if (map.size() == 0)
return;
auto mapItr = map.begin();
int vecItr = 0;
bool found = false;
for (; vecItr < vec.size(); ++vecItr)
{
if (vec[vecItr].getGlobalBounds().contains(mousePos))
{
found = true;
break;
}
if (vecItr % 2 == 0 && vecItr != 0)
mapItr++;
}
if (found)
{
// Decrementing the flag
mapItr->second--;
if (vecItr % 2 == 0)
vecItr++;
// Updating the string
if(set)
vec[vecItr].setString(std::to_string(mapItr->second));
else
{
std::string sign = "";
if (mapItr->second > 0)
sign = "+";
vec[vecItr].setString(sign + std::to_string(mapItr->second));
}
}
}
void FlagEditor::remove(const sf::Vector2f& mousePos, std::vector<sf::Text>& vec,
std::map<std::string, int>& map)
{
int vecSel = -1;
auto mapItr = map.begin();
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i].getGlobalBounds().contains(mousePos))
{
vecSel = i;
if (i % 2 == 1) // Clicked on the value of the flag
vecSel--;
}
if (i % 2 == 0 && i != 0)
mapItr++;
}
// If there was a match
if (vecSel != -1)
{
map.erase(mapItr);
vec.erase(vec.begin() + vecSel, vec.begin() + vecSel + 2);
}
}
void FlagEditor::increment(const sf::Vector2f& mousePos, std::vector<sf::Text>& vec,
std::map<std::string, int>& map, bool set)
{
int vecSel = -1;
auto mapItr = map.begin();
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i].getGlobalBounds().contains(mousePos))
{
vecSel = i;
if (i % 2 == 0) // Clicked on the name of the flag
vecSel = i + 1;
break;
}
if (i % 2 == 0 && i != 0)
mapItr++;
}
if (vecSel != -1)
{
mapItr->second++;
if(set)
vec[vecSel].setString(std::to_string(mapItr->second));
else
{
std::string sign = "";
if (mapItr->second > 0)
sign = "+";
vec[vecSel].setString(sign + std::to_string(mapItr->second));
}
}
}
void FlagEditor::inputString(std::string str)
{
int flagVal;
if (inStrings[0] == "")
{
inStrings[0] = str;
return;
}
else
{
inStrings[1] = str;
/*std::transform(str.begin(), str.end(), str.begin(), ::tolower);
if (str == "false")
{
inStrings[1] = str;
flagVal = false;
}
else if (str == "true")
{
inStrings[1] = str;
flagVal = true;
}
else
{
inStrings[0] = "";
inStrings[1] = "";
return;
}*/
try
{
flagVal = std::stoi(inStrings[1]);
}
catch (std::exception& e)
{
inStrings[0] = "";
inStrings[1] = "";
return;
}
}
// Both inStrings populated with valid values
switch ((TextBlocks)clickedButton)
{
case REQUIRED:
addText(requiredTexts);
conn.addFlag(inStrings[0], flagVal);
break;
case TRIGGERED:
addText(triggeredTexts);
scrollbox.setAnchor(&triggeredTexts.back());
conn.addTrigger(inStrings[0], flagVal);
break;
case GLOBAL:
addText(globalTexts);
globalFlags[inStrings[0]] = flagVal;
break;
case LOCAL:
addText(localTexts);
localFlags[inStrings[0]] = flagVal;
break;
}
moveTextBlock((TextBlocks)(clickedButton + 1), 50.f);
inStrings[0] = "";
inStrings[1] = "";
}
void FlagEditor::addText(std::vector<sf::Text>& vec)
{
auto ref = breakTexts[clickedButton];
int count = vec.size();
int widthPadding = 20;
vec.push_back(sf::Text(inStrings[0], fnt, charSize));
if (count != 0)
{
vec.back().setPosition(vec[count - 2].getPosition());
vec.back().move(0, vec[count-2].getGlobalBounds().height + 20);
}
else
{
vec.back().setPosition(ref.getPosition());
vec.back().move(10, ref.getGlobalBounds().height + 20);
}
auto keyItr = vec.back();
sf::Vector2f keyTextSize(keyItr.getGlobalBounds().width, keyItr.getGlobalBounds().height);
vec.push_back(sf::Text(inStrings[1], fnt, charSize));
if (count != 0)
{
vec.back().setPosition(vec[count - 2].getPosition());
vec.back().move(0 + widthPadding + keyTextSize.x, vec[count-2].getGlobalBounds().height + 20);
}
else
{
vec.back().setPosition(ref.getPosition());
vec.back().move(10 + widthPadding + keyTextSize.x, ref.getGlobalBounds().height + 20);
}
// Adding the text to our scrollbox
scrollbox.addElement(&vec.back());
scrollbox.addElement(&vec.back() - 1);
}
void FlagEditor::render(sf::RenderWindow& window)
{
window.draw(rect);
window.draw(scrollbox.getVisBounds());
for (auto i : localTexts)
window.draw(i);
for (auto i : globalTexts)
window.draw(i);
for (auto i : requiredTexts)
window.draw(i);
for (auto i : triggeredTexts)
window.draw(i);
for (auto i : breakTexts)
window.draw(i);
for (auto i : buttons)
i->draw(&window);
}
void FlagEditor::checkScroll(float delta) { scrollbox.scroll(delta); }
FlagEditor::~FlagEditor()
{
for (int i = 0; i < 4; ++i)
{
delete buttons[i];
buttons[i] = NULL;
}
}
<|endoftext|> |
<commit_before><commit_msg>Removed extra printout.<commit_after><|endoftext|> |
<commit_before>/*
* author: Max Kellermann <[email protected]>
*/
#ifndef SIGNAL_EVENT_HXX
#define SIGNAL_EVENT_HXX
#include "Event.hxx"
#include "util/BindMethod.hxx"
class SignalEvent {
Event event;
typedef BoundMethod<void(int)> Callback;
Callback callback;
public:
SignalEvent(EventLoop &loop, int sig, Callback _callback)
:event(loop, sig, EV_SIGNAL|EV_PERSIST, SignalCallback, this),
callback(_callback) {}
void Add(const struct timeval *timeout=nullptr) {
event.Add(timeout);
}
void Delete() {
event.Delete();
}
private:
static void SignalCallback(evutil_socket_t fd, short events, void *ctx);
};
#endif
<commit_msg>event/SignalEvent: make the callback const<commit_after>/*
* author: Max Kellermann <[email protected]>
*/
#ifndef SIGNAL_EVENT_HXX
#define SIGNAL_EVENT_HXX
#include "Event.hxx"
#include "util/BindMethod.hxx"
class SignalEvent {
Event event;
typedef BoundMethod<void(int)> Callback;
const Callback callback;
public:
SignalEvent(EventLoop &loop, int sig, Callback _callback)
:event(loop, sig, EV_SIGNAL|EV_PERSIST, SignalCallback, this),
callback(_callback) {}
void Add(const struct timeval *timeout=nullptr) {
event.Add(timeout);
}
void Delete() {
event.Delete();
}
private:
static void SignalCallback(evutil_socket_t fd, short events, void *ctx);
};
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QColorDialog>
#include <QDebug>
#include <QIcon>
#include <QPainter>
#include <QPixmap>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>
// CTK includes
#include "ctkColorDialog.h"
#include "ctkColorPickerButton.h"
class ctkColorPickerButtonPrivate
{
Q_DECLARE_PUBLIC(ctkColorPickerButton);
protected:
ctkColorPickerButton* const q_ptr;
public:
ctkColorPickerButtonPrivate(ctkColorPickerButton& object);
void init();
void computeIcon();
QString text()const;
QIcon Icon;
QColor Color;
QString ColorName;
bool DisplayColorName;
ctkColorPickerButton::ColorDialogOptions DialogOptions;
mutable QSize CachedSizeHint;
};
//-----------------------------------------------------------------------------
ctkColorPickerButtonPrivate::ctkColorPickerButtonPrivate(ctkColorPickerButton& object)
: q_ptr(&object)
{
this->Color = Qt::black;
this->ColorName = QString();
this->DisplayColorName = true;
this->DialogOptions = 0;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::init()
{
Q_Q(ctkColorPickerButton);
q->setCheckable(true);
QObject::connect(q, SIGNAL(toggled(bool)),
q, SLOT(onToggled(bool)));
this->computeIcon();
}
//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::computeIcon()
{
Q_Q(ctkColorPickerButton);
int _iconSize = q->style()->pixelMetric(QStyle::PM_SmallIconSize);
QPixmap pix(_iconSize, _iconSize);
pix.fill(this->Color.isValid() ?
q->palette().button().color() : Qt::transparent);
QPainter p(&pix);
p.setPen(QPen(Qt::gray));
p.setBrush(this->Color.isValid() ?
this->Color : QBrush(Qt::NoBrush));
p.drawRect(2, 2, pix.width() - 5, pix.height() - 5);
this->Icon = QIcon(pix);
}
//-----------------------------------------------------------------------------
QString ctkColorPickerButtonPrivate::text()const
{
Q_Q(const ctkColorPickerButton);
if (!this->DisplayColorName)
{
return q->text();
}
if (this->ColorName.isEmpty())
{
return this->Color.name();
}
else
{
return this->ColorName;
}
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(QWidget* _parent)
: QPushButton(_parent)
, d_ptr(new ctkColorPickerButtonPrivate(*this))
{
Q_D(ctkColorPickerButton);
d->init();
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QString& _text, QWidget* _parent)
: QPushButton(_text, _parent)
, d_ptr(new ctkColorPickerButtonPrivate(*this))
{
Q_D(ctkColorPickerButton);
d->init();
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QColor& _color,
const QString& _text,
QWidget* _parent)
: QPushButton(_text, _parent)
, d_ptr(new ctkColorPickerButtonPrivate(*this))
{
Q_D(ctkColorPickerButton);
d->init();
this->setColor(_color);
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::~ctkColorPickerButton()
{
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::changeColor()
{
Q_D(ctkColorPickerButton);
QColor newColor;
QString newColorName;
QColorDialog::ColorDialogOptions options;
options |= QColorDialog::ColorDialogOption(
static_cast<int>(d->DialogOptions & ShowAlphaChannel));
options |= QColorDialog::ColorDialogOption(
static_cast<int>(d->DialogOptions & NoButtons));
options |= QColorDialog::ColorDialogOption(
static_cast<int>(d->DialogOptions & DontUseNativeDialog));
if (d->DialogOptions & UseCTKColorDialog)
{
newColor = ctkColorDialog::getColor(d->Color, this, QString(""),options);
newColorName = ctkColorDialog::getColorName();
}
else
{
newColor = QColorDialog::getColor(d->Color, this, QString(""), options);
}
if (newColor.isValid())
{
this->setColor(newColor);
this->setColorName(newColorName);
}
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::onToggled(bool change)
{
if (change)
{
this->changeColor();
this->setChecked(false);
}
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDisplayColorName(bool displayColorName)
{
Q_D(ctkColorPickerButton);
d->DisplayColorName = displayColorName;
d->CachedSizeHint = QSize();
this->update();
this->updateGeometry();
}
//-----------------------------------------------------------------------------
bool ctkColorPickerButton::displayColorName()const
{
Q_D(const ctkColorPickerButton);
return d->DisplayColorName;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDialogOptions(const ColorDialogOptions& options)
{
Q_D(ctkColorPickerButton);
d->DialogOptions = options;
}
//-----------------------------------------------------------------------------
const ctkColorPickerButton::ColorDialogOptions& ctkColorPickerButton::dialogOptions()const
{
Q_D(const ctkColorPickerButton);
return d->DialogOptions;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setColor(const QColor& newColor)
{
Q_D(ctkColorPickerButton);
if (newColor == d->Color)
{
return;
}
d->Color = newColor;
d->computeIcon();
this->update();
emit colorChanged(d->Color);
}
//-----------------------------------------------------------------------------
QColor ctkColorPickerButton::color()const
{
Q_D(const ctkColorPickerButton);
return d->Color;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setColorName(const QString& newColorName)
{
Q_D(ctkColorPickerButton);
if (newColorName == d->ColorName)
{
return;
}
d->ColorName = newColorName;
d->CachedSizeHint = QSize();
this->update();
this->updateGeometry();
emit colorNameChanged(d->ColorName);
}
//-----------------------------------------------------------------------------
QString ctkColorPickerButton::colorName()const
{
Q_D(const ctkColorPickerButton);
return d->ColorName;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::paintEvent(QPaintEvent *)
{
Q_D(ctkColorPickerButton);
QStylePainter p(this);
QStyleOptionButton option;
this->initStyleOption(&option);
option.text = d->text();
option.icon = d->Icon;
p.drawControl(QStyle::CE_PushButton, option);
}
//-----------------------------------------------------------------------------
QSize ctkColorPickerButton::sizeHint()const
{
Q_D(const ctkColorPickerButton);
if (!d->DisplayColorName && !this->text().isEmpty())
{
return this->QPushButton::sizeHint();
}
if (d->CachedSizeHint.isValid())
{
return d->CachedSizeHint;
}
// If no text, the sizehint is a QToolButton sizeHint
QStyleOptionButton pushButtonOpt;
this->initStyleOption(&pushButtonOpt);
pushButtonOpt.text = d->text();
int iconSize = this->style()->pixelMetric(QStyle::PM_SmallIconSize);
if (pushButtonOpt.text == QString())
{
QStyleOptionToolButton opt;
(&opt)->QStyleOption::operator=(pushButtonOpt);
opt.arrowType = Qt::NoArrow;
opt.icon = d->Icon;
opt.iconSize = QSize(iconSize, iconSize);
opt.rect.setSize(opt.iconSize); // PM_MenuButtonIndicator depends on the height
d->CachedSizeHint = this->style()->sizeFromContents(
QStyle::CT_ToolButton, &opt, opt.iconSize, this).
expandedTo(QApplication::globalStrut());
}
else
{
pushButtonOpt.icon = d->Icon;
pushButtonOpt.iconSize = QSize(iconSize, iconSize);
pushButtonOpt.rect.setSize(pushButtonOpt.iconSize); // PM_MenuButtonIndicator depends on the height
d->CachedSizeHint = (style()->sizeFromContents(
QStyle::CT_PushButton, &pushButtonOpt, pushButtonOpt.iconSize, this).
expandedTo(QApplication::globalStrut()));
}
return d->CachedSizeHint;
}
<commit_msg>COMP: Fix QFlags deprecation warnings related to ctkColorPickerButton::ColorDialogOptions<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QColorDialog>
#include <QDebug>
#include <QIcon>
#include <QPainter>
#include <QPixmap>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>
// CTK includes
#include "ctkColorDialog.h"
#include "ctkColorPickerButton.h"
class ctkColorPickerButtonPrivate
{
Q_DECLARE_PUBLIC(ctkColorPickerButton);
protected:
ctkColorPickerButton* const q_ptr;
public:
ctkColorPickerButtonPrivate(ctkColorPickerButton& object);
void init();
void computeIcon();
QString text()const;
QIcon Icon;
QColor Color;
QString ColorName;
bool DisplayColorName;
ctkColorPickerButton::ColorDialogOptions DialogOptions;
mutable QSize CachedSizeHint;
};
//-----------------------------------------------------------------------------
ctkColorPickerButtonPrivate::ctkColorPickerButtonPrivate(ctkColorPickerButton& object)
: q_ptr(&object)
{
this->Color = Qt::black;
this->ColorName = QString();
this->DisplayColorName = true;
this->DialogOptions = ctkColorPickerButton::ColorDialogOptions();
}
//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::init()
{
Q_Q(ctkColorPickerButton);
q->setCheckable(true);
QObject::connect(q, SIGNAL(toggled(bool)),
q, SLOT(onToggled(bool)));
this->computeIcon();
}
//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::computeIcon()
{
Q_Q(ctkColorPickerButton);
int _iconSize = q->style()->pixelMetric(QStyle::PM_SmallIconSize);
QPixmap pix(_iconSize, _iconSize);
pix.fill(this->Color.isValid() ?
q->palette().button().color() : Qt::transparent);
QPainter p(&pix);
p.setPen(QPen(Qt::gray));
p.setBrush(this->Color.isValid() ?
this->Color : QBrush(Qt::NoBrush));
p.drawRect(2, 2, pix.width() - 5, pix.height() - 5);
this->Icon = QIcon(pix);
}
//-----------------------------------------------------------------------------
QString ctkColorPickerButtonPrivate::text()const
{
Q_Q(const ctkColorPickerButton);
if (!this->DisplayColorName)
{
return q->text();
}
if (this->ColorName.isEmpty())
{
return this->Color.name();
}
else
{
return this->ColorName;
}
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(QWidget* _parent)
: QPushButton(_parent)
, d_ptr(new ctkColorPickerButtonPrivate(*this))
{
Q_D(ctkColorPickerButton);
d->init();
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QString& _text, QWidget* _parent)
: QPushButton(_text, _parent)
, d_ptr(new ctkColorPickerButtonPrivate(*this))
{
Q_D(ctkColorPickerButton);
d->init();
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QColor& _color,
const QString& _text,
QWidget* _parent)
: QPushButton(_text, _parent)
, d_ptr(new ctkColorPickerButtonPrivate(*this))
{
Q_D(ctkColorPickerButton);
d->init();
this->setColor(_color);
}
//-----------------------------------------------------------------------------
ctkColorPickerButton::~ctkColorPickerButton()
{
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::changeColor()
{
Q_D(ctkColorPickerButton);
QColor newColor;
QString newColorName;
QColorDialog::ColorDialogOptions options;
options |= QColorDialog::ColorDialogOption(
static_cast<int>(d->DialogOptions & ShowAlphaChannel));
options |= QColorDialog::ColorDialogOption(
static_cast<int>(d->DialogOptions & NoButtons));
options |= QColorDialog::ColorDialogOption(
static_cast<int>(d->DialogOptions & DontUseNativeDialog));
if (d->DialogOptions & UseCTKColorDialog)
{
newColor = ctkColorDialog::getColor(d->Color, this, QString(""),options);
newColorName = ctkColorDialog::getColorName();
}
else
{
newColor = QColorDialog::getColor(d->Color, this, QString(""), options);
}
if (newColor.isValid())
{
this->setColor(newColor);
this->setColorName(newColorName);
}
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::onToggled(bool change)
{
if (change)
{
this->changeColor();
this->setChecked(false);
}
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDisplayColorName(bool displayColorName)
{
Q_D(ctkColorPickerButton);
d->DisplayColorName = displayColorName;
d->CachedSizeHint = QSize();
this->update();
this->updateGeometry();
}
//-----------------------------------------------------------------------------
bool ctkColorPickerButton::displayColorName()const
{
Q_D(const ctkColorPickerButton);
return d->DisplayColorName;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDialogOptions(const ColorDialogOptions& options)
{
Q_D(ctkColorPickerButton);
d->DialogOptions = options;
}
//-----------------------------------------------------------------------------
const ctkColorPickerButton::ColorDialogOptions& ctkColorPickerButton::dialogOptions()const
{
Q_D(const ctkColorPickerButton);
return d->DialogOptions;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setColor(const QColor& newColor)
{
Q_D(ctkColorPickerButton);
if (newColor == d->Color)
{
return;
}
d->Color = newColor;
d->computeIcon();
this->update();
emit colorChanged(d->Color);
}
//-----------------------------------------------------------------------------
QColor ctkColorPickerButton::color()const
{
Q_D(const ctkColorPickerButton);
return d->Color;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::setColorName(const QString& newColorName)
{
Q_D(ctkColorPickerButton);
if (newColorName == d->ColorName)
{
return;
}
d->ColorName = newColorName;
d->CachedSizeHint = QSize();
this->update();
this->updateGeometry();
emit colorNameChanged(d->ColorName);
}
//-----------------------------------------------------------------------------
QString ctkColorPickerButton::colorName()const
{
Q_D(const ctkColorPickerButton);
return d->ColorName;
}
//-----------------------------------------------------------------------------
void ctkColorPickerButton::paintEvent(QPaintEvent *)
{
Q_D(ctkColorPickerButton);
QStylePainter p(this);
QStyleOptionButton option;
this->initStyleOption(&option);
option.text = d->text();
option.icon = d->Icon;
p.drawControl(QStyle::CE_PushButton, option);
}
//-----------------------------------------------------------------------------
QSize ctkColorPickerButton::sizeHint()const
{
Q_D(const ctkColorPickerButton);
if (!d->DisplayColorName && !this->text().isEmpty())
{
return this->QPushButton::sizeHint();
}
if (d->CachedSizeHint.isValid())
{
return d->CachedSizeHint;
}
// If no text, the sizehint is a QToolButton sizeHint
QStyleOptionButton pushButtonOpt;
this->initStyleOption(&pushButtonOpt);
pushButtonOpt.text = d->text();
int iconSize = this->style()->pixelMetric(QStyle::PM_SmallIconSize);
if (pushButtonOpt.text == QString())
{
QStyleOptionToolButton opt;
(&opt)->QStyleOption::operator=(pushButtonOpt);
opt.arrowType = Qt::NoArrow;
opt.icon = d->Icon;
opt.iconSize = QSize(iconSize, iconSize);
opt.rect.setSize(opt.iconSize); // PM_MenuButtonIndicator depends on the height
d->CachedSizeHint = this->style()->sizeFromContents(
QStyle::CT_ToolButton, &opt, opt.iconSize, this).
expandedTo(QApplication::globalStrut());
}
else
{
pushButtonOpt.icon = d->Icon;
pushButtonOpt.iconSize = QSize(iconSize, iconSize);
pushButtonOpt.rect.setSize(pushButtonOpt.iconSize); // PM_MenuButtonIndicator depends on the height
d->CachedSizeHint = (style()->sizeFromContents(
QStyle::CT_PushButton, &pushButtonOpt, pushButtonOpt.iconSize, this).
expandedTo(QApplication::globalStrut()));
}
return d->CachedSizeHint;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#if ENABLE(WEB_AUDIO)
#include "modules/webaudio/ConvolverNode.h"
#include "core/platform/audio/Reverb.h"
#include "modules/webaudio/AudioBuffer.h"
#include "modules/webaudio/AudioContext.h"
#include "modules/webaudio/AudioNodeInput.h"
#include "modules/webaudio/AudioNodeOutput.h"
#include "wtf/MainThread.h"
// Note about empirical tuning:
// The maximum FFT size affects reverb performance and accuracy.
// If the reverb is single-threaded and processes entirely in the real-time audio thread,
// it's important not to make this too high. In this case 8192 is a good value.
// But, the Reverb object is multi-threaded, so we want this as high as possible without losing too much accuracy.
// Very large FFTs will have worse phase errors. Given these constraints 32768 is a good compromise.
const size_t MaxFFTSize = 32768;
namespace WebCore {
ConvolverNode::ConvolverNode(AudioContext* context, float sampleRate)
: AudioNode(context, sampleRate)
, m_normalize(true)
{
ScriptWrappable::init(this);
addInput(adoptPtr(new AudioNodeInput(this)));
addOutput(adoptPtr(new AudioNodeOutput(this, 2)));
// Node-specific default mixing rules.
m_channelCount = 2;
m_channelCountMode = ClampedMax;
m_channelInterpretation = AudioBus::Speakers;
setNodeType(NodeTypeConvolver);
initialize();
}
ConvolverNode::~ConvolverNode()
{
uninitialize();
}
void ConvolverNode::process(size_t framesToProcess)
{
AudioBus* outputBus = output(0)->bus();
ASSERT(outputBus);
// Synchronize with possible dynamic changes to the impulse response.
MutexTryLocker tryLocker(m_processLock);
if (tryLocker.locked()) {
if (!isInitialized() || !m_reverb.get())
outputBus->zero();
else {
// Process using the convolution engine.
// Note that we can handle the case where nothing is connected to the input, in which case we'll just feed silence into the convolver.
// FIXME: If we wanted to get fancy we could try to factor in the 'tail time' and stop processing once the tail dies down if
// we keep getting fed silence.
m_reverb->process(input(0)->bus(), outputBus, framesToProcess);
}
} else {
// Too bad - the tryLock() failed. We must be in the middle of setting a new impulse response.
outputBus->zero();
}
}
void ConvolverNode::reset()
{
MutexLocker locker(m_processLock);
if (m_reverb.get())
m_reverb->reset();
}
void ConvolverNode::initialize()
{
if (isInitialized())
return;
AudioNode::initialize();
}
void ConvolverNode::uninitialize()
{
if (!isInitialized())
return;
m_reverb.clear();
AudioNode::uninitialize();
}
void ConvolverNode::setBuffer(AudioBuffer* buffer)
{
ASSERT(isMainThread());
if (!buffer)
return;
unsigned numberOfChannels = buffer->numberOfChannels();
size_t bufferLength = buffer->length();
// The current implementation supports up to four channel impulse responses, which are interpreted as true-stereo (see Reverb class).
bool isBufferGood = numberOfChannels > 0 && numberOfChannels <= 4 && bufferLength;
ASSERT(isBufferGood);
if (!isBufferGood)
return;
// Wrap the AudioBuffer by an AudioBus. It's an efficient pointer set and not a memcpy().
// This memory is simply used in the Reverb constructor and no reference to it is kept for later use in that class.
RefPtr<AudioBus> bufferBus = AudioBus::create(numberOfChannels, bufferLength, false);
for (unsigned i = 0; i < numberOfChannels; ++i)
bufferBus->setChannelMemory(i, buffer->getChannelData(i)->data(), bufferLength);
bufferBus->setSampleRate(buffer->sampleRate());
// Create the reverb with the given impulse response.
bool useBackgroundThreads = !context()->isOfflineContext();
OwnPtr<Reverb> reverb = adoptPtr(new Reverb(bufferBus.get(), AudioNode::ProcessingSizeInFrames, MaxFFTSize, 2, useBackgroundThreads, m_normalize));
{
// Synchronize with process().
MutexLocker locker(m_processLock);
m_reverb = reverb.release();
m_buffer = buffer;
}
}
AudioBuffer* ConvolverNode::buffer()
{
ASSERT(isMainThread());
return m_buffer.get();
}
double ConvolverNode::tailTime() const
{
return m_reverb ? m_reverb->impulseResponseLength() / static_cast<double>(sampleRate()) : 0;
}
double ConvolverNode::latencyTime() const
{
return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0;
}
} // namespace WebCore
#endif // ENABLE(WEB_AUDIO)
<commit_msg>Fix threading races on ConvolverNode::m_reverb in ConvolverNode::tailTime()<commit_after>/*
* Copyright (C) 2010, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#if ENABLE(WEB_AUDIO)
#include "modules/webaudio/ConvolverNode.h"
#include "core/platform/audio/Reverb.h"
#include "modules/webaudio/AudioBuffer.h"
#include "modules/webaudio/AudioContext.h"
#include "modules/webaudio/AudioNodeInput.h"
#include "modules/webaudio/AudioNodeOutput.h"
#include "wtf/MainThread.h"
// Note about empirical tuning:
// The maximum FFT size affects reverb performance and accuracy.
// If the reverb is single-threaded and processes entirely in the real-time audio thread,
// it's important not to make this too high. In this case 8192 is a good value.
// But, the Reverb object is multi-threaded, so we want this as high as possible without losing too much accuracy.
// Very large FFTs will have worse phase errors. Given these constraints 32768 is a good compromise.
const size_t MaxFFTSize = 32768;
namespace WebCore {
ConvolverNode::ConvolverNode(AudioContext* context, float sampleRate)
: AudioNode(context, sampleRate)
, m_normalize(true)
{
ScriptWrappable::init(this);
addInput(adoptPtr(new AudioNodeInput(this)));
addOutput(adoptPtr(new AudioNodeOutput(this, 2)));
// Node-specific default mixing rules.
m_channelCount = 2;
m_channelCountMode = ClampedMax;
m_channelInterpretation = AudioBus::Speakers;
setNodeType(NodeTypeConvolver);
initialize();
}
ConvolverNode::~ConvolverNode()
{
uninitialize();
}
void ConvolverNode::process(size_t framesToProcess)
{
AudioBus* outputBus = output(0)->bus();
ASSERT(outputBus);
// Synchronize with possible dynamic changes to the impulse response.
MutexTryLocker tryLocker(m_processLock);
if (tryLocker.locked()) {
if (!isInitialized() || !m_reverb.get())
outputBus->zero();
else {
// Process using the convolution engine.
// Note that we can handle the case where nothing is connected to the input, in which case we'll just feed silence into the convolver.
// FIXME: If we wanted to get fancy we could try to factor in the 'tail time' and stop processing once the tail dies down if
// we keep getting fed silence.
m_reverb->process(input(0)->bus(), outputBus, framesToProcess);
}
} else {
// Too bad - the tryLock() failed. We must be in the middle of setting a new impulse response.
outputBus->zero();
}
}
void ConvolverNode::reset()
{
MutexLocker locker(m_processLock);
if (m_reverb.get())
m_reverb->reset();
}
void ConvolverNode::initialize()
{
if (isInitialized())
return;
AudioNode::initialize();
}
void ConvolverNode::uninitialize()
{
if (!isInitialized())
return;
m_reverb.clear();
AudioNode::uninitialize();
}
void ConvolverNode::setBuffer(AudioBuffer* buffer)
{
ASSERT(isMainThread());
if (!buffer)
return;
unsigned numberOfChannels = buffer->numberOfChannels();
size_t bufferLength = buffer->length();
// The current implementation supports up to four channel impulse responses, which are interpreted as true-stereo (see Reverb class).
bool isBufferGood = numberOfChannels > 0 && numberOfChannels <= 4 && bufferLength;
ASSERT(isBufferGood);
if (!isBufferGood)
return;
// Wrap the AudioBuffer by an AudioBus. It's an efficient pointer set and not a memcpy().
// This memory is simply used in the Reverb constructor and no reference to it is kept for later use in that class.
RefPtr<AudioBus> bufferBus = AudioBus::create(numberOfChannels, bufferLength, false);
for (unsigned i = 0; i < numberOfChannels; ++i)
bufferBus->setChannelMemory(i, buffer->getChannelData(i)->data(), bufferLength);
bufferBus->setSampleRate(buffer->sampleRate());
// Create the reverb with the given impulse response.
bool useBackgroundThreads = !context()->isOfflineContext();
OwnPtr<Reverb> reverb = adoptPtr(new Reverb(bufferBus.get(), AudioNode::ProcessingSizeInFrames, MaxFFTSize, 2, useBackgroundThreads, m_normalize));
{
// Synchronize with process().
MutexLocker locker(m_processLock);
m_reverb = reverb.release();
m_buffer = buffer;
}
}
AudioBuffer* ConvolverNode::buffer()
{
ASSERT(isMainThread());
return m_buffer.get();
}
double ConvolverNode::tailTime() const
{
MutexTryLocker tryLocker(m_processLock);
if (tryLocker.locked())
return m_reverb ? m_reverb->impulseResponseLength() / static_cast<double>(sampleRate()) : 0;
// Since we don't want to block the Audio Device thread, we return a large value
// instead of trying to acquire the lock.
return std::numeric_limits<double>::infinity();
}
double ConvolverNode::latencyTime() const
{
return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0;
}
} // namespace WebCore
#endif // ENABLE(WEB_AUDIO)
<|endoftext|> |
<commit_before>#ifdef _OPENMP
#include <omp.h>
#endif
#include <fftw3.h>
#ifdef INTEL_MKL_VERSION
#include "fftw3_mkl.h"
#endif
#include "common.h"
template <bool oddSize>
inline void fft_center(complexd * data, int size, int pitch){
bool flip = false;
for (int i = 0; i < size * pitch; i+=pitch) {
for (int j = 0; j < size; j++) {
if (flip) data[i+j] = complexd(-data[i+j].real(), -data[i+j].imag());
flip = !flip;
}
if (oddSize) flip = !flip;
}
}
// Very simple. Only for even sizes.
// And for even sizes fftshift and ifftshift coinside.
inline void fftshift_even(complexd * data, int size, int pitch){
complexd tmp;
int
halfsize = size / 2
, midi = halfsize * pitch
;
int i;
for (i = 0; i < midi; i+=pitch) {
for (int j = 0; j < halfsize; j++) {
tmp = data[i+midi+j+halfsize];
data[i+midi+j+halfsize] = data[i+j];
data[i+j] = tmp;
}
}
for (i = midi; i < size * pitch; i+=pitch) {
for (int j = 0; j < halfsize; j++) {
tmp = data[i-midi+j+halfsize];
data[i-midi+j+halfsize] = data[i+j];
data[i+j] = tmp;
}
}
}
#define dp reinterpret_cast<fftw_complex*>(data)
fftw_plan __fft_inplace(fftw_plan p, complexd * data, int size, int pitch){
// This does not quite work. Don't understand why yet.
// fft_center<false>(data, size, pitch);
fftshift_even(data, size, pitch);
if (p == NULL) {
fftw_iodim trans_dims[2] = {
{size, pitch, pitch}
, {size, 1, 1}
};
p = fftw_plan_guru_dft(
2, trans_dims
, 0, NULL
, dp, dp
, FFTW_FORWARD, FFTW_ESTIMATE
);
}
fftw_execute(p);
fftshift_even(data, size, pitch);
return p;
}
extern "C" {
fftw_plan fft_inplace_even(fftw_plan p, complexd * data, int size, int pitch){
return __fft_inplace(p, data, size, pitch);
}
void fftInitThreading() {
#ifdef _OPENMP
#ifdef INTEL_MKL_VERSION
// NOTE: Using Intel MKL (and threading particularly)
// could require a lot of additional setup
fftw3_mkl.number_of_user_threads = omp_get_max_threads();
#else
fftw_init_threads();
fftw_plan_with_nthreads(omp_get_max_threads());
#endif
#endif
}
}
<commit_msg>Kernel modification for previous commit.<commit_after>#ifdef _OPENMP
#include <omp.h>
#endif
#include <fftw3.h>
#ifdef INTEL_MKL_VERSION
#include "fftw3_mkl.h"
#endif
#include "common.h"
template <bool oddSize>
inline void fft_center(complexd * data, int size, int pitch){
bool flip = false;
for (int i = 0; i < size * pitch; i+=pitch) {
for (int j = 0; j < size; j++) {
if (flip) data[i+j] = complexd(-data[i+j].real(), -data[i+j].imag());
flip = !flip;
}
if (oddSize) flip = !flip;
}
}
// Very simple. Only for even sizes.
// And for even sizes fftshift and ifftshift coinside.
inline void fftshift_even(complexd * data, int size, int pitch){
complexd tmp;
int
halfsize = size / 2
, midi = halfsize * pitch
;
int i;
for (i = 0; i < midi; i+=pitch) {
for (int j = 0; j < halfsize; j++) {
tmp = data[i+midi+j+halfsize];
data[i+midi+j+halfsize] = data[i+j];
data[i+j] = tmp;
}
}
for (i = midi; i < size * pitch; i+=pitch) {
for (int j = 0; j < halfsize; j++) {
tmp = data[i-midi+j+halfsize];
data[i-midi+j+halfsize] = data[i+j];
data[i+j] = tmp;
}
}
}
#define dp reinterpret_cast<fftw_complex*>(data)
fftw_plan __fft_inplace(fftw_plan p, int sign, complexd * data, int size, int pitch){
// This does not quite work. Don't understand why yet.
// fft_center<false>(data, size, pitch);
fftshift_even(data, size, pitch);
if (p == NULL) {
fftw_iodim trans_dims[2] = {
{size, pitch, pitch}
, {size, 1, 1}
};
p = fftw_plan_guru_dft(
2, trans_dims
, 0, NULL
, dp, dp
, sign, FFTW_ESTIMATE
);
}
fftw_execute(p);
fftshift_even(data, size, pitch);
return p;
}
extern "C" {
fftw_plan fft_inplace_even(fftw_plan p, int sign, complexd * data, int size, int pitch){
return __fft_inplace(p, sign, data, size, pitch);
}
void fftInitThreading() {
#ifdef _OPENMP
#ifdef INTEL_MKL_VERSION
// NOTE: Using Intel MKL (and threading particularly)
// could require a lot of additional setup
fftw3_mkl.number_of_user_threads = omp_get_max_threads();
#else
fftw_init_threads();
fftw_plan_with_nthreads(omp_get_max_threads());
#endif
#endif
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTweetItem.h"
HTGTweetItem::HTGTweetItem(HTTweet *theTweet) : BListItem() {
this->theTweet = theTweet;
textView = NULL;
}
int HTGTweetItem::calculateSize(BView *owner) {
BFont textFont;
owner->GetFont(&textFont);
int calculatedSize = 0;
int sizeOfTextView = 0;
string tweetContent = theTweet->getText();
/*Create a testView for the text, so we can calculate the number of line breaks*/
BRect textRect(72,0, owner->Frame().right, 150);
HTGTweetTextView *calcView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,owner->Frame().right-72,100), B_NOT_RESIZABLE, B_WILL_DRAW);
calcView->setTweetId(theTweet->getId());
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(10);
calcView->SetFontAndColor(&textFont);
calcView->SetWordWrap(true);
calcView->MakeEditable(false);
calcView->SetText(theTweet->getText().c_str());
font_height height;
calcView->GetFontHeight(&height);
int lineHeight = (height.ascent + height.descent + height.leading);
sizeOfTextView = calcView->CountLines()*lineHeight;
calculatedSize = sizeOfTextView+15+15;
if(calculatedSize < 60)
calculatedSize = 60;
delete calcView;
return calculatedSize;
}
void HTGTweetItem::Update(BView *owner, const BFont* font) {
SetHeight(calculateSize(owner));
}
void HTGTweetItem::DrawItem(BView *owner, BRect frame, bool complete) {
BFont textFont;
owner->GetFont(&textFont);
/*Write screen name*/
owner->SetHighColor(100,100,100);
owner->MovePenTo(frame.left+60+4, frame.top+12);
owner->DrawString(theTweet->getScreenName().c_str());
/*Write time*/
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(theTweet->getRelativeDate().c_str())-5, frame.top+12);
owner->DrawString(theTweet->getRelativeDate().c_str());
/*Write source name*/
if(theTweet->getSourceName().length() < 25 && theTweet->getSourceName().length() > 1) {
std::string viaString = theTweet->getSourceName();
viaString.insert(0, "via ");
BFont textFont;
BFont currentFont;
owner->GetFont(&textFont);
owner->GetFont(¤tFont);
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(10);
owner->SetFont(&textFont, B_FONT_ALL);
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(viaString.c_str())-5, frame.bottom-5);
owner->DrawString(viaString.c_str());
owner->SetFont(¤tFont);
}
/*Write text*/
BRect textRect(60+4,frame.top+15, frame.right, frame.bottom-15);
if(textView == NULL) {
textView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,frame.right-60-4,frame.bottom-15), B_NOT_RESIZABLE, B_WILL_DRAW);
owner->AddChild(textView);
}
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(10);
textView->SetFontAndColor(&textFont);
textView->SetWordWrap(true);
textView->MakeEditable(false);
textView->setTweetId(theTweet->getId());
textView->SetText(theTweet->getText().c_str());
/*Draw seperator*/
owner->StrokeLine(BPoint(frame.left, frame.bottom), BPoint(frame.right, frame.bottom));
/*Draw userIcon*/
if(theTweet->isDownloadingBitmap())
theTweet->waitUntilDownloadComplete();
owner->SetDrawingMode(B_OP_ALPHA);
owner->DrawBitmapAsync(theTweet->getBitmap(), BRect(frame.left+6, frame.top+7+((Height()-60)/2), frame.left+48+6, frame.top+72-18+((Height()-60)/2)));
owner->SetDrawingMode(B_OP_OVER);
}
HTTweet* HTGTweetItem::getTweetPtr() {
return theTweet;
}
HTGTweetItem::~HTGTweetItem() {
if(textView != NULL) {
textView->RemoveSelf();
delete textView;
}
delete theTweet;
}
<commit_msg>Improved profile picture aspect-ratio and center alignment.<commit_after>/*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTweetItem.h"
HTGTweetItem::HTGTweetItem(HTTweet *theTweet) : BListItem() {
this->theTweet = theTweet;
textView = NULL;
}
int HTGTweetItem::calculateSize(BView *owner) {
BFont textFont;
owner->GetFont(&textFont);
int calculatedSize = 0;
int sizeOfTextView = 0;
string tweetContent = theTweet->getText();
/*Create a testView for the text, so we can calculate the number of line breaks*/
BRect textRect(72,0, owner->Frame().right, 150);
HTGTweetTextView *calcView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,owner->Frame().right-72,100), B_NOT_RESIZABLE, B_WILL_DRAW);
calcView->setTweetId(theTweet->getId());
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(10);
calcView->SetFontAndColor(&textFont);
calcView->SetWordWrap(true);
calcView->MakeEditable(false);
calcView->SetText(theTweet->getText().c_str());
font_height height;
calcView->GetFontHeight(&height);
int lineHeight = (height.ascent + height.descent + height.leading);
sizeOfTextView = calcView->CountLines()*lineHeight;
calculatedSize = sizeOfTextView+15+15;
if(calculatedSize < 60)
calculatedSize = 60;
delete calcView;
return calculatedSize;
}
void HTGTweetItem::Update(BView *owner, const BFont* font) {
SetHeight(calculateSize(owner));
}
void HTGTweetItem::DrawItem(BView *owner, BRect frame, bool complete) {
BFont textFont;
owner->GetFont(&textFont);
/*Write screen name*/
owner->SetHighColor(100,100,100);
owner->MovePenTo(frame.left+60+4, frame.top+12);
owner->DrawString(theTweet->getScreenName().c_str());
/*Write time*/
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(theTweet->getRelativeDate().c_str())-5, frame.top+12);
owner->DrawString(theTweet->getRelativeDate().c_str());
/*Write source name*/
if(theTweet->getSourceName().length() < 25 && theTweet->getSourceName().length() > 1) {
std::string viaString = theTweet->getSourceName();
viaString.insert(0, "via ");
BFont textFont;
BFont currentFont;
owner->GetFont(&textFont);
owner->GetFont(¤tFont);
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(10);
owner->SetFont(&textFont, B_FONT_ALL);
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(viaString.c_str())-5, frame.bottom-5);
owner->DrawString(viaString.c_str());
owner->SetFont(¤tFont);
}
/*Write text*/
BRect textRect(60+4,frame.top+15, frame.right, frame.bottom-15);
if(textView == NULL) {
textView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,frame.right-60-4,frame.bottom-15), B_NOT_RESIZABLE, B_WILL_DRAW);
owner->AddChild(textView);
}
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(10);
textView->SetFontAndColor(&textFont);
textView->SetWordWrap(true);
textView->MakeEditable(false);
textView->setTweetId(theTweet->getId());
textView->SetText(theTweet->getText().c_str());
/*Draw seperator*/
owner->StrokeLine(BPoint(frame.left, frame.bottom), BPoint(frame.right, frame.bottom));
/*Draw userIcon*/
if(theTweet->isDownloadingBitmap())
theTweet->waitUntilDownloadComplete();
owner->SetDrawingMode(B_OP_ALPHA);
owner->DrawBitmapAsync(theTweet->getBitmap(), BRect(frame.left+9, frame.top+5+((Height()-60)/2), frame.left+48+8, frame.top+72-20+((Height()-60)/2)));
owner->SetDrawingMode(B_OP_OVER);
}
HTTweet* HTGTweetItem::getTweetPtr() {
return theTweet;
}
HTGTweetItem::~HTGTweetItem() {
if(textView != NULL) {
textView->RemoveSelf();
delete textView;
}
delete theTweet;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//start watching ~/Dropbox folder contents (create, delete, move)
BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
// record each file in the folder so that we know the name on deletion
BEntry *entry = new BEntry;
status_t err2;
err = dir.GetNextEntry(entry);
while(err == B_OK) //loop over files
{
this->tracked_files.AddItem((void*)entry); //add file to my list
err2 = entry->GetNodeRef(&nref);
if(err2 == B_OK)
{
err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
if(err2 != B_OK)
printf("Watch file Node: Not OK\n");
}
entry = new BEntry;
err = dir.GetNextEntry(entry);
}
//delete that last BEntry...
}
/*
* Runs a command in the terminal, given the string you'd type
*/
int
run_script(const char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
(void) printf("RAWR%s", buf);
(void) pclose(ptr);
return 0;
}
/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
printf("Telling Dropbox to Delete\n");
BString s, dbfp;
s = BString(filepath);
s.RemoveFirst("/boot/home/Dropbox");
dbfp << "python db_rm.py " << s;
printf("%s\n",dbfp);
run_script(dbfp);
}
/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
BString s;
s = BString(local_path);
s.RemoveFirst("/boot/home/Dropbox/");
return s;
}
/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
BString s, dbfp;
dbfp = local_to_db_filepath(filepath);
s << "python db_put.py " << BString(filepath) << " " << dbfp;
printf("local filepath:%s\n",filepath);
printf("dropbox filepath:%s\n",dbfp.String());
run_script(s.String());
}
/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
BString s;
s << "python db_mkdir.py " << local_to_db_filepath(filepath);
printf("local filepath: %s\n", filepath);
printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
run_script(s.String());
}
/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
//is this file being move into or out of ~/Dropbox?
run_script("python db_ls.py");
}
/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
add_file_to_dropbox(filepath); //just put it?
}
/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
entry_ref ref;
BPath path;
const char * name;
msg->FindInt32("device",&ref.device);
msg->FindInt64("directory",&ref.directory);
msg->FindString("name",&name);
printf("name:%s\n",name);
ref.set_name(name);
BEntry new_file = BEntry(&ref);
new_file.GetPath(&path);
add_file_to_dropbox(path.Path());
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
moved_file(msg);
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
node_ref nref, cref;
msg->FindInt32("device",&nref.device);
msg->FindInt64("node",&nref.node);
BEntry *entryPtr;
int32 ktr = 0;
int32 limit = this->tracked_files.CountItems();
printf("About to loop\n");
while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++))&&(ktr<limit))
{
printf("In loop.\n");
entryPtr->GetNodeRef(&cref);
printf("GotNodeRef\n");
if(nref == cref)
{
printf("Deleting it\n");
BPath path;
entryPtr->GetPath(&path);
delete_file_on_dropbox(path.Path());
break; //break out of loop
}
}
break;
}
case B_STAT_CHANGED:
{
printf("EDITED FILE\n");
node_ref nref1,nref2;
msg->FindInt32("device",&nref1.device);
msg->FindInt64("node",&nref1.node);
BEntry * entryPtr;
int32 ktr = 0;
while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++)))
{
entryPtr->GetNodeRef(&nref2);
if(nref1 == nref2)
{
BPath path;
entryPtr->GetPath(&path);
update_file_in_dropbox(path.Path());
break;
}
}
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
main(void)
{
//set up application (watch Dropbox folder & contents)
App *app = new App();
//start the application
app->Run();
//clean up now that we're shutting down
delete app;
return 0;
}
<commit_msg>print out tracked files during initialization stage<commit_after>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//start watching ~/Dropbox folder contents (create, delete, move)
BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
// record each file in the folder so that we know the name on deletion
BEntry *entry = new BEntry;
status_t err2;
err = dir.GetNextEntry(entry);
BPath path;
while(err == B_OK) //loop over files
{
this->tracked_files.AddItem((void*)entry); //add file to my list
entry->GetPath(&path);
printf("tracking: %s\n",path.Path());
err2 = entry->GetNodeRef(&nref);
if(err2 == B_OK)
{
err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
if(err2 != B_OK)
printf("Watch file Node: Not OK\n");
}
entry = new BEntry;
err = dir.GetNextEntry(entry);
}
//delete that last BEntry...
}
/*
* Runs a command in the terminal, given the string you'd type
*/
int
run_script(const char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
(void) printf("RAWR%s", buf);
(void) pclose(ptr);
return 0;
}
/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
printf("Telling Dropbox to Delete\n");
BString s, dbfp;
s = BString(filepath);
s.RemoveFirst("/boot/home/Dropbox");
dbfp << "python db_rm.py " << s;
printf("%s\n",dbfp.String());
run_script(dbfp);
}
/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
BString s;
s = BString(local_path);
s.RemoveFirst("/boot/home/Dropbox/");
return s;
}
/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
BString s, dbfp;
dbfp = local_to_db_filepath(filepath);
s << "python db_put.py " << BString(filepath) << " " << dbfp;
printf("local filepath:%s\n",filepath);
printf("dropbox filepath:%s\n",dbfp.String());
run_script(s.String());
}
/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
BString s;
s << "python db_mkdir.py " << local_to_db_filepath(filepath);
printf("local filepath: %s\n", filepath);
printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
run_script(s.String());
}
/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
//is this file being move into or out of ~/Dropbox?
run_script("python db_ls.py");
}
/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
add_file_to_dropbox(filepath); //just put it?
}
/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
entry_ref ref;
BPath path;
const char * name;
msg->FindInt32("device",&ref.device);
msg->FindInt64("directory",&ref.directory);
msg->FindString("name",&name);
printf("name:%s\n",name);
ref.set_name(name);
BEntry new_file = BEntry(&ref);
new_file.GetPath(&path);
add_file_to_dropbox(path.Path());
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
moved_file(msg);
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
node_ref nref, cref;
msg->FindInt32("device",&nref.device);
msg->FindInt64("node",&nref.node);
BEntry *entryPtr;
int32 ktr = 0;
int32 limit = this->tracked_files.CountItems();
printf("About to loop\n");
while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++))&&(ktr<limit))
{
printf("In loop.\n");
entryPtr->GetNodeRef(&cref);
printf("GotNodeRef\n");
if(nref == cref)
{
printf("Deleting it\n");
BPath path;
entryPtr->GetPath(&path);
delete_file_on_dropbox(path.Path());
break; //break out of loop
}
}
break;
}
case B_STAT_CHANGED:
{
printf("EDITED FILE\n");
node_ref nref1,nref2;
msg->FindInt32("device",&nref1.device);
msg->FindInt64("node",&nref1.node);
BEntry * entryPtr;
int32 ktr = 0;
while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++)))
{
entryPtr->GetNodeRef(&nref2);
if(nref1 == nref2)
{
BPath path;
entryPtr->GetPath(&path);
update_file_in_dropbox(path.Path());
break;
}
}
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
main(void)
{
//set up application (watch Dropbox folder & contents)
App *app = new App();
//start the application
app->Run();
//clean up now that we're shutting down
delete app;
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2019 Denis Shienkov <[email protected]>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "stm8generalsettingsgroup_v3.h"
#include "../../iarewutils.h"
namespace qbs {
namespace iarew {
namespace stm8 {
namespace v3 {
constexpr int kGeneralArchiveVersion = 4;
constexpr int kGeneralDataVersion = 2;
namespace {
// Target page options.
struct TargetPageOptions final
{
enum CodeModel {
SmallCodeModel,
MediumCodeModel,
LargeCodeModel
};
enum DataModel {
SmallDataModel,
MediumDataModel,
LargeDataModel
};
explicit TargetPageOptions(const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = gen::utils::cppStringModuleProperties(
qbsProps, {QStringLiteral("driverFlags")});
// Detect target code model.
const QString codeModelValue = IarewUtils::flagValue(
flags, QStringLiteral("--code_model"));
if (codeModelValue == QLatin1String("small"))
codeModel = TargetPageOptions::SmallCodeModel;
else if (codeModelValue == QLatin1String("medium"))
codeModel = TargetPageOptions::MediumCodeModel;
else if (codeModelValue == QLatin1String("large"))
codeModel = TargetPageOptions::LargeCodeModel;
// Detect target data model.
const QString dataModelValue = IarewUtils::flagValue(
flags, QStringLiteral("--code_model"));
if (dataModelValue == QLatin1String("small"))
dataModel = TargetPageOptions::SmallDataModel;
else if (dataModelValue == QLatin1String("medium"))
dataModel = TargetPageOptions::MediumDataModel;
else if (dataModelValue == QLatin1String("large"))
dataModel = TargetPageOptions::LargeDataModel;
}
CodeModel codeModel = MediumCodeModel;
DataModel dataModel = MediumDataModel;
};
// Output page options.
struct OutputPageOptions final
{
explicit OutputPageOptions(const QString &baseDirectory,
const ProductData &qbsProduct)
{
binaryType = IarewUtils::outputBinaryType(qbsProduct);
binaryDirectory = gen::utils::binaryOutputDirectory(
baseDirectory, qbsProduct);
objectDirectory = gen::utils::objectsOutputDirectory(
baseDirectory, qbsProduct);
listingDirectory = gen::utils::listingOutputDirectory(
baseDirectory, qbsProduct);
}
IarewUtils::OutputBinaryType binaryType = IarewUtils::ApplicationOutputType;
QString binaryDirectory;
QString objectDirectory;
QString listingDirectory;
};
// Library configuration page options.
struct LibraryConfigPageOptions final
{
enum RuntimeLibrary {
NoLibrary,
NormalLibrary,
FullLibrary,
CustomLibrary
};
explicit LibraryConfigPageOptions(const QString &baseDirectory,
const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = IarewUtils::cppModuleCompilerFlags(qbsProps);
const QFileInfo configInfo(IarewUtils::flagValue(
flags,
QStringLiteral("--dlib_config")));
const QString configFilePath = configInfo.absoluteFilePath();
if (!configFilePath.isEmpty()) {
const QString libToolkitPath =
IarewUtils::libToolkitRootPath(qbsProduct);
if (configFilePath.startsWith(libToolkitPath,
Qt::CaseInsensitive)) {
if (configFilePath.endsWith(QLatin1String("n.h"),
Qt::CaseInsensitive)) {
libraryType = LibraryConfigPageOptions::NormalLibrary;
} else if (configFilePath.endsWith(QLatin1String("f.h"),
Qt::CaseInsensitive)) {
libraryType = LibraryConfigPageOptions::FullLibrary;
} else {
libraryType = LibraryConfigPageOptions::CustomLibrary;
}
configPath = IarewUtils::toolkitRelativeFilePath(
baseDirectory, configFilePath);
} else {
libraryType = LibraryConfigPageOptions::CustomLibrary;
configPath = configFilePath;
}
} else {
libraryType = LibraryConfigPageOptions::NoLibrary;
}
}
RuntimeLibrary libraryType = NoLibrary;
QString configPath;
};
// Library options page options.
struct LibraryOptionsPageOptions final
{
enum PrintfFormatter {
PrintfAutoFormatter = 0,
PrintfFullFormatter = 1,
PrintfFullNoMultibytesFormatter = 2,
PrintfLargeFormatter = 3,
PrintfLargeNoMultibytesFormatter = 4,
PrintfSmallFormatter = 5,
PrintfSmallNoMultibytesFormatter = 6,
PrintfTinyFormatter = 7
};
enum ScanfFormatter {
ScanfAutoFormatter = 0,
ScanfFullFormatter = 1,
ScanfFullNoMultibytesFormatter = 2,
ScanfLargeFormatter = 3,
ScanfLargeNoMultibytesFormatter = 4,
ScanfSmallFormatter = 5,
ScanfSmallNoMultibytesFormatter = 6
};
explicit LibraryOptionsPageOptions(const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = IarewUtils::cppModuleLinkerFlags(qbsProps);
for (auto flagIt = flags.cbegin(); flagIt < flags.cend(); ++flagIt) {
if (*flagIt != QLatin1String("--redirect"))
continue;
++flagIt;
if (flagIt->startsWith(QLatin1String("_printf="),
Qt::CaseInsensitive)) {
const QString prop = flagIt->split(
QLatin1Char('=')).at(1).toLower();
if (prop == QLatin1String("_printffull"))
printfFormatter = PrintfFullFormatter;
else if (prop == QLatin1String("_printffullnomb"))
printfFormatter = PrintfFullNoMultibytesFormatter;
else if (prop == QLatin1String("_printflarge"))
printfFormatter = PrintfLargeFormatter;
else if (prop == QLatin1String("_printflargenomb"))
printfFormatter = PrintfLargeFormatter;
else if (prop == QLatin1String("_printfsmall"))
printfFormatter = PrintfSmallFormatter;
else if (prop == QLatin1String("_printfsmallnomb"))
printfFormatter = PrintfSmallNoMultibytesFormatter;
else if (prop == QLatin1String("_printftiny"))
printfFormatter = PrintfTinyFormatter;
} else if (flagIt->startsWith(QLatin1String("_scanf="),
Qt::CaseInsensitive)) {
const QString prop = flagIt->split(
QLatin1Char('=')).at(1).toLower();
if (prop == QLatin1String("_scanffull"))
scanfFormatter = ScanfFullFormatter;
else if (prop == QLatin1String("_scanffullnomb"))
scanfFormatter = ScanfFullNoMultibytesFormatter;
else if (prop == QLatin1String("_scanflarge"))
scanfFormatter = ScanfLargeFormatter;
else if (prop == QLatin1String("_scanflargenomb"))
scanfFormatter = ScanfLargeFormatter;
else if (prop == QLatin1String("_scanfsmall"))
scanfFormatter = ScanfSmallFormatter;
else if (prop == QLatin1String("_scanfsmallnomb"))
scanfFormatter = ScanfSmallNoMultibytesFormatter;
}
}
}
PrintfFormatter printfFormatter = PrintfAutoFormatter;
ScanfFormatter scanfFormatter = ScanfAutoFormatter;
};
// Stack/heap page options.
struct StackHeapPageOptions final
{
explicit StackHeapPageOptions(const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = IarewUtils::cppModuleLinkerFlags(qbsProps);
const auto configDefs = IarewUtils::flagValues(
flags, QStringLiteral("--config_def"));
for (const auto &configDef : configDefs) {
const auto def = configDef.toString();
if (def.startsWith(QLatin1String("_CSTACK_SIZE="))) {
stackSize = def.split(QLatin1Char('=')).at(1);
} else if (def.startsWith(QLatin1String("_HEAP_SIZE="))) {
heapSize = def.split(QLatin1Char('=')).at(1);
}
}
}
QString stackSize;
QString heapSize;
};
} // namespace
// Stm8GeneralSettingsGroup
Stm8GeneralSettingsGroup::Stm8GeneralSettingsGroup(
const Project &qbsProject,
const ProductData &qbsProduct,
const std::vector<ProductData> &qbsProductDeps)
{
Q_UNUSED(qbsProductDeps)
setName(QByteArrayLiteral("General"));
setArchiveVersion(kGeneralArchiveVersion);
setDataVersion(kGeneralDataVersion);
setDataDebugInfo(gen::utils::debugInformation(qbsProduct));
const QString buildRootDirectory = gen::utils::buildRootPath(qbsProject);
buildTargetPage(qbsProduct);
buildOutputPage(buildRootDirectory, qbsProduct);
buildLibraryConfigPage(buildRootDirectory, qbsProduct);
buildLibraryOptionsPage(qbsProduct);
buildStackHeapPage(qbsProduct);
}
void Stm8GeneralSettingsGroup::buildTargetPage(
const ProductData &qbsProduct)
{
const TargetPageOptions opts(qbsProduct);
// Add 'GenCodeModel' item
// (Code model: small/medium/large).
addOptionsGroup(QByteArrayLiteral("GenCodeModel"),
{}, {opts.codeModel});
// Add 'GenDataModel' item
// (Data model: small/medium/large).
addOptionsGroup(QByteArrayLiteral("GenDataModel"),
{}, {opts.dataModel});
}
void Stm8GeneralSettingsGroup::buildOutputPage(
const QString &baseDirectory,
const ProductData &qbsProduct)
{
const OutputPageOptions opts(baseDirectory, qbsProduct);
// Add 'GOutputBinary' item (Output file: executable/library).
addOptionsGroup(QByteArrayLiteral("GOutputBinary"),
{}, {opts.binaryType});
// Add 'ExePath' item (Executable/binaries output directory).
addOptionsGroup(QByteArrayLiteral("ExePath"),
{}, {opts.binaryDirectory});
// Add 'ObjPath' item (Object files output directory).
addOptionsGroup(QByteArrayLiteral("ObjPath"),
{}, {opts.objectDirectory});
// Add 'ListPath' item (List files output directory).
addOptionsGroup(QByteArrayLiteral("ListPath"),
{}, {opts.listingDirectory});
}
void Stm8GeneralSettingsGroup::buildLibraryConfigPage(
const QString &baseDirectory,
const ProductData &qbsProduct)
{
const LibraryConfigPageOptions opts(baseDirectory, qbsProduct);
// Add 'GenRuntimeLibSelect' and 'GenRuntimeLibSelectSlave' items
// (Link with runtime: none/normal/full/custom).
addOptionsGroup(QByteArrayLiteral("GenRuntimeLibSelect"),
{}, {opts.libraryType});
addOptionsGroup(QByteArrayLiteral("GenRuntimeLibSelectSlave"),
{}, {opts.libraryType});
// Add 'GenRTConfigPath' item (Runtime configuration file).
addOptionsGroup(QByteArrayLiteral("GenRTConfigPath"),
{}, {opts.configPath});
}
void Stm8GeneralSettingsGroup::buildLibraryOptionsPage(
const ProductData &qbsProduct)
{
const LibraryOptionsPageOptions opts(qbsProduct);
// Add 'GenLibOutFormatter' item (Printf formatter).
addOptionsGroup(QByteArrayLiteral("GenLibOutFormatter"),
{}, {opts.printfFormatter});
// Add 'GenLibInFormatter' item (Scanf formatter).
addOptionsGroup(QByteArrayLiteral("GenLibInFormatter"),
{}, {opts.scanfFormatter});
}
void Stm8GeneralSettingsGroup::buildStackHeapPage(
const ProductData &qbsProduct)
{
const StackHeapPageOptions opts(qbsProduct);
// Add 'GenStackSize' item (Stack size).
addOptionsGroup(QByteArrayLiteral("GenStackSize"),
{}, {opts.stackSize});
// Add 'GenHeapSize' item (Heap size).
addOptionsGroup(QByteArrayLiteral("GenHeapSize"),
{}, {opts.heapSize});
}
} // namespace v3
} // namespace stm8
} // namespace iarew
} // namespace qbs
<commit_msg>baremetal: Fix typo at data model detection in IAREW STM8 generator<commit_after>/****************************************************************************
**
** Copyright (C) 2019 Denis Shienkov <[email protected]>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "stm8generalsettingsgroup_v3.h"
#include "../../iarewutils.h"
namespace qbs {
namespace iarew {
namespace stm8 {
namespace v3 {
constexpr int kGeneralArchiveVersion = 4;
constexpr int kGeneralDataVersion = 2;
namespace {
// Target page options.
struct TargetPageOptions final
{
enum CodeModel {
SmallCodeModel,
MediumCodeModel,
LargeCodeModel
};
enum DataModel {
SmallDataModel,
MediumDataModel,
LargeDataModel
};
explicit TargetPageOptions(const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = gen::utils::cppStringModuleProperties(
qbsProps, {QStringLiteral("driverFlags")});
// Detect target code model.
const QString codeModelValue = IarewUtils::flagValue(
flags, QStringLiteral("--code_model"));
if (codeModelValue == QLatin1String("small"))
codeModel = TargetPageOptions::SmallCodeModel;
else if (codeModelValue == QLatin1String("medium"))
codeModel = TargetPageOptions::MediumCodeModel;
else if (codeModelValue == QLatin1String("large"))
codeModel = TargetPageOptions::LargeCodeModel;
// Detect target data model.
const QString dataModelValue = IarewUtils::flagValue(
flags, QStringLiteral("--data_model"));
if (dataModelValue == QLatin1String("small"))
dataModel = TargetPageOptions::SmallDataModel;
else if (dataModelValue == QLatin1String("medium"))
dataModel = TargetPageOptions::MediumDataModel;
else if (dataModelValue == QLatin1String("large"))
dataModel = TargetPageOptions::LargeDataModel;
}
CodeModel codeModel = MediumCodeModel;
DataModel dataModel = MediumDataModel;
};
// Output page options.
struct OutputPageOptions final
{
explicit OutputPageOptions(const QString &baseDirectory,
const ProductData &qbsProduct)
{
binaryType = IarewUtils::outputBinaryType(qbsProduct);
binaryDirectory = gen::utils::binaryOutputDirectory(
baseDirectory, qbsProduct);
objectDirectory = gen::utils::objectsOutputDirectory(
baseDirectory, qbsProduct);
listingDirectory = gen::utils::listingOutputDirectory(
baseDirectory, qbsProduct);
}
IarewUtils::OutputBinaryType binaryType = IarewUtils::ApplicationOutputType;
QString binaryDirectory;
QString objectDirectory;
QString listingDirectory;
};
// Library configuration page options.
struct LibraryConfigPageOptions final
{
enum RuntimeLibrary {
NoLibrary,
NormalLibrary,
FullLibrary,
CustomLibrary
};
explicit LibraryConfigPageOptions(const QString &baseDirectory,
const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = IarewUtils::cppModuleCompilerFlags(qbsProps);
const QFileInfo configInfo(IarewUtils::flagValue(
flags,
QStringLiteral("--dlib_config")));
const QString configFilePath = configInfo.absoluteFilePath();
if (!configFilePath.isEmpty()) {
const QString libToolkitPath =
IarewUtils::libToolkitRootPath(qbsProduct);
if (configFilePath.startsWith(libToolkitPath,
Qt::CaseInsensitive)) {
if (configFilePath.endsWith(QLatin1String("n.h"),
Qt::CaseInsensitive)) {
libraryType = LibraryConfigPageOptions::NormalLibrary;
} else if (configFilePath.endsWith(QLatin1String("f.h"),
Qt::CaseInsensitive)) {
libraryType = LibraryConfigPageOptions::FullLibrary;
} else {
libraryType = LibraryConfigPageOptions::CustomLibrary;
}
configPath = IarewUtils::toolkitRelativeFilePath(
baseDirectory, configFilePath);
} else {
libraryType = LibraryConfigPageOptions::CustomLibrary;
configPath = configFilePath;
}
} else {
libraryType = LibraryConfigPageOptions::NoLibrary;
}
}
RuntimeLibrary libraryType = NoLibrary;
QString configPath;
};
// Library options page options.
struct LibraryOptionsPageOptions final
{
enum PrintfFormatter {
PrintfAutoFormatter = 0,
PrintfFullFormatter = 1,
PrintfFullNoMultibytesFormatter = 2,
PrintfLargeFormatter = 3,
PrintfLargeNoMultibytesFormatter = 4,
PrintfSmallFormatter = 5,
PrintfSmallNoMultibytesFormatter = 6,
PrintfTinyFormatter = 7
};
enum ScanfFormatter {
ScanfAutoFormatter = 0,
ScanfFullFormatter = 1,
ScanfFullNoMultibytesFormatter = 2,
ScanfLargeFormatter = 3,
ScanfLargeNoMultibytesFormatter = 4,
ScanfSmallFormatter = 5,
ScanfSmallNoMultibytesFormatter = 6
};
explicit LibraryOptionsPageOptions(const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = IarewUtils::cppModuleLinkerFlags(qbsProps);
for (auto flagIt = flags.cbegin(); flagIt < flags.cend(); ++flagIt) {
if (*flagIt != QLatin1String("--redirect"))
continue;
++flagIt;
if (flagIt->startsWith(QLatin1String("_printf="),
Qt::CaseInsensitive)) {
const QString prop = flagIt->split(
QLatin1Char('=')).at(1).toLower();
if (prop == QLatin1String("_printffull"))
printfFormatter = PrintfFullFormatter;
else if (prop == QLatin1String("_printffullnomb"))
printfFormatter = PrintfFullNoMultibytesFormatter;
else if (prop == QLatin1String("_printflarge"))
printfFormatter = PrintfLargeFormatter;
else if (prop == QLatin1String("_printflargenomb"))
printfFormatter = PrintfLargeFormatter;
else if (prop == QLatin1String("_printfsmall"))
printfFormatter = PrintfSmallFormatter;
else if (prop == QLatin1String("_printfsmallnomb"))
printfFormatter = PrintfSmallNoMultibytesFormatter;
else if (prop == QLatin1String("_printftiny"))
printfFormatter = PrintfTinyFormatter;
} else if (flagIt->startsWith(QLatin1String("_scanf="),
Qt::CaseInsensitive)) {
const QString prop = flagIt->split(
QLatin1Char('=')).at(1).toLower();
if (prop == QLatin1String("_scanffull"))
scanfFormatter = ScanfFullFormatter;
else if (prop == QLatin1String("_scanffullnomb"))
scanfFormatter = ScanfFullNoMultibytesFormatter;
else if (prop == QLatin1String("_scanflarge"))
scanfFormatter = ScanfLargeFormatter;
else if (prop == QLatin1String("_scanflargenomb"))
scanfFormatter = ScanfLargeFormatter;
else if (prop == QLatin1String("_scanfsmall"))
scanfFormatter = ScanfSmallFormatter;
else if (prop == QLatin1String("_scanfsmallnomb"))
scanfFormatter = ScanfSmallNoMultibytesFormatter;
}
}
}
PrintfFormatter printfFormatter = PrintfAutoFormatter;
ScanfFormatter scanfFormatter = ScanfAutoFormatter;
};
// Stack/heap page options.
struct StackHeapPageOptions final
{
explicit StackHeapPageOptions(const ProductData &qbsProduct)
{
const auto &qbsProps = qbsProduct.moduleProperties();
const QStringList flags = IarewUtils::cppModuleLinkerFlags(qbsProps);
const auto configDefs = IarewUtils::flagValues(
flags, QStringLiteral("--config_def"));
for (const auto &configDef : configDefs) {
const auto def = configDef.toString();
if (def.startsWith(QLatin1String("_CSTACK_SIZE="))) {
stackSize = def.split(QLatin1Char('=')).at(1);
} else if (def.startsWith(QLatin1String("_HEAP_SIZE="))) {
heapSize = def.split(QLatin1Char('=')).at(1);
}
}
}
QString stackSize;
QString heapSize;
};
} // namespace
// Stm8GeneralSettingsGroup
Stm8GeneralSettingsGroup::Stm8GeneralSettingsGroup(
const Project &qbsProject,
const ProductData &qbsProduct,
const std::vector<ProductData> &qbsProductDeps)
{
Q_UNUSED(qbsProductDeps)
setName(QByteArrayLiteral("General"));
setArchiveVersion(kGeneralArchiveVersion);
setDataVersion(kGeneralDataVersion);
setDataDebugInfo(gen::utils::debugInformation(qbsProduct));
const QString buildRootDirectory = gen::utils::buildRootPath(qbsProject);
buildTargetPage(qbsProduct);
buildOutputPage(buildRootDirectory, qbsProduct);
buildLibraryConfigPage(buildRootDirectory, qbsProduct);
buildLibraryOptionsPage(qbsProduct);
buildStackHeapPage(qbsProduct);
}
void Stm8GeneralSettingsGroup::buildTargetPage(
const ProductData &qbsProduct)
{
const TargetPageOptions opts(qbsProduct);
// Add 'GenCodeModel' item
// (Code model: small/medium/large).
addOptionsGroup(QByteArrayLiteral("GenCodeModel"),
{}, {opts.codeModel});
// Add 'GenDataModel' item
// (Data model: small/medium/large).
addOptionsGroup(QByteArrayLiteral("GenDataModel"),
{}, {opts.dataModel});
}
void Stm8GeneralSettingsGroup::buildOutputPage(
const QString &baseDirectory,
const ProductData &qbsProduct)
{
const OutputPageOptions opts(baseDirectory, qbsProduct);
// Add 'GOutputBinary' item (Output file: executable/library).
addOptionsGroup(QByteArrayLiteral("GOutputBinary"),
{}, {opts.binaryType});
// Add 'ExePath' item (Executable/binaries output directory).
addOptionsGroup(QByteArrayLiteral("ExePath"),
{}, {opts.binaryDirectory});
// Add 'ObjPath' item (Object files output directory).
addOptionsGroup(QByteArrayLiteral("ObjPath"),
{}, {opts.objectDirectory});
// Add 'ListPath' item (List files output directory).
addOptionsGroup(QByteArrayLiteral("ListPath"),
{}, {opts.listingDirectory});
}
void Stm8GeneralSettingsGroup::buildLibraryConfigPage(
const QString &baseDirectory,
const ProductData &qbsProduct)
{
const LibraryConfigPageOptions opts(baseDirectory, qbsProduct);
// Add 'GenRuntimeLibSelect' and 'GenRuntimeLibSelectSlave' items
// (Link with runtime: none/normal/full/custom).
addOptionsGroup(QByteArrayLiteral("GenRuntimeLibSelect"),
{}, {opts.libraryType});
addOptionsGroup(QByteArrayLiteral("GenRuntimeLibSelectSlave"),
{}, {opts.libraryType});
// Add 'GenRTConfigPath' item (Runtime configuration file).
addOptionsGroup(QByteArrayLiteral("GenRTConfigPath"),
{}, {opts.configPath});
}
void Stm8GeneralSettingsGroup::buildLibraryOptionsPage(
const ProductData &qbsProduct)
{
const LibraryOptionsPageOptions opts(qbsProduct);
// Add 'GenLibOutFormatter' item (Printf formatter).
addOptionsGroup(QByteArrayLiteral("GenLibOutFormatter"),
{}, {opts.printfFormatter});
// Add 'GenLibInFormatter' item (Scanf formatter).
addOptionsGroup(QByteArrayLiteral("GenLibInFormatter"),
{}, {opts.scanfFormatter});
}
void Stm8GeneralSettingsGroup::buildStackHeapPage(
const ProductData &qbsProduct)
{
const StackHeapPageOptions opts(qbsProduct);
// Add 'GenStackSize' item (Stack size).
addOptionsGroup(QByteArrayLiteral("GenStackSize"),
{}, {opts.stackSize});
// Add 'GenHeapSize' item (Heap size).
addOptionsGroup(QByteArrayLiteral("GenHeapSize"),
{}, {opts.heapSize});
}
} // namespace v3
} // namespace stm8
} // namespace iarew
} // namespace qbs
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemorunconfigurationwidget.h"
#include "maemodeviceconfigurations.h"
#include "maemomanager.h"
#include "maemorunconfiguration.h"
#include "maemosettingspage.h"
#include <coreplugin/icore.h>
#include <QtGui/QComboBox>
#include <QtGui/QCheckBox>
#include <QtGui/QDesktopServices>
#include <QtGui/QFormLayout>
#include <QtGui/QFrame>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
#include <QtGui/QToolButton>
namespace Qt4ProjectManager {
namespace Internal {
MaemoRunConfigurationWidget::MaemoRunConfigurationWidget(
MaemoRunConfiguration *runConfiguration, QWidget *parent)
: QWidget(parent), m_runConfiguration(runConfiguration)
{
QFormLayout *mainLayout = new QFormLayout;
setLayout(mainLayout);
mainLayout->setFormAlignment(Qt::AlignLeft | Qt::AlignVCenter);
m_configNameLineEdit = new QLineEdit(m_runConfiguration->displayName());
mainLayout->addRow(tr("Run configuration name:"), m_configNameLineEdit);
QWidget *devConfWidget = new QWidget;
QHBoxLayout *devConfLayout = new QHBoxLayout(devConfWidget);
m_devConfBox = new QComboBox;
m_devConfBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
devConfLayout->setMargin(0);
devConfLayout->addWidget(m_devConfBox);
QLabel *addDevConfLabel= new QLabel(tr("<a href=\"%1\">Manage device configurations</a>")
.arg(QLatin1String("deviceconfig")));
addDevConfLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
devConfLayout->addWidget(addDevConfLabel);
QLabel *debuggerConfLabel = new QLabel(tr("<a href=\"%1\">Set Debugger</a>")
.arg(QLatin1String("debugger")));
debuggerConfLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
devConfLayout->addWidget(debuggerConfLabel);
mainLayout->addRow(new QLabel(tr("Device Configuration:")), devConfWidget);
m_executableLabel = new QLabel(m_runConfiguration->executable());
mainLayout->addRow(tr("Executable:"), m_executableLabel);
m_argsLineEdit = new QLineEdit(m_runConfiguration->arguments().join(" "));
mainLayout->addRow(tr("Arguments:"), m_argsLineEdit);
mainLayout->addItem(new QSpacerItem(10, 10));
m_simNameLabel = new QLabel(tr("Simulator:"));
m_simValueLabel = new QLabel(m_runConfiguration->visibleSimulatorParameter());
mainLayout->addRow(m_simNameLabel, m_simValueLabel);
resetDeviceConfigurations();
connect(m_runConfiguration, SIGNAL(cachedSimulatorInformationChanged()),
this, SLOT(updateSimulatorPath()));
connect(m_runConfiguration, SIGNAL(deviceConfigurationsUpdated()),
this, SLOT(resetDeviceConfigurations()));
connect(m_configNameLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(configNameEdited(QString)));
connect(m_argsLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(argumentsEdited(QString)));
connect(m_devConfBox, SIGNAL(activated(QString)), this,
SLOT(deviceConfigurationChanged(QString)));
connect(m_runConfiguration, SIGNAL(targetInformationChanged()), this,
SLOT(updateTargetInformation()));
connect(addDevConfLabel, SIGNAL(linkActivated(QString)), this,
SLOT(showSettingsDialog(QString)));
connect(debuggerConfLabel, SIGNAL(linkActivated(QString)), this,
SLOT(showSettingsDialog(QString)));
}
void MaemoRunConfigurationWidget::configNameEdited(const QString &text)
{
m_runConfiguration->setDisplayName(text);
}
void MaemoRunConfigurationWidget::argumentsEdited(const QString &text)
{
m_runConfiguration->setArguments(text.split(' ', QString::SkipEmptyParts));
}
void MaemoRunConfigurationWidget::updateTargetInformation()
{
m_executableLabel->setText(m_runConfiguration->executable());
}
void MaemoRunConfigurationWidget::updateSimulatorPath()
{
m_simValueLabel->setText(m_runConfiguration->visibleSimulatorParameter());
}
void MaemoRunConfigurationWidget::deviceConfigurationChanged(const QString &name)
{
const MaemoDeviceConfig &devConfig
= MaemoDeviceConfigurations::instance().find(name);
setSimInfoVisible(devConfig);
m_runConfiguration->setDeviceConfig(devConfig);
}
void MaemoRunConfigurationWidget::setSimInfoVisible(const MaemoDeviceConfig &devConf)
{
const bool isSimulator = devConf.type == MaemoDeviceConfig::Simulator;
m_simNameLabel->setVisible(isSimulator);
m_simValueLabel->setVisible(isSimulator);
}
void MaemoRunConfigurationWidget::resetDeviceConfigurations()
{
m_devConfBox->clear();
const QList<MaemoDeviceConfig> &devConfs =
MaemoDeviceConfigurations::instance().devConfigs();
foreach (const MaemoDeviceConfig &devConf, devConfs)
m_devConfBox->addItem(devConf.name);
m_devConfBox->addItem(MaemoDeviceConfig().name);
const MaemoDeviceConfig &devConf = m_runConfiguration->deviceConfig();
m_devConfBox->setCurrentIndex(m_devConfBox->findText(devConf.name));
setSimInfoVisible(devConf);
}
void MaemoRunConfigurationWidget::showSettingsDialog(const QString &link)
{
if (link == QLatin1String("deviceconfig")) {
MaemoSettingsPage *page = MaemoManager::instance().settingsPage();
Core::ICore::instance()->showOptionsDialog(page->category(), page->id());
} else if (link == QLatin1String("debugger")) {
Core::ICore::instance()->showOptionsDialog(QLatin1String("O.Debugger"),
QLatin1String("M.Gdb"));
}
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Display simulator information only for valid run configs.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemorunconfigurationwidget.h"
#include "maemodeviceconfigurations.h"
#include "maemomanager.h"
#include "maemorunconfiguration.h"
#include "maemosettingspage.h"
#include <coreplugin/icore.h>
#include <QtGui/QComboBox>
#include <QtGui/QCheckBox>
#include <QtGui/QDesktopServices>
#include <QtGui/QFormLayout>
#include <QtGui/QFrame>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
#include <QtGui/QToolButton>
namespace Qt4ProjectManager {
namespace Internal {
MaemoRunConfigurationWidget::MaemoRunConfigurationWidget(
MaemoRunConfiguration *runConfiguration, QWidget *parent)
: QWidget(parent), m_runConfiguration(runConfiguration)
{
QFormLayout *mainLayout = new QFormLayout;
setLayout(mainLayout);
mainLayout->setFormAlignment(Qt::AlignLeft | Qt::AlignVCenter);
m_configNameLineEdit = new QLineEdit(m_runConfiguration->displayName());
mainLayout->addRow(tr("Run configuration name:"), m_configNameLineEdit);
QWidget *devConfWidget = new QWidget;
QHBoxLayout *devConfLayout = new QHBoxLayout(devConfWidget);
m_devConfBox = new QComboBox;
m_devConfBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
devConfLayout->setMargin(0);
devConfLayout->addWidget(m_devConfBox);
QLabel *addDevConfLabel= new QLabel(tr("<a href=\"%1\">Manage device configurations</a>")
.arg(QLatin1String("deviceconfig")));
addDevConfLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
devConfLayout->addWidget(addDevConfLabel);
QLabel *debuggerConfLabel = new QLabel(tr("<a href=\"%1\">Set Debugger</a>")
.arg(QLatin1String("debugger")));
debuggerConfLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
devConfLayout->addWidget(debuggerConfLabel);
mainLayout->addRow(new QLabel(tr("Device Configuration:")), devConfWidget);
m_executableLabel = new QLabel(m_runConfiguration->executable());
mainLayout->addRow(tr("Executable:"), m_executableLabel);
m_argsLineEdit = new QLineEdit(m_runConfiguration->arguments().join(" "));
mainLayout->addRow(tr("Arguments:"), m_argsLineEdit);
mainLayout->addItem(new QSpacerItem(10, 10));
m_simNameLabel = new QLabel(tr("Simulator:"));
m_simValueLabel = new QLabel(m_runConfiguration->visibleSimulatorParameter());
mainLayout->addRow(m_simNameLabel, m_simValueLabel);
resetDeviceConfigurations();
connect(m_runConfiguration, SIGNAL(cachedSimulatorInformationChanged()),
this, SLOT(updateSimulatorPath()));
connect(m_runConfiguration, SIGNAL(deviceConfigurationsUpdated()),
this, SLOT(resetDeviceConfigurations()));
connect(m_configNameLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(configNameEdited(QString)));
connect(m_argsLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(argumentsEdited(QString)));
connect(m_devConfBox, SIGNAL(activated(QString)), this,
SLOT(deviceConfigurationChanged(QString)));
connect(m_runConfiguration, SIGNAL(targetInformationChanged()), this,
SLOT(updateTargetInformation()));
connect(addDevConfLabel, SIGNAL(linkActivated(QString)), this,
SLOT(showSettingsDialog(QString)));
connect(debuggerConfLabel, SIGNAL(linkActivated(QString)), this,
SLOT(showSettingsDialog(QString)));
}
void MaemoRunConfigurationWidget::configNameEdited(const QString &text)
{
m_runConfiguration->setDisplayName(text);
}
void MaemoRunConfigurationWidget::argumentsEdited(const QString &text)
{
m_runConfiguration->setArguments(text.split(' ', QString::SkipEmptyParts));
}
void MaemoRunConfigurationWidget::updateTargetInformation()
{
m_executableLabel->setText(m_runConfiguration->executable());
}
void MaemoRunConfigurationWidget::updateSimulatorPath()
{
m_simValueLabel->setText(m_runConfiguration->visibleSimulatorParameter());
}
void MaemoRunConfigurationWidget::deviceConfigurationChanged(const QString &name)
{
const MaemoDeviceConfig &devConfig
= MaemoDeviceConfigurations::instance().find(name);
setSimInfoVisible(devConfig);
m_runConfiguration->setDeviceConfig(devConfig);
}
void MaemoRunConfigurationWidget::setSimInfoVisible(const MaemoDeviceConfig &devConf)
{
const bool isSimulator
= devConf.isValid() && devConf.type == MaemoDeviceConfig::Simulator;
m_simNameLabel->setVisible(isSimulator);
m_simValueLabel->setVisible(isSimulator);
}
void MaemoRunConfigurationWidget::resetDeviceConfigurations()
{
m_devConfBox->clear();
const QList<MaemoDeviceConfig> &devConfs =
MaemoDeviceConfigurations::instance().devConfigs();
foreach (const MaemoDeviceConfig &devConf, devConfs)
m_devConfBox->addItem(devConf.name);
m_devConfBox->addItem(MaemoDeviceConfig().name);
const MaemoDeviceConfig &devConf = m_runConfiguration->deviceConfig();
m_devConfBox->setCurrentIndex(m_devConfBox->findText(devConf.name));
setSimInfoVisible(devConf);
}
void MaemoRunConfigurationWidget::showSettingsDialog(const QString &link)
{
if (link == QLatin1String("deviceconfig")) {
MaemoSettingsPage *page = MaemoManager::instance().settingsPage();
Core::ICore::instance()->showOptionsDialog(page->category(), page->id());
} else if (link == QLatin1String("debugger")) {
Core::ICore::instance()->showOptionsDialog(QLatin1String("O.Debugger"),
QLatin1String("M.Gdb"));
}
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemorunconfigurationwidget.h"
#include "maemodeviceconfigurations.h"
#include "maemomanager.h"
#include "maemorunconfiguration.h"
#include "maemosettingspage.h"
#include <coreplugin/icore.h>
#include <QtGui/QComboBox>
#include <QtGui/QCheckBox>
#include <QtGui/QDesktopServices>
#include <QtGui/QFormLayout>
#include <QtGui/QFrame>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
#include <QtGui/QToolButton>
namespace Qt4ProjectManager {
namespace Internal {
MaemoRunConfigurationWidget::MaemoRunConfigurationWidget(
MaemoRunConfiguration *runConfiguration, QWidget *parent)
: QWidget(parent), m_runConfiguration(runConfiguration)
{
QFormLayout *mainLayout = new QFormLayout;
setLayout(mainLayout);
// TODO: Does not compile with the canonical form for some reason.
mainLayout->setFormAlignment(/* QFlags<Qt::AlignmentFlag>( */ Qt::AlignLeft /* ) */
| Qt::AlignVCenter);
m_configNameLineEdit = new QLineEdit(m_runConfiguration->name());
mainLayout->addRow(tr("Run configuration name:"), m_configNameLineEdit);
QWidget *devConfWidget = new QWidget;
QHBoxLayout *devConfLayout = new QHBoxLayout(devConfWidget);
m_devConfBox = new QComboBox;
m_devConfBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
devConfLayout->addWidget(m_devConfBox);
QLabel *addDevConfLabel
= new QLabel(tr("<a href=\"#\">Manage device configurations</a>"));
devConfLayout->addWidget(addDevConfLabel);
mainLayout->addRow(new QLabel(tr("Device Configuration:")), devConfWidget);
m_executableLabel = new QLabel(m_runConfiguration->executable());
mainLayout->addRow(tr("Executable:"), m_executableLabel);
m_argsLineEdit = new QLineEdit(m_runConfiguration->arguments().join(" "));
mainLayout->addRow(tr("Arguments:"), m_argsLineEdit);
m_debuggerLabel = new QLabel(m_runConfiguration->gdbCmd());
mainLayout->addRow(tr("Debugger:"), m_debuggerLabel);
mainLayout->addItem(new QSpacerItem(10, 10));
m_simPathNameLabel = new QLabel(tr("Simulator Path:"));
m_simPathValueLabel = new QLabel(m_runConfiguration->simulatorPath());
mainLayout->addRow(m_simPathNameLabel, m_simPathValueLabel);
resetDeviceConfigurations();
connect(m_runConfiguration, SIGNAL(cachedSimulatorInformationChanged()),
this, SLOT(updateSimulatorPath()));
connect(m_runConfiguration, SIGNAL(deviceConfigurationsUpdated()),
this, SLOT(resetDeviceConfigurations()));
connect(m_configNameLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(configNameEdited(QString)));
connect(m_argsLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(argumentsEdited(QString)));
connect(m_devConfBox, SIGNAL(activated(QString)), this,
SLOT(deviceConfigurationChanged(QString)));
connect(m_runConfiguration, SIGNAL(targetInformationChanged()), this,
SLOT(updateTargetInformation()));
connect(addDevConfLabel, SIGNAL(linkActivated(QString)), this,
SLOT(showSettingsDialog()));
}
void MaemoRunConfigurationWidget::configNameEdited(const QString &text)
{
m_runConfiguration->setName(text);
}
void MaemoRunConfigurationWidget::argumentsEdited(const QString &text)
{
m_runConfiguration->setArguments(text.split(' ', QString::SkipEmptyParts));
}
void MaemoRunConfigurationWidget::updateTargetInformation()
{
m_executableLabel->setText(m_runConfiguration->executable());
}
void MaemoRunConfigurationWidget::updateSimulatorPath()
{
m_simPathValueLabel->setText(m_runConfiguration->simulatorPath());
}
void MaemoRunConfigurationWidget::deviceConfigurationChanged(const QString &name)
{
const MaemoDeviceConfig &devConfig
= MaemoDeviceConfigurations::instance().find(name);
setSimInfoVisible(devConfig);
m_runConfiguration->setDeviceConfig(devConfig);
}
void MaemoRunConfigurationWidget::setSimInfoVisible(const MaemoDeviceConfig &devConf)
{
const bool isSimulator = devConf.type == MaemoDeviceConfig::Simulator;
m_simPathNameLabel->setVisible(isSimulator);
m_simPathValueLabel->setVisible(isSimulator);
}
void MaemoRunConfigurationWidget::resetDeviceConfigurations()
{
m_devConfBox->clear();
const QList<MaemoDeviceConfig> &devConfs =
MaemoDeviceConfigurations::instance().devConfigs();
foreach (const MaemoDeviceConfig &devConf, devConfs)
m_devConfBox->addItem(devConf.name);
m_devConfBox->addItem(MaemoDeviceConfig().name);
const MaemoDeviceConfig &devConf = m_runConfiguration->deviceConfig();
m_devConfBox->setCurrentIndex(m_devConfBox->findText(devConf.name));
setSimInfoVisible(devConf);
}
void MaemoRunConfigurationWidget::showSettingsDialog()
{
MaemoSettingsPage *settingsPage = MaemoManager::instance()->settingsPage();
Core::ICore::instance()->showOptionsDialog(settingsPage->category(),
settingsPage->id());
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Compile fix for 695349b6f4916dffe4eecc0e57bd8446f1aad3ed.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemorunconfigurationwidget.h"
#include "maemodeviceconfigurations.h"
#include "maemomanager.h"
#include "maemorunconfiguration.h"
#include "maemosettingspage.h"
#include <coreplugin/icore.h>
#include <QtGui/QComboBox>
#include <QtGui/QCheckBox>
#include <QtGui/QDesktopServices>
#include <QtGui/QFormLayout>
#include <QtGui/QFrame>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
#include <QtGui/QToolButton>
namespace Qt4ProjectManager {
namespace Internal {
MaemoRunConfigurationWidget::MaemoRunConfigurationWidget(
MaemoRunConfiguration *runConfiguration, QWidget *parent)
: QWidget(parent), m_runConfiguration(runConfiguration)
{
QFormLayout *mainLayout = new QFormLayout;
setLayout(mainLayout);
// TODO: Does not compile with the canonical form for some reason.
mainLayout->setFormAlignment(QFlags<Qt::AlignmentFlag>(Qt::AlignLeft)
| Qt::AlignVCenter);
m_configNameLineEdit = new QLineEdit(m_runConfiguration->name());
mainLayout->addRow(tr("Run configuration name:"), m_configNameLineEdit);
QWidget *devConfWidget = new QWidget;
QHBoxLayout *devConfLayout = new QHBoxLayout(devConfWidget);
m_devConfBox = new QComboBox;
m_devConfBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
devConfLayout->addWidget(m_devConfBox);
QLabel *addDevConfLabel
= new QLabel(tr("<a href=\"#\">Manage device configurations</a>"));
devConfLayout->addWidget(addDevConfLabel);
mainLayout->addRow(new QLabel(tr("Device Configuration:")), devConfWidget);
m_executableLabel = new QLabel(m_runConfiguration->executable());
mainLayout->addRow(tr("Executable:"), m_executableLabel);
m_argsLineEdit = new QLineEdit(m_runConfiguration->arguments().join(" "));
mainLayout->addRow(tr("Arguments:"), m_argsLineEdit);
m_debuggerLabel = new QLabel(m_runConfiguration->gdbCmd());
mainLayout->addRow(tr("Debugger:"), m_debuggerLabel);
mainLayout->addItem(new QSpacerItem(10, 10));
m_simPathNameLabel = new QLabel(tr("Simulator Path:"));
m_simPathValueLabel = new QLabel(m_runConfiguration->simulatorPath());
mainLayout->addRow(m_simPathNameLabel, m_simPathValueLabel);
resetDeviceConfigurations();
connect(m_runConfiguration, SIGNAL(cachedSimulatorInformationChanged()),
this, SLOT(updateSimulatorPath()));
connect(m_runConfiguration, SIGNAL(deviceConfigurationsUpdated()),
this, SLOT(resetDeviceConfigurations()));
connect(m_configNameLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(configNameEdited(QString)));
connect(m_argsLineEdit, SIGNAL(textEdited(QString)), this,
SLOT(argumentsEdited(QString)));
connect(m_devConfBox, SIGNAL(activated(QString)), this,
SLOT(deviceConfigurationChanged(QString)));
connect(m_runConfiguration, SIGNAL(targetInformationChanged()), this,
SLOT(updateTargetInformation()));
connect(addDevConfLabel, SIGNAL(linkActivated(QString)), this,
SLOT(showSettingsDialog()));
}
void MaemoRunConfigurationWidget::configNameEdited(const QString &text)
{
m_runConfiguration->setName(text);
}
void MaemoRunConfigurationWidget::argumentsEdited(const QString &text)
{
m_runConfiguration->setArguments(text.split(' ', QString::SkipEmptyParts));
}
void MaemoRunConfigurationWidget::updateTargetInformation()
{
m_executableLabel->setText(m_runConfiguration->executable());
}
void MaemoRunConfigurationWidget::updateSimulatorPath()
{
m_simPathValueLabel->setText(m_runConfiguration->simulatorPath());
}
void MaemoRunConfigurationWidget::deviceConfigurationChanged(const QString &name)
{
const MaemoDeviceConfig &devConfig
= MaemoDeviceConfigurations::instance().find(name);
setSimInfoVisible(devConfig);
m_runConfiguration->setDeviceConfig(devConfig);
}
void MaemoRunConfigurationWidget::setSimInfoVisible(const MaemoDeviceConfig &devConf)
{
const bool isSimulator = devConf.type == MaemoDeviceConfig::Simulator;
m_simPathNameLabel->setVisible(isSimulator);
m_simPathValueLabel->setVisible(isSimulator);
}
void MaemoRunConfigurationWidget::resetDeviceConfigurations()
{
m_devConfBox->clear();
const QList<MaemoDeviceConfig> &devConfs =
MaemoDeviceConfigurations::instance().devConfigs();
foreach (const MaemoDeviceConfig &devConf, devConfs)
m_devConfBox->addItem(devConf.name);
m_devConfBox->addItem(MaemoDeviceConfig().name);
const MaemoDeviceConfig &devConf = m_runConfiguration->deviceConfig();
m_devConfBox->setCurrentIndex(m_devConfBox->findText(devConf.name));
setSimInfoVisible(devConf);
}
void MaemoRunConfigurationWidget::showSettingsDialog()
{
MaemoSettingsPage *settingsPage = MaemoManager::instance()->settingsPage();
Core::ICore::instance()->showOptionsDialog(settingsPage->category(),
settingsPage->id());
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>#include <iostream>
MODULE(
"test", // name
{ // handlers
{"test", [] { std::cout << "hello world" << std::endl; }
}
})
<commit_msg>modules/test: fix curly brace closings<commit_after>#include <iostream>
MODULE(
"test", // name
{ // handlers
{"test", [] { std::cout << "hello world" << std::endl; }}
}
)
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* An application which acts as an openlcb hub with the GC protocol.
*
* @author Balazs Racz
* @date 3 Aug 2013
*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <memory>
#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"
Executor<1> g_executor{NO_THREAD()};
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
GcPacketPrinter packet_printer(&can_hub0);
OVERRIDE_CONST(gc_generate_newlines, 1);
int port = 12021;
const char *device_path = nullptr;
void usage(const char *e)
{
fprintf(stderr, "Usage: %s [-p port] [-d device_path]\n\n", e);
fprintf(stderr, "GridConnect CAN HUB.\nListens to a specific TCP port, "
"reads CAN packets from the incoming connections using "
"the GridConnect protocol, and forwards all incoming "
"packets to all other participants.\n\nArguments:\n");
fprintf(stderr, "\t-p port specifies the port number to listen on, "
"default is 12021.\n");
fprintf(stderr, "\t-d device is a path to a physical device doing "
"serial-CAN or USB-CAN. If specified, opens device and "
"adds it to the hub.\n");
exit(1);
}
void parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "hp:d:n:a:s:f:c:")) >= 0)
{
switch (opt)
{
case 'h':
usage(argv[0]);
break;
case 'd':
device_path = optarg;
break;
case 'p':
port = atoi(optarg);
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
usage(argv[0]);
}
}
}
class JSHubPort : public HubPortInterface
{
public:
JSHubPort(HubFlow *parent, emscripten::val send_fn)
: parent_(parent)
, sendFn_(send_fn)
{
HASSERT(sendFn_.typeof().as<std::string>() == "function");
parent_->register_port(this);
}
~JSHubPort()
{
parent_->unregister_port(this);
}
void send(HubPortInterface::message_type *buffer, unsigned priority = UINT_MAX) OVERRIDE
{
sendFn_((string &)*buffer->data());
buffer->unref();
}
void recv(string s)
{
auto *b = parent_->alloc();
b->data()->assign(s);
b->data()->skipMember_ = this;
parent_->send(b);
}
private:
HubFlow *parent_;
emscripten::val sendFn_;
};
class JSTcpHub
{
public:
JSTcpHub(CanHubFlow *hflow, int port)
: canHub_(hflow)
, gcHub_(canHub_->service())
, gcAdapter_(
GCAdapterBase::CreateGridConnectAdapter(&gcHub_, canHub_, false))
{
EM_ASM_(
{
var net = require('net');
var server = net.createServer(function(c)
{
console.log('client connected');
c.setEncoding('utf-8');
var client_port = new Module.JSHubPort($1, function(data)
{ c.write(data); });
c.on('close', function()
{
console.log('client disconnected');
client_port.delete ();
});
c.on('data', function(data)
{ client_port.recv(data); });
});
server.listen($0, function()
{ console.log('listening on port ' + $0); });
},
port, &gcHub_);
}
private:
CanHubFlow *canHub_;
HubFlow gcHub_;
std::unique_ptr<GCAdapterBase> gcAdapter_;
};
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
parse_args(argc, argv);
JSTcpHub hub(&can_hub0, port);
/* int dev_fd = 0;
while (1)
{
if (device_path && !dev_fd)
{
dev_fd = ::open(device_path, O_RDWR);
if (dev_fd > 0)
{
// Sets up the terminal in raw mode. Otherwise linux might echo
// characters coming in from the device and that will make
// packets go back to where they came from.
HASSERT(!tcflush(dev_fd, TCIOFLUSH));
struct termios settings;
HASSERT(!tcgetattr(dev_fd, &settings));
cfmakeraw(&settings);
HASSERT(!tcsetattr(dev_fd, TCSANOW, &settings));
LOG(INFO, "Opened device %s.\n", device_path);
create_gc_port_for_can_hub(&can_hub0, dev_fd);
}
else
{
LOG(ERROR, "Failed to open device %s: %s\n", device_path,
strerror(errno));
}
}
sleep(1);
}*/
g_executor.thread_body();
return 0;
}
EMSCRIPTEN_BINDINGS(js_hub_module)
{
emscripten::class_<JSHubPort>("JSHubPort")
.constructor<HubFlow *, emscripten::val>()
.function("recv", &JSHubPort::recv);
}
<commit_msg>Update js hub to work around unbound type exception on raw C pointers. At the same time, makes the gridconnect ports be parsed independently from each other, which is essential for not mixing up the characters that come in on different channels.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* An application which acts as an openlcb hub with the GC protocol.
*
* @author Balazs Racz
* @date 3 Aug 2013
*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <memory>
#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"
Executor<1> g_executor{NO_THREAD()};
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
GcPacketPrinter packet_printer(&can_hub0);
OVERRIDE_CONST(gc_generate_newlines, 1);
int port = 12021;
const char *device_path = nullptr;
int ws_port = -1;
void usage(const char *e)
{
fprintf(stderr, "Usage: %s [-p port] [-d device_path] [-w websocket_port]\n\n", e);
fprintf(stderr, "GridConnect CAN HUB.\nListens to a specific TCP port, "
"reads CAN packets from the incoming connections using "
"the GridConnect protocol, and forwards all incoming "
"packets to all other participants.\n\nArguments:\n");
fprintf(stderr, "\t-p port specifies the port number to listen on, "
"default is 12021.\n");
/* fprintf(stderr, "\t-d device is a path to a physical device doing "
"serial-CAN or USB-CAN. If specified, opens device and "
"adds it to the hub.\n");*/
fprintf(stderr, "\t-w websocket_port Opens a webserver on this port and serves up a websocket connection to the same CAN-bus.\n");
exit(1);
}
void parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "hp:w:")) >= 0)
{
switch (opt)
{
case 'h':
usage(argv[0]);
break;
/* case 'd':
device_path = optarg;
break;*/
case 'p':
port = atoi(optarg);
break;
case 'w':
ws_port = atoi(optarg);
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
usage(argv[0]);
}
}
}
class JSHubPort : public HubPortInterface
{
public:
JSHubPort(unsigned long parent, emscripten::val send_fn)
: parent_(reinterpret_cast<CanHubFlow*>(parent))
, sendFn_(send_fn)
, gcHub_(parent_->service())
, gcAdapter_(
GCAdapterBase::CreateGridConnectAdapter(&gcHub_, parent_, false))
{
HASSERT(sendFn_.typeof().as<std::string>() == "function");
gcHub_.register_port(this);
}
~JSHubPort()
{
gcHub_.unregister_port(this);
}
void send(HubPortInterface::message_type *buffer, unsigned priority = UINT_MAX) OVERRIDE
{
sendFn_((string &)*buffer->data());
buffer->unref();
}
void recv(string s)
{
auto *b = gcHub_.alloc();
b->data()->assign(s);
b->data()->skipMember_ = this;
gcHub_.send(b);
}
private:
CanHubFlow *parent_;
emscripten::val sendFn_;
HubFlow gcHub_;
std::unique_ptr<GCAdapterBase> gcAdapter_;
};
class JSTcpHub
{
public:
JSTcpHub(CanHubFlow *hflow, int port)
: canHub_(hflow)
{
EM_ASM_(
{
var net = require('net');
var server = net.createServer(function(c)
{
console.log('client connected');
c.setEncoding('utf-8');
var client_port = new Module.JSHubPort($1, function(data)
{ c.write(data); });
c.on('close', function()
{
console.log('client disconnected');
client_port.delete ();
});
c.on('data', function(data)
{ client_port.recv(data); });
});
server.listen($0, function()
{ console.log('listening on port ' + $0); });
},
port, (unsigned long)canHub_);
}
private:
CanHubFlow *canHub_;
};
/*
class JSWebsocketServer
{
public:
JSWebsocketServer(CanHubFlow* hflow, int port)
: canHub_(hflow)
};*/
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
parse_args(argc, argv);
JSTcpHub hub(&can_hub0, port);
/* int dev_fd = 0;
while (1)
{
if (device_path && !dev_fd)
{
dev_fd = ::open(device_path, O_RDWR);
if (dev_fd > 0)
{
// Sets up the terminal in raw mode. Otherwise linux might echo
// characters coming in from the device and that will make
// packets go back to where they came from.
HASSERT(!tcflush(dev_fd, TCIOFLUSH));
struct termios settings;
HASSERT(!tcgetattr(dev_fd, &settings));
cfmakeraw(&settings);
HASSERT(!tcsetattr(dev_fd, TCSANOW, &settings));
LOG(INFO, "Opened device %s.\n", device_path);
create_gc_port_for_can_hub(&can_hub0, dev_fd);
}
else
{
LOG(ERROR, "Failed to open device %s: %s\n", device_path,
strerror(errno));
}
}
sleep(1);
}*/
g_executor.thread_body();
return 0;
}
EMSCRIPTEN_BINDINGS(js_hub_module)
{
emscripten::class_<JSHubPort>("JSHubPort")
.constructor<unsigned long, emscripten::val>()
.function("recv", &JSHubPort::recv);
}
<|endoftext|> |
<commit_before>/* :
* Scheduler.cc : part of the Mace toolkit for building distributed systems
*
* Copyright (c) 2007, Charles Killian, Dejan Kostic, Ryan Braud, James W. Anderson, John Fisher-Ogden, Calvin Hubble, Duy Nguyen, Justin Burke, David Oppenheimer, Amin Vahdat, Adolfo Rodriguez, Sooraj Bhat
* 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 names of Duke University nor The University of
* California, San Diego, nor the names of the authors or 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.
*
* ----END-OF-LEGAL-STUFF---- */
#include "Accumulator.h"
#include "Scheduler.h"
#include "TimeUtil.h"
Scheduler* Scheduler::scheduler = 0;
Scheduler::Scheduler() : running(true), next(0) {
pthread_mutex_init(&slock, 0);
} // Scheduler
Scheduler::~Scheduler() {
haltScheduler();
} // ~Scheduler
void Scheduler::haltScheduler() {
if (scheduler) {
scheduler->lock();
if (params::get(params::MACE_LOG_ACCUMULATOR, 0)) {
Accumulator::stopLogging();
Accumulator::logAll();
}
bool r = scheduler->running;
scheduler->running = false;
scheduler->unlock();
if (r) {
scheduler->sig.signal();
assert(pthread_join(scheduler->schedulerThread, NULL) == 0);
}
}
Log::flush();
} // haltScheduler
uint64_t Scheduler::schedule(TimerHandler& timer, uint64_t time, bool abs) {
ADD_SELECTORS("Scheduler::schedule");
ScopedLock sl(slock);
if (!abs) {
time += TimeUtil::timeu();
}
// maceout << "scheduling " << timer.getId() << " for " << time << Log::endl;
timers.insert(std::make_pair(time, &timer));
if (time < next || next == 0) {
// maceout << "signaling" << Log::endl;
sig.signal();
}
return time;
} // schedule
void Scheduler::cancel(TimerHandler& timer) {
ADD_SELECTORS("Scheduler::cancel");
ScopedLock sl(slock);
// maceout << "canceling " << timer.getId() << Log::endl;
TimerMap::iterator i = timers.begin();
while (i != timers.end()) {
// maceout << "checking " << i->second->getId() << Log::endl;
if (i->second->getId() == timer.getId()) {
timers.erase(i);
if (!timers.empty()) {
next = timers.begin()->first;
// maceout << "set next=" << next << Log::endl;
}
// maceout << "returning" << Log::endl;
return;
}
i++;
}
} // cancel
void Scheduler::runSchedulerThread() {
ADD_SELECTORS("Scheduler::runSchedulerThread");
while (running) {
uint64_t pending = 0;
lock();
joinThreads(joinSet);
if (!timers.empty()) {
pending = timers.begin()->first;
next = pending;
// macedbg(1) << "got pending=" << pending << " next=" << next << Log::endl;
}
else {
next = 0;
unlock();
// macedbg(1) << "no timers, waiting for signal" << Log::endl;
sig.wait();
continue;
}
uint64_t now = TimeUtil::timeu();
uint64_t sleeptime = next - now;
// macedbg(1) << "now=" << now << " sleeptime=" << sleeptime << " next=" << next << Log::endl;
if ((now + CLOCK_RESOLUTION) > next) {
// macedbg(1) << (now + CLOCK_RESOLUTION) << " > " << next << ", firing" << Log::endl;
fireTimer(true);
}
else {
unlock();
// macedbg(1) << "sleeping for " << sleeptime << Log::endl;
int n = sig.wait(sleeptime);
// macedbg(1) << "sig returned " << n << Log::endl;
if (n) {
// another timer has been scheduled before pending
continue;
}
if (pending == next) {
// the pending timer has not been canceled
// macedbg(1) << "pending == next = " << next << ", firing" << Log::endl;
fireTimer(false);
}
}
}
lock();
joinThreads(joinSet);
unlock();
joinThreads(shutdownJoinSet);
} // runSchedulerThread
void Scheduler::fireTimer(bool locked) {
ADD_SELECTORS("Scheduler::fireTimer");
if (!locked) {
lock();
}
if (timers.empty()) {
unlock();
// maceout << "no timer to fire, returning" << Log::endl;
return;
}
TimerMap::iterator i = timers.begin();
TimerHandler* t = i->second;
timers.erase(i);
unlock();
// maceout << "firing " << t->getId() << Log::endl;
t->fire();
} // fireTimer
size_t Scheduler::joinThreads(IdThreadMap& s) {
size_t joinCount = 0;
for (IdThreadMap::const_iterator i = s.begin(); i != s.end(); i++) {
assert(pthread_join(i->second, NULL) == 0);
joinCount++;
}
if (joinCount) {
s.clear();
}
return joinCount;
} // joinThreads
void Scheduler::joinThread(uint64_t id, pthread_t tid) {
ScopedLock sl(slock);
if (running) {
ASSERT(pthread_equal(shutdownJoinSet[id], tid));
shutdownJoinSet.erase(id);
joinSet[id] = tid;
}
} // joinThread
void Scheduler::shutdownJoinThread(uint64_t id, pthread_t tid) {
ScopedLock sl(slock);
if (running) {
shutdownJoinSet[id] = tid;
}
} // shutdownJoinThread
void* Scheduler::startSchedulerThread(void* arg) {
Scheduler* s = (Scheduler*)arg;
s->runSchedulerThread();
return 0;
} // startSchedulerThread
<commit_msg>scheduler cancel bug fix ------------------------------------------------------------------------ r1147 | hyo | 2011-06-17 17:24:24 -0400 (Fri, 17 Jun 2011) | 1 line<commit_after>/* :
* Scheduler.cc : part of the Mace toolkit for building distributed systems
*
* Copyright (c) 2007, Charles Killian, Dejan Kostic, Ryan Braud, James W. Anderson, John Fisher-Ogden, Calvin Hubble, Duy Nguyen, Justin Burke, David Oppenheimer, Amin Vahdat, Adolfo Rodriguez, Sooraj Bhat
* 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 names of Duke University nor The University of
* California, San Diego, nor the names of the authors or 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.
*
* ----END-OF-LEGAL-STUFF---- */
#include "Accumulator.h"
#include "Scheduler.h"
#include "TimeUtil.h"
Scheduler* Scheduler::scheduler = 0;
Scheduler::Scheduler() : running(true), next(0) {
pthread_mutex_init(&slock, 0);
} // Scheduler
Scheduler::~Scheduler() {
haltScheduler();
} // ~Scheduler
void Scheduler::haltScheduler() {
if (scheduler) {
scheduler->lock();
if (params::get(params::MACE_LOG_ACCUMULATOR, 0)) {
Accumulator::stopLogging();
Accumulator::logAll();
}
bool r = scheduler->running;
scheduler->running = false;
scheduler->unlock();
if (r) {
scheduler->sig.signal();
assert(pthread_join(scheduler->schedulerThread, NULL) == 0);
}
}
Log::flush();
} // haltScheduler
uint64_t Scheduler::schedule(TimerHandler& timer, uint64_t time, bool abs) {
ADD_SELECTORS("Scheduler::schedule");
ScopedLock sl(slock);
if (!abs) {
time += TimeUtil::timeu();
}
// maceout << "scheduling " << timer.getId() << " for " << time << Log::endl;
timers.insert(std::make_pair(time, &timer));
if (time < next || next == 0) {
// maceout << "signaling" << Log::endl;
sig.signal();
}
return time;
} // schedule
void Scheduler::cancel(TimerHandler& timer) {
ADD_SELECTORS("Scheduler::cancel");
ScopedLock sl(slock);
// maceout << "canceling " << timer.getId() << Log::endl;
TimerMap::iterator i = timers.begin();
while (i != timers.end()) {
// maceout << "checking " << i->second->getId() << Log::endl;
if (i->second->getId() == timer.getId()) {
timers.erase(i);
if (!timers.empty()) {
next = timers.begin()->first;
// maceout << "set next=" << next << Log::endl;
} else {
next = 0;
}
// maceout << "returning" << Log::endl;
return;
}
i++;
}
} // cancel
void Scheduler::runSchedulerThread() {
ADD_SELECTORS("Scheduler::runSchedulerThread");
while (running) {
uint64_t pending = 0;
lock();
joinThreads(joinSet);
if (!timers.empty()) {
pending = timers.begin()->first;
next = pending;
// macedbg(1) << "got pending=" << pending << " next=" << next << Log::endl;
}
else {
next = 0;
unlock();
// macedbg(1) << "no timers, waiting for signal" << Log::endl;
sig.wait();
continue;
}
uint64_t now = TimeUtil::timeu();
uint64_t sleeptime = next - now;
// macedbg(1) << "now=" << now << " sleeptime=" << sleeptime << " next=" << next << Log::endl;
if ((now + CLOCK_RESOLUTION) > next) {
// macedbg(1) << (now + CLOCK_RESOLUTION) << " > " << next << ", firing" << Log::endl;
fireTimer(true);
}
else {
unlock();
// macedbg(1) << "sleeping for " << sleeptime << Log::endl;
int n = sig.wait(sleeptime);
// macedbg(1) << "sig returned " << n << Log::endl;
if (n) {
// another timer has been scheduled before pending
continue;
}
if (pending == next) {
// the pending timer has not been canceled
// macedbg(1) << "pending == next = " << next << ", firing" << Log::endl;
fireTimer(false);
}
}
}
lock();
joinThreads(joinSet);
unlock();
joinThreads(shutdownJoinSet);
} // runSchedulerThread
void Scheduler::fireTimer(bool locked) {
ADD_SELECTORS("Scheduler::fireTimer");
if (!locked) {
lock();
}
if (timers.empty()) {
unlock();
// maceout << "no timer to fire, returning" << Log::endl;
return;
}
TimerMap::iterator i = timers.begin();
TimerHandler* t = i->second;
timers.erase(i);
unlock();
// maceout << "firing " << t->getId() << Log::endl;
t->fire();
} // fireTimer
size_t Scheduler::joinThreads(IdThreadMap& s) {
size_t joinCount = 0;
for (IdThreadMap::const_iterator i = s.begin(); i != s.end(); i++) {
assert(pthread_join(i->second, NULL) == 0);
joinCount++;
}
if (joinCount) {
s.clear();
}
return joinCount;
} // joinThreads
void Scheduler::joinThread(uint64_t id, pthread_t tid) {
ScopedLock sl(slock);
if (running) {
ASSERT(pthread_equal(shutdownJoinSet[id], tid));
shutdownJoinSet.erase(id);
joinSet[id] = tid;
}
} // joinThread
void Scheduler::shutdownJoinThread(uint64_t id, pthread_t tid) {
ScopedLock sl(slock);
if (running) {
shutdownJoinSet[id] = tid;
}
} // shutdownJoinThread
void* Scheduler::startSchedulerThread(void* arg) {
Scheduler* s = (Scheduler*)arg;
s->runSchedulerThread();
return 0;
} // startSchedulerThread
<|endoftext|> |
<commit_before>#include "tpunit++.hpp"
#include "mock4cpp.h"
#include <string>
struct BasicVerification: tpunit::TestFixture {
BasicVerification() :
tpunit::TestFixture(
//
TEST(BasicVerification::verify_should_not_throw_exception_if_method_was_called), //
TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_called), //
TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed), //
TEST(BasicVerification::verify_method_was_called_at_least_once), //
TEST(BasicVerification::verify_method_was_called_exactly_once), //
TEST(BasicVerification::verify_method_was_never_called), //
TEST(BasicVerification::verify_method_was_called_exactly_x_times), //
TEST(BasicVerification::should_throw_IllegalArgumentException_on_negative_times_argument), //
TEST(BasicVerification::verify_with_filter), //
TEST(BasicVerification::verify_concatenated_sequence), //
TEST(BasicVerification::verify_repeated_sequence), //
TEST(BasicVerification::verify_multi_sequences_in_order),
TEST(BasicVerification::verify_no_other_invocations)//
) //
{
}
struct SomeInterface {
virtual int func(int) = 0;
virtual void proc(int) = 0;
};
void verify_should_throw_MethodCallVerificationException_if_method_was_not_called() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException);
}
void verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException);
}
void verify_should_not_throw_exception_if_method_was_called() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.proc(1);
Verify(mock[&SomeInterface::func]);
Verify(mock[&SomeInterface::proc]);
}
void verify_method_was_called_at_least_once() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException);
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.proc(2);
Verify(mock[&SomeInterface::func]);
Verify(mock[&SomeInterface::proc]);
i.func(1);
i.proc(2);
Verify(mock[&SomeInterface::func]);
Verify(mock[&SomeInterface::proc]);
}
void verify_method_was_called_exactly_once() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException);
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException);
i.func(1);
i.proc(1);
Verify(mock[&SomeInterface::func]).Once();
Verify(mock[&SomeInterface::proc]).Once();
i.func(1);
i.proc(1);
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException);
}
void verify_method_was_never_called() {
Mock<SomeInterface> mock;
Verify(mock[&SomeInterface::func]).Never();
Verify(mock[&SomeInterface::proc]).Never();
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
Verify(mock[&SomeInterface::func]).Never();
Verify(mock[&SomeInterface::proc]).Never();
i.func(1);
i.proc(1);
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Never(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Never(), mock4cpp::MethodCallVerificationException);
}
void verify_method_was_called_exactly_x_times() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException);
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException);
i.func(1);
i.func(1);
i.proc(1);
i.proc(1);
Verify(mock[&SomeInterface::func]).Times(2);
Verify(mock[&SomeInterface::proc]).Times(2);
i.func(1);
i.proc(1);
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException);
}
void should_throw_IllegalArgumentException_on_negative_times_argument() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(-1), mock4cpp::IllegalArgumentException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(-1), mock4cpp::IllegalArgumentException);
}
void verify_with_filter() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
Verify(mock[&SomeInterface::func].Using(1));
ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(2)), mock4cpp::MethodCallVerificationException);
}
void verify_concatenated_sequence() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.func(2);
i.func(3);
i.func(4);
Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2)).Once();
Verify(mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).AtLeastOnce();
Verify(mock[&SomeInterface::func].Using(3) + mock[&SomeInterface::func].Using(4)).Once();
Verify(mock[&SomeInterface::func] + mock[&SomeInterface::func]).Twice();
Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)).Never();
ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)),
mock4cpp::MethodCallVerificationException);
}
void verify_repeated_sequence() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.func(2);
i.func(3);
i.func(1);
i.func(2);
i.func(3);
Verify(mock[&SomeInterface::func] * 1).Times(6);
Verify(mock[&SomeInterface::func] * 2).Times(3);
Verify(mock[&SomeInterface::func] * 3).Times(2);
Verify(mock[&SomeInterface::func] * 4).Times(1);
Verify(mock[&SomeInterface::func] * 5).Times(1);
Verify(mock[&SomeInterface::func] * 6).Times(1);
Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).Twice();
Verify((mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)) * 2).Once();
Verify(mock[&SomeInterface::func].Using(1) * 2).Never();
ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) * 2), mock4cpp::MethodCallVerificationException);
}
void verify_multi_sequences_in_order() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.func(2);
i.func(3);
i.func(1);
i.func(2);
i.func(3);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(1);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(1);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(1);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(2);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(3);
Verify( //
mock[&SomeInterface::func]) //
.Times(6);
Verify( //
mock[&SomeInterface::func].Using(1) + //
mock[&SomeInterface::func].Using(2) + //
mock[&SomeInterface::func].Using(3)) //
.Times(2);
Verify( //
mock[&SomeInterface::func].Using(1) + //
mock[&SomeInterface::func].Using(2)) //
.Times(2);
Verify( //
mock[&SomeInterface::func].Using(2) + //
mock[&SomeInterface::func].Using(3)) //
.Times(2);
Verify( //
mock[&SomeInterface::func].Using(1)) //
.Times(2);
Verify(mock[&SomeInterface::func].Using(2) + //
mock[&SomeInterface::func].Using(1)).Never();
}
void verify_no_other_invocations() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
VerifyNoOtherInvocations(mock);
i.func(1);
i.func(1);
ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]).AtLeastOnce();
VerifyNoOtherInvocations(mock);
i.func(1);
i.func(1);
ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]*3);
ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]*4);
VerifyNoOtherInvocations(mock);
}
} __BasicVerification;
<commit_msg>add verifyNoOtherInvocations tests<commit_after>#include "tpunit++.hpp"
#include "mock4cpp.h"
#include <string>
struct BasicVerification: tpunit::TestFixture {
BasicVerification() :
tpunit::TestFixture(
//
TEST(BasicVerification::verify_should_not_throw_exception_if_method_was_called), //
TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_called), //
TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed), //
TEST(BasicVerification::verify_method_was_called_at_least_once), //
TEST(BasicVerification::verify_method_was_called_exactly_once), //
TEST(BasicVerification::verify_method_was_never_called), //
TEST(BasicVerification::verify_method_was_called_exactly_x_times), //
TEST(BasicVerification::should_throw_IllegalArgumentException_on_negative_times_argument), //
TEST(BasicVerification::verify_with_filter), //
TEST(BasicVerification::verify_concatenated_sequence), //
TEST(BasicVerification::verify_repeated_sequence), //
TEST(BasicVerification::verify_multi_sequences_in_order),
TEST(BasicVerification::verify_no_other_invocations_for_mock),//
TEST(BasicVerification::verify_no_other_invocations_for_method_filter)//
) //
{
}
struct SomeInterface {
virtual int func(int) = 0;
virtual void proc(int) = 0;
};
void verify_should_throw_MethodCallVerificationException_if_method_was_not_called() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException);
}
void verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException);
}
void verify_should_not_throw_exception_if_method_was_called() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.proc(1);
Verify(mock[&SomeInterface::func]);
Verify(mock[&SomeInterface::proc]);
}
void verify_method_was_called_at_least_once() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException);
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.proc(2);
Verify(mock[&SomeInterface::func]);
Verify(mock[&SomeInterface::proc]);
i.func(1);
i.proc(2);
Verify(mock[&SomeInterface::func]);
Verify(mock[&SomeInterface::proc]);
}
void verify_method_was_called_exactly_once() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException);
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException);
i.func(1);
i.proc(1);
Verify(mock[&SomeInterface::func]).Once();
Verify(mock[&SomeInterface::proc]).Once();
i.func(1);
i.proc(1);
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException);
}
void verify_method_was_never_called() {
Mock<SomeInterface> mock;
Verify(mock[&SomeInterface::func]).Never();
Verify(mock[&SomeInterface::proc]).Never();
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
Verify(mock[&SomeInterface::func]).Never();
Verify(mock[&SomeInterface::proc]).Never();
i.func(1);
i.proc(1);
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Never(), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Never(), mock4cpp::MethodCallVerificationException);
}
void verify_method_was_called_exactly_x_times() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException);
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException);
i.func(1);
i.func(1);
i.proc(1);
i.proc(1);
Verify(mock[&SomeInterface::func]).Times(2);
Verify(mock[&SomeInterface::proc]).Times(2);
i.func(1);
i.proc(1);
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException);
}
void should_throw_IllegalArgumentException_on_negative_times_argument() {
Mock<SomeInterface> mock;
ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(-1), mock4cpp::IllegalArgumentException);
ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(-1), mock4cpp::IllegalArgumentException);
}
void verify_with_filter() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
Verify(mock[&SomeInterface::func].Using(1));
ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(2)), mock4cpp::MethodCallVerificationException);
}
void verify_concatenated_sequence() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.func(2);
i.func(3);
i.func(4);
Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2)).Once();
Verify(mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).AtLeastOnce();
Verify(mock[&SomeInterface::func].Using(3) + mock[&SomeInterface::func].Using(4)).Once();
Verify(mock[&SomeInterface::func] + mock[&SomeInterface::func]).Twice();
Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)).Never();
ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)),
mock4cpp::MethodCallVerificationException);
}
void verify_repeated_sequence() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.func(2);
i.func(3);
i.func(1);
i.func(2);
i.func(3);
Verify(mock[&SomeInterface::func] * 1).Times(6);
Verify(mock[&SomeInterface::func] * 2).Times(3);
Verify(mock[&SomeInterface::func] * 3).Times(2);
Verify(mock[&SomeInterface::func] * 4).Times(1);
Verify(mock[&SomeInterface::func] * 5).Times(1);
Verify(mock[&SomeInterface::func] * 6).Times(1);
Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).Twice();
Verify((mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)) * 2).Once();
Verify(mock[&SomeInterface::func].Using(1) * 2).Never();
ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) * 2), mock4cpp::MethodCallVerificationException);
}
void verify_multi_sequences_in_order() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]);
SomeInterface &i = mock.get();
i.func(1);
i.func(2);
i.func(3);
i.func(1);
i.func(2);
i.func(3);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(1);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(1);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(1);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(2);
Verify( //
mock[&SomeInterface::func], //
mock[&SomeInterface::func]) //
.Times(3);
Verify( //
mock[&SomeInterface::func]) //
.Times(6);
Verify( //
mock[&SomeInterface::func].Using(1) + //
mock[&SomeInterface::func].Using(2) + //
mock[&SomeInterface::func].Using(3)) //
.Times(2);
Verify( //
mock[&SomeInterface::func].Using(1) + //
mock[&SomeInterface::func].Using(2)) //
.Times(2);
Verify( //
mock[&SomeInterface::func].Using(2) + //
mock[&SomeInterface::func].Using(3)) //
.Times(2);
Verify( //
mock[&SomeInterface::func].Using(1)) //
.Times(2);
Verify(mock[&SomeInterface::func].Using(2) + //
mock[&SomeInterface::func].Using(1)).Never();
}
void verify_no_other_invocations_for_mock() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func]);
SomeInterface &i = mock.get();
VerifyNoOtherInvocations(mock);
i.func(1);
i.func(1);
ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]).AtLeastOnce();
VerifyNoOtherInvocations(mock);
i.func(1);
i.func(1);
ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]*3);
ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]*4);
VerifyNoOtherInvocations(mock);
}
void verify_no_other_invocations_for_method_filter() {
Mock<SomeInterface> mock;
Stub(mock[&SomeInterface::func]);
SomeInterface &i = mock.get();
VerifyNoOtherInvocations(mock[&SomeInterface::func]);
i.func(1);
i.func(1);
ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]).AtLeastOnce();
VerifyNoOtherInvocations(mock[&SomeInterface::func]);
i.func(1);
i.func(1);
ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]*3);
ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException);
Verify(mock[&SomeInterface::func]*4);
VerifyNoOtherInvocations(mock[&SomeInterface::func]);
}
} __BasicVerification;
<|endoftext|> |
<commit_before>/*********************************************************************************
* Copyright (c) 2015, Peter Andreas Entschev
* 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 fft_benchmark 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 "common.hpp"
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fftw3.h>
static const int NSamplesMin = 128;
static const int NSamplesMax = 4096;
static const int Batches = 10;
static const int Rank = 2;
static const int Iterations = 10;
int main(int argc, char* argv[])
{
#if __cplusplus > 199711L
std::chrono::high_resolution_clock::time_point tStart, tEnd;
#else
std::clock_t tStart, tEnd;
#endif
for (int n = NSamplesMin; n <= NSamplesMax; n <<= 1) {
int fft_dims[3];
int batch_dist = 1;
for (int i = 0; i < Rank; i++) {
fft_dims[i] = n;
batch_dist *= fft_dims[i];
}
size_t bufferLen = batch_dist * 2 * Batches;
// No data is copied to buffers as FFT performance is not data
// dependent, but only size dependent
float* bufferIn = new float[bufferLen];
float* bufferOut = new float[bufferLen];
std::cout << "Number of dimensions: " << Rank << std::endl;
std::cout << "Matrix dimensions: " << n << "x" << n << std::endl;
std::cout << "Batch size: " << Batches << std::endl;
// In-place plan
fftwf_plan inPlan = fftwf_plan_many_dft(Rank, fft_dims, Batches,
(fftwf_complex*)bufferOut, NULL, 1, batch_dist,
(fftwf_complex*)bufferOut, NULL, 1, batch_dist,
FFTW_FORWARD, FFTW_ESTIMATE);
// Make sure the plan is properly initialized before benchmarking
fftwf_execute(inPlan);
tStart = getTime();
for (int i = 0; i < Iterations; i++) {
// Compute forward FFT
fftwf_execute(inPlan);
}
tEnd = getTime();
std::cout << "In-place C2C FFT time for " << Iterations << " runs: " << getTimeCount(tEnd, tStart) << " ms" << std::endl;
// Destroy in-place plan
fftwf_destroy_plan(inPlan);
// Out-of-place plan
fftwf_plan outPlan = fftwf_plan_many_dft(Rank, fft_dims, Batches,
(fftwf_complex*)bufferIn, NULL, 1, batch_dist,
(fftwf_complex*)bufferOut, NULL, 1, batch_dist,
FFTW_FORWARD, FFTW_ESTIMATE);
// Make sure the plan is properly initialized before benchmarking
fftwf_execute(outPlan);
tStart = getTime();
for (int i = 0; i < Iterations; i++) {
// Compute forward FFT
fftwf_execute(outPlan);
}
tEnd = getTime();
std::cout << "Out-of-place C2C FFT time for " << Iterations << " runs: " << getTimeCount(tEnd, tStart) << " ms" << std::endl;
tStart = getTime();
for (int i = 0; i < Iterations; i++) {
memcpy(bufferOut, bufferIn, bufferLen * sizeof(float));
//for (int j = 0; j < bufferLen; j++)
// bufferOut[j] = bufferIn[j];
// Compute forward FFT
fftwf_execute(outPlan);
}
tEnd = getTime();
std::cout << "Buffer Copy + Out-of-place C2C FFT time for " << Iterations << " runs: " << getTimeCount(tEnd, tStart) << " ms" << std::endl << std::endl;
// Destroy out-of-place plan
fftwf_destroy_plan(outPlan);
delete[] bufferIn;
delete[] bufferOut
}
return 0;
}
<commit_msg>Added missing semicolon to FFTW3 benchmark code<commit_after>/*********************************************************************************
* Copyright (c) 2015, Peter Andreas Entschev
* 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 fft_benchmark 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 "common.hpp"
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fftw3.h>
static const int NSamplesMin = 128;
static const int NSamplesMax = 4096;
static const int Batches = 10;
static const int Rank = 2;
static const int Iterations = 10;
int main(int argc, char* argv[])
{
#if __cplusplus > 199711L
std::chrono::high_resolution_clock::time_point tStart, tEnd;
#else
std::clock_t tStart, tEnd;
#endif
for (int n = NSamplesMin; n <= NSamplesMax; n <<= 1) {
int fft_dims[3];
int batch_dist = 1;
for (int i = 0; i < Rank; i++) {
fft_dims[i] = n;
batch_dist *= fft_dims[i];
}
size_t bufferLen = batch_dist * 2 * Batches;
// No data is copied to buffers as FFT performance is not data
// dependent, but only size dependent
float* bufferIn = new float[bufferLen];
float* bufferOut = new float[bufferLen];
std::cout << "Number of dimensions: " << Rank << std::endl;
std::cout << "Matrix dimensions: " << n << "x" << n << std::endl;
std::cout << "Batch size: " << Batches << std::endl;
// In-place plan
fftwf_plan inPlan = fftwf_plan_many_dft(Rank, fft_dims, Batches,
(fftwf_complex*)bufferOut, NULL, 1, batch_dist,
(fftwf_complex*)bufferOut, NULL, 1, batch_dist,
FFTW_FORWARD, FFTW_ESTIMATE);
// Make sure the plan is properly initialized before benchmarking
fftwf_execute(inPlan);
tStart = getTime();
for (int i = 0; i < Iterations; i++) {
// Compute forward FFT
fftwf_execute(inPlan);
}
tEnd = getTime();
std::cout << "In-place C2C FFT time for " << Iterations << " runs: " << getTimeCount(tEnd, tStart) << " ms" << std::endl;
// Destroy in-place plan
fftwf_destroy_plan(inPlan);
// Out-of-place plan
fftwf_plan outPlan = fftwf_plan_many_dft(Rank, fft_dims, Batches,
(fftwf_complex*)bufferIn, NULL, 1, batch_dist,
(fftwf_complex*)bufferOut, NULL, 1, batch_dist,
FFTW_FORWARD, FFTW_ESTIMATE);
// Make sure the plan is properly initialized before benchmarking
fftwf_execute(outPlan);
tStart = getTime();
for (int i = 0; i < Iterations; i++) {
// Compute forward FFT
fftwf_execute(outPlan);
}
tEnd = getTime();
std::cout << "Out-of-place C2C FFT time for " << Iterations << " runs: " << getTimeCount(tEnd, tStart) << " ms" << std::endl;
tStart = getTime();
for (int i = 0; i < Iterations; i++) {
memcpy(bufferOut, bufferIn, bufferLen * sizeof(float));
//for (int j = 0; j < bufferLen; j++)
// bufferOut[j] = bufferIn[j];
// Compute forward FFT
fftwf_execute(outPlan);
}
tEnd = getTime();
std::cout << "Buffer Copy + Out-of-place C2C FFT time for " << Iterations << " runs: " << getTimeCount(tEnd, tStart) << " ms" << std::endl << std::endl;
// Destroy out-of-place plan
fftwf_destroy_plan(outPlan);
delete[] bufferIn;
delete[] bufferOut;
}
return 0;
}
<|endoftext|> |
<commit_before>
#include "algorithm.h"
#include "alignment.h"
#include "array.h"
#include "bitset.h"
#include "container.h"
#include "crc8_ccitt.h"
#include "crc16.h"
#include "crc16_ccitt.h"
#include "crc16_kermit.h"
#include "crc32.h"
#include "crc64_ecma.h"
#include "cyclic_value.h"
#include "deque.h"
#if !defined(COMPILER_IAR)
#include "variant.h"
#endif
#if defined(COMPILER_KEIL)
#pragma diag_suppress 550
#pragma diag_suppress 177
#endif
//*****************************************************************************
// algorithm
//*****************************************************************************
void test_algorithm()
{
int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
std::pair<int*, int*> result1;
std::pair<int, int> result2;
int x = 0;
int y = 1;
int* p;
bool b;
// minmax_element
result1 = etl::minmax_element(etl::begin(data), etl::end(data));
result1 = etl::minmax_element(etl::begin(data), etl::end(data), std::greater<int>());
// minmax
result2 = etl::minmax(x, y);
result2 = etl::minmax(x, y, std::greater<int>());
// is_sorted_until
p = etl::is_sorted_until(etl::begin(data), etl::end(data));
p = etl::is_sorted_until(etl::begin(data), etl::end(data), std::greater<int>());
// is_sorted
b = etl::is_sorted(etl::begin(data), etl::end(data));
b = etl::is_sorted(etl::begin(data), etl::end(data), std::greater<int>());
// copy_n
p = etl::copy_n(etl::begin(data), 5, etl::begin(data2));
// copy_if
p = etl::copy_if(etl::begin(data), etl::end(data), etl::begin(data2), std::bind2nd(std::greater<int>(), 4));
// find_if_not
p = etl::find_if_not(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// all_of
b = etl::all_of(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// any_of
b = etl::any_of(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// none_of
b = etl::none_of(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// is_permutation
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2));
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2), std::equal_to<int>());
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2), etl::end(data2));
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2), etl::end(data2), std::equal_to<int>());
// is_partitioned
b = etl::is_partitioned(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// partition_point
p = etl::partition_point(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// partition_copy
result1 = etl::partition_copy(etl::begin(data), etl::end(data), etl::begin(data2), etl::begin(data3), std::bind2nd(std::greater<int>(), 4));
}
//*****************************************************************************
// alignment
//*****************************************************************************
etl::aligned_storage<100, 8>::type data9;
etl::aligned_storage_as<100, double>::type data10;
void test_alignment()
{
int a = static_cast<int&>(data9);
etl::aligned_storage<1, 1>::type data1;
etl::aligned_storage<1, 2>::type data2;
etl::aligned_storage<1, 4>::type data3;
etl::aligned_storage<1, 8>::type data4;
etl::aligned_storage_as<1, char>::type data5;
etl::aligned_storage_as<1, short>::type data6;
etl::aligned_storage_as<1, int>::type data7;
etl::aligned_storage_as<1, double>::type data8;
}
//*****************************************************************************
// array
//*****************************************************************************
void test_array()
{
etl::array<int, 10> a;
int i = a[4];
int s = a.size();
a.fill(45);
}
//*****************************************************************************
// bitset
//*****************************************************************************
void test_bitset()
{
etl::bitset<7> b7; // uint8_t
etl::bitset<8> b8; // uint8_t
etl::bitset<9> b9; // uint16_t
etl::bitset<15> b15; // uint16_t
etl::bitset<16> b16; // uint16_t
etl::bitset<17> b17; // uint32_t
etl::bitset<31> b31; // uint32_t
etl::bitset<32> b32; // uint32_t
etl::bitset<33> b33; // uint64_t
etl::bitset<63> b63; // uint64_t
etl::bitset<64> b64; // uint64_t
etl::bitset<65> b65; // 2 * uint64_t
b65.set();
b65.set(4, true);
b65.reset();
b65.reset(37);
b65 = ~b65;
bool b = b65[4];
b = b65[64];
b65.flip();
b65.flip(5);
etl::bitset<7>::iterator b1 = b7.begin();
etl::bitset<7>::iterator e1 = b7.end();
etl::bitset<7>::const_iterator b2 = b7.cbegin();
etl::bitset<7>::const_iterator e2 = b7.cend();
++b1;
--e1;
b2 += 2;
e2 -= 2;
*b1 = true;
const etl::bitset<7>::iterator b3 = b7.begin();
bool t = *b3;
}
//*****************************************************************************
// crc
//*****************************************************************************
void test_crc()
{
int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
uint8_t crc1 = etl::crc8_ccitt<>(etl::begin(data), etl::end(data));
uint8_t crc2 = etl::crc8_ccitt<etl::endian::big>(etl::begin(data), etl::end(data));
uint16_t crc3 = etl::crc16<>(etl::begin(data), etl::end(data));
uint16_t crc4 = etl::crc16<etl::endian::big>(etl::begin(data), etl::end(data));
uint16_t crc5 = etl::crc16_ccitt<>(etl::begin(data), etl::end(data));
uint16_t crc6 = etl::crc16_ccitt<etl::endian::big>(etl::begin(data), etl::end(data));
uint16_t crc7 = etl::crc16_kermit<>(etl::begin(data), etl::end(data));
uint16_t crc8 = etl::crc16_kermit<etl::endian::big>(etl::begin(data), etl::end(data));
uint32_t crc9 = etl::crc32<>(etl::begin(data), etl::end(data));
uint32_t crc10 = etl::crc32<etl::endian::big>(etl::begin(data), etl::end(data));
uint64_t crc11 = etl::crc64_ecma<>(etl::begin(data), etl::end(data));
uint64_t crc12 = etl::crc64_ecma<etl::endian::big>(etl::begin(data), etl::end(data));
}
//*****************************************************************************
// deque
//*****************************************************************************
void test_cyclic_value()
{
etl::cyclic_value<int, 1, 10> cv1;
etl::cyclic_value<int> cv2;
cv2.set(3, 8);
cv1.advance(3);
cv1.to_first();
cv1.to_last();
--cv1;
++cv1;
int f = cv1.first();
int l = cv1.last();
int v = cv1;
cv1 = v;
cv1 = cv2;
bool b;
b = cv1 == cv2;
b = cv1 != cv2;
}
//*****************************************************************************
// cyclic_value
//*****************************************************************************
void test_deque()
{
}
//*****************************************************************************
// main
//*****************************************************************************
int main()
{
test_alignment();
}
<commit_msg>More tests<commit_after>
#include "algorithm.h"
#include "alignment.h"
#include "array.h"
#include "bitset.h"
#include "container.h"
#include "crc8_ccitt.h"
#include "crc16.h"
#include "crc16_ccitt.h"
#include "crc16_kermit.h"
#include "crc32.h"
#include "crc64_ecma.h"
#include "cyclic_value.h"
#include "deque.h"
#include "io_port.h"
#include "vector.h"
#include "variant.h"
#if defined(COMPILER_KEIL)
#pragma diag_suppress 550
#pragma diag_suppress 177
#endif
#if defined(COMPILER_IAR)
#pragma diag_suppress = pe177
#endif
struct Test
{
Test(int i, double d)
: i(i),
d(d)
{
}
int i;
double d;
};
//*****************************************************************************
// algorithm
//*****************************************************************************
void test_algorithm()
{
int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
std::pair<int*, int*> result1;
std::pair<int, int> result2;
int x = 0;
int y = 1;
int* p;
bool b;
// minmax_element
result1 = etl::minmax_element(etl::begin(data), etl::end(data));
result1 = etl::minmax_element(etl::begin(data), etl::end(data), std::greater<int>());
// minmax
result2 = etl::minmax(x, y);
result2 = etl::minmax(x, y, std::greater<int>());
// is_sorted_until
p = etl::is_sorted_until(etl::begin(data), etl::end(data));
p = etl::is_sorted_until(etl::begin(data), etl::end(data), std::greater<int>());
// is_sorted
b = etl::is_sorted(etl::begin(data), etl::end(data));
b = etl::is_sorted(etl::begin(data), etl::end(data), std::greater<int>());
// copy_n
p = etl::copy_n(etl::begin(data), 5, etl::begin(data2));
// copy_if
p = etl::copy_if(etl::begin(data), etl::end(data), etl::begin(data2), std::bind2nd(std::greater<int>(), 4));
// find_if_not
p = etl::find_if_not(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// all_of
b = etl::all_of(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// any_of
b = etl::any_of(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// none_of
b = etl::none_of(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// is_permutation
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2));
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2), std::equal_to<int>());
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2), etl::end(data2));
b = etl::is_permutation(etl::begin(data), etl::end(data), etl::begin(data2), etl::end(data2), std::equal_to<int>());
// is_partitioned
b = etl::is_partitioned(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// partition_point
p = etl::partition_point(etl::begin(data), etl::end(data), std::bind2nd(std::greater<int>(), 4));
// partition_copy
result1 = etl::partition_copy(etl::begin(data), etl::end(data), etl::begin(data2), etl::begin(data3), std::bind2nd(std::greater<int>(), 4));
}
//*****************************************************************************
// alignment
//*****************************************************************************
etl::aligned_storage<100, 8>::type data9;
etl::aligned_storage_as<100, double>::type data10;
void test_alignment()
{
int a = static_cast<int&>(data9);
etl::aligned_storage<1, 1>::type data1;
etl::aligned_storage<1, 2>::type data2;
etl::aligned_storage<1, 4>::type data3;
etl::aligned_storage<1, 8>::type data4;
etl::aligned_storage_as<1, char>::type data5;
etl::aligned_storage_as<1, short>::type data6;
etl::aligned_storage_as<1, int>::type data7;
etl::aligned_storage_as<1, double>::type data8;
}
//*****************************************************************************
// array
//*****************************************************************************
void test_array()
{
etl::array<int, 10> a;
int i = a[4];
int s = a.size();
a.fill(45);
}
//*****************************************************************************
// bitset
//*****************************************************************************
void test_bitset()
{
etl::bitset<7> b7; // uint8_t
etl::bitset<8> b8; // uint8_t
etl::bitset<9> b9; // uint16_t
etl::bitset<15> b15; // uint16_t
etl::bitset<16> b16; // uint16_t
etl::bitset<17> b17; // uint32_t
etl::bitset<31> b31; // uint32_t
etl::bitset<32> b32; // uint32_t
etl::bitset<33> b33; // uint64_t
etl::bitset<63> b63; // uint64_t
etl::bitset<64> b64; // uint64_t
etl::bitset<65> b65; // 2 * uint64_t
b65.set();
b65.set(4, true);
b65.reset();
b65.reset(37);
b65 = ~b65;
bool b = b65[4];
b = b65[64];
b65.flip();
b65.flip(5);
etl::bitset<7>::iterator b1 = b7.begin();
etl::bitset<7>::iterator e1 = b7.end();
etl::bitset<7>::const_iterator b2 = b7.cbegin();
etl::bitset<7>::const_iterator e2 = b7.cend();
++b1;
--e1;
b2 += 2;
e2 -= 2;
*b1 = true;
const etl::bitset<7>::iterator b3 = b7.begin();
bool t = *b3;
}
//*****************************************************************************
// crc
//*****************************************************************************
void test_crc()
{
int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
uint8_t crc1 = etl::crc8_ccitt<>(etl::begin(data), etl::end(data));
uint8_t crc2 = etl::crc8_ccitt<etl::endian::big>(etl::begin(data), etl::end(data));
uint16_t crc3 = etl::crc16<>(etl::begin(data), etl::end(data));
uint16_t crc4 = etl::crc16<etl::endian::big>(etl::begin(data), etl::end(data));
uint16_t crc5 = etl::crc16_ccitt<>(etl::begin(data), etl::end(data));
uint16_t crc6 = etl::crc16_ccitt<etl::endian::big>(etl::begin(data), etl::end(data));
uint16_t crc7 = etl::crc16_kermit<>(etl::begin(data), etl::end(data));
uint16_t crc8 = etl::crc16_kermit<etl::endian::big>(etl::begin(data), etl::end(data));
uint32_t crc9 = etl::crc32<>(etl::begin(data), etl::end(data));
uint32_t crc10 = etl::crc32<etl::endian::big>(etl::begin(data), etl::end(data));
uint64_t crc11 = etl::crc64_ecma<>(etl::begin(data), etl::end(data));
uint64_t crc12 = etl::crc64_ecma<etl::endian::big>(etl::begin(data), etl::end(data));
}
//*****************************************************************************
// deque
//*****************************************************************************
void test_cyclic_value()
{
etl::cyclic_value<int, 1, 10> cv1;
etl::cyclic_value<int> cv2;
cv2.set(3, 8);
cv1.advance(3);
cv1.to_first();
cv1.to_last();
--cv1;
++cv1;
int f = cv1.first();
int l = cv1.last();
int v = cv1;
cv1 = v;
cv1 = cv2;
bool b;
b = cv1 == cv2;
b = cv1 != cv2;
}
template <uintptr_t ADDRESS>
struct serial_port
{
etl::io_port_ro<uint8_t, ADDRESS> rxdata;
etl::io_port_wo<uint8_t, ADDRESS + 1> txdata;
etl::io_port_rw<uint16_t, ADDRESS + 2> control;
etl::io_port_ro<uint16_t, ADDRESS + 4> status;
etl::io_port_wos<uint8_t, ADDRESS + 6> control2;
};
struct dynamic_serial_port
{
dynamic_serial_port(uint8_t* base)
: rxdata(base),
txdata(base + 1),
control(base + 2),
status(base + 4),
control2(base + 6)
{
}
etl::io_port_ro<uint8_t> rxdata;
etl::io_port_wo<uint8_t> txdata;
etl::io_port_rw<uint16_t> control;
etl::io_port_ro<uint16_t> status;
etl::io_port_wos<uint8_t> control2;
};
//*****************************************************************************
// io_port
//*****************************************************************************
void test_io_port()
{
serial_port<0x1234> port1;
uint8_t rxdata = port1.rxdata;
port1.txdata = 0x34;
port1.control = 0x5678; // Little endian.
uint16_t status = port1.status;
port1.control2 = 0xDE;
int control2 = port1.control2;
uint8_t memory[7];
dynamic_serial_port port2(memory);
uint8_t rxdata2 = port2.rxdata;
port2.txdata = 0x34;
port2.control = 0x5678; // Little endian.
uint16_t status2 = port2.status;
port2.control2 = 0xDE;
int control22 = port2.control2;
}
//*****************************************************************************
// variant
//*****************************************************************************
void test_variant()
{
typedef etl::variant<int, double, Test> Data;
Data data;
data = int(1);
int i = data;
data = double(2.2);
double d = data;
data = Test(3, 3.3);
Test test(data);
}
//*****************************************************************************
// deque
//*****************************************************************************
void test_deque()
{
typedef etl::deque<Test, 10> Data;
Data data;
data.push_back(Test(1, 1.1));
data.push_back(Test(2, 2.2));
Data::iterator it = data.begin();
data.erase(it);
}
//*****************************************************************************
// vector
//*****************************************************************************
void test_vector()
{
typedef etl::vector<Test, 10> Data;
Data data;
data.push_back(Test(1, 1.1));
data.push_back(Test(2, 2.2));
Data::iterator it = data.begin();
data.erase(it);
}
//*****************************************************************************
// main
//*****************************************************************************
int main()
{
test_algorithm();
test_alignment();
test_array();
test_bitset();
test_crc();
test_cyclic_value();
test_deque();
test_vector();
test_io_port();
}
<|endoftext|> |
<commit_before>#include "im3d_example.h"
static GLuint g_vaIm3d; // vertex array object
static GLuint g_vbIm3d; // vertex buffer
static GLuint g_shIm3dPoints;
static GLuint g_shIm3dLines;
static GLuint g_shIm3dTriangles;
using namespace Im3d;
// The draw callback is where Im3d draw lists are rendered by the application. Im3d::Draw can potentially
// call this function multiple times per primtive type, if sorting is enabled.
// The example below shows the simplest possible draw callback. Variations on this are possible, for example
// using a depth buffer. See the shader source file for more details.
// For VR, the simplest option is to call Im3d::Draw() once per eye with the appropriate framebuffer bound,
// passing the appropriate view-projection matrix. A more efficient scheme would be to render to both eyes
// inside the draw callback to avoid uploading the vertex data twice.
// Note that there is no guarantee that the data in _drawList will exist after this function exits.
void Im3d_Draw(const Im3d::DrawList& _drawList)
{
AppData& ad = GetAppData();
// setting the framebuffer, viewport and pipeline states can (and should) be done prior to calling Im3d::Draw
glAssert(glViewport(0, 0, (GLsizei)ad.m_viewportSize.x, (GLsizei)ad.m_viewportSize.y));
glAssert(glEnable(GL_BLEND));
glAssert(glBlendEquation(GL_FUNC_ADD));
glAssert(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
glAssert(glEnable(GL_PROGRAM_POINT_SIZE));
GLenum prim;
GLuint sh;
switch (_drawList.m_primType) {
case Im3d::DrawPrimitive_Points:
prim = GL_POINTS;
sh = g_shIm3dPoints;
glAssert(glDisable(GL_CULL_FACE)); // points are view-aligned
break;
case Im3d::DrawPrimitive_Lines:
prim = GL_LINES;
sh = g_shIm3dLines;
glAssert(glDisable(GL_CULL_FACE)); // lines are view-aligned
break;
case Im3d::DrawPrimitive_Triangles:
prim = GL_TRIANGLES;
sh = g_shIm3dTriangles;
//glAssert(glEnable(GL_CULL_FACE)); // culling valid for triangles, but optional
break;
default:
IM3D_ASSERT(false);
return;
};
glAssert(glBindVertexArray(g_vaIm3d));
glAssert(glBindBuffer(GL_ARRAY_BUFFER, g_vbIm3d));
glAssert(glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)_drawList.m_vertexCount * sizeof(Im3d::VertexData), (GLvoid*)_drawList.m_vertexData, GL_STREAM_DRAW));
glAssert(glUseProgram(sh));
glAssert(glUniform2f(glGetUniformLocation(sh, "uViewport"), ad.m_viewportSize.x, ad.m_viewportSize.y));
glAssert(glUniformMatrix4fv(glGetUniformLocation(sh, "uViewProjMatrix"), 1, false, (const GLfloat*)g_Example->m_camViewProj));
glAssert(glDrawArrays(prim, 0, (GLsizei)_drawList.m_vertexCount));
}
// At the top of each frame, the application must fill the Im3d::AppData struct and then call Im3d::NewFrame.
// The example below shows how to do this, in particular how to generate the 'cursor ray' from a mouse position
// which is necessary for interacting with gizmos.
void Im3d_Update()
{
AppData& ad = GetAppData();
ad.m_deltaTime = g_Example->m_deltaTime;
ad.m_viewportSize = Vec2((float)g_Example->m_width, (float)g_Example->m_height);
ad.m_viewOrigin = g_Example->m_camPos;
ad.m_tanHalfFov = tanf(g_Example->m_camFovRad * 0.5f);
// Cursor ray from mouse position; for VR this might be the position/orientation of the HMD or a tracked controller
Vec2 cursorPos = g_Example->getWindowRelativeCursor();
cursorPos = (cursorPos / ad.m_viewportSize) * 2.0f - 1.0f;
cursorPos.y = -cursorPos.y; // window origin is top-left, ndc is bottom-left
ad.m_cursorRayOrigin = ad.m_viewOrigin;
float aspect = ad.m_viewportSize.x / ad.m_viewportSize.y;
ad.m_cursorRayDirection = g_Example->m_camWorld * Normalize(Vec4(cursorPos.x * ad.m_tanHalfFov * aspect, cursorPos.y * ad.m_tanHalfFov, -1.0f, 0.0f));
// Fill the key state array; using GetAsyncKeyState here but this could equally well be done via the window proc.
// All key states have an equivalent 'Action_' enum which may be more intuitive to use for VR
// (e.g. Mouse_Down == Action_Select).
ad.m_keyDown[Im3d::Mouse_Left] = (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0;
Im3d::NewFrame();
}
bool Im3d_Init()
{
{
GLuint vs = LoadCompileShader(GL_VERTEX_SHADER, "im3d.glsl", "VERTEX_SHADER\0POINTS\0");
GLuint fs = LoadCompileShader(GL_FRAGMENT_SHADER, "im3d.glsl", "FRAGMENT_SHADER\0POINTS\0");
if (vs && fs) {
glAssert(g_shIm3dPoints = glCreateProgram());
glAssert(glAttachShader(g_shIm3dPoints, vs));
glAssert(glAttachShader(g_shIm3dPoints, fs));
bool ret = LinkShaderProgram(g_shIm3dPoints);
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(fs));
if (!ret) {
return false;
}
} else {
return false;
}
}
{
GLuint vs = LoadCompileShader(GL_VERTEX_SHADER, "im3d.glsl", "VERTEX_SHADER\0LINES\0");
GLuint gs = LoadCompileShader(GL_GEOMETRY_SHADER, "im3d.glsl", "GEOMETRY_SHADER\0LINES\0");
GLuint fs = LoadCompileShader(GL_FRAGMENT_SHADER, "im3d.glsl", "FRAGMENT_SHADER\0LINES\0");
if (vs && gs && fs) {
glAssert(g_shIm3dLines = glCreateProgram());
glAssert(glAttachShader(g_shIm3dLines, vs));
glAssert(glAttachShader(g_shIm3dLines, gs));
glAssert(glAttachShader(g_shIm3dLines, fs));
bool ret = LinkShaderProgram(g_shIm3dLines);
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(gs));
glAssert(glDeleteShader(fs));
if (!ret) {
return false;
}
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(fs));
} else {
return false;
}
}
{
GLuint vs = LoadCompileShader(GL_VERTEX_SHADER, "im3d.glsl", "VERTEX_SHADER\0TRIANGLES\0");
GLuint fs = LoadCompileShader(GL_FRAGMENT_SHADER, "im3d.glsl", "FRAGMENT_SHADER\0TRIANGLES\0");
if (vs && fs) {
glAssert(g_shIm3dTriangles = glCreateProgram());
glAssert(glAttachShader(g_shIm3dTriangles, vs));
glAssert(glAttachShader(g_shIm3dTriangles, fs));
bool ret = LinkShaderProgram(g_shIm3dTriangles);
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(fs));
if (!ret) {
return false;
}
} else {
return false;
}
}
glAssert(glCreateBuffers(1, &g_vbIm3d));;
glAssert(glCreateVertexArrays(1, &g_vaIm3d));
glAssert(glBindVertexArray(g_vaIm3d));
glAssert(glBindBuffer(GL_ARRAY_BUFFER, g_vbIm3d));
glAssert(glEnableVertexAttribArray(0));
glAssert(glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Im3d::VertexData), (GLvoid*)offsetof(Im3d::VertexData, m_positionSize)));
glAssert(glEnableVertexAttribArray(1));
glAssert(glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Im3d::VertexData), (GLvoid*)offsetof(Im3d::VertexData, m_color)));
glAssert(glBindVertexArray(0));
GetAppData().drawCallback = &Im3d_Draw;
return true;
}
void Im3d_Shutdown()
{
glAssert(glDeleteVertexArrays(1, &g_vaIm3d));
glAssert(glDeleteBuffers(1, &g_vbIm3d));
glAssert(glDeleteProgram(g_shIm3dPoints));
glAssert(glDeleteProgram(g_shIm3dLines));
glAssert(glDeleteProgram(g_shIm3dTriangles));
}
<commit_msg>Comment about view origin<commit_after>#include "im3d_example.h"
static GLuint g_vaIm3d; // vertex array object
static GLuint g_vbIm3d; // vertex buffer
static GLuint g_shIm3dPoints;
static GLuint g_shIm3dLines;
static GLuint g_shIm3dTriangles;
using namespace Im3d;
// The draw callback is where Im3d draw lists are rendered by the application. Im3d::Draw can potentially
// call this function multiple times per primtive type, if sorting is enabled.
// The example below shows the simplest possible draw callback. Variations on this are possible, for example
// using a depth buffer. See the shader source file for more details.
// For VR, the simplest option is to call Im3d::Draw() once per eye with the appropriate framebuffer bound,
// passing the appropriate view-projection matrix. A more efficient scheme would be to render to both eyes
// inside the draw callback to avoid uploading the vertex data twice.
// Note that there is no guarantee that the data in _drawList will exist after this function exits.
void Im3d_Draw(const Im3d::DrawList& _drawList)
{
AppData& ad = GetAppData();
// setting the framebuffer, viewport and pipeline states can (and should) be done prior to calling Im3d::Draw
glAssert(glViewport(0, 0, (GLsizei)ad.m_viewportSize.x, (GLsizei)ad.m_viewportSize.y));
glAssert(glEnable(GL_BLEND));
glAssert(glBlendEquation(GL_FUNC_ADD));
glAssert(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
glAssert(glEnable(GL_PROGRAM_POINT_SIZE));
GLenum prim;
GLuint sh;
switch (_drawList.m_primType) {
case Im3d::DrawPrimitive_Points:
prim = GL_POINTS;
sh = g_shIm3dPoints;
glAssert(glDisable(GL_CULL_FACE)); // points are view-aligned
break;
case Im3d::DrawPrimitive_Lines:
prim = GL_LINES;
sh = g_shIm3dLines;
glAssert(glDisable(GL_CULL_FACE)); // lines are view-aligned
break;
case Im3d::DrawPrimitive_Triangles:
prim = GL_TRIANGLES;
sh = g_shIm3dTriangles;
//glAssert(glEnable(GL_CULL_FACE)); // culling valid for triangles, but optional
break;
default:
IM3D_ASSERT(false);
return;
};
glAssert(glBindVertexArray(g_vaIm3d));
glAssert(glBindBuffer(GL_ARRAY_BUFFER, g_vbIm3d));
glAssert(glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)_drawList.m_vertexCount * sizeof(Im3d::VertexData), (GLvoid*)_drawList.m_vertexData, GL_STREAM_DRAW));
glAssert(glUseProgram(sh));
glAssert(glUniform2f(glGetUniformLocation(sh, "uViewport"), ad.m_viewportSize.x, ad.m_viewportSize.y));
glAssert(glUniformMatrix4fv(glGetUniformLocation(sh, "uViewProjMatrix"), 1, false, (const GLfloat*)g_Example->m_camViewProj));
glAssert(glDrawArrays(prim, 0, (GLsizei)_drawList.m_vertexCount));
}
// At the top of each frame, the application must fill the Im3d::AppData struct and then call Im3d::NewFrame.
// The example below shows how to do this, in particular how to generate the 'cursor ray' from a mouse position
// which is necessary for interacting with gizmos.
void Im3d_Update()
{
AppData& ad = GetAppData();
ad.m_deltaTime = g_Example->m_deltaTime;
ad.m_viewportSize = Vec2((float)g_Example->m_width, (float)g_Example->m_height);
ad.m_tanHalfFov = tanf(g_Example->m_camFovRad * 0.5f); // vertical fov
ad.m_viewOrigin = g_Example->m_camPos; // for VR use the head position
// Cursor ray from mouse position; for VR this might be the position/orientation of the HMD or a tracked controller
Vec2 cursorPos = g_Example->getWindowRelativeCursor();
cursorPos = (cursorPos / ad.m_viewportSize) * 2.0f - 1.0f;
cursorPos.y = -cursorPos.y; // window origin is top-left, ndc is bottom-left
ad.m_cursorRayOrigin = ad.m_viewOrigin;
float aspect = ad.m_viewportSize.x / ad.m_viewportSize.y;
ad.m_cursorRayDirection = g_Example->m_camWorld * Normalize(Vec4(cursorPos.x * ad.m_tanHalfFov * aspect, cursorPos.y * ad.m_tanHalfFov, -1.0f, 0.0f));
// Fill the key state array; using GetAsyncKeyState here but this could equally well be done via the window proc.
// All key states have an equivalent 'Action_' enum which may be more intuitive to use for VR
// (e.g. Mouse_Down == Action_Select).
ad.m_keyDown[Im3d::Mouse_Left] = (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0;
Im3d::NewFrame();
}
bool Im3d_Init()
{
{
GLuint vs = LoadCompileShader(GL_VERTEX_SHADER, "im3d.glsl", "VERTEX_SHADER\0POINTS\0");
GLuint fs = LoadCompileShader(GL_FRAGMENT_SHADER, "im3d.glsl", "FRAGMENT_SHADER\0POINTS\0");
if (vs && fs) {
glAssert(g_shIm3dPoints = glCreateProgram());
glAssert(glAttachShader(g_shIm3dPoints, vs));
glAssert(glAttachShader(g_shIm3dPoints, fs));
bool ret = LinkShaderProgram(g_shIm3dPoints);
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(fs));
if (!ret) {
return false;
}
} else {
return false;
}
}
{
GLuint vs = LoadCompileShader(GL_VERTEX_SHADER, "im3d.glsl", "VERTEX_SHADER\0LINES\0");
GLuint gs = LoadCompileShader(GL_GEOMETRY_SHADER, "im3d.glsl", "GEOMETRY_SHADER\0LINES\0");
GLuint fs = LoadCompileShader(GL_FRAGMENT_SHADER, "im3d.glsl", "FRAGMENT_SHADER\0LINES\0");
if (vs && gs && fs) {
glAssert(g_shIm3dLines = glCreateProgram());
glAssert(glAttachShader(g_shIm3dLines, vs));
glAssert(glAttachShader(g_shIm3dLines, gs));
glAssert(glAttachShader(g_shIm3dLines, fs));
bool ret = LinkShaderProgram(g_shIm3dLines);
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(gs));
glAssert(glDeleteShader(fs));
if (!ret) {
return false;
}
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(fs));
} else {
return false;
}
}
{
GLuint vs = LoadCompileShader(GL_VERTEX_SHADER, "im3d.glsl", "VERTEX_SHADER\0TRIANGLES\0");
GLuint fs = LoadCompileShader(GL_FRAGMENT_SHADER, "im3d.glsl", "FRAGMENT_SHADER\0TRIANGLES\0");
if (vs && fs) {
glAssert(g_shIm3dTriangles = glCreateProgram());
glAssert(glAttachShader(g_shIm3dTriangles, vs));
glAssert(glAttachShader(g_shIm3dTriangles, fs));
bool ret = LinkShaderProgram(g_shIm3dTriangles);
glAssert(glDeleteShader(vs));
glAssert(glDeleteShader(fs));
if (!ret) {
return false;
}
} else {
return false;
}
}
glAssert(glCreateBuffers(1, &g_vbIm3d));;
glAssert(glCreateVertexArrays(1, &g_vaIm3d));
glAssert(glBindVertexArray(g_vaIm3d));
glAssert(glBindBuffer(GL_ARRAY_BUFFER, g_vbIm3d));
glAssert(glEnableVertexAttribArray(0));
glAssert(glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Im3d::VertexData), (GLvoid*)offsetof(Im3d::VertexData, m_positionSize)));
glAssert(glEnableVertexAttribArray(1));
glAssert(glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Im3d::VertexData), (GLvoid*)offsetof(Im3d::VertexData, m_color)));
glAssert(glBindVertexArray(0));
GetAppData().drawCallback = &Im3d_Draw;
return true;
}
void Im3d_Shutdown()
{
glAssert(glDeleteVertexArrays(1, &g_vaIm3d));
glAssert(glDeleteBuffers(1, &g_vbIm3d));
glAssert(glDeleteProgram(g_shIm3dPoints));
glAssert(glDeleteProgram(g_shIm3dLines));
glAssert(glDeleteProgram(g_shIm3dTriangles));
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <cmath> // rand()
#include <sstream>
#include <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;
using namespace std::chrono;
std::string HTML_RESPONSE() {
const int color = rand();
/* HTML Fonts */
std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";
/* HTML */
std::stringstream stream;
stream << "<!DOCTYPE html><html><head>"
<< "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
<< "</head><body>"
<< "<h1 style='color: #" << std::hex << (color >> 8) << "'>"
<< "<span style='"+ubuntu_medium+"'>Include</span><span style='"+ubuntu_light+"'>OS</span></h1>"
<< "<h2>Now speaks TCP!</h2>"
// .... generate more dynamic content
<< "<p>This is improvised http, but proper stuff is in the works.</p>"
<< "<footer><hr/>© 2016, IncludeOS AS @ 60° north</footer>"
<< "</body></html>";
const std::string html = stream.str();
const std::string header
{
"HTTP/1.1 200 OK\n"
"Date: Mon, 01 Jan 1970 00:00:01 GMT\n"
"Server: IncludeOS prototype 4.0\n"
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\n"
"Content-Type: text/html; charset=UTF-8\n"
"Content-Length: "+std::to_string(html.size())+'\n'
"Accept-Ranges: bytes\n"
"Connection: close\n\n"
};
return header + html;
}
const std::string NOT_FOUND = "HTTP/1.1 404 Not Found \nConnection: close\n\n";
void Service::start() {
// Assign a driver (VirtioNet) to a network interface (eth0)
// @note: We could determine the appropirate driver dynamically, but then we'd
// have to include all the drivers into the image, which we want to avoid.
hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
// Bring up a network stack, attached to the nic
// @note : No parameters after 'nic' means we'll use DHCP for IP config.
inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);
// Static IP configuration, until we (possibly) get DHCP
// @note : Mostly to get a robust demo service that it works with and without DHCP
inet->network_config( { 10,0,0,42 }, // IP
{ 255,255,255,0 }, // Netmask
{ 10,0,0,1 }, // Gateway
{ 8,8,8,8 } ); // DNS
srand(OS::cycles_since_boot());
// Set up a TCP server on port 80
auto& server = inet->tcp().bind(80);
hw::PIT::instance().on_repeated_timeout(30s, []{
printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
});
// Add a TCP connection handler - here a hardcoded HTTP-service
server.onAccept([] (auto conn) -> bool {
printf("<Service> @onAccept - Connection attempt from: %s \n",
conn->to_string().c_str());
return true; // allow all connections
})
.onConnect([] (auto conn) {
printf("<Service> @onConnect - Connection successfully established.\n");
// read async with a buffer size of 1024 bytes
// define what to do when data is read
conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
// create string from buffer
std::string data { (char*)buf.get(), n };
printf("<Service> @read:\n%s\n", data.c_str());
if (data.find("GET / ") != std::string::npos) {
// create response
std::string response = HTML_RESPONSE();
// write the data from the string with the strings size
conn->write(response.data(), response.size(), [](size_t n) {
printf("<Service> @write: %u bytes written\n", n);
});
}
else {
conn->write(NOT_FOUND.data(), NOT_FOUND.size());
}
});
})
.onDisconnect([](auto conn, auto reason) {
printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
conn->close();
})
.onPacketReceived([](auto, auto packet) {
printf("@Packet: %s\n", packet->to_string().c_str());
})
.onError([](auto, auto err) {
printf("<Service> @onError - %s\n", err.what());
});
printf("*** TEST SERVICE STARTED *** \n");
}
<commit_msg>Removed whitespace from output<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <cmath> // rand()
#include <sstream>
#include <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;
using namespace std::chrono;
std::string HTML_RESPONSE() {
const int color = rand();
/* HTML Fonts */
std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";
/* HTML */
std::stringstream stream;
stream << "<!DOCTYPE html><html><head>"
<< "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
<< "</head><body>"
<< "<h1 style='color: #" << std::hex << (color >> 8) << "'>"
<< "<span style='"+ubuntu_medium+"'>Include</span><span style='"+ubuntu_light+"'>OS</span></h1>"
<< "<h2>Now speaks TCP!</h2>"
// .... generate more dynamic content
<< "<p>This is improvised http, but proper stuff is in the works.</p>"
<< "<footer><hr/>© 2016, IncludeOS AS @ 60° north</footer>"
<< "</body></html>";
const std::string html = stream.str();
const std::string header
{
"HTTP/1.1 200 OK\n"
"Date: Mon, 01 Jan 1970 00:00:01 GMT\n"
"Server: IncludeOS prototype 4.0\n"
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\n"
"Content-Type: text/html; charset=UTF-8\n"
"Content-Length: "+std::to_string(html.size())+'\n'
"Accept-Ranges: bytes\n"
"Connection: close\n\n"
};
return header + html;
}
const std::string NOT_FOUND = "HTTP/1.1 404 Not Found\nConnection: close\n\n";
void Service::start() {
// Assign a driver (VirtioNet) to a network interface (eth0)
// @note: We could determine the appropirate driver dynamically, but then we'd
// have to include all the drivers into the image, which we want to avoid.
hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
// Bring up a network stack, attached to the nic
// @note : No parameters after 'nic' means we'll use DHCP for IP config.
inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);
// Static IP configuration, until we (possibly) get DHCP
// @note : Mostly to get a robust demo service that it works with and without DHCP
inet->network_config( { 10,0,0,42 }, // IP
{ 255,255,255,0 }, // Netmask
{ 10,0,0,1 }, // Gateway
{ 8,8,8,8 } ); // DNS
srand(OS::cycles_since_boot());
// Set up a TCP server on port 80
auto& server = inet->tcp().bind(80);
hw::PIT::instance().on_repeated_timeout(30s, []{
printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
});
// Add a TCP connection handler - here a hardcoded HTTP-service
server.onAccept([] (auto conn) -> bool {
printf("<Service> @onAccept - Connection attempt from: %s \n",
conn->to_string().c_str());
return true; // allow all connections
})
.onConnect([] (auto conn) {
printf("<Service> @onConnect - Connection successfully established.\n");
// read async with a buffer size of 1024 bytes
// define what to do when data is read
conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
// create string from buffer
std::string data { (char*)buf.get(), n };
printf("<Service> @read:\n%s\n", data.c_str());
if (data.find("GET / ") != std::string::npos) {
// create response
std::string response = HTML_RESPONSE();
// write the data from the string with the strings size
conn->write(response.data(), response.size(), [](size_t n) {
printf("<Service> @write: %u bytes written\n", n);
});
}
else {
conn->write(NOT_FOUND.data(), NOT_FOUND.size());
}
});
})
.onDisconnect([](auto conn, auto reason) {
printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
conn->close();
})
.onPacketReceived([](auto, auto packet) {
printf("@Packet: %s\n", packet->to_string().c_str());
})
.onError([](auto, auto err) {
printf("<Service> @onError - %s\n", err.what());
});
printf("*** TEST SERVICE STARTED *** \n");
}
<|endoftext|> |
<commit_before>/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2011 Novell, Inc <[email protected]> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#ifndef _INTL_INSTANCE_HXX
#define _INTL_INSTANCE_HXX
#include <comphelper/processfactory.hxx>
#include <comphelper/componentfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
// ugly but so is this namespacing evil.
#define css ::com::sun::star
// Helper to share code between activators with a fallback MSF.
// Potentially this may also needs to find the library the component
// is implemented inside, but at least centralises this.
inline css::uno::Reference<css::uno::XInterface>
intl_createInstance( const css::uno::Reference< css::lang::XMultiServiceFactory > & xOptSF,
const char *serviceName, const char *context )
{
css::uno::Reference<css::uno::XInterface> xRet;
css::uno::Reference<css::lang::XMultiServiceFactory > xSMgr( xOptSF );
try {
if (!xSMgr.is())
xSMgr = ::comphelper::getProcessServiceFactory();
xRet = xSMgr->createInstance( rtl::OUString::createFromAscii( serviceName ) );
} catch (css::uno::Exception &e) {
#ifdef DBG_UTIL
ByteString aMsg( context );
aMsg += "ctor: Exception caught\n";
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#else
(void)e; (void)context;
#endif
xRet = css::uno::Reference<css::uno::XInterface>();
}
return xRet;
}
#endif // _INTL_INSTANCE_HXX
<commit_msg>fix build, add mode-lines, use rtl::OStringBuffer<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2011 Novell, Inc <[email protected]> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#ifndef _INTL_INSTANCE_HXX
#define _INTL_INSTANCE_HXX
#include <comphelper/processfactory.hxx>
#include <comphelper/componentfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <rtl/strbuf.hxx>
// ugly but so is this namespacing evil.
#define css ::com::sun::star
// Helper to share code between activators with a fallback MSF.
// Potentially this may also needs to find the library the component
// is implemented inside, but at least centralises this.
inline css::uno::Reference<css::uno::XInterface>
intl_createInstance( const css::uno::Reference< css::lang::XMultiServiceFactory > & xOptSF,
const char *serviceName, const char *context )
{
css::uno::Reference<css::uno::XInterface> xRet;
css::uno::Reference<css::lang::XMultiServiceFactory > xSMgr( xOptSF );
try
{
if (!xSMgr.is())
xSMgr = ::comphelper::getProcessServiceFactory();
xRet = xSMgr->createInstance( rtl::OUString::createFromAscii( serviceName ) );
}
catch (const css::uno::Exception &e)
{
#ifdef DBG_UTIL
rtl::OStringBuffer aMsg( context );
aMsg.append(RTL_CONSTASCII_STRINGPARAM("ctor: Exception caught\n"));
aMsg.append(rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8));
DBG_ERRORFILE(aMsg.getStr());
#else
(void)e; (void)context;
#endif
xRet = css::uno::Reference<css::uno::XInterface>();
}
return xRet;
}
#endif // _INTL_INSTANCE_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>//
// Created by mathias on 6/9/16.
//
#include "flightControl/blindFlight.h"
#include "OpenCv/CV_Handler.h"
#define NUM_THREADS 4
#define LOOP_RATE (50)
void *controlThread(void *thread_arg);
void *buttonThread(void *thread_arg);
void *cvThread(void *thread_arg);
void *navdataThread(void *thread_Arg);
bool started = false;
FlightController *controller;
CV_Handler *cvHandler;
Nav *navdata;
struct thread_data {
int argc;
char **argv;
};
struct thread_data td[NUM_THREADS];
int main(int argc, char **argv){
td[0].argc = argc;
td[0].argv = argv;
ros::init(argc, argv, "blindFlight");
ros::NodeHandle n;
controller = new FlightController(LOOP_RATE, n);
cvHandler = new CV_Handler();
navdata = new Nav(n);
pthread_t threads[NUM_THREADS];
pthread_create(&threads[0], NULL, buttonThread, &td[0]);
pthread_create(&threads[1], NULL, cvThread, &td[1]);
pthread_create(&threads[2], NULL, navdataThread, &td[2]);
ros::spin();
pthread_exit(NULL);
}
void *controlThread(void *thread_arg){
controller->run(navdata, cvHandler);
started = false;
pthread_exit(NULL);
}
void *navdataThread(void *thread_arg){
navdata->run();
pthread_exit(NULL);
}
void *buttonThread(void *thread_arg) {
struct thread_data *thread_data;
thread_data = (struct thread_data *) thread_arg;
// Creating Control panel
QApplication a(thread_data->argc, thread_data->argv);
ControlPanel w;
w.show();
a.exec();
pthread_exit(NULL);
}
void *cvThread(void *thread_arg) {
cvHandler->run();
pthread_exit(NULL);
}
void blindFlight::abortProgram(void) {
ROS_INFO("MANUEL ABORT!");
controller->land();
}
void blindFlight::resetProgram(void) {
ROS_INFO("MANUEL RESET!");
controller->reset();
}
void blindFlight::startProgram(void) {
if (!started) {
ROS_INFO("STARTING!");
pthread_t thread;
pthread_create(&thread, NULL, controlThread, &td[0]);
started = true;
}
}<commit_msg>Removed stupid include<commit_after>//
// Created by mathias on 6/9/16.
//
#include <QApplication>
#include "OpenCv/CV_Handler.h"
#include "flightControl/FlightController.h"
#include "GUI/ControlPanel/controlpanel.h"
#define NUM_THREADS 4
#define LOOP_RATE (50)
void *controlThread(void *thread_arg);
void *buttonThread(void *thread_arg);
void *cvThread(void *thread_arg);
void *navdataThread(void *thread_Arg);
bool started = false;
FlightController *controller;
CV_Handler *cvHandler;
Nav *navdata;
struct thread_data {
int argc;
char **argv;
};
struct thread_data td[NUM_THREADS];
int main(int argc, char **argv){
td[0].argc = argc;
td[0].argv = argv;
ros::init(argc, argv, "blindFlight");
ros::NodeHandle n;
controller = new FlightController(LOOP_RATE, n);
cvHandler = new CV_Handler();
navdata = new Nav(n);
pthread_t threads[NUM_THREADS];
pthread_create(&threads[0], NULL, buttonThread, &td[0]);
pthread_create(&threads[1], NULL, cvThread, &td[1]);
pthread_create(&threads[2], NULL, navdataThread, &td[2]);
ros::spin();
pthread_exit(NULL);
}
void *controlThread(void *thread_arg){
controller->run(navdata, cvHandler);
started = false;
pthread_exit(NULL);
}
void *navdataThread(void *thread_arg){
navdata->run();
pthread_exit(NULL);
}
void *buttonThread(void *thread_arg) {
struct thread_data *thread_data;
thread_data = (struct thread_data *) thread_arg;
// Creating Control panel
QApplication a(thread_data->argc, thread_data->argv);
ControlPanel w;
w.show();
a.exec();
pthread_exit(NULL);
}
void *cvThread(void *thread_arg) {
cvHandler->run();
pthread_exit(NULL);
}
void blindFlight::abortProgram(void) {
ROS_INFO("MANUEL ABORT!");
controller->land();
}
void blindFlight::resetProgram(void) {
ROS_INFO("MANUEL RESET!");
controller->reset();
}
void blindFlight::startProgram(void) {
if (!started) {
ROS_INFO("STARTING!");
pthread_t thread;
pthread_create(&thread, NULL, controlThread, &td[0]);
started = true;
}
}<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <arrayfire.h>
#include <iostream>
#include <cstdio>
using namespace af;
using namespace std;
static const int width = 512, height = 512;
void simulate(af::array &parts, af::array &vels, af::array &forces){
parts += vels;
//calculate distance to center
float center_coors[2] = { width / 2, height / 2 };
af::array col = tile(af::array(1, 2, center_coors), parts.dims(0));
af::array diff = parts - col;
af::array dist = sqrt( diff.col(0)*diff.col(0) + diff.col(1)*diff.col(1) );
forces = -1 * diff;
forces.col(0) /= dist; //normalize force vectors
forces.col(1) /= dist; //normalize force vectors
//update velocities from forces
vels += forces;
}
void collisions(af::array &parts, af::array &vels){
//clamp particles inside screen border
parts.col(0) = min(width, max(0, parts.col(0)));
parts.col(1) = min(height - 1, max(0, parts.col(1)));
//calculate distance to center
float center_coors[2] = { width / 2, height / 2 };
af::array col = tile(af::array(1, 2, center_coors), parts.dims(0));
af::array diff = parts - col;
af::array dist = sqrt( diff.col(0)*diff.col(0) + diff.col(1)*diff.col(1) );
/*
//collide with center sphere
int radius = 50;
af::array col_ids = dist(dist<radius);
if(col_ids.dims(0) > 0) {
//vels(col_ids, span) += -1 * parts(col_ids, span);
vels(col_ids, span) = 0;
}
*/
}
int main(int argc, char *argv[])
{
try {
const static int total_particles=200;
static const int reset = 500;
af::info();
af::Window myWindow(width, height, "Gravity Simulation using ArrayFire");
int frame_count = 0;
// Initialize the kernel array just once
const af::array draw_kernel = gaussianKernel(3, 3);
// Generate a random starting state
af::array particles = af::randu(total_particles,2);
particles.col(0) *= width;
particles.col(1) *= height;
af::array velocities = af::randn(total_particles, 2);
af::array forces = af::randn(total_particles, 2);
af::array image = af::constant(0, width, height);
af::array ids(total_particles, u32);
while(!myWindow.close()) {
ids = (particles.col(0).as(u32) * height) + particles.col(1).as(u32);
image(ids) += 255;
image = convolve2(image, draw_kernel);
myWindow.image(image);
image(span, span) = 0;
frame_count++;
// Generate a random starting state
if(frame_count % reset == 0) {
particles = af::randu(total_particles,2);
particles.col(0) *= width;
particles.col(1) *= height;
velocities = af::randn(total_particles, 2);
}
//run force simulation and update particles
simulate(particles, velocities, forces);
//check for collisions and adjust velocities accordingly
collisions(particles, velocities);
}
} catch (af::exception& e) {
fprintf(stderr, "%s\n", e.what());
throw;
}
#ifdef WIN32 // pause in Windows
if (!(argc == 2 && argv[1][0] == '-')) {
printf("hit [enter]...");
fflush(stdout);
getchar();
}
#endif
return 0;
}
<commit_msg>add collisions, split vectors into components for performance<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <arrayfire.h>
#include <iostream>
#include <cstdio>
using namespace af;
using namespace std;
static const int width = 512, height = 512;
static const int pixels_per_unit = 20;
af::array p_x;
af::array p_y;
af::array vels_x;
af::array vels_y;
af::array forces_x;
af::array forces_y;
void simulate(float dt){
p_x += vels_x * pixels_per_unit * dt;
p_y += vels_y * pixels_per_unit * dt;
//calculate distance to center
af::array diff_x = p_x - width/2;
af::array diff_y = p_y - height/2;
af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );
//calculate normalised force vectors
forces_x = -1 * diff_x / dist;
forces_y = -1 * diff_y / dist;
//update force scaled to time and magnitude constant
forces_x *= pixels_per_unit * dt;
forces_y *= pixels_per_unit * dt;
//dampening
vels_x *= 1 - (0.005*dt);
vels_y *= 1 - (0.005*dt);
//update velocities from forces
vels_x += forces_x;
vels_y += forces_y;
}
void collisions(){
//clamp particles inside screen border
af::array projected_px = min(width, max(0, p_x));
af::array projected_py = min(height - 1, max(0, p_y));
//calculate distance to center
af::array diff_x = projected_px - width/2;
af::array diff_y = projected_py - height/2;
af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );
//collide with center sphere
const int radius = 50;
const float elastic_constant = 0.91f;
if(sum<int>(dist<radius) > 0) {
vels_x(dist<radius) = -elastic_constant * vels_x(dist<radius);
vels_y(dist<radius) = -elastic_constant * vels_y(dist<radius);
//normalize diff vector
diff_x /= dist;
diff_y /= dist;
//place all particle colliding with sphere on surface
p_x(dist<radius) = width/2 + diff_x(dist<radius) * radius;
p_y(dist<radius) = height/2 + diff_y(dist<radius) * radius;
}
}
int main(int argc, char *argv[])
{
try {
const static int total_particles = 1000;
static const int reset = 500;
af::info();
af::Window myWindow(width, height, "Gravity Simulation using ArrayFire");
int frame_count = 0;
// Initialize the kernel array just once
const af::array draw_kernel = gaussianKernel(3, 3);
// Generate a random starting state
p_x = af::randu(total_particles) * width;
p_y = af::randu(total_particles) * height;
vels_x = af::randn(total_particles);
vels_y = af::randn(total_particles);
forces_x = af::randn(total_particles);
forces_y = af::randn(total_particles);
af::array image = af::constant(0, width, height);
af::array ids(total_particles, u32);
af::timer timer = af::timer::start();
while(!myWindow.close()) {
float dt = af::timer::stop(timer);
timer = af::timer::start();
ids = (p_x.as(u32) * height) + p_y.as(u32);
image(ids) += 255;
image = convolve2(image, draw_kernel);
myWindow.image(image);
image = af::constant(0, image.dims());
frame_count++;
// Generate a random starting state
if(frame_count % reset == 0) {
p_x = af::randu(total_particles) * width;
p_y = af::randu(total_particles) * height;
vels_x = af::randn(total_particles);
vels_y = af::randn(total_particles);
}
//check for collisions and adjust velocities accordingly
collisions();
//run force simulation and update particles
simulate(dt);
}
} catch (af::exception& e) {
fprintf(stderr, "%s\n", e.what());
throw;
}
#ifdef WIN32 // pause in Windows
if (!(argc == 2 && argv[1][0] == '-')) {
printf("hit [enter]...");
fflush(stdout);
getchar();
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>//
// LinearFilter.h
// Clock Signal
//
// Created by Thomas Harte on 01/10/2011.
// Copyright 2011 Thomas Harte. All rights reserved.
//
#ifndef FIRFilter_hpp
#define FIRFilter_hpp
/*
The FIR filter takes a 1d PCM signal with
a given sample rate and filters it according
to a specified filter (band pass only at
present, more to come if required). The number
of taps (ie, samples considered simultaneously
to make an output sample) is configurable;
smaller numbers permit a filter that operates
more quickly and with less lag but less
effectively.
FIR filters are window functions; expected use is
to point sample an input that has been subject to
a filter.
*/
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#else
#define kCSKaiserBesselFilterFixedMultiplier 32767.0f
#define kCSKaiserBesselFilterFixedShift 15
#endif
namespace SignalProcessing {
class FIRFilter {
public:
/*!
Creates an instance of @c FIRFilter.
@param number_of_taps The size of window for input data.
@param input_sample_rate The sampling rate of the input signal.
@param low_frequency The lowest frequency of signal to retain in the output.
@param high_frequency The highest frequency of signal to retain in the output.
@param attenuation The attenuation of the discarded frequencies.
*/
FIRFilter(unsigned int number_of_taps, float input_sample_rate, float low_frequency, float high_frequency, float attenuation);
~FIRFilter();
/*! A suggested default attenuation value. */
constexpr static float DefaultAttenuation = 60.0f;
/*!
Applies the filter to one batch of input samples, returning the net result.
@param src The source buffer to apply the filter to.
@returns The result of applying the filter.
*/
inline short apply(const short *src) {
#ifdef __APPLE__
short result;
vDSP_dotpr_s1_15(filter_coefficients_, 1, src, 1, &result, number_of_taps_);
return result;
#else
int outputValue = 0;
for(unsigned int c = 0; c < number_of_taps_; c++) {
outputValue += filter_coefficients_[c] * src[c];
}
return (short)(outputValue >> kCSKaiserBesselFilterFixedShift);
#endif
}
inline unsigned int get_number_of_taps() {
return number_of_taps_;
}
void get_coefficients(float *coefficients);
private:
short *filter_coefficients_;
unsigned int number_of_taps_;
static void coefficients_for_idealised_filter_response(short *filterCoefficients, float *A, float attenuation, unsigned int numberOfTaps);
static float ino(float a);
};
}
#endif
<commit_msg>Fixes the FIR filter again from the Apple side.<commit_after>//
// LinearFilter.h
// Clock Signal
//
// Created by Thomas Harte on 01/10/2011.
// Copyright 2011 Thomas Harte. All rights reserved.
//
#ifndef FIRFilter_hpp
#define FIRFilter_hpp
/*
The FIR filter takes a 1d PCM signal with
a given sample rate and filters it according
to a specified filter (band pass only at
present, more to come if required). The number
of taps (ie, samples considered simultaneously
to make an output sample) is configurable;
smaller numbers permit a filter that operates
more quickly and with less lag but less
effectively.
FIR filters are window functions; expected use is
to point sample an input that has been subject to
a filter.
*/
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#endif
namespace SignalProcessing {
class FIRFilter {
private:
static constexpr float kCSKaiserBesselFilterFixedMultiplier = 32767.0f;
static constexpr int kCSKaiserBesselFilterFixedShift = 15;
public:
/*!
Creates an instance of @c FIRFilter.
@param number_of_taps The size of window for input data.
@param input_sample_rate The sampling rate of the input signal.
@param low_frequency The lowest frequency of signal to retain in the output.
@param high_frequency The highest frequency of signal to retain in the output.
@param attenuation The attenuation of the discarded frequencies.
*/
FIRFilter(unsigned int number_of_taps, float input_sample_rate, float low_frequency, float high_frequency, float attenuation);
~FIRFilter();
/*! A suggested default attenuation value. */
constexpr static float DefaultAttenuation = 60.0f;
/*!
Applies the filter to one batch of input samples, returning the net result.
@param src The source buffer to apply the filter to.
@returns The result of applying the filter.
*/
inline short apply(const short *src) {
#ifdef __APPLE__
short result;
vDSP_dotpr_s1_15(filter_coefficients_, 1, src, 1, &result, number_of_taps_);
return result;
#else
int outputValue = 0;
for(unsigned int c = 0; c < number_of_taps_; c++) {
outputValue += filter_coefficients_[c] * src[c];
}
return (short)(outputValue >> kCSKaiserBesselFilterFixedShift);
#endif
}
inline unsigned int get_number_of_taps() {
return number_of_taps_;
}
void get_coefficients(float *coefficients);
private:
short *filter_coefficients_;
unsigned int number_of_taps_;
static void coefficients_for_idealised_filter_response(short *filterCoefficients, float *A, float attenuation, unsigned int numberOfTaps);
static float ino(float a);
};
}
#endif
<|endoftext|> |
<commit_before>#include "PlatformEntity.h"
PlatformEntity::PlatformEntity() {}
PlatformEntity::~PlatformEntity()
{
this->Shutdown();
}
int PlatformEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, AIComponent * aiComp)
{
int result = 0;
this->InitializeBase(entityID, pComp, gComp, nullptr, aiComp);
return result;
}
int PlatformEntity::Shutdown()
{
int result = 0;
if (this->m_ActiveSound != nullptr)
this->m_ActiveSound->drop();
return result;
}
int PlatformEntity::Update(float deltaTime, InputHandler * inputHandler)
{
int result = 0;
this->SyncComponents();
// Adjust misplaced graphics component - hack...
this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort,
DirectX::XMMatrixTranslationFromVector(
DirectX::XMVectorSubtract(this->m_pComp->PC_pos,
DirectX::XMVECTOR{
m_gComp->modelPtr->GetOBBData().position.x,
m_gComp->modelPtr->GetOBBData().position.y,
m_gComp->modelPtr->GetOBBData().position.z, 0})));
if (this->GetAIComponent()->AC_triggered)
{
if (this->m_ActiveSound == nullptr)
{
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
this->m_ActiveSound = SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LIFT, pos, true, true);
}
else
{
if (this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setIsPaused(false);
}
}
}
else
{
if (this->m_ActiveSound != nullptr && !this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setPlayPosition(0);
this->m_ActiveSound->setIsPaused(true); //Pause the walking sound
}
}
return result;
}
int PlatformEntity::React(int entityID, EVENT reactEvent)
{
switch (reactEvent)
{
//case FIELD_CONTAINS:
// break;
//case FIELD_ENTERED:
// break;
//case FIELD_EXITED:
// break;
//case FIELD_CONDITIONS_MET:
// break;
//case FIELD_ENABLED:
// break;
//case FIELD_DISABLED:
// break;
case BUTTON_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case BUTTON_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
case LEVER_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case LEVER_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
case WHEEL_INCREASING:
printf("INCREASING\n");
this->GetAIComponent()->AC_triggered = true;
break;
case WHEEL_DECREASING:
printf("INCREASING\n");
this->GetAIComponent()->AC_triggered = true;
break;
case WHEEL_RESET:
printf("RESET\n");
//this->GetAIComponent()->AC_triggered = false;
int temp;
if (this->GetAIComponent()->AC_direction == 0)
{
this->GetAIComponent()->AC_direction = 1;
/*int i = this->GetAIComponent()->AC_nextWaypointID;
int k = this->GetAIComponent()->AC_latestWaypointID;*/
temp = this->GetAIComponent()->AC_nextWaypointID;
this->GetAIComponent()->AC_nextWaypointID = this->GetAIComponent()->AC_latestWaypointID;
this->GetAIComponent()->AC_latestWaypointID = temp;
this->GetAIComponent()->AC_WaypointUpdated = false;
}
else
{
this->GetAIComponent()->AC_direction = 0;
temp = this->GetAIComponent()->AC_nextWaypointID;
this->GetAIComponent()->AC_nextWaypointID = this->GetAIComponent()->AC_latestWaypointID;
this->GetAIComponent()->AC_latestWaypointID = temp;
this->GetAIComponent()->AC_WaypointUpdated = false;
}
break;
default:
break;
}
return 1;
}<commit_msg>UPDATE Moved Logic from PlatformEntity<commit_after>#include "PlatformEntity.h"
PlatformEntity::PlatformEntity() {}
PlatformEntity::~PlatformEntity()
{
this->Shutdown();
}
int PlatformEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, AIComponent * aiComp)
{
int result = 0;
this->InitializeBase(entityID, pComp, gComp, nullptr, aiComp);
return result;
}
int PlatformEntity::Shutdown()
{
int result = 0;
if (this->m_ActiveSound != nullptr)
this->m_ActiveSound->drop();
return result;
}
int PlatformEntity::Update(float deltaTime, InputHandler * inputHandler)
{
int result = 0;
this->SyncComponents();
// Adjust misplaced graphics component - hack...
this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort,
DirectX::XMMatrixTranslationFromVector(
DirectX::XMVectorSubtract(this->m_pComp->PC_pos,
DirectX::XMVECTOR{
m_gComp->modelPtr->GetOBBData().position.x,
m_gComp->modelPtr->GetOBBData().position.y,
m_gComp->modelPtr->GetOBBData().position.z, 0})));
if (this->GetAIComponent()->AC_triggered)
{
if (this->m_ActiveSound == nullptr)
{
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
this->m_ActiveSound = SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LIFT, pos, true, true);
}
else
{
if (this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setIsPaused(false);
}
}
}
else
{
if (this->m_ActiveSound != nullptr && !this->m_ActiveSound->getIsPaused())
{
this->m_ActiveSound->setPlayPosition(0);
this->m_ActiveSound->setIsPaused(true); //Pause the walking sound
}
}
return result;
}
int PlatformEntity::React(int entityID, EVENT reactEvent)
{
switch (reactEvent)
{
//case FIELD_CONTAINS:
// break;
//case FIELD_ENTERED:
// break;
//case FIELD_EXITED:
// break;
//case FIELD_CONDITIONS_MET:
// break;
//case FIELD_ENABLED:
// break;
//case FIELD_DISABLED:
// break;
case BUTTON_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case BUTTON_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
case LEVER_DEACTIVE:
this->GetAIComponent()->AC_triggered = false;
break;
case LEVER_ACTIVE:
this->GetAIComponent()->AC_triggered = true;
break;
case WHEEL_INCREASING:
printf("INCREASING\n");
this->GetAIComponent()->AC_triggered = true;
this->GetAIComponent()->AC_reset = false;
break;
case WHEEL_DECREASING:
printf("INCREASING\n");
this->GetAIComponent()->AC_triggered = true;
//this->GetAIComponent()->AC_reset = false;
break;
case WHEEL_RESET:
printf("RESET\n");
this->GetAIComponent()->AC_triggered = true;
//this->GetAIComponent()->AC_reset = true;
break;
default:
break;
}
return 1;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Facebook, 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 <vector>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <osquery/config.h>
#include <osquery/enroll.h>
#include <osquery/flags.h>
#include <osquery/registry.h>
#include "osquery/dispatcher/dispatcher.h"
#include "osquery/remote/requests.h"
#include "osquery/remote/serializers/json.h"
#include "osquery/remote/utility.h"
#include "osquery/core/conversions.h"
namespace pt = boost::property_tree;
namespace osquery {
CLI_FLAG(uint64,
config_tls_max_attempts,
3,
"Number of attempts to retry a TLS config/enroll request");
/// Config retrieval TLS endpoint (path) using TLS hostname.
CLI_FLAG(string,
config_tls_endpoint,
"",
"TLS/HTTPS endpoint for config retrieval");
/// Config polling/updating, only applies to TLS configurations.
CLI_FLAG(uint64,
config_tls_refresh,
0,
"Optional interval in seconds to re-read configuration");
DECLARE_bool(tls_secret_always);
DECLARE_string(tls_enroll_override);
DECLARE_bool(tls_node_api);
class TLSConfigPlugin;
class TLSConfigPlugin : public ConfigPlugin,
std::enable_shared_from_this<TLSConfigPlugin> {
public:
Status setUp() override;
Status genConfig(std::map<std::string, std::string>& config) override;
protected:
/// Calculate the URL once and cache the result.
std::string uri_;
};
class TLSConfigRefreshRunner : public InternalRunnable {
public:
explicit TLSConfigRefreshRunner(
const std::shared_ptr<TLSConfigPlugin>& plugin)
: plugin_(plugin) {}
/// A simple wait/interruptible lock.
void start();
private:
std::shared_ptr<TLSConfigPlugin> plugin_{nullptr};
};
REGISTER(TLSConfigPlugin, "config", "tls");
Status TLSConfigPlugin::setUp() {
// If the initial configuration includes a non-0 refresh, start an additional
// service that sleeps and periodically regenerates the configuration.
if (FLAGS_config_tls_refresh >= 1) {
Dispatcher::addService(
std::make_shared<TLSConfigRefreshRunner>(shared_from_this()));
}
uri_ = TLSRequestHelper::makeURI(FLAGS_config_tls_endpoint);
return Status(0, "OK");
}
Status TLSConfigPlugin::genConfig(std::map<std::string, std::string>& config) {
std::string json;
auto s = TLSRequestHelper::go<JSONSerializer>(
uri_, json, FLAGS_config_tls_max_attempts);
if (!s.ok()) {
return s;
}
if (FLAGS_tls_node_api) {
// The node API embeds configuration data (JSON escaped).
pt::ptree tree;
try {
std::stringstream input;
input << json;
pt::read_json(input, tree);
} catch (const pt::json_parser::json_parser_error& e) {
VLOG(1) << "Could not parse JSON from TLS node API";
}
// Re-encode the config key into JSON.
config["tls_plugin"] = unescapeUnicode(tree.get("config", ""));
} else {
config["tls_plugin"] = json;
}
return s;
}
void TLSConfigRefreshRunner::start() {
while (true) {
// Cool off and time wait the configured period.
// Apply this interruption initially as at t=0 the config was read.
osquery::interruptableSleep(FLAGS_config_tls_refresh * 1000);
// The config instance knows the TLS plugin is selected.
std::map<std::string, std::string> config;
if (plugin_->genConfig(config)) {
Config::getInstance().update(config);
}
}
}
}
<commit_msg>Fix quick regression with config refresh runner<commit_after>/*
* Copyright (c) 2014, Facebook, 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 <vector>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <osquery/config.h>
#include <osquery/enroll.h>
#include <osquery/flags.h>
#include <osquery/registry.h>
#include "osquery/dispatcher/dispatcher.h"
#include "osquery/remote/requests.h"
#include "osquery/remote/serializers/json.h"
#include "osquery/remote/utility.h"
#include "osquery/core/conversions.h"
namespace pt = boost::property_tree;
namespace osquery {
CLI_FLAG(uint64,
config_tls_max_attempts,
3,
"Number of attempts to retry a TLS config/enroll request");
/// Config retrieval TLS endpoint (path) using TLS hostname.
CLI_FLAG(string,
config_tls_endpoint,
"",
"TLS/HTTPS endpoint for config retrieval");
/// Config polling/updating, only applies to TLS configurations.
CLI_FLAG(uint64,
config_tls_refresh,
0,
"Optional interval in seconds to re-read configuration");
DECLARE_bool(tls_secret_always);
DECLARE_string(tls_enroll_override);
DECLARE_bool(tls_node_api);
class TLSConfigPlugin;
class TLSConfigPlugin : public ConfigPlugin,
std::enable_shared_from_this<TLSConfigPlugin> {
public:
Status setUp() override;
Status genConfig(std::map<std::string, std::string>& config) override;
protected:
/// Calculate the URL once and cache the result.
std::string uri_;
};
class TLSConfigRefreshRunner : public InternalRunnable {
public:
/// A simple wait/interruptible lock.
void start();
};
REGISTER(TLSConfigPlugin, "config", "tls");
Status TLSConfigPlugin::setUp() {
uri_ = TLSRequestHelper::makeURI(FLAGS_config_tls_endpoint);
// If the initial configuration includes a non-0 refresh, start an additional
// service that sleeps and periodically regenerates the configuration.
if (FLAGS_config_tls_refresh >= 1) {
Dispatcher::addService(std::make_shared<TLSConfigRefreshRunner>());
}
return Status(0, "OK");
}
Status TLSConfigPlugin::genConfig(std::map<std::string, std::string>& config) {
std::string json;
auto s = TLSRequestHelper::go<JSONSerializer>(
uri_, json, FLAGS_config_tls_max_attempts);
if (!s.ok()) {
return s;
}
if (FLAGS_tls_node_api) {
// The node API embeds configuration data (JSON escaped).
pt::ptree tree;
try {
std::stringstream input;
input << json;
pt::read_json(input, tree);
} catch (const pt::json_parser::json_parser_error& e) {
VLOG(1) << "Could not parse JSON from TLS node API";
}
// Re-encode the config key into JSON.
config["tls_plugin"] = unescapeUnicode(tree.get("config", ""));
} else {
config["tls_plugin"] = json;
}
return s;
}
void TLSConfigRefreshRunner::start() {
while (true) {
// Cool off and time wait the configured period.
// Apply this interruption initially as at t=0 the config was read.
osquery::interruptableSleep(FLAGS_config_tls_refresh * 1000);
// Access the configuration.
auto plugin = Registry::get("config", "tls");
if (plugin != nullptr) {
auto config_plugin = std::dynamic_pointer_cast<ConfigPlugin>(plugin);
// The config instance knows the TLS plugin is selected.
std::map<std::string, std::string> config;
if (config_plugin->genConfig(config)) {
Config::getInstance().update(config);
}
}
}
}
}
<|endoftext|> |
<commit_before>#include <mlk/network/network.h>
int main()
{
// create a udp socket
mlk::ntw::sock<mlk::ntw::sock_type::udp, false> udp_sock; // the boolean sets blocking mode(true) or non-blocking mode(false)
mlk::ntw::ip_address to_addr{"my_address.com:my_port"}; // <- this will look up the ip from host 'my_address.com'
// possible alternative: addr{"192.168.1.1, 80, false"}; <- this will NOT look up the ip address
mlk::data_packet data{'r', 'e', 'q', 'u', 'e', 's', 't'};
udp_sock.send(to_addr, data); // send data to host
mlk::ntw::ip_address from_addr;
udp_sock.recv(from_addr, data, 1024); // better: loop this recv when mode is non-blocking
if(!udp_sock.error())
std::cout << data.data() << std::endl; // display the got data response
// TCP isnt implemented yet
}
<commit_msg>forgot include<commit_after>#include <mlk/network/network.h>
#include <iostream>
int main()
{
// create a udp socket
mlk::ntw::sock<mlk::ntw::sock_type::udp, false> udp_sock; // the boolean sets blocking mode(true) or non-blocking mode(false)
mlk::ntw::ip_address to_addr{"my_address.com:my_port"}; // <- this will look up the ip from host 'my_address.com'
// possible alternative: addr{"192.168.1.1, 80, false"}; <- this will NOT look up the ip address
mlk::data_packet data{'r', 'e', 'q', 'u', 'e', 's', 't'};
udp_sock.send(to_addr, data); // send data to host
mlk::ntw::ip_address from_addr;
udp_sock.recv(from_addr, data, 1024); // better: loop this recv when mode is non-blocking
if(!udp_sock.error())
std::cout << data.data() << std::endl; // display the got data response
// TCP isnt implemented yet
}
<|endoftext|> |
<commit_before>// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "NdiMediaPrivate.h"
#include "Modules/ModuleManager.h"
#include "INdiMediaModule.h"
#include "Ndi.h"
#include "NdiMediaFinder.h"
#include "NdiMediaPlayer.h"
DEFINE_LOG_CATEGORY(LogNdiMedia);
#define LOCTEXT_NAMESPACE "FNdiMediaModule"
/**
* Implements the NdiMedia module.
*/
class FNdiMediaModule
: public INdiMediaModule
{
public:
/** Default constructor. */
FNdiMediaModule()
: Initialized(false)
{ }
public:
//~ INdiMediaModule interface
virtual TSharedPtr<IMediaPlayer, ESPMode::ThreadSafe> CreatePlayer(IMediaEventSink& EventSink) override
{
if (!Initialized)
{
return nullptr;
}
return MakeShared<FNdiMediaPlayer, ESPMode::ThreadSafe>(EventSink);
}
public:
//~ IModuleInterface interface
virtual void StartupModule() override
{
// initialize NDI
if (!FNdi::Initialize())
{
UE_LOG(LogNdiMedia, Error, TEXT("Failed to initialize NDI"));
return;
}
// initialize NDI finder
GetMutableDefault<UNdiMediaFinder>()->Initialize();
Initialized = true;
}
virtual void ShutdownModule() override
{
if (!Initialized)
{
return;
}
Initialized = false;
// shut down NDI
FNdi::Shutdown();
}
private:
/** Whether the module has been initialized. */
bool Initialized;
};
IMPLEMENT_MODULE(FNdiMediaModule, NdiMedia);
#undef LOCTEXT_NAMESPACE
<commit_msg>Always shut down NDI on plug-in unload.<commit_after>// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "NdiMediaPrivate.h"
#include "Modules/ModuleManager.h"
#include "INdiMediaModule.h"
#include "Ndi.h"
#include "NdiMediaFinder.h"
#include "NdiMediaPlayer.h"
DEFINE_LOG_CATEGORY(LogNdiMedia);
#define LOCTEXT_NAMESPACE "FNdiMediaModule"
/**
* Implements the NdiMedia module.
*/
class FNdiMediaModule
: public INdiMediaModule
{
public:
/** Default constructor. */
FNdiMediaModule()
: Initialized(false)
{ }
public:
//~ INdiMediaModule interface
virtual TSharedPtr<IMediaPlayer, ESPMode::ThreadSafe> CreatePlayer(IMediaEventSink& EventSink) override
{
if (!Initialized)
{
return nullptr;
}
return MakeShared<FNdiMediaPlayer, ESPMode::ThreadSafe>(EventSink);
}
public:
//~ IModuleInterface interface
virtual void StartupModule() override
{
if (!FNdi::Initialize())
{
UE_LOG(LogNdiMedia, Error, TEXT("Failed to initialize NDI"));
return;
}
GetMutableDefault<UNdiMediaFinder>()->Initialize();
Initialized = true;
}
virtual void ShutdownModule() override
{
FNdi::Shutdown();
Initialized = false;
}
private:
/** Whether the module has been initialized. */
bool Initialized;
};
IMPLEMENT_MODULE(FNdiMediaModule, NdiMedia);
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Facebook, 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 <algorithm>
#include <mutex>
#include <stdexcept>
#include <sys/stat.h>
#include <snappy.h>
#include <rocksdb/env.h>
#include <rocksdb/options.h>
#include <osquery/database.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/status.h>
#include "osquery/database/db_handle.h"
namespace osquery {
class RocksDatabasePlugin : public DatabasePlugin {
public:
/// Data retrieval method.
Status get(const std::string& domain,
const std::string& key,
std::string& value) const;
/// Data storage method.
Status put(const std::string& domain,
const std::string& key,
const std::string& value);
/// Data removal method.
Status remove(const std::string& domain, const std::string& k);
/// Key/index lookup method.
Status scan(const std::string& domain,
std::vector<std::string>& results) const;
};
/// Backing-storage provider for osquery internal/core.
REGISTER_INTERNAL(RocksDatabasePlugin, "database", "rocks");
/////////////////////////////////////////////////////////////////////////////
// Constants
/////////////////////////////////////////////////////////////////////////////
bool DBHandle::kDBHandleOptionAllowOpen = false;
bool DBHandle::kDBHandleOptionRequireWrite = false;
const std::string kPersistentSettings = "configurations";
const std::string kQueries = "queries";
const std::string kEvents = "events";
const std::string kLogs = "logs";
/**
* @brief A const vector of column families in RocksDB
*
* RocksDB has a concept of "column families" which are kind of like tables
* in other databases. kDomainds is populated with a list of all column
* families. If a string exists in kDomains, it's a column family in the
* database.
*/
const std::vector<std::string> kDomains = {
kPersistentSettings, kQueries, kEvents, kLogs};
CLI_FLAG(string,
database_path,
"/var/osquery/osquery.db",
"If using a disk-based backing store, specify a path");
FLAG_ALIAS(std::string, db_path, database_path);
CLI_FLAG(bool,
database_in_memory,
false,
"Keep osquery backing-store in memory");
FLAG_ALIAS(bool, use_in_memory_database, database_in_memory);
/////////////////////////////////////////////////////////////////////////////
// constructors and destructors
/////////////////////////////////////////////////////////////////////////////
/// A queryable mutex around database sanity checking.
static bool kCheckingDB = false;
void GlogRocksDBLogger::Logv(const char* format, va_list ap) {
// Convert RocksDB log to string and check if header or level-ed log.
char buffer[501] = {0};
vsnprintf(buffer, 500, format, ap);
va_end(ap);
if (buffer[0] != '[') {
return;
}
if (buffer[1] == 'E' || buffer[1] == 'W') {
LOG(INFO) << "RocksDB: " << buffer;
}
}
DBHandle::DBHandle(const std::string& path, bool in_memory)
: path_(path), in_memory_(in_memory) {
if (!kDBHandleOptionAllowOpen) {
LOG(WARNING) << RLOG(1629) << "Not allowed to create DBHandle instance";
}
// Set meta-data (mostly) handling options.
options_.create_if_missing = true;
options_.create_missing_column_families = true;
options_.info_log_level = rocksdb::ERROR_LEVEL;
options_.log_file_time_to_roll = 0;
options_.keep_log_file_num = 10;
options_.max_log_file_size = 1024 * 1024 * 1;
options_.stats_dump_period_sec = 0;
// Performance and optimization settings.
options_.num_levels = 1;
options_.compression = rocksdb::kNoCompression;
options_.compaction_style = rocksdb::kCompactionStyleLevel;
options_.arena_block_size = (4 * 1024);
options_.write_buffer_size = (4 * 1024) * 100; // 100 blocks.
options_.max_write_buffer_number = 2;
options_.min_write_buffer_number_to_merge = 2;
options_.max_background_compactions = 1;
options_.max_background_flushes = 1;
// Create an environment to replace the default logger.
if (logger_ == nullptr) {
logger_ = std::make_shared<GlogRocksDBLogger>();
}
options_.info_log = logger_;
column_families_.push_back(rocksdb::ColumnFamilyDescriptor(
rocksdb::kDefaultColumnFamilyName, options_));
for (const auto& cf_name : kDomains) {
column_families_.push_back(
rocksdb::ColumnFamilyDescriptor(cf_name, options_));
}
// Make the magic happen.
open();
}
void DBHandle::open() {
if (in_memory_) {
// Remove when MemEnv is included in librocksdb
// options_.env = rocksdb::NewMemEnv(rocksdb::Env::Default());
throw std::runtime_error("Cannot start in-memory RocksDB: Requires MemEnv");
}
if (pathExists(path_).ok() && !isReadable(path_).ok()) {
throw std::runtime_error("Cannot read RocksDB path: " + path_);
}
if (!kCheckingDB) {
VLOG(1) << "Opening RocksDB handle: " << path_;
}
auto s =
rocksdb::DB::Open(options_, path_, column_families_, &handles_, &db_);
if (!s.ok() || db_ == nullptr) {
if (kDBHandleOptionRequireWrite) {
// A failed open in R/W mode is a runtime error.
throw std::runtime_error(s.ToString());
}
if (!kCheckingDB) {
VLOG(1) << "Opening RocksDB failed: Continuing with read-only support";
}
#if !defined(ROCKSDB_LITE)
// RocksDB LITE does not support readonly mode.
// The database was readable but could not be opened, either (1) it is not
// writable or (2) it is already opened by another process.
// Try to open the database in a ReadOnly mode.
rocksdb::DB::OpenForReadOnly(
options_, path_, column_families_, &handles_, &db_);
#endif
// Also disable event publishers.
Flag::updateValue("disable_events", "true");
read_only_ = true;
}
// RocksDB may not create/append a directory with acceptable permissions.
if (!read_only_ && chmod(path_.c_str(), S_IRWXU) != 0) {
throw std::runtime_error("Cannot set permissions on RocksDB path: " +
path_);
}
}
DBHandle::~DBHandle() { close(); }
void DBHandle::close() {
for (auto handle : handles_) {
delete handle;
}
if (db_ != nullptr) {
delete db_;
}
}
/////////////////////////////////////////////////////////////////////////////
// getInstance methods
/////////////////////////////////////////////////////////////////////////////
DBHandleRef DBHandle::getInstance() {
return getInstance(FLAGS_database_path, FLAGS_database_in_memory);
}
bool DBHandle::checkDB() {
// Allow database instances to check if a status/sanity check was requested.
kCheckingDB = true;
try {
auto handle = DBHandle(FLAGS_database_path, FLAGS_database_in_memory);
kCheckingDB = false;
if (kDBHandleOptionRequireWrite && handle.read_only_) {
return false;
}
} catch (const std::exception& e) {
kCheckingDB = false;
VLOG(1) << e.what();
return false;
}
return true;
}
DBHandleRef DBHandle::getInstanceInMemory() { return getInstance("", true); }
DBHandleRef DBHandle::getInstanceAtPath(const std::string& path) {
return getInstance(path, false);
}
DBHandleRef DBHandle::getInstance(const std::string& path, bool in_memory) {
static DBHandleRef db_handle = DBHandleRef(new DBHandle(path, in_memory));
return db_handle;
}
void DBHandle::resetInstance(const std::string& path, bool in_memory) {
close();
path_ = path;
in_memory_ = in_memory;
open();
}
/////////////////////////////////////////////////////////////////////////////
// getters and setters
/////////////////////////////////////////////////////////////////////////////
rocksdb::DB* DBHandle::getDB() const { return db_; }
rocksdb::ColumnFamilyHandle* DBHandle::getHandleForColumnFamily(
const std::string& cf) const {
try {
for (size_t i = 0; i < kDomains.size(); i++) {
if (kDomains[i] == cf) {
return handles_[i];
}
}
} catch (const std::exception& e) {
// pass through and return nullptr
}
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////
// Data manipulation methods
/////////////////////////////////////////////////////////////////////////////
Status DBHandle::Get(const std::string& domain,
const std::string& key,
std::string& value) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto s = getDB()->Get(rocksdb::ReadOptions(), cfh, key, &value);
return Status(s.code(), s.ToString());
}
Status DBHandle::Put(const std::string& domain,
const std::string& key,
const std::string& value) const {
if (read_only_) {
return Status(0, "Database in readonly mode");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto s = getDB()->Put(rocksdb::WriteOptions(), cfh, key, value);
if (s.code() != 0 && s.IsIOError()) {
// An error occurred, check if it is an IO error and remove the offending
// specific filename or log name.
std::string error_string = s.ToString();
size_t error_pos = error_string.find_last_of(":");
if (error_pos != std::string::npos) {
return Status(s.code(), "IOError: " + error_string.substr(error_pos + 2));
}
}
return Status(s.code(), s.ToString());
}
Status DBHandle::Delete(const std::string& domain,
const std::string& key) const {
if (read_only_) {
return Status(0, "Database in readonly mode");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::WriteOptions();
// We could sync here, but large deletes will cause multi-syncs.
// For example: event record expirations found in an expired index.
// options.sync = true;
auto s = getDB()->Delete(options, cfh, key);
return Status(s.code(), s.ToString());
}
Status DBHandle::Scan(const std::string& domain,
std::vector<std::string>& results) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto it = getDB()->NewIterator(rocksdb::ReadOptions(), cfh);
if (it == nullptr) {
return Status(1, "Could not get iterator for " + domain);
}
for (it->SeekToFirst(); it->Valid(); it->Next()) {
results.push_back(it->key().ToString());
}
delete it;
return Status(0, "OK");
}
Status RocksDatabasePlugin::get(const std::string& domain,
const std::string& key,
std::string& value) const {
return DBHandle::getInstance()->Get(domain, key, value);
}
Status RocksDatabasePlugin::put(const std::string& domain,
const std::string& key,
const std::string& value) {
return DBHandle::getInstance()->Put(domain, key, value);
}
Status RocksDatabasePlugin::remove(const std::string& domain,
const std::string& key) {
return DBHandle::getInstance()->Delete(domain, key);
}
Status RocksDatabasePlugin::scan(const std::string& domain,
std::vector<std::string>& results) const {
return DBHandle::getInstance()->Scan(domain, results);
}
}
<commit_msg>Remove num_levels explicit definition for RocksDB<commit_after>/*
* Copyright (c) 2014, Facebook, 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 <algorithm>
#include <mutex>
#include <stdexcept>
#include <sys/stat.h>
#include <snappy.h>
#include <rocksdb/env.h>
#include <rocksdb/options.h>
#include <osquery/database.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/status.h>
#include "osquery/database/db_handle.h"
namespace osquery {
class RocksDatabasePlugin : public DatabasePlugin {
public:
/// Data retrieval method.
Status get(const std::string& domain,
const std::string& key,
std::string& value) const;
/// Data storage method.
Status put(const std::string& domain,
const std::string& key,
const std::string& value);
/// Data removal method.
Status remove(const std::string& domain, const std::string& k);
/// Key/index lookup method.
Status scan(const std::string& domain,
std::vector<std::string>& results) const;
};
/// Backing-storage provider for osquery internal/core.
REGISTER_INTERNAL(RocksDatabasePlugin, "database", "rocks");
/////////////////////////////////////////////////////////////////////////////
// Constants
/////////////////////////////////////////////////////////////////////////////
bool DBHandle::kDBHandleOptionAllowOpen = false;
bool DBHandle::kDBHandleOptionRequireWrite = false;
const std::string kPersistentSettings = "configurations";
const std::string kQueries = "queries";
const std::string kEvents = "events";
const std::string kLogs = "logs";
/**
* @brief A const vector of column families in RocksDB
*
* RocksDB has a concept of "column families" which are kind of like tables
* in other databases. kDomainds is populated with a list of all column
* families. If a string exists in kDomains, it's a column family in the
* database.
*/
const std::vector<std::string> kDomains = {
kPersistentSettings, kQueries, kEvents, kLogs};
CLI_FLAG(string,
database_path,
"/var/osquery/osquery.db",
"If using a disk-based backing store, specify a path");
FLAG_ALIAS(std::string, db_path, database_path);
CLI_FLAG(bool,
database_in_memory,
false,
"Keep osquery backing-store in memory");
FLAG_ALIAS(bool, use_in_memory_database, database_in_memory);
/////////////////////////////////////////////////////////////////////////////
// constructors and destructors
/////////////////////////////////////////////////////////////////////////////
/// A queryable mutex around database sanity checking.
static bool kCheckingDB = false;
void GlogRocksDBLogger::Logv(const char* format, va_list ap) {
// Convert RocksDB log to string and check if header or level-ed log.
char buffer[501] = {0};
vsnprintf(buffer, 500, format, ap);
va_end(ap);
if (buffer[0] != '[') {
return;
}
if (buffer[1] == 'E' || buffer[1] == 'W') {
LOG(INFO) << "RocksDB: " << buffer;
}
}
DBHandle::DBHandle(const std::string& path, bool in_memory)
: path_(path), in_memory_(in_memory) {
if (!kDBHandleOptionAllowOpen) {
LOG(WARNING) << RLOG(1629) << "Not allowed to create DBHandle instance";
}
// Set meta-data (mostly) handling options.
options_.create_if_missing = true;
options_.create_missing_column_families = true;
options_.info_log_level = rocksdb::ERROR_LEVEL;
options_.log_file_time_to_roll = 0;
options_.keep_log_file_num = 10;
options_.max_log_file_size = 1024 * 1024 * 1;
options_.stats_dump_period_sec = 0;
// Performance and optimization settings.
options_.compression = rocksdb::kNoCompression;
options_.compaction_style = rocksdb::kCompactionStyleLevel;
options_.arena_block_size = (4 * 1024);
options_.write_buffer_size = (4 * 1024) * 100; // 100 blocks.
options_.max_write_buffer_number = 2;
options_.min_write_buffer_number_to_merge = 2;
options_.max_background_compactions = 1;
options_.max_background_flushes = 1;
// Create an environment to replace the default logger.
if (logger_ == nullptr) {
logger_ = std::make_shared<GlogRocksDBLogger>();
}
options_.info_log = logger_;
column_families_.push_back(rocksdb::ColumnFamilyDescriptor(
rocksdb::kDefaultColumnFamilyName, options_));
for (const auto& cf_name : kDomains) {
column_families_.push_back(
rocksdb::ColumnFamilyDescriptor(cf_name, options_));
}
// Make the magic happen.
open();
}
void DBHandle::open() {
if (in_memory_) {
// Remove when MemEnv is included in librocksdb
// options_.env = rocksdb::NewMemEnv(rocksdb::Env::Default());
throw std::runtime_error("Cannot start in-memory RocksDB: Requires MemEnv");
}
if (pathExists(path_).ok() && !isReadable(path_).ok()) {
throw std::runtime_error("Cannot read RocksDB path: " + path_);
}
if (!kCheckingDB) {
VLOG(1) << "Opening RocksDB handle: " << path_;
}
auto s =
rocksdb::DB::Open(options_, path_, column_families_, &handles_, &db_);
if (!s.ok() || db_ == nullptr) {
if (kDBHandleOptionRequireWrite) {
// A failed open in R/W mode is a runtime error.
throw std::runtime_error(s.ToString());
}
if (!kCheckingDB) {
VLOG(1) << "Opening RocksDB failed: Continuing with read-only support";
}
#if !defined(ROCKSDB_LITE)
// RocksDB LITE does not support readonly mode.
// The database was readable but could not be opened, either (1) it is not
// writable or (2) it is already opened by another process.
// Try to open the database in a ReadOnly mode.
rocksdb::DB::OpenForReadOnly(
options_, path_, column_families_, &handles_, &db_);
#endif
// Also disable event publishers.
Flag::updateValue("disable_events", "true");
read_only_ = true;
}
// RocksDB may not create/append a directory with acceptable permissions.
if (!read_only_ && chmod(path_.c_str(), S_IRWXU) != 0) {
throw std::runtime_error("Cannot set permissions on RocksDB path: " +
path_);
}
}
DBHandle::~DBHandle() { close(); }
void DBHandle::close() {
for (auto handle : handles_) {
delete handle;
}
if (db_ != nullptr) {
delete db_;
}
}
/////////////////////////////////////////////////////////////////////////////
// getInstance methods
/////////////////////////////////////////////////////////////////////////////
DBHandleRef DBHandle::getInstance() {
return getInstance(FLAGS_database_path, FLAGS_database_in_memory);
}
bool DBHandle::checkDB() {
// Allow database instances to check if a status/sanity check was requested.
kCheckingDB = true;
try {
auto handle = DBHandle(FLAGS_database_path, FLAGS_database_in_memory);
kCheckingDB = false;
if (kDBHandleOptionRequireWrite && handle.read_only_) {
return false;
}
} catch (const std::exception& e) {
kCheckingDB = false;
VLOG(1) << e.what();
return false;
}
return true;
}
DBHandleRef DBHandle::getInstanceInMemory() { return getInstance("", true); }
DBHandleRef DBHandle::getInstanceAtPath(const std::string& path) {
return getInstance(path, false);
}
DBHandleRef DBHandle::getInstance(const std::string& path, bool in_memory) {
static DBHandleRef db_handle = DBHandleRef(new DBHandle(path, in_memory));
return db_handle;
}
void DBHandle::resetInstance(const std::string& path, bool in_memory) {
close();
path_ = path;
in_memory_ = in_memory;
open();
}
/////////////////////////////////////////////////////////////////////////////
// getters and setters
/////////////////////////////////////////////////////////////////////////////
rocksdb::DB* DBHandle::getDB() const { return db_; }
rocksdb::ColumnFamilyHandle* DBHandle::getHandleForColumnFamily(
const std::string& cf) const {
try {
for (size_t i = 0; i < kDomains.size(); i++) {
if (kDomains[i] == cf) {
return handles_[i];
}
}
} catch (const std::exception& e) {
// pass through and return nullptr
}
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////
// Data manipulation methods
/////////////////////////////////////////////////////////////////////////////
Status DBHandle::Get(const std::string& domain,
const std::string& key,
std::string& value) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto s = getDB()->Get(rocksdb::ReadOptions(), cfh, key, &value);
return Status(s.code(), s.ToString());
}
Status DBHandle::Put(const std::string& domain,
const std::string& key,
const std::string& value) const {
if (read_only_) {
return Status(0, "Database in readonly mode");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto s = getDB()->Put(rocksdb::WriteOptions(), cfh, key, value);
if (s.code() != 0 && s.IsIOError()) {
// An error occurred, check if it is an IO error and remove the offending
// specific filename or log name.
std::string error_string = s.ToString();
size_t error_pos = error_string.find_last_of(":");
if (error_pos != std::string::npos) {
return Status(s.code(), "IOError: " + error_string.substr(error_pos + 2));
}
}
return Status(s.code(), s.ToString());
}
Status DBHandle::Delete(const std::string& domain,
const std::string& key) const {
if (read_only_) {
return Status(0, "Database in readonly mode");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::WriteOptions();
// We could sync here, but large deletes will cause multi-syncs.
// For example: event record expirations found in an expired index.
// options.sync = true;
auto s = getDB()->Delete(options, cfh, key);
return Status(s.code(), s.ToString());
}
Status DBHandle::Scan(const std::string& domain,
std::vector<std::string>& results) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto it = getDB()->NewIterator(rocksdb::ReadOptions(), cfh);
if (it == nullptr) {
return Status(1, "Could not get iterator for " + domain);
}
for (it->SeekToFirst(); it->Valid(); it->Next()) {
results.push_back(it->key().ToString());
}
delete it;
return Status(0, "OK");
}
Status RocksDatabasePlugin::get(const std::string& domain,
const std::string& key,
std::string& value) const {
return DBHandle::getInstance()->Get(domain, key, value);
}
Status RocksDatabasePlugin::put(const std::string& domain,
const std::string& key,
const std::string& value) {
return DBHandle::getInstance()->Put(domain, key, value);
}
Status RocksDatabasePlugin::remove(const std::string& domain,
const std::string& key) {
return DBHandle::getInstance()->Delete(domain, key);
}
Status RocksDatabasePlugin::scan(const std::string& domain,
std::vector<std::string>& results) const {
return DBHandle::getInstance()->Scan(domain, results);
}
}
<|endoftext|> |
<commit_before>AliAnalysisTaskSEHFQA* AddTaskHFQA(AliAnalysisTaskSEHFQA::DecChannel ch,TString filecutsname="D0toKpiCuts.root",Bool_t readMC=kFALSE, Bool_t simplemode=kFALSE){
//
// Test macro for the AliAnalysisTaskSE for HF mesons quality assurance
//Author: C.Bianchin [email protected]
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskHFQA", "No analysis manager to connect to.");
return NULL;
}
Bool_t stdcuts=kFALSE;
TFile* filecuts=new TFile(filecutsname.Data());
if(!filecuts->IsOpen()){
cout<<"Input file not found: using std cut object"<<endl;
stdcuts=kTRUE;
}
Bool_t onoff[4]={kTRUE,kTRUE,kFALSE,kTRUE};
AliRDHFCuts *analysiscuts=0x0;
TString filename="",out1name="nEntriesQA",out2name="outputPid",out3name="outputTrack",out4name="cuts",out5name="countersCentrality",out6name="outputCentrCheck",out7name="outputEvSel",inname="input",suffix="",cutsobjname="",centr="";
filename = AliAnalysisManager::GetCommonFileName();
filename += ":PWG3_D2H_QA";
switch (ch){
case 0:
cutsobjname="AnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDplustoKpipi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(cutsobjname);
suffix="Dplus";
break;
case 1:
cutsobjname="D0toKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(cutsobjname);
suffix="D0";
break;
case 2:
cutsobjname="DStartoKpipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDStartoKpipi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsDstartoKpipi*)filecuts->Get(cutsobjname);
suffix="Dstar";
break;
case 3:
cutsobjname="DstoKKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDstoKKpi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsDstoKKpi*)filecuts->Get(cutsobjname);
suffix="Ds";
break;
case 4:
cutsobjname="D0toKpipipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpipipi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsD0toKpipipi*)filecuts->Get(cutsobjname);
suffix="D04";
break;
case 5:
cutsobjname="LctopKpiAnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsLctopKpi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get(cutsobjname);
suffix="Lc";
break;
}
inname+=suffix;
out1name+=suffix;
out2name+=suffix;
out3name+=suffix;
out4name=cutsobjname;
out5name+=suffix;
out6name+=suffix;
out7name+=suffix;
if(!analysiscuts && filecutsname!="none"){
cout<<"Specific AliRDHFCuts not found"<<endl;
return;
}
centr=Form("%.0f%.0f",analysiscuts->GetMinCentrality(),analysiscuts->GetMaxCentrality());
inname+=centr;
out1name+=centr;
out2name+=centr;
out3name+=centr;
out4name+=centr;
out5name+=centr;
out6name+=centr;
out7name+=centr;
AliAnalysisTaskSEHFQA* taskQA=new AliAnalysisTaskSEHFQA(Form("QA%s",suffix.Data()),ch,analysiscuts);
taskQA->SetReadMC(readMC);
taskQA->SetSimpleMode(simplemode); // set to kTRUE to go faster in PbPb
taskQA->SetTrackOn(onoff[0]);
taskQA->SetPIDOn(onoff[1]);
taskQA->SetCentralityOn(onoff[2]);
taskQA->SetEvSelectionOn(onoff[3]);
mgr->AddTask(taskQA);
//
// Create containers for input/output
AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer);
mgr->ConnectInput(taskQA,0,mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(out1name,TH1F::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //events analysed
mgr->ConnectOutput(taskQA,1,coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(out2name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //PID
if(onoff[1]) mgr->ConnectOutput(taskQA,2,coutput2);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of tracks
if(onoff[0]) mgr->ConnectOutput(taskQA,3,coutput3);
AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(out4name,AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
mgr->ConnectOutput(taskQA,4,coutput4);
AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(out5name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(onoff[2]) mgr->ConnectOutput(taskQA,5,coutput5);
AliAnalysisDataContainer *coutput6 = mgr->CreateContainer(out6name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(onoff[2]) mgr->ConnectOutput(taskQA,6,coutput6);
AliAnalysisDataContainer *coutput7 = mgr->CreateContainer(out7name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //event selection
if(onoff[3]) mgr->ConnectOutput(taskQA,7,coutput7);
return taskQA;
}
<commit_msg>fix (Alessandro)<commit_after>AliAnalysisTaskSEHFQA* AddTaskHFQA(AliAnalysisTaskSEHFQA::DecChannel ch,TString filecutsname="D0toKpiCuts.root",Bool_t readMC=kFALSE, Bool_t simplemode=kFALSE){
//
// Test macro for the AliAnalysisTaskSE for HF mesons quality assurance
//Author: C.Bianchin [email protected]
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskHFQA", "No analysis manager to connect to.");
return NULL;
}
Bool_t stdcuts=kFALSE;
TFile* filecuts=new TFile(filecutsname.Data());
if(!filecuts->IsOpen()){
cout<<"Input file not found: using std cut object"<<endl;
stdcuts=kTRUE;
}
Bool_t onoff[4]={kTRUE,kTRUE,kFALSE,kTRUE};
AliRDHFCuts *analysiscuts=0x0;
TString filename="",out1name="nEntriesQA",out2name="outputPid",out3name="outputTrack",out4name="cuts",out5name="countersCentrality",out6name="outputCentrCheck",out7name="outputEvSel",inname="input",suffix="",cutsobjname="",centr="";
filename = AliAnalysisManager::GetCommonFileName();
filename += ":PWG3_D2H_QA";
switch (ch){
case 0:
cutsobjname="AnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDplustoKpipi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(cutsobjname);
suffix="Dplus";
break;
case 1:
cutsobjname="D0toKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(cutsobjname);
suffix="D0";
break;
case 2:
cutsobjname="DStartoKpipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDStartoKpipi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(cutsobjname);
suffix="Dstar";
break;
case 3:
cutsobjname="DstoKKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDstoKKpi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsDstoKKpi*)filecuts->Get(cutsobjname);
suffix="Ds";
break;
case 4:
cutsobjname="D0toKpipipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpipipi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsD0toKpipipi*)filecuts->Get(cutsobjname);
suffix="D04";
break;
case 5:
cutsobjname="LctopKpiAnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsLctopKpi();
analysiscuts->SetStandardCutsPP2010();
}
else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get(cutsobjname);
suffix="Lc";
break;
}
inname+=suffix;
out1name+=suffix;
out2name+=suffix;
out3name+=suffix;
out4name=cutsobjname;
out5name+=suffix;
out6name+=suffix;
out7name+=suffix;
if(!analysiscuts && filecutsname!="none"){
cout<<"Specific AliRDHFCuts not found"<<endl;
return;
}
centr=Form("%.0f%.0f",analysiscuts->GetMinCentrality(),analysiscuts->GetMaxCentrality());
inname+=centr;
out1name+=centr;
out2name+=centr;
out3name+=centr;
out4name+=centr;
out5name+=centr;
out6name+=centr;
out7name+=centr;
AliAnalysisTaskSEHFQA* taskQA=new AliAnalysisTaskSEHFQA(Form("QA%s",suffix.Data()),ch,analysiscuts);
taskQA->SetReadMC(readMC);
taskQA->SetSimpleMode(simplemode); // set to kTRUE to go faster in PbPb
taskQA->SetTrackOn(onoff[0]);
taskQA->SetPIDOn(onoff[1]);
taskQA->SetCentralityOn(onoff[2]);
taskQA->SetEvSelectionOn(onoff[3]);
mgr->AddTask(taskQA);
//
// Create containers for input/output
AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer);
mgr->ConnectInput(taskQA,0,mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(out1name,TH1F::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //events analysed
mgr->ConnectOutput(taskQA,1,coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(out2name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //PID
if(onoff[1]) mgr->ConnectOutput(taskQA,2,coutput2);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of tracks
if(onoff[0]) mgr->ConnectOutput(taskQA,3,coutput3);
AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(out4name,AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
mgr->ConnectOutput(taskQA,4,coutput4);
AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(out5name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(onoff[2]) mgr->ConnectOutput(taskQA,5,coutput5);
AliAnalysisDataContainer *coutput6 = mgr->CreateContainer(out6name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(onoff[2]) mgr->ConnectOutput(taskQA,6,coutput6);
AliAnalysisDataContainer *coutput7 = mgr->CreateContainer(out7name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //event selection
if(onoff[3]) mgr->ConnectOutput(taskQA,7,coutput7);
return taskQA;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Milian Wolff <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file libheaptrack.cpp
*
* @brief Collect raw heaptrack data by overloading heap allocation functions.
*/
#include <cstdio>
#include <stdio_ext.h>
#include <cstdlib>
#include <atomic>
#include <unordered_map>
#include <string>
#include <tuple>
#include <memory>
#include <unordered_set>
#include <mutex>
#include <boost/algorithm/string/replace.hpp>
#include <dlfcn.h>
#include <link.h>
#include "tracetree.h"
#include "timer.h"
/**
* uncomment this to get extended debug code for known pointers
* there are still some malloc functions I'm missing apparently,
* related to TLS and such I guess
*/
// #define DEBUG_MALLOC_PTRS
using namespace std;
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using cfree_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
using dlclose_t = int (*) (void*);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
cfree_t real_cfree = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
dlclose_t real_dlclose = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
/**
* Similar to std::lock_guard but operates on the internal stream lock of a FILE*.
*/
class LockGuard
{
public:
LockGuard(FILE* file)
: file(file)
{
flockfile(file);
}
~LockGuard()
{
funlockfile(file);
}
private:
FILE* file;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
void prepare_fork();
void parent_fork();
void child_fork();
struct Data
{
Data()
{
pthread_atfork(&prepare_fork, &parent_fork, &child_fork);
string outputFileName = env("DUMP_HEAPTRACK_OUTPUT");
if (outputFileName.empty()) {
// env var might not be set when linked directly into an executable
outputFileName = "heaptrack.$$";
} else if (outputFileName == "-" || outputFileName == "stdout") {
out = stdout;
} else if (outputFileName == "stderr") {
out = stderr;
}
if (!out) {
boost::replace_all(outputFileName, "$$", to_string(getpid()));
out = fopen(outputFileName.c_str(), "w");
__fsetlocking(out, FSETLOCKING_BYCALLER);
}
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
// TODO: remember meta data about host application, such as cmdline, date of run, ...
// cleanup environment to prevent tracing of child apps
unsetenv("DUMP_HEAPTRACK_OUTPUT");
unsetenv("LD_PRELOAD");
timer.setInterval(1, 0);
}
~Data()
{
HandleGuard::inHandler = true;
if (out) {
fclose(out);
}
}
void updateModuleCache()
{
fprintf(out, "m -\n");
foundExe = false;
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (!data->foundExe) {
isExe = true;
data->foundExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
const uintptr_t addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
const uintptr_t addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
fprintf(data->out, "m %s %d %lx %lx\n", fileName, isExe, addressStart, addressEnd);
}
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
Trace trace;
if (!trace.fill()) {
return;
}
LockGuard lock(out);
if (lastTimerElapsed != timer.timesElapsed()) {
lastTimerElapsed = timer.timesElapsed();
fprintf(out, "c %lx\n", lastTimerElapsed);
}
if (moduleCacheDirty) {
updateModuleCache();
}
const size_t index = traceTree.index(trace, out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it == known.end());
known.insert(ptr);
#endif
fprintf(out, "+ %lx %lx %lx\n", size, index, reinterpret_cast<uintptr_t>(ptr));
}
void handleFree(void* ptr)
{
LockGuard lock(out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it != known.end());
known.erase(it);
#endif
fprintf(out, "- %lx\n", reinterpret_cast<uintptr_t>(ptr));
}
TraceTree traceTree;
/**
* Note: We use the C stdio API here for performance reasons.
* Esp. in multi-threaded environments this is much faster
* to produce non-per-line-interleaved output.
*/
FILE* out = nullptr;
size_t lastTimerElapsed = 0;
Timer timer;
bool foundExe = false;
#ifdef DEBUG_MALLOC_PTRS
unordered_set<void*> known;
#endif
};
unique_ptr<Data> data;
void prepare_fork()
{
// don't do any custom malloc handling while inside fork
HandleGuard::inHandler = true;
}
void parent_fork()
{
// the parent process can now continue its custom malloc tracking
HandleGuard::inHandler = false;
}
void child_fork()
{
// but the forked child process cleans up itself
// this is important to prevent two processes writing to the same file
if (data) {
data->out = nullptr;
data.reset(nullptr);
}
HandleGuard::inHandler = true;
}
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
abort();
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
abort();
}
return buf + oldOffset;
}
void init()
{
static once_flag once;
call_once(once, [] {
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
abort();
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_dlclose = findReal<dlclose_t>("dlclose");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_cfree = findReal<cfree_t>("cfree");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
if (unw_set_caching_policy(unw_local_addr_space, UNW_CACHE_PER_THREAD)) {
fprintf(stderr, "Failed to enable per-thread libunwind caching.\n");
}
if (unw_set_cache_log_size(unw_local_addr_space, 10)) {
fprintf(stderr, "Failed to set libunwind cache size.\n");
}
data.reset(new Data);
});
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
// call handler before handing over the real free implementation
// to ensure the ptr is not reused in-between and thus the output
// stays consistent
if (ptr && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleFree(ptr);
}
real_free(ptr);
}
void cfree(void* ptr)
{
if (!real_cfree) {
init();
}
// call handler before handing over the real free implementation
// to ensure the ptr is not reused in-between and thus the output
// stays consistent
if (ptr && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleFree(ptr);
}
real_cfree(ptr);
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
if (ptr) {
data->handleFree(ptr);
}
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
int dlclose(void *handle)
{
if (!real_dlclose) {
init();
}
int ret = real_dlclose(handle);
if (!ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<commit_msg>Fixup handling of posix_memaling.<commit_after>/*
* Copyright 2014 Milian Wolff <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file libheaptrack.cpp
*
* @brief Collect raw heaptrack data by overloading heap allocation functions.
*/
#include <cstdio>
#include <stdio_ext.h>
#include <cstdlib>
#include <atomic>
#include <unordered_map>
#include <string>
#include <tuple>
#include <memory>
#include <unordered_set>
#include <mutex>
#include <boost/algorithm/string/replace.hpp>
#include <dlfcn.h>
#include <link.h>
#include "tracetree.h"
#include "timer.h"
/**
* uncomment this to get extended debug code for known pointers
* there are still some malloc functions I'm missing apparently,
* related to TLS and such I guess
*/
// #define DEBUG_MALLOC_PTRS
using namespace std;
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using cfree_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
using dlclose_t = int (*) (void*);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
cfree_t real_cfree = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
dlclose_t real_dlclose = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
/**
* Similar to std::lock_guard but operates on the internal stream lock of a FILE*.
*/
class LockGuard
{
public:
LockGuard(FILE* file)
: file(file)
{
flockfile(file);
}
~LockGuard()
{
funlockfile(file);
}
private:
FILE* file;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
void prepare_fork();
void parent_fork();
void child_fork();
struct Data
{
Data()
{
pthread_atfork(&prepare_fork, &parent_fork, &child_fork);
string outputFileName = env("DUMP_HEAPTRACK_OUTPUT");
if (outputFileName.empty()) {
// env var might not be set when linked directly into an executable
outputFileName = "heaptrack.$$";
} else if (outputFileName == "-" || outputFileName == "stdout") {
out = stdout;
} else if (outputFileName == "stderr") {
out = stderr;
}
if (!out) {
boost::replace_all(outputFileName, "$$", to_string(getpid()));
out = fopen(outputFileName.c_str(), "w");
__fsetlocking(out, FSETLOCKING_BYCALLER);
}
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
// TODO: remember meta data about host application, such as cmdline, date of run, ...
// cleanup environment to prevent tracing of child apps
unsetenv("DUMP_HEAPTRACK_OUTPUT");
unsetenv("LD_PRELOAD");
timer.setInterval(1, 0);
}
~Data()
{
HandleGuard::inHandler = true;
if (out) {
fclose(out);
}
}
void updateModuleCache()
{
fprintf(out, "m -\n");
foundExe = false;
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (!data->foundExe) {
isExe = true;
data->foundExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
const uintptr_t addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
const uintptr_t addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
fprintf(data->out, "m %s %d %lx %lx\n", fileName, isExe, addressStart, addressEnd);
}
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
Trace trace;
if (!trace.fill()) {
return;
}
LockGuard lock(out);
if (lastTimerElapsed != timer.timesElapsed()) {
lastTimerElapsed = timer.timesElapsed();
fprintf(out, "c %lx\n", lastTimerElapsed);
}
if (moduleCacheDirty) {
updateModuleCache();
}
const size_t index = traceTree.index(trace, out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it == known.end());
known.insert(ptr);
#endif
fprintf(out, "+ %lx %lx %lx\n", size, index, reinterpret_cast<uintptr_t>(ptr));
}
void handleFree(void* ptr)
{
LockGuard lock(out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it != known.end());
known.erase(it);
#endif
fprintf(out, "- %lx\n", reinterpret_cast<uintptr_t>(ptr));
}
TraceTree traceTree;
/**
* Note: We use the C stdio API here for performance reasons.
* Esp. in multi-threaded environments this is much faster
* to produce non-per-line-interleaved output.
*/
FILE* out = nullptr;
size_t lastTimerElapsed = 0;
Timer timer;
bool foundExe = false;
#ifdef DEBUG_MALLOC_PTRS
unordered_set<void*> known;
#endif
};
unique_ptr<Data> data;
void prepare_fork()
{
// don't do any custom malloc handling while inside fork
HandleGuard::inHandler = true;
}
void parent_fork()
{
// the parent process can now continue its custom malloc tracking
HandleGuard::inHandler = false;
}
void child_fork()
{
// but the forked child process cleans up itself
// this is important to prevent two processes writing to the same file
if (data) {
data->out = nullptr;
data.reset(nullptr);
}
HandleGuard::inHandler = true;
}
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
abort();
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
abort();
}
return buf + oldOffset;
}
void init()
{
static once_flag once;
call_once(once, [] {
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
abort();
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_dlclose = findReal<dlclose_t>("dlclose");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_cfree = findReal<cfree_t>("cfree");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
if (unw_set_caching_policy(unw_local_addr_space, UNW_CACHE_PER_THREAD)) {
fprintf(stderr, "Failed to enable per-thread libunwind caching.\n");
}
if (unw_set_cache_log_size(unw_local_addr_space, 10)) {
fprintf(stderr, "Failed to set libunwind cache size.\n");
}
data.reset(new Data);
});
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
// call handler before handing over the real free implementation
// to ensure the ptr is not reused in-between and thus the output
// stays consistent
if (ptr && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleFree(ptr);
}
real_free(ptr);
}
void cfree(void* ptr)
{
if (!real_cfree) {
init();
}
// call handler before handing over the real free implementation
// to ensure the ptr is not reused in-between and thus the output
// stays consistent
if (ptr && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleFree(ptr);
}
real_cfree(ptr);
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
if (ptr) {
data->handleFree(ptr);
}
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (!ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
int dlclose(void *handle)
{
if (!real_dlclose) {
init();
}
int ret = real_dlclose(handle);
if (!ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<|endoftext|> |
<commit_before>#include "scriptwidget.h"
#include "ui_scriptwidget.h"
#include "stepsel.h"
#include <QPlainTextEdit>
using namespace Vipster;
ScriptWidget::ScriptWidget(QWidget *parent) :
BaseWidget(parent),
ui(new Ui::ScriptWidget)
{
ui->setupUi(this);
}
ScriptWidget::~ScriptWidget()
{
delete ui;
}
std::istream& operator>>(std::istream& is, std::tuple<const Step&, Vec&, bool> dat){
auto c = static_cast<char>((is >> std::ws).peek());
const Step& step = std::get<0>(dat);
Vec& vec = std::get<1>(dat);
bool optional = std::get<2>(dat);
if(!is.good()){
if(optional){
return is;
}
throw Error("Mandatory vector missing");
}
if(c == '('){
// explicit vector
is >> c >> vec[0] >> c >> vec[1] >> c >> vec[2] >> c;
if(c != ')'){
std::string fmt;
is >> fmt;
if(fmt.back() == ')'){
fmt.pop_back();
}else{
is >> c;
if(c != ')'){
throw Error("Unterminated vector");
}
}
std::transform(fmt.begin(), fmt.end(), fmt.begin(), ::tolower);
std::map<std::string, AtomFmt> fmtmap={
{"angstrom", AtomFmt::Angstrom},
{"bohr", AtomFmt::Bohr},
{"crystal", AtomFmt::Crystal},
{"alat", AtomFmt::Alat}
};
vec = step.formatVec(vec, fmtmap.at(fmt), step.getFmt());
}
}else if(c == '-'){
// negated position vector
size_t id;
is >> c >> id;
vec = -step[id].coord;
}else{
// position or difference vector
size_t id1, id2;
is >> id1;
c = static_cast<char>(is.peek());
if(c == '-'){
is >> id2;
vec = step[id1].coord - step[id2].coord;
}else{
vec = step[id1].coord;
}
}
return is;
};
void ScriptWidget::evalScript()
{
guiChange_t change;
if(ui->trajecCheck->isChecked()){
change = GuiChange::trajec;
for(auto& s: master->curMol->getSteps()){
auto& sel = master->stepdata[&s].sel;
if(!sel){
// if step hasn't been loaded before, need to create selection
sel = std::make_unique<Step::selection>(s.select(SelectionFilter{}));
}
change |= evalImpl(s, *sel);
}
if(change == GuiChange::trajec){
change = 0;
}
}else{
change = evalImpl(*master->curStep, *master->curSel);
}
triggerUpdate(change);
}
guiChange_t ScriptWidget::evalImpl(Step& step, Step::selection& stepSel)
{
struct ScriptOp{
enum class Mode{None, Rotate, Shift, Mirror, Rename, Select, Define};
std::string target;
Mode mode{Mode::None};
float f{};
std::string s1{}, s2{};
Vipster::Vec v1{}, v2{}, v3{};
};
auto script_str = static_cast<QPlainTextEdit*>(ui->inputEdit)->toPlainText().toStdString();
auto script = std::stringstream{script_str};
guiChange_t change{};
std::map<std::string, Step::selection> definitions{};
std::vector<ScriptOp> operations{};
std::string line, op_pre, op(3, ' '), name;
const bool _false{false}, _true{true};
while(std::getline(script, line)){
auto line_stream = std::stringstream{line};
line_stream >> op_pre;
std::transform(op_pre.begin(), op_pre.begin()+4, op.begin(), ::tolower);
// Create op on stack
change |= GuiChange::atoms;
line_stream >> name;
operations.push_back({name});
auto& action = operations.back();
// TODO: check when and how stream extraction fails
if(op == "rot"){
action.mode = ScriptOp::Mode::Rotate;
line_stream >> action.f;
line_stream >> std::tie(step, action.v1, _false);
line_stream >> std::tie(step, action.v2, _true);
}else if(op == "shi"){
action.mode = ScriptOp::Mode::Shift;
line_stream >> std::tie(step, action.v1, _false);
action.f = 1.f;
line_stream >> action.f;
}else if(op == "mir"){
action.mode = ScriptOp::Mode::Mirror;
line_stream >> std::tie(step, action.v1, _false);
line_stream >> std::tie(step, action.v2, _false);
line_stream >> std::tie(step, action.v3, _true);
}else if(op == "ren"){
action.mode = ScriptOp::Mode::Rename;
line_stream >> action.s1;
}else if(op == "sel"){
action.mode = ScriptOp::Mode::Select;
std::getline(line_stream, action.s1);
}else if(op == "def"){
action.mode = ScriptOp::Mode::Define;
line_stream >> action.s1;
std::getline(line_stream, action.s2);
}else{
throw Error("Unknown operator");
}
}
auto execOp = [&definitions, &stepSel](auto& step, const ScriptOp& op){
switch (op.mode) {
case ScriptOp::Mode::Rotate:
step.modRotate(op.f, op.v1, op.v2);
break;
case ScriptOp::Mode::Shift:
step.modShift(op.v1, op.f);
break;
case ScriptOp::Mode::Mirror:
step.modMirror(op.v1, op.v2, op.v3);
break;
case ScriptOp::Mode::Rename:
for(auto& at: step){
at.name = op.s1;
}
break;
case ScriptOp::Mode::Select:
stepSel = step.select(op.s1);
break;
case ScriptOp::Mode::Define:
{
auto pos = definitions.find(op.s1);
if(pos == definitions.end()){
definitions.insert({op.s1, step.select(op.s2)});
}else{
pos->second = step.select(op.s2);
}
}
break;
default:
throw Error("Invalid operation");
}
};
for(const auto& op: operations){
if(op.target == "all"){
execOp(step, op);
}else if(op.target == "sel"){
execOp(stepSel, op);
}else{
execOp(definitions.at(op.target), op);
}
}
return change;
}
<commit_msg>fix difference-vectors in script-widget<commit_after>#include "scriptwidget.h"
#include "ui_scriptwidget.h"
#include "stepsel.h"
#include <QPlainTextEdit>
using namespace Vipster;
ScriptWidget::ScriptWidget(QWidget *parent) :
BaseWidget(parent),
ui(new Ui::ScriptWidget)
{
ui->setupUi(this);
}
ScriptWidget::~ScriptWidget()
{
delete ui;
}
std::istream& operator>>(std::istream& is, std::tuple<const Step&, Vec&, bool> dat){
auto c = static_cast<char>((is >> std::ws).peek());
const Step& step = std::get<0>(dat);
Vec& vec = std::get<1>(dat);
bool optional = std::get<2>(dat);
if(!is.good()){
if(optional){
return is;
}
throw Error("Mandatory vector missing");
}
if(c == '('){
// explicit vector
is >> c >> vec[0] >> c >> vec[1] >> c >> vec[2] >> c;
if(c != ')'){
std::string fmt;
is >> fmt;
if(fmt.back() == ')'){
fmt.pop_back();
}else{
is >> c;
if(c != ')'){
throw Error("Unterminated vector");
}
}
std::transform(fmt.begin(), fmt.end(), fmt.begin(), ::tolower);
std::map<std::string, AtomFmt> fmtmap={
{"angstrom", AtomFmt::Angstrom},
{"bohr", AtomFmt::Bohr},
{"crystal", AtomFmt::Crystal},
{"alat", AtomFmt::Alat}
};
vec = step.formatVec(vec, fmtmap.at(fmt), step.getFmt());
}
}else if(c == '-'){
// negated position vector
size_t id;
is >> c >> id;
vec = -step[id].coord;
}else{
// position or difference vector
size_t id1, id2;
is >> id1;
c = static_cast<char>(is.peek());
if(c == '-'){
is >> c >> id2;
vec = step[id1].coord - step[id2].coord;
}else{
vec = step[id1].coord;
}
}
return is;
};
void ScriptWidget::evalScript()
{
guiChange_t change;
if(ui->trajecCheck->isChecked()){
change = GuiChange::trajec;
for(auto& s: master->curMol->getSteps()){
auto& sel = master->stepdata[&s].sel;
if(!sel){
// if step hasn't been loaded before, need to create selection
sel = std::make_unique<Step::selection>(s.select(SelectionFilter{}));
}
change |= evalImpl(s, *sel);
}
if(change == GuiChange::trajec){
change = 0;
}
}else{
change = evalImpl(*master->curStep, *master->curSel);
}
triggerUpdate(change);
}
guiChange_t ScriptWidget::evalImpl(Step& step, Step::selection& stepSel)
{
struct ScriptOp{
enum class Mode{None, Rotate, Shift, Mirror, Rename, Select, Define};
std::string target;
Mode mode{Mode::None};
float f{};
std::string s1{}, s2{};
Vipster::Vec v1{}, v2{}, v3{};
};
auto script_str = static_cast<QPlainTextEdit*>(ui->inputEdit)->toPlainText().toStdString();
auto script = std::stringstream{script_str};
guiChange_t change{};
std::map<std::string, Step::selection> definitions{};
std::vector<ScriptOp> operations{};
std::string line, op_pre, op(3, ' '), name;
const bool _false{false}, _true{true};
while(std::getline(script, line)){
auto line_stream = std::stringstream{line};
line_stream >> op_pre;
std::transform(op_pre.begin(), op_pre.begin()+4, op.begin(), ::tolower);
// Create op on stack
change |= GuiChange::atoms;
line_stream >> name;
operations.push_back({name});
auto& action = operations.back();
// TODO: check when and how stream extraction fails
if(op == "rot"){
action.mode = ScriptOp::Mode::Rotate;
line_stream >> action.f;
line_stream >> std::tie(step, action.v1, _false);
line_stream >> std::tie(step, action.v2, _true);
}else if(op == "shi"){
action.mode = ScriptOp::Mode::Shift;
line_stream >> std::tie(step, action.v1, _false);
action.f = 1.f;
line_stream >> action.f;
}else if(op == "mir"){
action.mode = ScriptOp::Mode::Mirror;
line_stream >> std::tie(step, action.v1, _false);
line_stream >> std::tie(step, action.v2, _false);
line_stream >> std::tie(step, action.v3, _true);
}else if(op == "ren"){
action.mode = ScriptOp::Mode::Rename;
line_stream >> action.s1;
}else if(op == "sel"){
action.mode = ScriptOp::Mode::Select;
std::getline(line_stream, action.s1);
}else if(op == "def"){
action.mode = ScriptOp::Mode::Define;
line_stream >> action.s1;
std::getline(line_stream, action.s2);
}else{
throw Error("Unknown operator");
}
}
auto execOp = [&definitions, &stepSel](auto& step, const ScriptOp& op){
switch (op.mode) {
case ScriptOp::Mode::Rotate:
step.modRotate(op.f, op.v1, op.v2);
break;
case ScriptOp::Mode::Shift:
step.modShift(op.v1, op.f);
break;
case ScriptOp::Mode::Mirror:
step.modMirror(op.v1, op.v2, op.v3);
break;
case ScriptOp::Mode::Rename:
for(auto& at: step){
at.name = op.s1;
}
break;
case ScriptOp::Mode::Select:
stepSel = step.select(op.s1);
break;
case ScriptOp::Mode::Define:
{
auto pos = definitions.find(op.s1);
if(pos == definitions.end()){
definitions.insert({op.s1, step.select(op.s2)});
}else{
pos->second = step.select(op.s2);
}
}
break;
default:
throw Error("Invalid operation");
}
};
for(const auto& op: operations){
if(op.target == "all"){
execOp(step, op);
}else if(op.target == "sel"){
execOp(stepSel, op);
}else{
execOp(definitions.at(op.target), op);
}
}
return change;
}
<|endoftext|> |
<commit_before>//===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DAGISelMatcher.h"
#include "CodeGenDAGPatterns.h"
#include "Record.h"
#include "llvm/ADT/StringMap.h"
using namespace llvm;
namespace {
class MatcherGen {
const PatternToMatch &Pattern;
const CodeGenDAGPatterns &CGP;
/// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
/// out with all of the types removed. This allows us to insert type checks
/// as we scan the tree.
TreePatternNode *PatWithNoTypes;
/// VariableMap - A map from variable names ('$dst') to the recorded operand
/// number that they were captured as. These are biased by 1 to make
/// insertion easier.
StringMap<unsigned> VariableMap;
unsigned NextRecordedOperandNo;
MatcherNodeWithChild *Matcher;
MatcherNodeWithChild *CurPredicate;
public:
MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
~MatcherGen() {
delete PatWithNoTypes;
}
void EmitMatcherCode();
MatcherNodeWithChild *GetMatcher() const { return Matcher; }
MatcherNodeWithChild *GetCurPredicate() const { return CurPredicate; }
private:
void AddMatcherNode(MatcherNodeWithChild *NewNode);
void InferPossibleTypes();
void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
void EmitLeafMatchCode(const TreePatternNode *N);
void EmitOperatorMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes);
};
} // end anon namespace.
MatcherGen::MatcherGen(const PatternToMatch &pattern,
const CodeGenDAGPatterns &cgp)
: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Matcher(0), CurPredicate(0) {
// We need to produce the matcher tree for the patterns source pattern. To do
// this we need to match the structure as well as the types. To do the type
// matching, we want to figure out the fewest number of type checks we need to
// emit. For example, if there is only one integer type supported by a
// target, there should be no type comparisons at all for integer patterns!
//
// To figure out the fewest number of type checks needed, clone the pattern,
// remove the types, then perform type inference on the pattern as a whole.
// If there are unresolved types, emit an explicit check for those types,
// apply the type to the tree, then rerun type inference. Iterate until all
// types are resolved.
//
PatWithNoTypes = Pattern.getSrcPattern()->clone();
PatWithNoTypes->RemoveAllTypes();
// If there are types that are manifestly known, infer them.
InferPossibleTypes();
}
/// InferPossibleTypes - As we emit the pattern, we end up generating type
/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
/// want to propagate implied types as far throughout the tree as possible so
/// that we avoid doing redundant type checks. This does the type propagation.
void MatcherGen::InferPossibleTypes() {
// TP - Get *SOME* tree pattern, we don't care which. It is only used for
// diagnostics, which we know are impossible at this point.
TreePattern &TP = *CGP.pf_begin()->second;
try {
bool MadeChange = true;
while (MadeChange)
MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
true/*Ignore reg constraints*/);
} catch (...) {
errs() << "Type constraint application shouldn't fail!";
abort();
}
}
/// AddMatcherNode - Add a matcher node to the current graph we're building.
void MatcherGen::AddMatcherNode(MatcherNodeWithChild *NewNode) {
if (CurPredicate != 0)
CurPredicate->setChild(NewNode);
else
Matcher = NewNode;
CurPredicate = NewNode;
}
/// EmitLeafMatchCode - Generate matching code for leaf nodes.
void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
assert(N->isLeaf() && "Not a leaf?");
// Direct match against an integer constant.
if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
if (DI == 0) {
errs() << "Unknown leaf kind: " << *DI << "\n";
abort();
}
Record *LeafRec = DI->getDef();
if (// Handle register references. Nothing to do here, they always match.
LeafRec->isSubClassOf("RegisterClass") ||
LeafRec->isSubClassOf("PointerLikeRegClass") ||
LeafRec->isSubClassOf("Register") ||
// Place holder for SRCVALUE nodes. Nothing to do here.
LeafRec->getName() == "srcvalue")
return;
if (LeafRec->isSubClassOf("ValueType"))
return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
if (LeafRec->isSubClassOf("CondCode"))
return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
if (LeafRec->isSubClassOf("ComplexPattern")) {
// We can't model ComplexPattern uses that don't have their name taken yet.
// The OPC_CheckComplexPattern operation implicitly records the results.
if (N->getName().empty()) {
errs() << "We expect complex pattern uses to have names: " << *N << "\n";
exit(1);
}
// Handle complex pattern.
const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
return AddMatcherNode(new CheckComplexPatMatcherNode(CP));
}
errs() << "Unknown leaf kind: " << *N << "\n";
abort();
}
void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes) {
assert(!N->isLeaf() && "Not an operator?");
const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
// If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
// a constant without a predicate fn that has more that one bit set, handle
// this as a special case. This is usually for targets that have special
// handling of certain large constants (e.g. alpha with it's 8/16/32-bit
// handling stuff). Using these instructions is often far more efficient
// than materializing the constant. Unfortunately, both the instcombiner
// and the dag combiner can often infer that bits are dead, and thus drop
// them from the mask in the dag. For example, it might turn 'AND X, 255'
// into 'AND X, 254' if it knows the low bit is set. Emit code that checks
// to handle this.
if ((N->getOperator()->getName() == "and" ||
N->getOperator()->getName() == "or") &&
N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
if (N->getOperator()->getName() == "and")
AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
else
AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
// Match the LHS of the AND as appropriate.
AddMatcherNode(new MoveChildMatcherNode(0));
EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
AddMatcherNode(new MoveParentMatcherNode());
return;
}
}
}
// Check that the current opcode lines up.
AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
// If this node has a chain, then the chain is operand #0 is the SDNode, and
// the child numbers of the node are all offset by one.
unsigned OpNo = 0;
if (N->NodeHasProperty(SDNPHasChain, CGP)) {
OpNo = 1;
// If this node is not the root and the subtree underneath it produces a
// chain, then the result of matching the node is also produce a chain.
// Beyond that, this means that we're also folding (at least) the root node
// into the node that produce the chain (for example, matching
// "(add reg, (load ptr))" as a add_with_memory on X86). This is
// problematic, if the 'reg' node also uses the load (say, its chain).
// Graphically:
//
// [LD]
// ^ ^
// | \ DAG's like cheese.
// / |
// / [YY]
// | ^
// [XX]--/
//
// It would be invalid to fold XX and LD. In this case, folding the two
// nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
// To prevent this, we emit a dynamic check for legality before allowing
// this to be folded.
//
const TreePatternNode *Root = Pattern.getSrcPattern();
if (N != Root) { // Not the root of the pattern.
// If there is a node between the root and this node, then we definitely
// need to emit the check.
bool NeedCheck = !Root->hasChild(N);
// If it *is* an immediate child of the root, we can still need a check if
// the root SDNode has multiple inputs. For us, this means that it is an
// intrinsic, has multiple operands, or has other inputs like chain or
// flag).
if (!NeedCheck) {
const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
NeedCheck =
Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
PInfo.getNumOperands() > 1 ||
PInfo.hasProperty(SDNPHasChain) ||
PInfo.hasProperty(SDNPInFlag) ||
PInfo.hasProperty(SDNPOptInFlag);
}
if (NeedCheck)
AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
}
}
// FIXME: Need to generate IsChainCompatible checks.
for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
// Get the code suitable for matching this child. Move to the child, check
// it then move back to the parent.
AddMatcherNode(new MoveChildMatcherNode(OpNo));
EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
AddMatcherNode(new MoveParentMatcherNode());
}
}
void MatcherGen::EmitMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes) {
// If N and NodeNoTypes don't agree on a type, then this is a case where we
// need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
// reinfer any correlated types.
if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
NodeNoTypes->setTypes(N->getExtTypes());
InferPossibleTypes();
}
// If this node has a name associated with it, capture it in VariableMap. If
// we already saw this in the pattern, emit code to verify dagness.
if (!N->getName().empty()) {
unsigned &VarMapEntry = VariableMap[N->getName()];
if (VarMapEntry == 0) {
VarMapEntry = NextRecordedOperandNo+1;
unsigned NumRecorded;
// If this is a complex pattern, the match operation for it will
// implicitly record all of the outputs of it (which may be more than
// one).
if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
// Record the right number of operands.
NumRecorded = AM->getNumOperands()-1;
if (AM->hasProperty(SDNPHasChain))
NumRecorded += 2; // Input and output chains.
} else {
// If it is a normal named node, we must emit a 'Record' opcode.
AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
NumRecorded = 1;
}
NextRecordedOperandNo += NumRecorded;
} else {
// If we get here, this is a second reference to a specific name. Since
// we already have checked that the first reference is valid, we don't
// have to recursively match it, just check that it's the same as the
// previously named thing.
AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
return;
}
}
// If there are node predicates for this node, generate their checks.
for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
if (N->isLeaf())
EmitLeafMatchCode(N);
else
EmitOperatorMatchCode(N, NodeNoTypes);
}
void MatcherGen::EmitMatcherCode() {
// If the pattern has a predicate on it (e.g. only enabled when a subtarget
// feature is around, do the check).
if (!Pattern.getPredicateCheck().empty())
AddMatcherNode(new
CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
// Emit the matcher for the pattern structure and types.
EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
}
MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
const CodeGenDAGPatterns &CGP) {
MatcherGen Gen(Pattern, CGP);
// Generate the code for the matcher.
Gen.EmitMatcherCode();
// If the match succeeds, then we generate Pattern.
EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
// Link it into the pattern.
if (MatcherNodeWithChild *Pred = Gen.GetCurPredicate()) {
Pred->setChild(Result);
return Gen.GetMatcher();
}
// Unconditional match.
return Result;
}
<commit_msg>record input chains.<commit_after>//===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DAGISelMatcher.h"
#include "CodeGenDAGPatterns.h"
#include "Record.h"
#include "llvm/ADT/StringMap.h"
using namespace llvm;
namespace {
class MatcherGen {
const PatternToMatch &Pattern;
const CodeGenDAGPatterns &CGP;
/// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
/// out with all of the types removed. This allows us to insert type checks
/// as we scan the tree.
TreePatternNode *PatWithNoTypes;
/// VariableMap - A map from variable names ('$dst') to the recorded operand
/// number that they were captured as. These are biased by 1 to make
/// insertion easier.
StringMap<unsigned> VariableMap;
unsigned NextRecordedOperandNo;
MatcherNodeWithChild *Matcher;
MatcherNodeWithChild *CurPredicate;
public:
MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
~MatcherGen() {
delete PatWithNoTypes;
}
void EmitMatcherCode();
MatcherNodeWithChild *GetMatcher() const { return Matcher; }
MatcherNodeWithChild *GetCurPredicate() const { return CurPredicate; }
private:
void AddMatcherNode(MatcherNodeWithChild *NewNode);
void InferPossibleTypes();
void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
void EmitLeafMatchCode(const TreePatternNode *N);
void EmitOperatorMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes);
};
} // end anon namespace.
MatcherGen::MatcherGen(const PatternToMatch &pattern,
const CodeGenDAGPatterns &cgp)
: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Matcher(0), CurPredicate(0) {
// We need to produce the matcher tree for the patterns source pattern. To do
// this we need to match the structure as well as the types. To do the type
// matching, we want to figure out the fewest number of type checks we need to
// emit. For example, if there is only one integer type supported by a
// target, there should be no type comparisons at all for integer patterns!
//
// To figure out the fewest number of type checks needed, clone the pattern,
// remove the types, then perform type inference on the pattern as a whole.
// If there are unresolved types, emit an explicit check for those types,
// apply the type to the tree, then rerun type inference. Iterate until all
// types are resolved.
//
PatWithNoTypes = Pattern.getSrcPattern()->clone();
PatWithNoTypes->RemoveAllTypes();
// If there are types that are manifestly known, infer them.
InferPossibleTypes();
}
/// InferPossibleTypes - As we emit the pattern, we end up generating type
/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
/// want to propagate implied types as far throughout the tree as possible so
/// that we avoid doing redundant type checks. This does the type propagation.
void MatcherGen::InferPossibleTypes() {
// TP - Get *SOME* tree pattern, we don't care which. It is only used for
// diagnostics, which we know are impossible at this point.
TreePattern &TP = *CGP.pf_begin()->second;
try {
bool MadeChange = true;
while (MadeChange)
MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
true/*Ignore reg constraints*/);
} catch (...) {
errs() << "Type constraint application shouldn't fail!";
abort();
}
}
/// AddMatcherNode - Add a matcher node to the current graph we're building.
void MatcherGen::AddMatcherNode(MatcherNodeWithChild *NewNode) {
if (CurPredicate != 0)
CurPredicate->setChild(NewNode);
else
Matcher = NewNode;
CurPredicate = NewNode;
}
/// EmitLeafMatchCode - Generate matching code for leaf nodes.
void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
assert(N->isLeaf() && "Not a leaf?");
// Direct match against an integer constant.
if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
if (DI == 0) {
errs() << "Unknown leaf kind: " << *DI << "\n";
abort();
}
Record *LeafRec = DI->getDef();
if (// Handle register references. Nothing to do here, they always match.
LeafRec->isSubClassOf("RegisterClass") ||
LeafRec->isSubClassOf("PointerLikeRegClass") ||
LeafRec->isSubClassOf("Register") ||
// Place holder for SRCVALUE nodes. Nothing to do here.
LeafRec->getName() == "srcvalue")
return;
if (LeafRec->isSubClassOf("ValueType"))
return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
if (LeafRec->isSubClassOf("CondCode"))
return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
if (LeafRec->isSubClassOf("ComplexPattern")) {
// We can't model ComplexPattern uses that don't have their name taken yet.
// The OPC_CheckComplexPattern operation implicitly records the results.
if (N->getName().empty()) {
errs() << "We expect complex pattern uses to have names: " << *N << "\n";
exit(1);
}
// Handle complex pattern.
const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
return AddMatcherNode(new CheckComplexPatMatcherNode(CP));
}
errs() << "Unknown leaf kind: " << *N << "\n";
abort();
}
void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes) {
assert(!N->isLeaf() && "Not an operator?");
const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
// If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
// a constant without a predicate fn that has more that one bit set, handle
// this as a special case. This is usually for targets that have special
// handling of certain large constants (e.g. alpha with it's 8/16/32-bit
// handling stuff). Using these instructions is often far more efficient
// than materializing the constant. Unfortunately, both the instcombiner
// and the dag combiner can often infer that bits are dead, and thus drop
// them from the mask in the dag. For example, it might turn 'AND X, 255'
// into 'AND X, 254' if it knows the low bit is set. Emit code that checks
// to handle this.
if ((N->getOperator()->getName() == "and" ||
N->getOperator()->getName() == "or") &&
N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
if (N->getOperator()->getName() == "and")
AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
else
AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
// Match the LHS of the AND as appropriate.
AddMatcherNode(new MoveChildMatcherNode(0));
EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
AddMatcherNode(new MoveParentMatcherNode());
return;
}
}
}
// Check that the current opcode lines up.
AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
// If this node has a chain, then the chain is operand #0 is the SDNode, and
// the child numbers of the node are all offset by one.
unsigned OpNo = 0;
if (N->NodeHasProperty(SDNPHasChain, CGP)) {
// Record the input chain, which is always input #0 of the SDNode.
AddMatcherNode(new MoveChildMatcherNode(0));
++NextRecordedOperandNo;
AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
"' input chain"));
AddMatcherNode(new MoveParentMatcherNode());
// Don't look at the input chain when matching the tree pattern to the
// SDNode.
OpNo = 1;
// If this node is not the root and the subtree underneath it produces a
// chain, then the result of matching the node is also produce a chain.
// Beyond that, this means that we're also folding (at least) the root node
// into the node that produce the chain (for example, matching
// "(add reg, (load ptr))" as a add_with_memory on X86). This is
// problematic, if the 'reg' node also uses the load (say, its chain).
// Graphically:
//
// [LD]
// ^ ^
// | \ DAG's like cheese.
// / |
// / [YY]
// | ^
// [XX]--/
//
// It would be invalid to fold XX and LD. In this case, folding the two
// nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
// To prevent this, we emit a dynamic check for legality before allowing
// this to be folded.
//
const TreePatternNode *Root = Pattern.getSrcPattern();
if (N != Root) { // Not the root of the pattern.
// If there is a node between the root and this node, then we definitely
// need to emit the check.
bool NeedCheck = !Root->hasChild(N);
// If it *is* an immediate child of the root, we can still need a check if
// the root SDNode has multiple inputs. For us, this means that it is an
// intrinsic, has multiple operands, or has other inputs like chain or
// flag).
if (!NeedCheck) {
const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
NeedCheck =
Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
PInfo.getNumOperands() > 1 ||
PInfo.hasProperty(SDNPHasChain) ||
PInfo.hasProperty(SDNPInFlag) ||
PInfo.hasProperty(SDNPOptInFlag);
}
if (NeedCheck)
AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
}
}
// FIXME: Need to generate IsChainCompatible checks.
for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
// Get the code suitable for matching this child. Move to the child, check
// it then move back to the parent.
AddMatcherNode(new MoveChildMatcherNode(OpNo));
EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
AddMatcherNode(new MoveParentMatcherNode());
}
}
void MatcherGen::EmitMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes) {
// If N and NodeNoTypes don't agree on a type, then this is a case where we
// need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
// reinfer any correlated types.
if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
NodeNoTypes->setTypes(N->getExtTypes());
InferPossibleTypes();
}
// If this node has a name associated with it, capture it in VariableMap. If
// we already saw this in the pattern, emit code to verify dagness.
if (!N->getName().empty()) {
unsigned &VarMapEntry = VariableMap[N->getName()];
if (VarMapEntry == 0) {
VarMapEntry = NextRecordedOperandNo+1;
unsigned NumRecorded;
// If this is a complex pattern, the match operation for it will
// implicitly record all of the outputs of it (which may be more than
// one).
if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
// Record the right number of operands.
NumRecorded = AM->getNumOperands()-1;
if (AM->hasProperty(SDNPHasChain))
NumRecorded += 2; // Input and output chains.
} else {
// If it is a normal named node, we must emit a 'Record' opcode.
AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
NumRecorded = 1;
}
NextRecordedOperandNo += NumRecorded;
} else {
// If we get here, this is a second reference to a specific name. Since
// we already have checked that the first reference is valid, we don't
// have to recursively match it, just check that it's the same as the
// previously named thing.
AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
return;
}
}
// If there are node predicates for this node, generate their checks.
for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
if (N->isLeaf())
EmitLeafMatchCode(N);
else
EmitOperatorMatchCode(N, NodeNoTypes);
}
void MatcherGen::EmitMatcherCode() {
// If the pattern has a predicate on it (e.g. only enabled when a subtarget
// feature is around, do the check).
if (!Pattern.getPredicateCheck().empty())
AddMatcherNode(new
CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
// Emit the matcher for the pattern structure and types.
EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
}
MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
const CodeGenDAGPatterns &CGP) {
MatcherGen Gen(Pattern, CGP);
// Generate the code for the matcher.
Gen.EmitMatcherCode();
// If the match succeeds, then we generate Pattern.
EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
// Link it into the pattern.
if (MatcherNodeWithChild *Pred = Gen.GetCurPredicate()) {
Pred->setChild(Result);
return Gen.GetMatcher();
}
// Unconditional match.
return Result;
}
<|endoftext|> |
<commit_before>#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/session.hpp"
#include <boost/utility.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/thread/mutex.hpp>
#include "test.hpp"
using namespace libtorrent;
using namespace boost::filesystem;
int test_main()
{
const int piece_size = 16;
const int half = piece_size / 2;
torrent_info info;
info.set_piece_size(piece_size);
info.add_file("temp_storage/test1.tmp", 17);
info.add_file("temp_storage/test2.tmp", 612);
info.add_file("temp_storage/test3.tmp", 0);
info.add_file("temp_storage/test4.tmp", 0);
info.add_file("temp_storage/test5.tmp", 1);
char piece0[piece_size] =
{ 6, 6, 6, 6, 6, 6, 6, 6
, 9, 9, 9, 9, 9, 9, 9, 9};
char piece1[piece_size] =
{ 0, 0, 0, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1};
char piece2[piece_size] =
{ 0, 0, 1, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1};
info.set_hash(0, hasher(piece0, piece_size).final());
info.set_hash(1, hasher(piece1, piece_size).final());
info.set_hash(2, hasher(piece2, piece_size).final());
info.create_torrent();
create_directory(initial_path() / "temp_storage");
int num_pieces = (1 + 612 + 17 + piece_size - 1) / piece_size;
TEST_CHECK(info.num_pieces() == num_pieces);
char piece[piece_size];
{ // avoid having two storages use the same files
storage s(info, initial_path());
// write piece 1 (in slot 0)
s.write(piece1, 0, 0, half);
s.write(piece1 + half, 0, half, half);
// verify piece 1
s.read(piece, 0, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece1));
// do the same with piece 0 and 2 (in slot 1 and 2)
s.write(piece0, 1, 0, piece_size);
s.write(piece2, 2, 0, piece_size);
// verify piece 0 and 2
s.read(piece, 1, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece0));
s.read(piece, 2, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece2));
// make sure the files have the correct size
TEST_CHECK(file_size(initial_path() / "temp_storage" / "test1.tmp") == 17);
TEST_CHECK(file_size(initial_path() / "temp_storage" / "test2.tmp") == 31);
s.release_files();
}
// make sure the piece_manager can identify the pieces
piece_manager pm(info, initial_path());
boost::mutex lock;
libtorrent::detail::piece_checker_data d;
std::vector<bool> pieces;
num_pieces = 0;
TEST_CHECK(pm.check_fastresume(d, pieces, num_pieces, true) == false);
bool finished = false;
float progress;
num_pieces = 0;
while (!finished)
boost::tie(finished, progress) = pm.check_files(pieces, num_pieces);
TEST_CHECK(num_pieces == std::count(pieces.begin(), pieces.end()
, true));
pm.read(piece, 0, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece0));
pm.read(piece, 1, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece1));
pm.read(piece, 2, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece2));
pm.release_files();
remove_all(initial_path() / "temp_storage");
return 0;
}
<commit_msg>updated storage test<commit_after>#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/session.hpp"
#include <boost/utility.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/thread/mutex.hpp>
#include "test.hpp"
using namespace libtorrent;
using namespace boost::filesystem;
int test_main()
{
const int piece_size = 16;
const int half = piece_size / 2;
torrent_info info;
info.set_piece_size(piece_size);
info.add_file("temp_storage/test1.tmp", 17);
info.add_file("temp_storage/test2.tmp", 612);
info.add_file("temp_storage/test3.tmp", 0);
info.add_file("temp_storage/test4.tmp", 0);
info.add_file("temp_storage/test5.tmp", 1);
char piece0[piece_size] =
{ 6, 6, 6, 6, 6, 6, 6, 6
, 9, 9, 9, 9, 9, 9, 9, 9};
char piece1[piece_size] =
{ 0, 0, 0, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1};
char piece2[piece_size] =
{ 0, 0, 1, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1};
info.set_hash(0, hasher(piece0, piece_size).final());
info.set_hash(1, hasher(piece1, piece_size).final());
info.set_hash(2, hasher(piece2, piece_size).final());
info.create_torrent();
create_directory(initial_path() / "temp_storage");
int num_pieces = (1 + 612 + 17 + piece_size - 1) / piece_size;
TEST_CHECK(info.num_pieces() == num_pieces);
char piece[piece_size];
{ // avoid having two storages use the same files
storage s(info, initial_path());
// write piece 1 (in slot 0)
s.write(piece1, 0, 0, half);
s.write(piece1 + half, 0, half, half);
// verify piece 1
s.read(piece, 0, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece1));
// do the same with piece 0 and 2 (in slot 1 and 2)
s.write(piece0, 1, 0, piece_size);
s.write(piece2, 2, 0, piece_size);
// verify piece 0 and 2
s.read(piece, 1, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece0));
s.read(piece, 2, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece2));
// make sure the files have the correct size
TEST_CHECK(file_size(initial_path() / "temp_storage" / "test1.tmp") == 17);
TEST_CHECK(file_size(initial_path() / "temp_storage" / "test2.tmp") == 31);
s.release_files();
}
// make sure the piece_manager can identify the pieces
piece_manager pm(info, initial_path());
boost::mutex lock;
libtorrent::detail::piece_checker_data d;
std::vector<bool> pieces;
num_pieces = 0;
TEST_CHECK(pm.check_fastresume(d, pieces, num_pieces, true) == false);
bool finished = false;
float progress;
num_pieces = 0;
while (!finished)
boost::tie(finished, progress) = pm.check_files(pieces, num_pieces);
TEST_CHECK(num_pieces == std::count(pieces.begin(), pieces.end()
, true));
pm.read(piece, 0, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece0));
pm.read(piece, 1, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece1));
pm.read(piece, 2, 0, piece_size);
TEST_CHECK(std::equal(piece, piece + piece_size, piece2));
pm.release_files();
TEST_CHECK(exists("temp_storage/test3.tmp"));
TEST_CHECK(exists("temp_storage/test4.tmp"));
remove_all(initial_path() / "temp_storage");
return 0;
}
<|endoftext|> |
<commit_before>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/alert_types.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using namespace libtorrent;
void test_running_torrent(boost::intrusive_ptr<torrent_info> info, size_type file_size)
{
session ses(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48130, 48140), "0.0.0.0", 0);
ses.set_alert_mask(alert::storage_notification);
add_torrent_params p;
p.ti = info;
p.save_path = ".";
torrent_handle h = ses.add_torrent(p);
test_sleep(500);
torrent_status st = h.status();
std::cout << "total_wanted: " << st.total_wanted << " : " << file_size * 3 << std::endl;
TEST_CHECK(st.total_wanted == file_size * 3);
std::cout << "total_wanted_done: " << st.total_wanted_done << " : 0" << std::endl;
TEST_CHECK(st.total_wanted_done == 0);
std::vector<int> prio(3, 1);
prio[0] = 0;
h.prioritize_files(prio);
test_sleep(500);
st = h.status();
std::cout << "total_wanted: " << st.total_wanted << " : " << file_size * 2 << std::endl;
TEST_CHECK(st.total_wanted == file_size * 2);
std::cout << "total_wanted_done: " << st.total_wanted_done << " : 0" << std::endl;
TEST_CHECK(st.total_wanted_done == 0);
prio[1] = 0;
h.prioritize_files(prio);
test_sleep(500);
st = h.status();
std::cout << "total_wanted: " << st.total_wanted << " : " << file_size << std::endl;
TEST_CHECK(st.total_wanted == file_size);
std::cout << "total_wanted_done: " << st.total_wanted_done << " : 0" << std::endl;
TEST_CHECK(st.total_wanted_done == 0);
if (info->num_pieces() > 0)
{
h.piece_priority(0, 1);
st = h.status();
TEST_CHECK(st.pieces[0] == false);
std::vector<char> piece(info->piece_length());
for (int i = 0; i < int(piece.size()); ++i)
piece[i] = (i % 26) + 'A';
h.add_piece(0, &piece[0]);
test_sleep(10000);
st = h.status();
TEST_CHECK(st.pieces[0] == true);
std::cout << "reading piece 0" << std::endl;
h.read_piece(0);
alert const* a = ses.wait_for_alert(seconds(10));
bool passed = false;
while (a)
{
std::auto_ptr<alert> al = ses.pop_alert();
assert(al.get());
std::cout << " " << al->message() << std::endl;
if (read_piece_alert* rpa = dynamic_cast<read_piece_alert*>(al.get()))
{
std::cout << "SUCCEEDED!" << std::endl;
passed = true;
TEST_CHECK(memcmp(&piece[0], rpa->buffer.get(), piece.size()) == 0);
TEST_CHECK(rpa->size == info->piece_size(0));
TEST_CHECK(rpa->piece == 0);
break;
}
a = ses.wait_for_alert(seconds(10));
TEST_CHECK(a);
}
TEST_CHECK(passed);
}
}
int test_main()
{
{
remove("test_torrent_dir2/tmp1");
remove("test_torrent_dir2/tmp2");
remove("test_torrent_dir2/tmp3");
file_storage fs;
size_type file_size = 1 * 1024 * 1024 * 1024;
fs.add_file("test_torrent_dir2/tmp1", file_size);
fs.add_file("test_torrent_dir2/tmp2", file_size);
fs.add_file("test_torrent_dir2/tmp3", file_size);
libtorrent::create_torrent t(fs, 4 * 1024 * 1024);
t.add_tracker("http://non-existing.com/announce");
std::vector<char> piece(4 * 1024 * 1024);
for (int i = 0; i < int(piece.size()); ++i)
piece[i] = (i % 26) + 'A';
// calculate the hash for all pieces
sha1_hash ph = hasher(&piece[0], piece.size()).final();
int num = t.num_pieces();
TEST_CHECK(t.num_pieces() > 0);
for (int i = 0; i < num; ++i)
t.set_hash(i, ph);
std::vector<char> tmp;
std::back_insert_iterator<std::vector<char> > out(tmp);
bencode(out, t.generate());
boost::intrusive_ptr<torrent_info> info(new torrent_info(&tmp[0], tmp.size()));
TEST_CHECK(info->num_pieces() > 0);
test_running_torrent(info, file_size);
}
{
file_storage fs;
fs.add_file("test_torrent_dir2/tmp1", 0);
libtorrent::create_torrent t(fs, 4 * 1024 * 1024);
t.add_tracker("http://non-existing.com/announce");
std::vector<char> tmp;
std::back_insert_iterator<std::vector<char> > out(tmp);
bencode(out, t.generate());
boost::intrusive_ptr<torrent_info> info(new torrent_info(&tmp[0], tmp.size()));
test_running_torrent(info, 0);
}
return 0;
}
<commit_msg>added license to test_torrent.cpp<commit_after>/*
Copyright (c) 2008, Arvid Norberg
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 author 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.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/alert_types.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using namespace libtorrent;
void test_running_torrent(boost::intrusive_ptr<torrent_info> info, size_type file_size)
{
session ses(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48130, 48140), "0.0.0.0", 0);
ses.set_alert_mask(alert::storage_notification);
add_torrent_params p;
p.ti = info;
p.save_path = ".";
torrent_handle h = ses.add_torrent(p);
test_sleep(500);
torrent_status st = h.status();
std::cout << "total_wanted: " << st.total_wanted << " : " << file_size * 3 << std::endl;
TEST_CHECK(st.total_wanted == file_size * 3);
std::cout << "total_wanted_done: " << st.total_wanted_done << " : 0" << std::endl;
TEST_CHECK(st.total_wanted_done == 0);
std::vector<int> prio(3, 1);
prio[0] = 0;
h.prioritize_files(prio);
test_sleep(500);
st = h.status();
std::cout << "total_wanted: " << st.total_wanted << " : " << file_size * 2 << std::endl;
TEST_CHECK(st.total_wanted == file_size * 2);
std::cout << "total_wanted_done: " << st.total_wanted_done << " : 0" << std::endl;
TEST_CHECK(st.total_wanted_done == 0);
prio[1] = 0;
h.prioritize_files(prio);
test_sleep(500);
st = h.status();
std::cout << "total_wanted: " << st.total_wanted << " : " << file_size << std::endl;
TEST_CHECK(st.total_wanted == file_size);
std::cout << "total_wanted_done: " << st.total_wanted_done << " : 0" << std::endl;
TEST_CHECK(st.total_wanted_done == 0);
if (info->num_pieces() > 0)
{
h.piece_priority(0, 1);
st = h.status();
TEST_CHECK(st.pieces[0] == false);
std::vector<char> piece(info->piece_length());
for (int i = 0; i < int(piece.size()); ++i)
piece[i] = (i % 26) + 'A';
h.add_piece(0, &piece[0]);
test_sleep(10000);
st = h.status();
TEST_CHECK(st.pieces[0] == true);
std::cout << "reading piece 0" << std::endl;
h.read_piece(0);
alert const* a = ses.wait_for_alert(seconds(10));
bool passed = false;
while (a)
{
std::auto_ptr<alert> al = ses.pop_alert();
assert(al.get());
std::cout << " " << al->message() << std::endl;
if (read_piece_alert* rpa = dynamic_cast<read_piece_alert*>(al.get()))
{
std::cout << "SUCCEEDED!" << std::endl;
passed = true;
TEST_CHECK(memcmp(&piece[0], rpa->buffer.get(), piece.size()) == 0);
TEST_CHECK(rpa->size == info->piece_size(0));
TEST_CHECK(rpa->piece == 0);
break;
}
a = ses.wait_for_alert(seconds(10));
TEST_CHECK(a);
}
TEST_CHECK(passed);
}
}
int test_main()
{
{
remove("test_torrent_dir2/tmp1");
remove("test_torrent_dir2/tmp2");
remove("test_torrent_dir2/tmp3");
file_storage fs;
size_type file_size = 1 * 1024 * 1024 * 1024;
fs.add_file("test_torrent_dir2/tmp1", file_size);
fs.add_file("test_torrent_dir2/tmp2", file_size);
fs.add_file("test_torrent_dir2/tmp3", file_size);
libtorrent::create_torrent t(fs, 4 * 1024 * 1024);
t.add_tracker("http://non-existing.com/announce");
std::vector<char> piece(4 * 1024 * 1024);
for (int i = 0; i < int(piece.size()); ++i)
piece[i] = (i % 26) + 'A';
// calculate the hash for all pieces
sha1_hash ph = hasher(&piece[0], piece.size()).final();
int num = t.num_pieces();
TEST_CHECK(t.num_pieces() > 0);
for (int i = 0; i < num; ++i)
t.set_hash(i, ph);
std::vector<char> tmp;
std::back_insert_iterator<std::vector<char> > out(tmp);
bencode(out, t.generate());
boost::intrusive_ptr<torrent_info> info(new torrent_info(&tmp[0], tmp.size()));
TEST_CHECK(info->num_pieces() > 0);
test_running_torrent(info, file_size);
}
{
file_storage fs;
fs.add_file("test_torrent_dir2/tmp1", 0);
libtorrent::create_torrent t(fs, 4 * 1024 * 1024);
t.add_tracker("http://non-existing.com/announce");
std::vector<char> tmp;
std::back_insert_iterator<std::vector<char> > out(tmp);
bencode(out, t.generate());
boost::intrusive_ptr<torrent_info> info(new torrent_info(&tmp[0], tmp.size()));
test_running_torrent(info, 0);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <realm/version.hpp>
#include "test.hpp"
using namespace realm;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
TEST(Version_General)
{
CHECK_EQUAL(REALM_VER_MAJOR, Version::get_major());
CHECK_EQUAL(REALM_VER_MINOR, Version::get_minor());
CHECK_EQUAL(REALM_VER_PATCH, Version::get_patch());
CHECK_EQUAL(REALM_VER_PATCH, Version::get_patch());
CHECK_EQUAL(true, Version::is_at_least(0,0,0));
CHECK_EQUAL(true, Version::is_at_least(0,1,5));
CHECK_EQUAL(true, Version::is_at_least(0,1,6));
// Below might have to be updated when the version is incremented
CHECK_EQUAL(true, Version::is_at_least(0,1,9));
CHECK_EQUAL(false, Version::is_at_least(1,0,0));
CHECK_EQUAL(true, Version::is_at_least(0,2,0));
}
<commit_msg>Fixed version unit test to deal with 1.0.0. Yeah, this is not a PR because the condition depends on the version bump commit parent of this commit.<commit_after>#include <string>
#include <iostream>
#include <realm/version.hpp>
#include "test.hpp"
using namespace realm;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
TEST(Version_General)
{
CHECK_EQUAL(REALM_VER_MAJOR, Version::get_major());
CHECK_EQUAL(REALM_VER_MINOR, Version::get_minor());
CHECK_EQUAL(REALM_VER_PATCH, Version::get_patch());
CHECK_EQUAL(REALM_VER_PATCH, Version::get_patch());
CHECK_EQUAL(true, Version::is_at_least(0,0,0));
CHECK_EQUAL(true, Version::is_at_least(0,1,5));
CHECK_EQUAL(true, Version::is_at_least(0,1,6));
// Below might have to be updated when the version is incremented
CHECK_EQUAL(true, Version::is_at_least(0,1,9));
CHECK_EQUAL(true, Version::is_at_least(1,0,0));
CHECK_EQUAL(false, Version::is_at_least(2,0,0));
CHECK_EQUAL(true, Version::is_at_least(0,2,0));
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "rtos.h"
#if defined(MBED_RTOS_SINGLE_THREAD)
#error [NOT_SUPPORTED] test not supported
#endif
#define TEST_STACK_SIZE 512
#define SIGNAL_SET_VALUE 0x01
const int SIGNALS_TO_EMIT = 100;
const int SIGNAL_HANDLE_DELEY = 25;
DigitalOut led(LED1);
int signal_counter = 0;
void led_thread() {
while (true) {
// Signal flags that are reported as event are automatically cleared.
Thread::signal_wait(SIGNAL_SET_VALUE);
led = !led;
signal_counter++;
}
}
int main (void) {
GREENTEA_SETUP(20, "default_auto");
Thread thread(osPriorityNormal, TEST_STACK_SIZE);
thread.start(led_thread);
bool result = false;
printf("Handling %d signals...\r\n", SIGNALS_TO_EMIT);
while (true) {
Thread::wait(2 * SIGNAL_HANDLE_DELEY);
thread.signal_set(SIGNAL_SET_VALUE);
if (signal_counter == SIGNALS_TO_EMIT) {
printf("Handled %d signals\r\n", signal_counter);
result = true;
break;
}
}
GREENTEA_TESTSUITE_RESULT(result);
return 0;
}
<commit_msg>Extends test set for signals<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "utest/utest.h"
#include "unity/unity.h"
using utest::v1::Case;
#if defined(MBED_RTOS_SINGLE_THREAD)
#error [NOT_SUPPORTED] test not supported
#endif
#define TEST_STACK_SIZE 512
#define MAX_FLAG_POS 30
#define ALL_SIGNALS 0x7fffffff
#define NO_SIGNALS 0x0
#define PROHIBITED_SIGNAL 0x80000000
#define SIGNAL1 0x1
#define SIGNAL2 0x2
#define SIGNAL3 0x4
struct Sync {
Sync(Semaphore &parent, Semaphore &child): sem_parent(parent), sem_child(child)
{}
Semaphore &sem_parent;
Semaphore &sem_child;
};
/* In order to successfully run this test suite when compiled with --profile=debug
* error() has to be redefined as noop.
*
* ThreadFlags calls RTX API which uses Event Recorder functionality. When compiled
* with MBED_TRAP_ERRORS_ENABLED=1 (set in debug profile) EvrRtxEventFlagsError() calls error()
* which aborts test program.
*/
#if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED
void error(const char* format, ...) {
(void) format;
}
#endif
template <int32_t signals, uint32_t timeout, int32_t test_val>
void run_signal_wait(void)
{
osEvent ev = Thread::signal_wait(signals, timeout);
TEST_ASSERT_EQUAL(test_val, ev.status);
}
template <int32_t signals, uint32_t timeout, int32_t test_val>
void run_release_signal_wait(Semaphore *sem)
{
sem->release();
osEvent ev = Thread::signal_wait(signals, timeout);
TEST_ASSERT_EQUAL(test_val, ev.status);
}
template <int32_t signals, uint32_t timeout, int32_t test_val>
void run_release_wait_signal_wait(Sync *sync)
{
sync->sem_parent.release();
sync->sem_child.wait();
osEvent ev = Thread::signal_wait(signals, timeout);
TEST_ASSERT_EQUAL(test_val, ev.status);
}
template <int32_t signals, int32_t test_val>
void run_clear(void)
{
int32_t ret = Thread::signal_clr(signals);
TEST_ASSERT_EQUAL(test_val, ret);
}
template <int32_t signals, int32_t test_val>
void run_wait_clear(Sync *sync)
{
sync->sem_parent.release();
sync->sem_child.wait();
int32_t ret = Thread::signal_clr(signals);
TEST_ASSERT_EQUAL(test_val, ret);
}
template <int32_t signals1, int32_t signals2, int32_t test_val1, int32_t test_val2>
void run_double_wait_clear(Sync *sync)
{
int32_t ret;
sync->sem_parent.release();
sync->sem_child.wait();
ret = Thread::signal_clr(signals1);
TEST_ASSERT_EQUAL(test_val1, ret);
ret = Thread::signal_clr(signals2);
TEST_ASSERT_EQUAL(test_val2, ret);
}
void run_loop_wait_clear(Sync *sync)
{
int32_t signals = NO_SIGNALS;
for (int i = 0; i <= MAX_FLAG_POS; i++) {
int32_t signal = 1 << i;
signals |= signal;
sync->sem_child.wait();
int32_t ret = Thread::signal_clr(NO_SIGNALS);
TEST_ASSERT_EQUAL(signals, ret);
sync->sem_parent.release();
}
}
/** Validate that call signal_clr(NO_SIGNALS) doesn't change thread signals and return actual signals
Given two threads A & B are started, B with all signals already set
When thread B calls @a signal_clr(NO_SIGNALS)
Then thread B @a signal_clr status should be ALL_SIGNALS indicating that thread B state is unchanged
*/
void test_clear_no_signals(void)
{
Semaphore sem_parent(0, 1);
Semaphore sem_child(0, 1);
Sync sync(sem_parent, sem_child);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_double_wait_clear<NO_SIGNALS, NO_SIGNALS, ALL_SIGNALS, ALL_SIGNALS>, &sync));
sem_parent.wait();
t.signal_set(ALL_SIGNALS);
sem_child.release();
t.join();
}
/** Validate if any signals are set on just created thread
Given the thread is running
When thread execute @a signal_clr(NO_SIGNALS)
Then thread @a signal_clr return status should be NO_SIGNALS(0) indicating no signals set
*/
void test_init_state(void)
{
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_clear<NO_SIGNALS, NO_SIGNALS>));
t.join();
}
/** Validate all signals set in one shot
Given two threads A & B are started
When thread A call @a signal_set(ALL_SIGNALS) with all possible signals
Then thread B @a signal_clr(NO_SIGNALS) status should be ALL_SIGNALS indicating all signals set correctly
*/
void test_set_all(void)
{
int32_t ret;
Semaphore sem_parent(0, 1);
Semaphore sem_child(0, 1);
Sync sync(sem_parent, sem_child);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_wait_clear<NO_SIGNALS, ALL_SIGNALS>, &sync));
sem_parent.wait();
ret = t.signal_set(ALL_SIGNALS);
TEST_ASSERT_EQUAL(ALL_SIGNALS, ret);
sem_child.release();
t.join();
}
/** Validate that call signal_set with prohibited signal doesn't change thread signals
Given two threads A & B are started, B with all signals set
When thread A executes @a signal_set(PROHIBITED_SIGNAL) with prohibited signal
Then thread B @a signal_clr(NO_SIGNALS) status should be ALL_SIGNALS indicating that thread B signals are unchanged
@note Each signal has up to 31 event flags 0x1, 0x2, 0x4, 0x8, ..., 0x40000000
Most significant bit is reserved and thereby flag 0x80000000 is prohibited
*/
void test_set_prohibited(void)
{
int32_t ret;
Semaphore sem_parent(0, 1);
Semaphore sem_child(0, 1);
Sync sync(sem_parent, sem_child);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_wait_clear<NO_SIGNALS, ALL_SIGNALS>, &sync));
sem_parent.wait();
t.signal_set(ALL_SIGNALS);
ret = t.signal_set(PROHIBITED_SIGNAL);
TEST_ASSERT_EQUAL(osErrorParameter, ret);
sem_child.release();
t.join();
}
/** Validate all signals clear in one shot
Given two threads A & B are started, B with all signals set
When thread B execute @a signal_clr(ALL_SIGNALS) with all possible signals
Then thread B @a signal_clr(NO_SIGNALS) status should be NO_SIGNALS(0) indicating all signals cleared correctly
*/
void test_clear_all(void)
{
Semaphore sem_parent(0, 1);
Semaphore sem_child(0, 1);
Sync sync(sem_parent, sem_child);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_double_wait_clear<ALL_SIGNALS, NO_SIGNALS, ALL_SIGNALS, NO_SIGNALS>, &sync));
sem_parent.wait();
t.signal_set(ALL_SIGNALS);
sem_child.release();
t.join();
}
/** Validate all signals set one by one in loop
Given two threads A & B are started
When thread A executes @a signal_set(signal) in loop with all possible signals
*/
void test_set_all_loop(void)
{
int32_t ret;
Semaphore sem_parent(0, 1);
Semaphore sem_child(0, 1);
Sync sync(sem_parent, sem_child);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_loop_wait_clear, &sync));
int32_t signals = 0;
for (int i = 0; i <= MAX_FLAG_POS; i++) {
int32_t signal = 1 << i;
ret = t.signal_set(signal);
signals |= signal;
TEST_ASSERT_EQUAL(signals, ret);
sem_child.release();
sem_parent.wait();
}
t.join();
}
/** Validate signal_wait return status if timeout specified
Given the thread is running
When thread executes @a signal_wait(signals, timeout) with specified signals and timeout
Then thread @a signal_wait status should be osEventTimeout indicating a timeout
thread @a signal_wait status should be osOK indicating 0[ms] timeout set
*/
template <int32_t signals, uint32_t timeout, int32_t status>
void test_wait_timeout(void)
{
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_signal_wait<signals, timeout, status>));
t.join();
}
/** Validate that call of signal_wait return correctly when thread has all signals already set
Given two threads A & B are started, B with all signals already set
When thread B executes @a signal_wait(ALL_SIGNALS, osWaitForever),
Then thread B @a signal_wait return immediately with status osEventSignal indicating all wait signals was already set
*/
void test_wait_all_already_set(void)
{
Semaphore sem_parent(0, 1);
Semaphore sem_child(0, 1);
Sync sync(sem_parent, sem_child);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_release_wait_signal_wait<ALL_SIGNALS, osWaitForever, osEventSignal>, &sync));
sem_parent.wait();
TEST_ASSERT_EQUAL(Thread::WaitingSemaphore, t.get_state());
t.signal_set(ALL_SIGNALS);
sem_child.release();
t.join();
}
/** Validate if signal_wait return correctly when all signals set
Given two threads A & B are started and B waiting for a thread flag to be set
When thread A executes @a signal_set(ALL_SIGNALS) with all possible signals
Then thread B @a signal_wait status is osEventSignal indicating all wait signals was set
*/
void test_wait_all(void)
{
Semaphore sem(0, 1);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_release_signal_wait<ALL_SIGNALS, osWaitForever, osEventSignal>, &sem));
sem.wait();
TEST_ASSERT_EQUAL(Thread::WaitingThreadFlag, t.get_state());
t.signal_set(ALL_SIGNALS);
t.join();
}
/** Validate if signal_wait accumulate signals and return correctly when all signals set
Given two threads A & B are started and B waiting for a thread signals to be set
When thread A executes @a signal_set setting all signals in loop
Then thread B @a signal_wait status is osEventSignal indicating that all wait signals was set
*/
void test_wait_all_loop(void)
{
int32_t ret;
Semaphore sem(0, 1);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_release_signal_wait<ALL_SIGNALS, osWaitForever, osEventSignal>, &sem));
sem.wait();
TEST_ASSERT_EQUAL(Thread::WaitingThreadFlag, t.get_state());
for (int i = 0; i < MAX_FLAG_POS; i++) {
int32_t signal = 1 << i;
ret = t.signal_set(signal);
}
ret = t.signal_set(1 << MAX_FLAG_POS);
TEST_ASSERT_EQUAL(NO_SIGNALS, ret);
t.join();
}
/** Validate if setting same signal twice cause any unwanted behaviour
Given two threads A & B are started and B waiting for a thread signals to be set
When thread A executes @a signal_set twice for the same signal
Then thread A @a signal_set status is current signal set
thread B @a signal_wait status is osEventSignal indicating that all wait signals was set
*/
void test_set_double(void)
{
int32_t ret;
Semaphore sem(0, 1);
Thread t(osPriorityNormal, TEST_STACK_SIZE);
t.start(callback(run_release_signal_wait<SIGNAL1|SIGNAL2|SIGNAL3, osWaitForever, osEventSignal>, &sem));
sem.wait();
TEST_ASSERT_EQUAL(Thread::WaitingThreadFlag, t.get_state());
ret = t.signal_set(SIGNAL1);
TEST_ASSERT_EQUAL(SIGNAL1, ret);
ret = t.signal_set(SIGNAL2);
TEST_ASSERT_EQUAL(SIGNAL1 | SIGNAL2, ret);
ret = t.signal_set(SIGNAL2);
TEST_ASSERT_EQUAL(SIGNAL1 | SIGNAL2, ret);
TEST_ASSERT_EQUAL(Thread::WaitingThreadFlag, t.get_state());
ret = t.signal_set(SIGNAL3);
TEST_ASSERT_EQUAL(NO_SIGNALS, ret);
t.join();
}
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(10, "default_auto");
return utest::v1::verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
Case("Validate that call signal_clr(NO_SIGNALS) doesn't change thread signals and return actual signals", test_clear_no_signals),
Case("Validate if any signals are set on just created thread", test_init_state),
Case("Validate all signals set in one shot", test_set_all),
Case("Validate that call signal_set with prohibited signal doesn't change thread signals", test_set_prohibited),
Case("Validate all signals clear in one shot", test_clear_all),
Case("Validate all signals set one by one in loop", test_set_all_loop),
Case("Validate signal_wait return status if timeout specified: 0[ms] no signals", test_wait_timeout<0, 0, osOK>),
Case("Validate signal_wait return status if timeout specified: 0[ms] all signals", test_wait_timeout<ALL_SIGNALS, 0, osOK>),
Case("Validate signal_wait return status if timeout specified: 1[ms] no signals", test_wait_timeout<0, 1, osEventTimeout>),
Case("Validate signal_wait return status if timeout specified: 1[ms] all signals", test_wait_timeout<ALL_SIGNALS, 1, osEventTimeout>),
Case("Validate that call of signal_wait return correctly when thread has all signals already set", test_wait_all_already_set),
Case("Validate if signal_wait return correctly when all signals set", test_wait_all),
Case("Validate if signal_wait accumulate signals and return correctly when all signals set", test_wait_all_loop),
Case("Validate if setting same signal twice cause any unwanted behaviour", test_set_double)
};
utest::v1::Specification specification(test_setup, cases);
int main()
{
return !utest::v1::Harness::run(specification);
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief R8C Flash Programmer
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "r8c_protocol.hpp"
#include <iostream>
#include <iomanip>
#include <random>
#include "motsx_io.hpp"
void dump_(const uint8_t* top, uint32_t len, uint32_t ofs, uint32_t w = 16)
{
using namespace std;
cout << hex;
uint32_t l = 0;
for(uint32_t i = 0; i < len; ++i) {
if(l == 0) {
cout << uppercase << setw(4) << setfill('0') << ofs << "- ";
}
int d = static_cast<int>(*top);
++top;
cout << uppercase << setw(2) << setfill('0') << d;
++l;
++ofs;
if(l >= w) {
cout << endl;
l = 0;
} else {
cout << ' ';
}
}
cout << dec;
}
class r8c_prog {
bool verbose_;
r8c::protocol proto_;
std::string ver_;
r8c::protocol::id_t id_;
public:
r8c_prog(bool verbose) : verbose_(verbose) {
id_.fill();
}
bool start(const std::string& path, uint32_t brate) {
using namespace r8c;
// 開始
if(!proto_.start(path)) {
std::cerr << "Can't open path: '" << path << "'" << std::endl;
return false;
}
// コネクション
if(!proto_.connection()) {
proto_.end();
std::cerr << "Connection device error..." << std::endl;
return false;
}
if(verbose_) {
std::cout << "Connection OK." << std::endl;
}
// ボーレート変更
speed_t speed;
switch(brate) {
case 9600: speed = B9600; break;
case 19200: speed = B19200; break;
case 38400: speed = B38400; break;
case 57600: speed = B57600; break;
case 115200: speed = B115200; break;
default:
proto_.end();
std::cerr << "Baud rate error: " << brate << std::endl;
return false;
}
if(!proto_.change_speed(speed)) {
proto_.end();
std::cerr << "Change speed error: " << brate << std::endl;
return false;
}
if(verbose_) {
std::cout << "Change speed OK: " << brate << " [bps]" << std::endl;
}
// バージョンの取得
ver_ = proto_.get_version();
if(ver_.empty()) {
proto_.end();
std::cerr << "Get version error..." << std::endl;
return false;
}
if(verbose_) {
std::cout << "Version: '" << ver_ << "'" << std::endl;
}
// ID チェック認証
if(!proto_.id_inspection(id_)) {
std::cerr << "ID error: ";
for(int i = 0; i < 7; ++i) {
std::cerr << std::hex << std::setw(2) << std::uppercase << std::setfill('0')
<< "0x" << static_cast<int>(id_.buff[i]) << ' ';
}
proto_.end();
std::cerr << std::dec << std::endl;
return false;
}
if(verbose_) {
std::cout << "ID OK: ";
for(int i = 0; i < 7; ++i) {
std::cout << std::hex << std::setw(2) << std::uppercase << std::setfill('0')
<< "0x" << static_cast<int>(id_.buff[i]) << ' ';
}
std::cout << std::endl;
}
return true;
}
bool erase(uint32_t top) {
// イレース
if(!proto_.erase_page(top)) {
std::cerr << "Erase error: " << std::hex << std::setw(6)
<< static_cast<int>(top) << " to " << static_cast<int>(top + 255)
<< std::endl;
return false;
}
return true;
}
bool write(uint32_t top, const uint8_t* data) {
using namespace r8c;
// ページ書き込み
if(!proto_.write_page(top, data)) {
std::cerr << "Write error: " << std::hex << std::setw(6)
<< static_cast<int>(top) << " to " << static_cast<int>(top + 255)
<< std::endl;
return false;
}
return true;
}
bool verify(uint32_t top, const uint8_t* data) {
// ページ読み込み
uint8_t tmp[256];
if(!proto_.read_page(top, tmp)) {
std::cerr << "Read error: " << std::hex << std::setw(6)
<< static_cast<int>(top) << " to " << static_cast<int>(top + 255)
<< std::endl;
return false;
}
for(int i = 0; i < 256; ++i) {
if(data[i] != tmp[i]) {
std::cerr << "Verify error: " << std::hex << std::setw(6)
<< "0x" << static_cast<int>(top)
<< std::setw(2) << static_cast<int>(data[top + i]) << " -> "
<< static_cast<int>(tmp[i])
<< std::endl;
return false;
}
}
return true;
}
#if 0
std::mt19937 mt(0x1234);
protocol::array_type ar;
for(int i = 0; i < 256; ++i) {
ar.push_back(mt() & 255);
}
dump_(&ar[0], 256, 0x8000);
#endif
void end() {
proto_.end();
}
};
static bool erase_(r8c_prog& prog, utils::motsx_io& motf)
{
std::cout << "Erase: ";
bool noerr = true;
for(uint32_t a = motf.get_min(); a <= motf.get_max(); a += 256) {
const std::vector<uint8_t>& mem = motf.get_memory();
bool erase = false;
for(int i = 0; i < 256; ++i) {
if(mem[a + i] != 0xff) {
erase = true;
break;
}
}
if(erase) {
if(!prog.erase(a)) {
noerr = false;
break;
}
std::cout << '#' << std::flush;
}
}
std::cout << std::endl;
return noerr;
}
static bool write_(r8c_prog& prog, utils::motsx_io& motf)
{
bool noerr = true;
std::cout << "Write: ";
for(uint32_t a = motf.get_min(); a <= motf.get_max(); a += 256) {
const std::vector<uint8_t>& mem = motf.get_memory();
bool skip = true;
for(int i = 0; i < 256; ++i) {
if(mem[a + i] != 0xff) {
skip = false;
break;
}
}
if(skip) continue;
if(!prog.write(a, &mem[a])) {
noerr = false;
break;
}
std::cout << '#' << std::flush;
}
std::cout << std::endl;
return noerr;
}
static bool verify_(r8c_prog& prog, utils::motsx_io& motf)
{
bool noerr = true;
std::cout << "Verify: ";
for(uint32_t a = motf.get_min(); a <= motf.get_max(); a += 256) {
const std::vector<uint8_t>& mem = motf.get_memory();
bool skip = true;
for(int i = 0; i < 256; ++i) {
if(mem[a + i] != 0xff) {
skip = false;
break;
}
}
if(skip) continue;
if(!prog.verify(a, &mem[a])) {
noerr = false;
break;
}
std::cout << '#' << std::flush;
}
std::cout << std::endl;
return noerr;
}
struct options {
bool verbose;
std::string inp_file;
std::string device;
bool dv;
uint32_t baud_rate;
bool br;
std::string dev_path;
bool dp;
bool erase;
bool write;
bool verify;
options() : verbose(false),
inp_file(),
device(), dv(false),
baud_rate(57600), br(false),
dev_path(), dp(false),
erase(false), write(false), verify(false) { }
void set_str(const std::string& t) {
if(br) {
int val;
if(utils::string_to_int(t, val)) {
baud_rate = val;
} else {
std::cerr << "Options error: baud rate: " << t << std::endl;
}
br = false;
} else if(dv) {
device = t;
dv = false;
} else if(dp) {
dev_path = t;
dp = false;
} else {
inp_file = t;
}
}
};
static void title_(const std::string& cmd)
{
std::cout << "R8C programmer" << std::endl;
std::cout << cmd << std::endl;
}
int main(int argc, char* argv[])
{
if(argc == 1) {
title_(argv[0]);
return 0;
}
options opt;
for(int i = 1; i < argc; ++i) {
const std::string p = argv[i];
if(p[0] == '-') {
if(p == "-verbose") opt.verbose = true;
else if(p == "-s") opt.br = true;
else if(p == "-d") opt.dv = true;
else if(p == "-P") opt.dp = true;
else if(p == "-e") opt.erase = true;
else if(p == "-w") opt.write = true;
else if(p == "-v") opt.verify = true;
} else {
opt.set_str(p);
}
}
utils::motsx_io motf;
if(!motf.load(opt.inp_file)) {
std::cerr << "Can't load input file: '" << opt.inp_file << "'" << std::endl;
return -1;
}
if(opt.verbose) {
std::cout << "Load data: ";
std::cout << std::hex << std::uppercase << std::setfill('0')
<< std::setw(6) << static_cast<int>(motf.get_min()) << " to "
<< std::setw(6) << static_cast<int>(motf.get_max())
<< std::dec << std::endl;
}
// test
if(opt.dev_path.empty()) {
opt.dev_path = "/dev/tty.usbserial-A600e0xq";
}
r8c_prog prog(opt.verbose);
if(!prog.start(opt.dev_path, opt.baud_rate)) {
return -1;
}
if(opt.erase) {
if(!erase_(prog, motf)) {
return -1;
}
}
if(opt.write) {
if(!write_(prog, motf)) {
return -1;
}
}
if(opt.verify) {
if(!verify_(prog, motf)) {
return -1;
}
}
}
<commit_msg>update help<commit_after>//=====================================================================//
/*! @file
@brief R8C Flash Programmer
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "r8c_protocol.hpp"
#include <iostream>
#include <iomanip>
#include <random>
#include "motsx_io.hpp"
static const std::string version_ = "0.20b";
void dump_(const uint8_t* top, uint32_t len, uint32_t ofs, uint32_t w = 16)
{
using namespace std;
cout << hex;
uint32_t l = 0;
for(uint32_t i = 0; i < len; ++i) {
if(l == 0) {
cout << uppercase << setw(4) << setfill('0') << ofs << "- ";
}
int d = static_cast<int>(*top);
++top;
cout << uppercase << setw(2) << setfill('0') << d;
++l;
++ofs;
if(l >= w) {
cout << endl;
l = 0;
} else {
cout << ' ';
}
}
cout << dec;
}
class r8c_prog {
bool verbose_;
r8c::protocol proto_;
std::string ver_;
r8c::protocol::id_t id_;
public:
r8c_prog(bool verbose) : verbose_(verbose) {
id_.fill();
}
bool start(const std::string& path, uint32_t brate) {
using namespace r8c;
// 開始
if(!proto_.start(path)) {
std::cerr << "Can't open path: '" << path << "'" << std::endl;
return false;
}
// コネクション
if(!proto_.connection()) {
proto_.end();
std::cerr << "Connection device error..." << std::endl;
return false;
}
if(verbose_) {
std::cout << "Connection OK." << std::endl;
}
// ボーレート変更
speed_t speed;
switch(brate) {
case 9600: speed = B9600; break;
case 19200: speed = B19200; break;
case 38400: speed = B38400; break;
case 57600: speed = B57600; break;
case 115200: speed = B115200; break;
default:
proto_.end();
std::cerr << "Baud rate error: " << brate << std::endl;
return false;
}
if(!proto_.change_speed(speed)) {
proto_.end();
std::cerr << "Change speed error: " << brate << std::endl;
return false;
}
if(verbose_) {
std::cout << "Change speed OK: " << brate << " [bps]" << std::endl;
}
// バージョンの取得
ver_ = proto_.get_version();
if(ver_.empty()) {
proto_.end();
std::cerr << "Get version error..." << std::endl;
return false;
}
if(verbose_) {
std::cout << "Version: '" << ver_ << "'" << std::endl;
}
// ID チェック認証
if(!proto_.id_inspection(id_)) {
std::cerr << "ID error: ";
for(int i = 0; i < 7; ++i) {
std::cerr << std::hex << std::setw(2) << std::uppercase << std::setfill('0')
<< "0x" << static_cast<int>(id_.buff[i]) << ' ';
}
proto_.end();
std::cerr << std::dec << std::endl;
return false;
}
if(verbose_) {
std::cout << "ID OK: ";
for(int i = 0; i < 7; ++i) {
std::cout << std::hex << std::setw(2) << std::uppercase << std::setfill('0')
<< "0x" << static_cast<int>(id_.buff[i]) << ' ';
}
std::cout << std::endl;
}
return true;
}
bool erase(uint32_t top) {
// イレース
if(!proto_.erase_page(top)) {
std::cerr << "Erase error: " << std::hex << std::setw(6)
<< static_cast<int>(top) << " to " << static_cast<int>(top + 255)
<< std::endl;
return false;
}
return true;
}
bool write(uint32_t top, const uint8_t* data) {
using namespace r8c;
// ページ書き込み
if(!proto_.write_page(top, data)) {
std::cerr << "Write error: " << std::hex << std::setw(6)
<< static_cast<int>(top) << " to " << static_cast<int>(top + 255)
<< std::endl;
return false;
}
return true;
}
bool verify(uint32_t top, const uint8_t* data) {
// ページ読み込み
uint8_t tmp[256];
if(!proto_.read_page(top, tmp)) {
std::cerr << "Read error: " << std::hex << std::setw(6)
<< static_cast<int>(top) << " to " << static_cast<int>(top + 255)
<< std::endl;
return false;
}
for(int i = 0; i < 256; ++i) {
if(data[i] != tmp[i]) {
std::cerr << "Verify error: " << std::hex << std::setw(6)
<< "0x" << static_cast<int>(top)
<< std::setw(2) << static_cast<int>(data[top + i]) << " -> "
<< static_cast<int>(tmp[i])
<< std::endl;
return false;
}
}
return true;
}
#if 0
std::mt19937 mt(0x1234);
protocol::array_type ar;
for(int i = 0; i < 256; ++i) {
ar.push_back(mt() & 255);
}
dump_(&ar[0], 256, 0x8000);
#endif
void end() {
proto_.end();
}
};
static bool erase_(r8c_prog& prog, utils::motsx_io& motf)
{
std::cout << "Erase: ";
bool noerr = true;
for(uint32_t a = motf.get_min(); a <= motf.get_max(); a += 256) {
const std::vector<uint8_t>& mem = motf.get_memory();
bool erase = false;
for(int i = 0; i < 256; ++i) {
if(mem[a + i] != 0xff) {
erase = true;
break;
}
}
if(erase) {
if(!prog.erase(a)) {
noerr = false;
break;
}
std::cout << '#' << std::flush;
}
}
std::cout << std::endl;
return noerr;
}
static bool write_(r8c_prog& prog, utils::motsx_io& motf)
{
bool noerr = true;
std::cout << "Write: ";
for(uint32_t a = motf.get_min(); a <= motf.get_max(); a += 256) {
const std::vector<uint8_t>& mem = motf.get_memory();
bool skip = true;
for(int i = 0; i < 256; ++i) {
if(mem[a + i] != 0xff) {
skip = false;
break;
}
}
if(skip) continue;
if(!prog.write(a, &mem[a])) {
noerr = false;
break;
}
std::cout << '#' << std::flush;
}
std::cout << std::endl;
return noerr;
}
static bool verify_(r8c_prog& prog, utils::motsx_io& motf)
{
bool noerr = true;
std::cout << "Verify: ";
for(uint32_t a = motf.get_min(); a <= motf.get_max(); a += 256) {
const std::vector<uint8_t>& mem = motf.get_memory();
bool skip = true;
for(int i = 0; i < 256; ++i) {
if(mem[a + i] != 0xff) {
skip = false;
break;
}
}
if(skip) continue;
if(!prog.verify(a, &mem[a])) {
noerr = false;
break;
}
std::cout << '#' << std::flush;
}
std::cout << std::endl;
return noerr;
}
struct options {
bool verbose;
std::string inp_file;
std::string device;
bool dv;
uint32_t baud_rate;
bool br;
std::string dev_path;
bool dp;
bool erase;
bool write;
bool verify;
options() : verbose(false),
inp_file(),
device(), dv(false),
baud_rate(57600), br(false),
dev_path(), dp(false),
erase(false), write(false), verify(false) { }
void set_speed(const std::string& t) {
int val;
if(utils::string_to_int(t, val)) {
baud_rate = val;
} else {
std::cerr << "Options error: baud rate speed: " << t << std::endl;
}
}
void set_str(const std::string& t) {
if(br) {
set_speed(t);
br = false;
} else if(dv) {
device = t;
dv = false;
} else if(dp) {
dev_path = t;
dp = false;
} else {
inp_file = t;
}
}
};
static void title_(const std::string& cmd)
{
using namespace std;
std::string c = utils::get_file_base(cmd);
cout << "Renesas R8C Series Programmer Version" << version_ << endl;
cout << "Copyright (C) 2015, Hiramatsu Kunihito ([email protected])" << endl;
cout << "usage:" << endl;
cout << c << "[options] [mot/id/conf file] ..." << endl;
cout << endl;
cout << "Options :" << endl;
cout << "-d, --device=DEVICE\t\tSpecify device name" << endl;
cout << "-e, --erase\t\t\tPerform a device erase to a minimum" << endl;
// cout << "-E, --erase-all, --erase-chip\tPerform rom and data flash erase" << endl;
// cout << " --erase-rom\t\t\tPerform rom flash erase" << endl;
// cout << " --erase-data\t\tPerform data flash erase" << endl;
// cout << "-i, --id=xx:xx:xx:xx:xx:xx:xx\tSpecify protect ID" << endl;
cout << "-p, --programmer=PROGRAMMER\tSpecify programmer name" << endl;
cout << "-P, --port=PORT\t\t\tSpecify serial port" << endl;
// cout << "-q\t\t\t\tQuell progress output" << endl;
// cout << "-r, --read\t\t\tPerform data read" << endl;
cout << "-s, --speed=SPEED\t\tSpecify serial speed" << endl;
cout << "-v, --verify\t\t\tPerform data verify" << endl;
// cout << " --device-list\t\tDisplay device list" << endl;
// cout << " --programmer-list\t\tDisplay programmer list" << endl;
cout << "-V, --verbose\t\t\tVerbose output" << endl;
cout << "-w, --write\t\t\tPerform data write" << endl;
// cout << "-h, --help\t\t\tDisplay this" << endl;
// cout << " --version\t\t\tDisplay version No." << endl;
}
int main(int argc, char* argv[])
{
if(argc == 1) {
title_(argv[0]);
return 0;
}
options opt;
for(int i = 1; i < argc; ++i) {
const std::string p = argv[i];
if(p[0] == '-') {
if(p == "-V" || p == "-verbose") opt.verbose = true;
else if(p == "-s") opt.br = true;
else if(p == "-d") opt.dv = true;
else if(p == "-P") opt.dp = true;
else if(p == "-e" || p == "--erase") opt.erase = true;
else if(p == "-w" || p == "--write") opt.write = true;
else if(p == "-v" || p == "--verify") opt.verify = true;
} else {
opt.set_str(p);
}
}
utils::motsx_io motf;
if(!motf.load(opt.inp_file)) {
std::cerr << "Can't load input file: '" << opt.inp_file << "'" << std::endl;
return -1;
}
if(opt.verbose) {
std::cout << "Load data: ";
std::cout << std::hex << std::uppercase << std::setfill('0')
<< std::setw(6) << static_cast<int>(motf.get_min()) << " to "
<< std::setw(6) << static_cast<int>(motf.get_max())
<< std::dec << std::endl;
}
// test
if(opt.dev_path.empty()) {
opt.dev_path = "/dev/tty.usbserial-A600e0xq";
}
r8c_prog prog(opt.verbose);
if(!prog.start(opt.dev_path, opt.baud_rate)) {
return -1;
}
if(opt.erase) {
if(!erase_(prog, motf)) {
return -1;
}
}
if(opt.write) {
if(!write_(prog, motf)) {
return -1;
}
}
if(opt.verify) {
if(!verify_(prog, motf)) {
return -1;
}
}
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperTopic.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include <functional>
#include <boost/test/unit_test.hpp>
#include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
BOOST_AUTO_TEST_SUITE(whisper)
BOOST_AUTO_TEST_CASE(topic)
{
cnote << "Testing Whisper...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
bool started = false;
unsigned result = 0;
std::thread listener([&]()
{
setThreadName("other");
Host ph("Test", NetworkPreferences(50303, "", false, true));
auto wh = ph.registerCapability(new WhisperHost());
ph.start();
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("odd"));
started = true;
for (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
result += last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!started)
this_thread::sleep_for(chrono::milliseconds(50));
Host ph("Test", NetworkPreferences(50300, "", false, true));
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50303);
KeyPair us = KeyPair::create();
for (int i = 0; i < 10; ++i)
{
wh->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
this_thread::sleep_for(chrono::milliseconds(250));
}
listener.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);
}
BOOST_AUTO_TEST_CASE(forwarding)
{
cnote << "Testing Whisper forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
unsigned result = 0;
bool done = false;
bool startedListener = false;
std::thread listener([&]()
{
setThreadName("listener");
// Host must be configured not to share peers.
Host ph("Listner", NetworkPreferences(50303, "", false, true));
ph.setIdealPeerCount(0);
auto wh = ph.registerCapability(new WhisperHost());
ph.start();
startedListener = true;
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
while (!startedListener)
this_thread::sleep_for(chrono::milliseconds(50));
// Host must be configured not to share peers.
Host ph("Forwarder", NetworkPreferences(50305, "", false, true));
ph.setIdealPeerCount(0);
auto wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50303);
startedForwarder = true;
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(50));
Host ph("Sender", NetworkPreferences(50300, "", false, true));
ph.setIdealPeerCount(0);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50305);
KeyPair us = KeyPair::create();
wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
listener.join();
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_CASE(asyncforwarding)
{
cnote << "Testing Whisper async forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 2;
unsigned result = 0;
bool done = false;
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
// Host must be configured not to share peers.
Host ph("Forwarder", NetworkPreferences(50305, "", false, true));
ph.setIdealPeerCount(0);
auto wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50303);
startedForwarder = true;
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(50));
{
Host ph("Sender", NetworkPreferences(50300, "", false, true));
ph.setIdealPeerCount(0);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50305);
KeyPair us = KeyPair::create();
wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
}
{
Host ph("Listener", NetworkPreferences(50300, "", false, true));
ph.setIdealPeerCount(0);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50305);
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
}
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Don't count same messages twice.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperTopic.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include <functional>
#include <boost/test/unit_test.hpp>
#include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
BOOST_AUTO_TEST_SUITE(whisper)
BOOST_AUTO_TEST_CASE(topic)
{
cnote << "Testing Whisper...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
bool started = false;
unsigned result = 0;
std::thread listener([&]()
{
setThreadName("other");
Host ph("Test", NetworkPreferences(50303, "", false, true));
auto wh = ph.registerCapability(new WhisperHost());
ph.start();
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("odd"));
started = true;
set<unsigned> received;
for (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
last = RLP(msg.payload()).toInt<unsigned>();
if (received.count(last))
continue;
received.insert(last);
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
result += last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!started)
this_thread::sleep_for(chrono::milliseconds(50));
Host ph("Test", NetworkPreferences(50300, "", false, true));
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50303);
KeyPair us = KeyPair::create();
for (int i = 0; i < 10; ++i)
{
wh->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
this_thread::sleep_for(chrono::milliseconds(250));
}
listener.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);
}
BOOST_AUTO_TEST_CASE(forwarding)
{
cnote << "Testing Whisper forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
unsigned result = 0;
bool done = false;
bool startedListener = false;
std::thread listener([&]()
{
setThreadName("listener");
// Host must be configured not to share peers.
Host ph("Listner", NetworkPreferences(50303, "", false, true));
ph.setIdealPeerCount(0);
auto wh = ph.registerCapability(new WhisperHost());
ph.start();
startedListener = true;
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
while (!startedListener)
this_thread::sleep_for(chrono::milliseconds(50));
// Host must be configured not to share peers.
Host ph("Forwarder", NetworkPreferences(50305, "", false, true));
ph.setIdealPeerCount(0);
auto wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50303);
startedForwarder = true;
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(50));
Host ph("Sender", NetworkPreferences(50300, "", false, true));
ph.setIdealPeerCount(0);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50305);
KeyPair us = KeyPair::create();
wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
listener.join();
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_CASE(asyncforwarding)
{
cnote << "Testing Whisper async forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 2;
unsigned result = 0;
bool done = false;
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
// Host must be configured not to share peers.
Host ph("Forwarder", NetworkPreferences(50305, "", false, true));
ph.setIdealPeerCount(0);
auto wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50303);
startedForwarder = true;
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(50));
{
Host ph("Sender", NetworkPreferences(50300, "", false, true));
ph.setIdealPeerCount(0);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50305);
KeyPair us = KeyPair::create();
wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
}
{
Host ph("Listener", NetworkPreferences(50300, "", false, true));
ph.setIdealPeerCount(0);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
this_thread::sleep_for(chrono::milliseconds(500));
ph.start();
this_thread::sleep_for(chrono::milliseconds(500));
ph.connect("127.0.0.1", 50305);
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
}
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#include "bytes_ostream.hh"
#include "query-request.hh"
#include "md5_hasher.hh"
#include <experimental/optional>
#include <seastar/util/bool_class.hh>
namespace stdx = std::experimental;
namespace query {
// result_memory_limiter, result_memory_accounter and result_memory_tracker
// form an infrastructure for limiting size of query results.
//
// result_memory_limiter is a shard-local object which ensures that all results
// combined do not use more than 10% of the shard memory.
//
// result_memory_accounter is used by result producers, updates the shard-local
// limits as well as keeps track of the individual maximum result size limit
// which is 1 MB.
//
// result_memory_tracker is just an object that makes sure the
// result_memory_limiter is notified when memory is released (but not sooner).
class result_memory_accounter;
class result_memory_limiter {
const size_t _maximum_total_result_memory;
semaphore _memory_limiter;
public:
static constexpr size_t minimum_result_size = 4 * 1024;
static constexpr size_t maximum_result_size = 1 * 1024 * 1024;
public:
result_memory_limiter()
: _maximum_total_result_memory(memory::stats().total_memory() / 10)
, _memory_limiter(_maximum_total_result_memory)
{ }
result_memory_limiter(const result_memory_limiter&) = delete;
result_memory_limiter(result_memory_limiter&&) = delete;
ssize_t total_used_memory() const {
return _maximum_total_result_memory - _memory_limiter.available_units();
}
// Reserves minimum_result_size and creates new memory accounter for
// mutation query. Uses the specified maximum result size and may be
// stopped before reaching it due to memory pressure on shard.
future<result_memory_accounter> new_mutation_read(size_t max_result_size);
// Reserves minimum_result_size and creates new memory accounter for
// data query. Uses the specified maximum result size, result will *not*
// be stopped due to on shard memory pressure in order to avoid digest
// mismatches.
future<result_memory_accounter> new_data_read(size_t max_result_size);
// Creates a memory accounter for digest reads. Such accounter doesn't
// contribute to the shard memory usage, but still stops producing the
// result after individual limit has been reached.
future<result_memory_accounter> new_digest_read(size_t max_result_size);
// Checks whether the result can grow any more, takes into account only
// the per shard limit.
stop_iteration check() const {
return stop_iteration(_memory_limiter.current() <= 0);
}
// Consumes n bytes from memory limiter and checks whether the result
// can grow any more (considering just the per-shard limit).
stop_iteration update_and_check(size_t n) {
_memory_limiter.consume(n);
return check();
}
void release(size_t n) noexcept {
_memory_limiter.signal(n);
}
semaphore& sem() noexcept { return _memory_limiter; }
};
class result_memory_tracker {
semaphore_units<> _units;
size_t _used_memory;
private:
static thread_local semaphore _dummy;
public:
result_memory_tracker() noexcept : _units(_dummy, 0), _used_memory(0) { }
result_memory_tracker(semaphore& sem, size_t blocked, size_t used) noexcept
: _units(sem, blocked), _used_memory(used) { }
size_t used_memory() const { return _used_memory; }
};
class result_memory_accounter {
result_memory_limiter* _limiter = nullptr;
size_t _blocked_bytes = 0;
size_t _used_memory = 0;
size_t _total_used_memory = 0;
size_t _maximum_result_size;
stop_iteration _stop_on_global_limit;
private:
// Mutation query accounter. Uses provided individual result size limit and
// will stop when shard memory pressure grows too high.
struct mutation_query_tag { };
explicit result_memory_accounter(mutation_query_tag, result_memory_limiter& limiter, size_t max_size) noexcept
: _limiter(&limiter)
, _blocked_bytes(result_memory_limiter::minimum_result_size)
, _maximum_result_size(max_size)
, _stop_on_global_limit(true)
{ }
// Data query accounter. Uses provided individual result size limit and
// will *not* stop even though shard memory pressure grows too high.
struct data_query_tag { };
explicit result_memory_accounter(data_query_tag, result_memory_limiter& limiter, size_t max_size) noexcept
: _limiter(&limiter)
, _blocked_bytes(result_memory_limiter::minimum_result_size)
, _maximum_result_size(max_size)
{ }
// Digest query accounter. Uses provided individual result size limit and
// will *not* stop even though shard memory pressure grows too high. This
// accounter does not contribute to the shard memory limits.
struct digest_query_tag { };
explicit result_memory_accounter(digest_query_tag, result_memory_limiter&, size_t max_size) noexcept
: _blocked_bytes(0)
, _maximum_result_size(max_size)
{ }
friend class result_memory_limiter;
public:
// State of a accounter on another shard. Used to pass information about
// the size of the result so far in range queries.
class foreign_state {
size_t _used_memory;
public:
explicit foreign_state(size_t used_mem) : _used_memory(used_mem) { }
size_t used_memory() const { return _used_memory; }
};
public:
result_memory_accounter() = default;
// This constructor is used in cases when a result is produced on multiple
// shards (range queries). foreign_accounter is an accounter that, possibly,
// exist on the other shard and is used for merging the result. This
// accouter will learn how big the total result alread is and limit the
// part produced on this shard so that after merging the final result
// does not exceed the individual limit.
result_memory_accounter(result_memory_limiter& limiter, foreign_state fstate) noexcept
: _limiter(&limiter)
, _total_used_memory(fstate.used_memory())
{ }
result_memory_accounter(result_memory_accounter&& other) noexcept
: _limiter(std::exchange(other._limiter, nullptr))
, _blocked_bytes(other._blocked_bytes)
, _used_memory(other._used_memory)
, _total_used_memory(other._total_used_memory)
, _maximum_result_size(other._maximum_result_size)
, _stop_on_global_limit(other._stop_on_global_limit)
{ }
result_memory_accounter& operator=(result_memory_accounter&& other) noexcept {
if (this != &other) {
this->~result_memory_accounter();
new (this) result_memory_accounter(std::move(other));
}
return *this;
}
~result_memory_accounter() {
if (_limiter) {
_limiter->release(_blocked_bytes);
}
}
size_t used_memory() const { return _used_memory; }
foreign_state state_for_another_shard() {
return foreign_state(_used_memory);
}
// Consume n more bytes for the result. Returns stop_iteration::yes if
// the result cannot grow any more (taking into account both individual
// and per-shard limits).
stop_iteration update_and_check(size_t n) {
_used_memory += n;
_total_used_memory += n;
auto stop = stop_iteration(_total_used_memory > _maximum_result_size);
if (_limiter && _used_memory > _blocked_bytes) {
auto to_block = std::min(_used_memory - _blocked_bytes, n);
_blocked_bytes += to_block;
stop = (_limiter->update_and_check(to_block) && _stop_on_global_limit) || stop;
}
return stop;
}
// Checks whether the result can grow any more.
stop_iteration check() const {
stop_iteration stop { _total_used_memory > result_memory_limiter::maximum_result_size };
if (!stop && _used_memory >= _blocked_bytes && _limiter) {
return _limiter->check() && _stop_on_global_limit;
}
return stop;
}
// Consume n more bytes for the result.
void update(size_t n) {
update_and_check(n);
}
result_memory_tracker done() && {
if (!_limiter) {
return { };
}
auto& sem = std::exchange(_limiter, nullptr)->sem();
return result_memory_tracker(sem, _blocked_bytes, _used_memory);
}
};
inline future<result_memory_accounter> result_memory_limiter::new_mutation_read(size_t max_size) {
return _memory_limiter.wait(minimum_result_size).then([this, max_size] {
return result_memory_accounter(result_memory_accounter::mutation_query_tag(), *this, max_size);
});
}
inline future<result_memory_accounter> result_memory_limiter::new_data_read(size_t max_size) {
return _memory_limiter.wait(minimum_result_size).then([this, max_size] {
return result_memory_accounter(result_memory_accounter::data_query_tag(), *this, max_size);
});
}
inline future<result_memory_accounter> result_memory_limiter::new_digest_read(size_t max_size) {
return make_ready_future<result_memory_accounter>(result_memory_accounter(result_memory_accounter::digest_query_tag(), *this, max_size));
}
enum class result_request {
only_result,
only_digest,
result_and_digest,
};
class result_digest {
public:
static_assert(16 == CryptoPP::Weak::MD5::DIGESTSIZE, "MD5 digest size is all wrong");
using type = std::array<uint8_t, 16>;
private:
type _digest;
public:
result_digest() = default;
result_digest(type&& digest) : _digest(std::move(digest)) {}
const type& get() const { return _digest; }
bool operator==(const result_digest& rh) const {
return _digest == rh._digest;
}
bool operator!=(const result_digest& rh) const {
return _digest != rh._digest;
}
};
//
// The query results are stored in a serialized form. This is in order to
// address the following problems, which a structured format has:
//
// - high level of indirection (vector of vectors of vectors of blobs), which
// is not CPU cache friendly
//
// - high allocation rate due to fine-grained object structure
//
// On replica side, the query results are probably going to be serialized in
// the transport layer anyway, so serializing the results up-front doesn't add
// net work. There is no processing of the query results on replica other than
// concatenation in case of range queries and checksum calculation. If query
// results are collected in serialized form from different cores, we can
// concatenate them without copying by simply appending the fragments into the
// packet.
//
// On coordinator side, the query results would have to be parsed from the
// transport layer buffers anyway, so the fact that iterators parse it also
// doesn't add net work, but again saves allocations and copying. The CQL
// server doesn't need complex data structures to process the results, it just
// goes over it linearly consuming it.
//
// The coordinator side could be optimized even further for CQL queries which
// do not need processing (eg. select * from cf where ...). We could make the
// replica send the query results in the format which is expected by the CQL
// binary protocol client. So in the typical case the coordinator would just
// pass the data using zero-copy to the client, prepending a header.
//
// Users which need more complex structure of query results can convert this
// to query::result_set.
//
// Related headers:
// - query-result-reader.hh
// - query-result-writer.hh
struct short_read_tag { };
using short_read = bool_class<short_read_tag>;
class result {
bytes_ostream _w;
stdx::optional<result_digest> _digest;
stdx::optional<uint32_t> _row_count;
api::timestamp_type _last_modified = api::missing_timestamp;
short_read _short_read;
query::result_memory_tracker _memory_tracker;
stdx::optional<uint32_t> _partition_count;
public:
class builder;
class partition_writer;
friend class result_merger;
result();
result(bytes_ostream&& w, short_read sr, stdx::optional<uint32_t> c = { }, stdx::optional<uint32_t> pc = { },
result_memory_tracker memory_tracker = { })
: _w(std::move(w))
, _row_count(c)
, _short_read(sr)
, _memory_tracker(std::move(_memory_tracker))
, _partition_count(pc)
{
w.reduce_chunk_count();
}
result(bytes_ostream&& w, stdx::optional<result_digest> d, api::timestamp_type last_modified,
short_read sr, stdx::optional<uint32_t> c = { }, stdx::optional<uint32_t> pc = { }, result_memory_tracker memory_tracker = { })
: _w(std::move(w))
, _digest(d)
, _row_count(c)
, _last_modified(last_modified)
, _short_read(sr)
, _memory_tracker(std::move(memory_tracker))
, _partition_count(pc)
{
w.reduce_chunk_count();
}
result(result&&) = default;
result(const result&) = default;
result& operator=(result&&) = default;
result& operator=(const result&) = default;
const bytes_ostream& buf() const {
return _w;
}
const stdx::optional<result_digest>& digest() const {
return _digest;
}
const stdx::optional<uint32_t>& row_count() const {
return _row_count;
}
const api::timestamp_type last_modified() const {
return _last_modified;
}
short_read is_short_read() const {
return _short_read;
}
const stdx::optional<uint32_t>& partition_count() const {
return _partition_count;
}
void calculate_counts(const query::partition_slice&);
struct printer {
schema_ptr s;
const query::partition_slice& slice;
const query::result& res;
};
sstring pretty_print(schema_ptr, const query::partition_slice&) const;
printer pretty_printer(schema_ptr, const query::partition_slice&) const;
};
std::ostream& operator<<(std::ostream& os, const query::result::printer&);
}
<commit_msg>result_memory_tracker: fix too-short short reads<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#include "bytes_ostream.hh"
#include "query-request.hh"
#include "md5_hasher.hh"
#include <experimental/optional>
#include <seastar/util/bool_class.hh>
namespace stdx = std::experimental;
namespace query {
// result_memory_limiter, result_memory_accounter and result_memory_tracker
// form an infrastructure for limiting size of query results.
//
// result_memory_limiter is a shard-local object which ensures that all results
// combined do not use more than 10% of the shard memory.
//
// result_memory_accounter is used by result producers, updates the shard-local
// limits as well as keeps track of the individual maximum result size limit
// which is 1 MB.
//
// result_memory_tracker is just an object that makes sure the
// result_memory_limiter is notified when memory is released (but not sooner).
class result_memory_accounter;
class result_memory_limiter {
const size_t _maximum_total_result_memory;
semaphore _memory_limiter;
public:
static constexpr size_t minimum_result_size = 4 * 1024;
static constexpr size_t maximum_result_size = 1 * 1024 * 1024;
public:
result_memory_limiter()
: _maximum_total_result_memory(memory::stats().total_memory() / 10)
, _memory_limiter(_maximum_total_result_memory)
{ }
result_memory_limiter(const result_memory_limiter&) = delete;
result_memory_limiter(result_memory_limiter&&) = delete;
ssize_t total_used_memory() const {
return _maximum_total_result_memory - _memory_limiter.available_units();
}
// Reserves minimum_result_size and creates new memory accounter for
// mutation query. Uses the specified maximum result size and may be
// stopped before reaching it due to memory pressure on shard.
future<result_memory_accounter> new_mutation_read(size_t max_result_size);
// Reserves minimum_result_size and creates new memory accounter for
// data query. Uses the specified maximum result size, result will *not*
// be stopped due to on shard memory pressure in order to avoid digest
// mismatches.
future<result_memory_accounter> new_data_read(size_t max_result_size);
// Creates a memory accounter for digest reads. Such accounter doesn't
// contribute to the shard memory usage, but still stops producing the
// result after individual limit has been reached.
future<result_memory_accounter> new_digest_read(size_t max_result_size);
// Checks whether the result can grow any more, takes into account only
// the per shard limit.
stop_iteration check() const {
return stop_iteration(_memory_limiter.current() <= 0);
}
// Consumes n bytes from memory limiter and checks whether the result
// can grow any more (considering just the per-shard limit).
stop_iteration update_and_check(size_t n) {
_memory_limiter.consume(n);
return check();
}
void release(size_t n) noexcept {
_memory_limiter.signal(n);
}
semaphore& sem() noexcept { return _memory_limiter; }
};
class result_memory_tracker {
semaphore_units<> _units;
size_t _used_memory;
private:
static thread_local semaphore _dummy;
public:
result_memory_tracker() noexcept : _units(_dummy, 0), _used_memory(0) { }
result_memory_tracker(semaphore& sem, size_t blocked, size_t used) noexcept
: _units(sem, blocked), _used_memory(used) { }
size_t used_memory() const { return _used_memory; }
};
class result_memory_accounter {
result_memory_limiter* _limiter = nullptr;
size_t _blocked_bytes = 0;
size_t _used_memory = 0;
size_t _total_used_memory = 0;
size_t _maximum_result_size = 0;
stop_iteration _stop_on_global_limit;
private:
// Mutation query accounter. Uses provided individual result size limit and
// will stop when shard memory pressure grows too high.
struct mutation_query_tag { };
explicit result_memory_accounter(mutation_query_tag, result_memory_limiter& limiter, size_t max_size) noexcept
: _limiter(&limiter)
, _blocked_bytes(result_memory_limiter::minimum_result_size)
, _maximum_result_size(max_size)
, _stop_on_global_limit(true)
{ }
// Data query accounter. Uses provided individual result size limit and
// will *not* stop even though shard memory pressure grows too high.
struct data_query_tag { };
explicit result_memory_accounter(data_query_tag, result_memory_limiter& limiter, size_t max_size) noexcept
: _limiter(&limiter)
, _blocked_bytes(result_memory_limiter::minimum_result_size)
, _maximum_result_size(max_size)
{ }
// Digest query accounter. Uses provided individual result size limit and
// will *not* stop even though shard memory pressure grows too high. This
// accounter does not contribute to the shard memory limits.
struct digest_query_tag { };
explicit result_memory_accounter(digest_query_tag, result_memory_limiter&, size_t max_size) noexcept
: _blocked_bytes(0)
, _maximum_result_size(max_size)
{ }
friend class result_memory_limiter;
public:
// State of a accounter on another shard. Used to pass information about
// the size of the result so far in range queries.
class foreign_state {
size_t _used_memory;
size_t _max_result_size;
public:
foreign_state(size_t used_mem, size_t max_result_size)
: _used_memory(used_mem), _max_result_size(max_result_size) { }
size_t used_memory() const { return _used_memory; }
size_t max_result_size() const { return _max_result_size; }
};
public:
result_memory_accounter() = default;
// This constructor is used in cases when a result is produced on multiple
// shards (range queries). foreign_accounter is an accounter that, possibly,
// exist on the other shard and is used for merging the result. This
// accouter will learn how big the total result alread is and limit the
// part produced on this shard so that after merging the final result
// does not exceed the individual limit.
result_memory_accounter(result_memory_limiter& limiter, foreign_state fstate) noexcept
: _limiter(&limiter)
, _total_used_memory(fstate.used_memory())
, _maximum_result_size(fstate.max_result_size())
{ }
result_memory_accounter(result_memory_accounter&& other) noexcept
: _limiter(std::exchange(other._limiter, nullptr))
, _blocked_bytes(other._blocked_bytes)
, _used_memory(other._used_memory)
, _total_used_memory(other._total_used_memory)
, _maximum_result_size(other._maximum_result_size)
, _stop_on_global_limit(other._stop_on_global_limit)
{ }
result_memory_accounter& operator=(result_memory_accounter&& other) noexcept {
if (this != &other) {
this->~result_memory_accounter();
new (this) result_memory_accounter(std::move(other));
}
return *this;
}
~result_memory_accounter() {
if (_limiter) {
_limiter->release(_blocked_bytes);
}
}
size_t used_memory() const { return _used_memory; }
foreign_state state_for_another_shard() {
return foreign_state(_used_memory, _maximum_result_size);
}
// Consume n more bytes for the result. Returns stop_iteration::yes if
// the result cannot grow any more (taking into account both individual
// and per-shard limits).
stop_iteration update_and_check(size_t n) {
_used_memory += n;
_total_used_memory += n;
auto stop = stop_iteration(_total_used_memory > _maximum_result_size);
if (_limiter && _used_memory > _blocked_bytes) {
auto to_block = std::min(_used_memory - _blocked_bytes, n);
_blocked_bytes += to_block;
stop = (_limiter->update_and_check(to_block) && _stop_on_global_limit) || stop;
}
return stop;
}
// Checks whether the result can grow any more.
stop_iteration check() const {
stop_iteration stop { _total_used_memory > result_memory_limiter::maximum_result_size };
if (!stop && _used_memory >= _blocked_bytes && _limiter) {
return _limiter->check() && _stop_on_global_limit;
}
return stop;
}
// Consume n more bytes for the result.
void update(size_t n) {
update_and_check(n);
}
result_memory_tracker done() && {
if (!_limiter) {
return { };
}
auto& sem = std::exchange(_limiter, nullptr)->sem();
return result_memory_tracker(sem, _blocked_bytes, _used_memory);
}
};
inline future<result_memory_accounter> result_memory_limiter::new_mutation_read(size_t max_size) {
return _memory_limiter.wait(minimum_result_size).then([this, max_size] {
return result_memory_accounter(result_memory_accounter::mutation_query_tag(), *this, max_size);
});
}
inline future<result_memory_accounter> result_memory_limiter::new_data_read(size_t max_size) {
return _memory_limiter.wait(minimum_result_size).then([this, max_size] {
return result_memory_accounter(result_memory_accounter::data_query_tag(), *this, max_size);
});
}
inline future<result_memory_accounter> result_memory_limiter::new_digest_read(size_t max_size) {
return make_ready_future<result_memory_accounter>(result_memory_accounter(result_memory_accounter::digest_query_tag(), *this, max_size));
}
enum class result_request {
only_result,
only_digest,
result_and_digest,
};
class result_digest {
public:
static_assert(16 == CryptoPP::Weak::MD5::DIGESTSIZE, "MD5 digest size is all wrong");
using type = std::array<uint8_t, 16>;
private:
type _digest;
public:
result_digest() = default;
result_digest(type&& digest) : _digest(std::move(digest)) {}
const type& get() const { return _digest; }
bool operator==(const result_digest& rh) const {
return _digest == rh._digest;
}
bool operator!=(const result_digest& rh) const {
return _digest != rh._digest;
}
};
//
// The query results are stored in a serialized form. This is in order to
// address the following problems, which a structured format has:
//
// - high level of indirection (vector of vectors of vectors of blobs), which
// is not CPU cache friendly
//
// - high allocation rate due to fine-grained object structure
//
// On replica side, the query results are probably going to be serialized in
// the transport layer anyway, so serializing the results up-front doesn't add
// net work. There is no processing of the query results on replica other than
// concatenation in case of range queries and checksum calculation. If query
// results are collected in serialized form from different cores, we can
// concatenate them without copying by simply appending the fragments into the
// packet.
//
// On coordinator side, the query results would have to be parsed from the
// transport layer buffers anyway, so the fact that iterators parse it also
// doesn't add net work, but again saves allocations and copying. The CQL
// server doesn't need complex data structures to process the results, it just
// goes over it linearly consuming it.
//
// The coordinator side could be optimized even further for CQL queries which
// do not need processing (eg. select * from cf where ...). We could make the
// replica send the query results in the format which is expected by the CQL
// binary protocol client. So in the typical case the coordinator would just
// pass the data using zero-copy to the client, prepending a header.
//
// Users which need more complex structure of query results can convert this
// to query::result_set.
//
// Related headers:
// - query-result-reader.hh
// - query-result-writer.hh
struct short_read_tag { };
using short_read = bool_class<short_read_tag>;
class result {
bytes_ostream _w;
stdx::optional<result_digest> _digest;
stdx::optional<uint32_t> _row_count;
api::timestamp_type _last_modified = api::missing_timestamp;
short_read _short_read;
query::result_memory_tracker _memory_tracker;
stdx::optional<uint32_t> _partition_count;
public:
class builder;
class partition_writer;
friend class result_merger;
result();
result(bytes_ostream&& w, short_read sr, stdx::optional<uint32_t> c = { }, stdx::optional<uint32_t> pc = { },
result_memory_tracker memory_tracker = { })
: _w(std::move(w))
, _row_count(c)
, _short_read(sr)
, _memory_tracker(std::move(_memory_tracker))
, _partition_count(pc)
{
w.reduce_chunk_count();
}
result(bytes_ostream&& w, stdx::optional<result_digest> d, api::timestamp_type last_modified,
short_read sr, stdx::optional<uint32_t> c = { }, stdx::optional<uint32_t> pc = { }, result_memory_tracker memory_tracker = { })
: _w(std::move(w))
, _digest(d)
, _row_count(c)
, _last_modified(last_modified)
, _short_read(sr)
, _memory_tracker(std::move(memory_tracker))
, _partition_count(pc)
{
w.reduce_chunk_count();
}
result(result&&) = default;
result(const result&) = default;
result& operator=(result&&) = default;
result& operator=(const result&) = default;
const bytes_ostream& buf() const {
return _w;
}
const stdx::optional<result_digest>& digest() const {
return _digest;
}
const stdx::optional<uint32_t>& row_count() const {
return _row_count;
}
const api::timestamp_type last_modified() const {
return _last_modified;
}
short_read is_short_read() const {
return _short_read;
}
const stdx::optional<uint32_t>& partition_count() const {
return _partition_count;
}
void calculate_counts(const query::partition_slice&);
struct printer {
schema_ptr s;
const query::partition_slice& slice;
const query::result& res;
};
sstring pretty_print(schema_ptr, const query::partition_slice&) const;
printer pretty_printer(schema_ptr, const query::partition_slice&) const;
};
std::ostream& operator<<(std::ostream& os, const query::result::printer&);
}
<|endoftext|> |
<commit_before>#ifndef EXAMPLES_MPI_DOMAIN_PARTITION_HPP
#define EXAMPLES_MPI_DOMAIN_PARTITION_HPP
#include <vector>
#include <utility>
#include <boost/foreach.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/adapted/boost_array.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/index/rtree.hpp>
BOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)
template <int NDIM>
class domain_partition {
public:
typedef boost::array<ptrdiff_t, NDIM> point;
typedef boost::geometry::model::box<point> box;
typedef std::pair<box, int> process;
domain_partition(point lo, point hi, int num_processes) {
split(box(lo, hi), num_processes);
for(int i = 0; i < num_processes; ++i)
rtree.insert( std::make_pair(subdomains[i], i) );
}
std::pair<int, ptrdiff_t> index(point p) const {
namespace bgi = boost::geometry::index;
BOOST_FOREACH(const process &v, rtree | bgi::adaptors::queried(bgi::intersects(p)) )
{
return std::make_pair(v.second, local_index(v.first, p));
}
// Unreachable:
return std::make_pair(0, 0l);
}
size_t size(size_t process) const {
point lo = subdomains[process].min_corner();
point hi = subdomains[process].max_corner();
size_t v = 1;
for(int i = 0; i < NDIM; ++i)
v *= hi[i] - lo[i] + 1;
return v;
}
const box& domain(size_t process) const {
return subdomains[process];
}
private:
std::vector<box> subdomains;
boost::geometry::index::rtree<
process,
boost::geometry::index::quadratic<16>
> rtree;
static ptrdiff_t local_index(box domain, point p) {
point lo = domain.min_corner();
point hi = domain.max_corner();
ptrdiff_t stride = 1, idx = 0;
for(int i = 0; i < NDIM; ++i) {
idx += (p[i] - lo[i]) * stride;
stride *= hi[i] - lo[i] + 1;
}
return idx;
}
void split(box domain, int np) {
if (np == 1) {
subdomains.push_back(domain);
return;
}
point lo = domain.min_corner();
point hi = domain.max_corner();
// Get longest dimension of the domain
int wd = 0;
for(int i = 1; i < NDIM; ++i)
if (hi[i] - lo[i] > hi[wd] - lo[wd]) wd = i;
ptrdiff_t mid = lo[wd] + (hi[wd] - lo[wd]) * (np / 2) / np;
box sd1 = domain;
box sd2 = domain;
sd1.max_corner()[wd] = mid;
sd2.min_corner()[wd] = mid + 1;
split(sd1, np / 2);
split(sd2, np - np / 2);
}
};
#endif
<commit_msg>Handle empty domains in domain_partition<commit_after>#ifndef EXAMPLES_MPI_DOMAIN_PARTITION_HPP
#define EXAMPLES_MPI_DOMAIN_PARTITION_HPP
#include <vector>
#include <utility>
#include <boost/foreach.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/adapted/boost_array.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/index/rtree.hpp>
BOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)
template <int NDIM>
class domain_partition {
public:
typedef boost::array<ptrdiff_t, NDIM> point;
typedef boost::geometry::model::box<point> box;
typedef std::pair<box, int> process;
domain_partition(point lo, point hi, int num_processes) {
split(box(lo, hi), num_processes);
for(int i = 0; i < num_processes; ++i)
rtree.insert( std::make_pair(subdomains[i], i) );
}
std::pair<int, ptrdiff_t> index(point p) const {
namespace bgi = boost::geometry::index;
BOOST_FOREACH(const process &v, rtree | bgi::adaptors::queried(bgi::intersects(p)) )
{
return std::make_pair(v.second, local_index(v.first, p));
}
// Unreachable:
return std::make_pair(0, 0l);
}
size_t size(size_t process) const {
if (process >= subdomains.size()) return 0;
point lo = subdomains[process].min_corner();
point hi = subdomains[process].max_corner();
size_t v = 1;
for(int i = 0; i < NDIM; ++i)
v *= hi[i] - lo[i] + 1;
return v;
}
box domain(size_t process) const {
if (process < subdomains.size())
return subdomains[process];
else {
boost::array<ptrdiff_t, 3> lo = { { 0, 0, 0} };
boost::array<ptrdiff_t, 3> hi = { {-1, -1, -1} };
return box(lo, hi);
}
}
private:
std::vector<box> subdomains;
boost::geometry::index::rtree<
process,
boost::geometry::index::quadratic<16>
> rtree;
static ptrdiff_t local_index(box domain, point p) {
point lo = domain.min_corner();
point hi = domain.max_corner();
ptrdiff_t stride = 1, idx = 0;
for(int i = 0; i < NDIM; ++i) {
idx += (p[i] - lo[i]) * stride;
stride *= hi[i] - lo[i] + 1;
}
return idx;
}
void split(box domain, int np) {
if (np == 1) {
subdomains.push_back(domain);
return;
}
point lo = domain.min_corner();
point hi = domain.max_corner();
// Get longest dimension of the domain
int wd = 0;
for(int i = 1; i < NDIM; ++i)
if (hi[i] - lo[i] > hi[wd] - lo[wd]) wd = i;
ptrdiff_t mid = lo[wd] + (hi[wd] - lo[wd]) * (np / 2) / np;
box sd1 = domain;
box sd2 = domain;
sd1.max_corner()[wd] = mid;
sd2.min_corner()[wd] = mid + 1;
split(sd1, np / 2);
split(sd2, np - np / 2);
}
};
#endif
<|endoftext|> |
<commit_before>/*===========================================
GRRLIB (GX Version)
Example code by Xane
This example shows a basic particle
engine creating a Smokebomb.
============================================*/
#include <grrlib.h>
#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <math.h>
#include <ogc/lwp_watchdog.h>
#include <vector>
// Include Graphics
#include "GFX/RGFX_Background.h"
#include "GFX/RGFX_Crosshair.h"
#include "GFX/RGFX_Smoke.h"
#include "GFX/RGFX_Font.h"
// Define Effects
#define EFFECT_SMOKEBOMB 1
// Random Number (0 - 1) in float
#define RANDOM ((((float)(rand() % 12))/12)-0.5)
using std::vector;
Mtx GXmodelView2D;
// Basic structure to hold particle data
typedef struct Particle {
u8 id;
float x, y;
float sx, sy;
u16 rot;
u8 frame, framecnt, framedelay;
u8 red, green, blue;
float scale, alpha;
float sscale, salpha;
float scolor;
GRRLIB_texImg *tex;
} Particle;
// Vector used as a container to iterate through all members of GRRLIB_texImg
static vector<GRRLIB_texImg *> TextureList;
static vector<Particle *> ParticleList;
static vector<Particle *> ParticleListTmp;
// Declare static functions
static void ExitGame();
static void createEffect( u8 id, int _x, int _y );
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue );
static bool updateParticle( Particle *part );
static u8 CalculateFrameRate();
static u8 ClampVar8 (f32 Value);
// Initialize general variables
extern GXRModeObj *rmode;
ir_t P1Mote;
short WinW;
short WinH;
int P1MX, P1MY;
// Prepare Graphics
GRRLIB_texImg *GFX_Background;
GRRLIB_texImg *GFX_Crosshair;
GRRLIB_texImg *GFX_Smoke;
GRRLIB_texImg *GFX_Font;
int main() {
u32 WPADKeyDown;
u8 FPS = 0;
u32 ParticleCnt = 0;
// Init GRRLIB & WiiUse
GRRLIB_Init();
WinW = rmode->fbWidth;
WinH = rmode->efbHeight;
WPAD_Init();
WPAD_SetIdleTimeout( 60*10 );
WPAD_SetDataFormat( WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR );
// Load textures
GFX_Background = GRRLIB_LoadTextureJPG(RGFX_Background);
GFX_Crosshair = GRRLIB_LoadTexturePNG(RGFX_Crosshair);
GFX_Smoke = GRRLIB_LoadTexturePNG(RGFX_Smoke);
GFX_Font = GRRLIB_LoadTexturePNG(RGFX_Font);
GRRLIB_InitTileSet( GFX_Font, 8, 16, 32 );
// Set handles
GRRLIB_SetMidHandle( GFX_Crosshair, true );
GRRLIB_SetMidHandle( GFX_Smoke, true );
// Feed the vector with the textures
TextureList.push_back( GFX_Background );
TextureList.push_back( GFX_Crosshair );
TextureList.push_back( GFX_Smoke );
TextureList.push_back( GFX_Font );
while (true) {
WPAD_ScanPads();
WPADKeyDown = WPAD_ButtonsDown(WPAD_CHAN_0);
WPAD_SetVRes(WPAD_CHAN_0, WinW, WinH);
WPAD_IR(WPAD_CHAN_0, &P1Mote);
// Resetting Vars
GRRLIB_SetBlend( GRRLIB_BLEND_ALPHA );
ParticleCnt = 0;
// WiiMote IR Viewport correction
P1MX = P1Mote.sx - 150;
P1MY = P1Mote.sy - 150;
// Drawing Background
GRRLIB_DrawImg( 0, 0, GFX_Background, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Add any pending objects into the main container
if (ParticleListTmp.size()) {
for(u32 i = 0; i<ParticleListTmp.size();i++) {
ParticleList.push_back(ParticleListTmp[i]);
}
ParticleListTmp.clear();
}
// Update and draw all particles
for (vector<Particle *>::iterator PartIter = ParticleList.begin(); PartIter != ParticleList.end();) {
if (updateParticle((*PartIter)) == true) {
GRRLIB_DrawImg( (*PartIter)->x, (*PartIter)->y, (*PartIter)->tex, (*PartIter)->rot, (*PartIter)->scale, (*PartIter)->scale, RGBA( (*PartIter)->red, (*PartIter)->green, (*PartIter)->blue, ClampVar8((*PartIter)->alpha*255) ) );
} else {
free( (*PartIter) );
ParticleList.erase(PartIter);
continue;
}
ParticleCnt += 1;
PartIter++;
}
// Draw Crosshair
GRRLIB_DrawImg( P1MX, P1MY, GFX_Crosshair, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Draw Text
GRRLIB_Rectangle( 28, 28, 280, 20, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 32, GFX_Font, 0xFFFFFFFF, 1, "Point your WiiMote on the screen." );
GRRLIB_Rectangle( 28, 48, 200, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 48, GFX_Font, 0xFFFFFFFF, 1, "Number of Particle: %d", ParticleCnt );
GRRLIB_Rectangle( 28, 64, 64, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 64, GFX_Font, 0xFFFFFFFF, 1, "FPS: %d", FPS );
// Renders the Scene
GRRLIB_Render();
FPS = CalculateFrameRate();
if (WPADKeyDown & WPAD_BUTTON_B) {
createEffect( EFFECT_SMOKEBOMB, P1MX, P1MY );
}
if (WPADKeyDown & WPAD_BUTTON_HOME) {
ExitGame();
}
}
ExitGame();
return 0;
}
static void createEffect( u8 id, int _x, int _y ) {
u8 _ColorAdd = 0;
switch (id) {
case EFFECT_SMOKEBOMB:
for (u8 i = 0; i < 5; i++) {
createParticle( 1, (_x + (RANDOM * 10)), (_y + (RANDOM * 10)), (1.4f+(RANDOM*0.20)), 1.0f, 64, 64, 64 );
}
for (u8 i = 0; i < 20; i++) {
createParticle( 3, (_x + (RANDOM * 50)), (_y + (RANDOM * 50)), 1.25f, 1.5f, 92, 92, 92 );
}
for (u8 i = 0; i < 5; i++) {
_ColorAdd = (RANDOM*75);
createParticle( 2, (_x + (RANDOM * 40)), (_y + (RANDOM * 40)), (1.0f+(RANDOM*0.20)), 1.0f, 128+_ColorAdd, 128+_ColorAdd, 128+_ColorAdd );
}
break;
}
}
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue ) {
Particle *part = (struct Particle *)calloc(1, sizeof(Particle));
part->id = _id;
part->x = _x;
part->y = _y;
part->rot = rand() % 360;
part->red = _red;
part->green = _green;
part->blue = _blue;
part->scale = _scale;
part->alpha = _alpha;
part->tex = GFX_Smoke;
part->sy = RANDOM;
part->sx = RANDOM;
part->sscale = 0.9985;
part->salpha = 0.985;
switch (part->id) {
case 1:
part->sy = RANDOM * 0.5;
part->sx = RANDOM * 0.5;
part->sscale = 0.999;
part->salpha = 0.992;
part->framedelay = 10;
part->framecnt = 2;
break;
case 2:
part->scolor = 0.98;
part->salpha = 0.95;
break;
case 3:
part->sy = (RANDOM * 8);
part->sx = (RANDOM * 8);
part->salpha = 0.85;
part->scolor = 0.95;
break;
}
ParticleListTmp.push_back( part );
}
static bool updateParticle( Particle *part ) {
if (part->alpha < 0.05) { part->alpha -= 0.001; }
if (part->alpha < 0.1) { part->alpha -= 0.001; }
part->x += part->sx;
part->y += part->sy;
part->scale *= part->sscale;
part->alpha *= part->salpha;
switch (part->id) {
case 1:
if (part->alpha < 0.25) { part->alpha -= 0.001; }
if (part->framecnt == 0) {
part->framecnt = 20;
part->red -= 1;
part->green -= 1;
part->blue -= 1;
}
part->framecnt -= 1;
break;
case 2:
case 3:
part->red *= part->scolor;
part->green *= part->scolor;
part->blue *= part->scolor;
break;
}
if ((part->scale < 0) || (part->alpha < 0)) { return false; }
return true;
}
static void ExitGame() {
// Free all memory used by textures.
for (vector<GRRLIB_texImg *>::iterator TexIter = TextureList.begin(); TexIter != TextureList.end(); TexIter++) {
free((*TexIter)->data);
free((*TexIter));
}
TextureList.clear();
// Deinitialize GRRLIB & Video
GRRLIB_Exit();
// Exit application
exit(0);
}
static u8 CalculateFrameRate() {
static u8 frameCount = 0;
static u32 lastTime;
static u8 FPS = 0;
u32 currentTime = ticks_to_millisecs(gettime());
frameCount++;
if(currentTime - lastTime > 1000) {
lastTime = currentTime;
FPS = frameCount;
frameCount = 0;
}
return FPS;
}
/**
* A helper function for the YCbCr -> RGB conversion.
* Clamps the given value into a range of 0 - 255 and thus preventing an overflow.
* @param Value The value to clamp. Using float to increase the precision. This makes a full spectrum (0 - 255) possible.
* @return Returns a clean, clamped unsigned char.
*/
static u8 ClampVar8 (f32 Value) {
Value = roundf(Value);
if (Value < 0) Value = 0;
else if (Value > 255) Value = 255;
return (u8)Value;
}
<commit_msg>Use C++11 / C++14 in Particle example<commit_after>/*===========================================
GRRLIB (GX Version)
Example code by Xane
This example shows a basic particle
engine creating a Smokebomb.
============================================*/
#include <grrlib.h>
#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <math.h>
#include <ogc/lwp_watchdog.h>
#include <vector>
// Include Graphics
#include "GFX/RGFX_Background.h"
#include "GFX/RGFX_Crosshair.h"
#include "GFX/RGFX_Smoke.h"
#include "GFX/RGFX_Font.h"
// Define Effects
#define EFFECT_SMOKEBOMB 1
// Random Number (0 - 1) in float
#define RANDOM ((((float)(rand() % 12))/12)-0.5)
Mtx GXmodelView2D;
// Basic structure to hold particle data
typedef struct Particle {
u8 id;
float x, y;
float sx, sy;
u16 rot;
u8 frame, framecnt, framedelay;
u8 red, green, blue;
float scale, alpha;
float sscale, salpha;
float scolor;
GRRLIB_texImg *tex;
} Particle;
// Vector used as a container to iterate through all members of GRRLIB_texImg
static std::vector<GRRLIB_texImg *> TextureList;
static std::vector<Particle *> ParticleList;
static std::vector<Particle *> ParticleListTmp;
// Declare static functions
static void ExitGame();
static void createEffect( u8 id, int _x, int _y );
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue );
static bool updateParticle( Particle *part );
static u8 CalculateFrameRate();
static u8 ClampVar8 (f32 Value);
// Initialize general variables
extern GXRModeObj *rmode;
// Prepare Graphics
GRRLIB_texImg *GFX_Background;
GRRLIB_texImg *GFX_Crosshair;
GRRLIB_texImg *GFX_Smoke;
GRRLIB_texImg *GFX_Font;
int main() {
ir_t P1Mote;
u8 FPS = 0;
// Init GRRLIB & WiiUse
GRRLIB_Init();
short WinW = rmode->fbWidth;
short WinH = rmode->efbHeight;
WPAD_Init();
WPAD_SetIdleTimeout( 60*10 );
WPAD_SetDataFormat( WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR );
// Load textures
GFX_Background = GRRLIB_LoadTextureJPG(RGFX_Background);
GFX_Crosshair = GRRLIB_LoadTexturePNG(RGFX_Crosshair);
GFX_Smoke = GRRLIB_LoadTexturePNG(RGFX_Smoke);
GFX_Font = GRRLIB_LoadTexturePNG(RGFX_Font);
GRRLIB_InitTileSet( GFX_Font, 8, 16, 32 );
// Set handles
GRRLIB_SetMidHandle( GFX_Crosshair, true );
GRRLIB_SetMidHandle( GFX_Smoke, true );
// Feed the vector with the textures
TextureList = { GFX_Background, GFX_Crosshair, GFX_Smoke, GFX_Font };
while (true) {
WPAD_ScanPads();
u32 WPADKeyDown = WPAD_ButtonsDown(WPAD_CHAN_0);
WPAD_SetVRes(WPAD_CHAN_0, WinW, WinH);
WPAD_IR(WPAD_CHAN_0, &P1Mote);
// Resetting Vars
GRRLIB_SetBlend( GRRLIB_BLEND_ALPHA );
u32 ParticleCnt = 0;
// WiiMote IR Viewport correction
int P1MX = P1Mote.sx - 150;
int P1MY = P1Mote.sy - 150;
// Drawing Background
GRRLIB_DrawImg( 0, 0, GFX_Background, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Add any pending objects into the main container
ParticleList.insert(ParticleList.end(), ParticleListTmp.begin(), ParticleListTmp.end());
ParticleListTmp.clear();
// Update and draw all particles
for (auto PartIter = ParticleList.begin(); PartIter != ParticleList.end();) {
if (updateParticle((*PartIter)) == true) {
GRRLIB_DrawImg( (*PartIter)->x, (*PartIter)->y, (*PartIter)->tex, (*PartIter)->rot, (*PartIter)->scale, (*PartIter)->scale, RGBA( (*PartIter)->red, (*PartIter)->green, (*PartIter)->blue, ClampVar8((*PartIter)->alpha*255) ) );
} else {
free( (*PartIter) );
ParticleList.erase(PartIter);
continue;
}
ParticleCnt++;
PartIter++;
}
// Draw Crosshair
GRRLIB_DrawImg( P1MX, P1MY, GFX_Crosshair, 0, 1, 1, RGBA(255, 255, 255, 255) );
// Draw Text
GRRLIB_Rectangle( 28, 28, 280, 20, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 32, GFX_Font, 0xFFFFFFFF, 1, "Point your WiiMote on the screen." );
GRRLIB_Rectangle( 28, 48, 200, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 48, GFX_Font, 0xFFFFFFFF, 1, "Number of Particle: %d", ParticleCnt );
GRRLIB_Rectangle( 28, 64, 64, 16, RGBA(0, 0, 0, 160), 1 );
GRRLIB_Printf ( 32, 64, GFX_Font, 0xFFFFFFFF, 1, "FPS: %d", FPS );
// Renders the Scene
GRRLIB_Render();
FPS = CalculateFrameRate();
if (WPADKeyDown & WPAD_BUTTON_B) {
createEffect( EFFECT_SMOKEBOMB, P1MX, P1MY );
}
if (WPADKeyDown & WPAD_BUTTON_HOME) {
ExitGame();
}
}
ExitGame();
return 0;
}
static void createEffect( u8 id, int _x, int _y ) {
u8 _ColorAdd = 0;
switch (id) {
case EFFECT_SMOKEBOMB:
for (u8 i = 0; i < 5; i++) {
createParticle( 1, (_x + (RANDOM * 10)), (_y + (RANDOM * 10)), (1.4f+(RANDOM*0.20)), 1.0f, 64, 64, 64 );
}
for (u8 i = 0; i < 20; i++) {
createParticle( 3, (_x + (RANDOM * 50)), (_y + (RANDOM * 50)), 1.25f, 1.5f, 92, 92, 92 );
}
for (u8 i = 0; i < 5; i++) {
_ColorAdd = (RANDOM*75);
createParticle( 2, (_x + (RANDOM * 40)), (_y + (RANDOM * 40)), (1.0f+(RANDOM*0.20)), 1.0f, 128+_ColorAdd, 128+_ColorAdd, 128+_ColorAdd );
}
break;
}
}
static void createParticle( u8 _id, int _x, int _y, float _scale, float _alpha, u8 _red, u8 _green, u8 _blue ) {
Particle *part = (struct Particle *)calloc(1, sizeof(Particle));
part->id = _id;
part->x = _x;
part->y = _y;
part->rot = rand() % 360;
part->red = _red;
part->green = _green;
part->blue = _blue;
part->scale = _scale;
part->alpha = _alpha;
part->tex = GFX_Smoke;
part->sy = RANDOM;
part->sx = RANDOM;
part->sscale = 0.9985;
part->salpha = 0.985;
switch (part->id) {
case 1:
part->sy = RANDOM * 0.5;
part->sx = RANDOM * 0.5;
part->sscale = 0.999;
part->salpha = 0.992;
part->framedelay = 10;
part->framecnt = 2;
break;
case 2:
part->scolor = 0.98;
part->salpha = 0.95;
break;
case 3:
part->sy = (RANDOM * 8);
part->sx = (RANDOM * 8);
part->salpha = 0.85;
part->scolor = 0.95;
break;
}
ParticleListTmp.push_back( part );
}
static bool updateParticle( Particle *part ) {
if (part->alpha < 0.05) { part->alpha -= 0.001; }
if (part->alpha < 0.1) { part->alpha -= 0.001; }
part->x += part->sx;
part->y += part->sy;
part->scale *= part->sscale;
part->alpha *= part->salpha;
switch (part->id) {
case 1:
if (part->alpha < 0.25) { part->alpha -= 0.001; }
if (part->framecnt == 0) {
part->framecnt = 20;
part->red -= 1;
part->green -= 1;
part->blue -= 1;
}
part->framecnt -= 1;
break;
case 2:
case 3:
part->red *= part->scolor;
part->green *= part->scolor;
part->blue *= part->scolor;
break;
}
if ((part->scale < 0) || (part->alpha < 0)) { return false; }
return true;
}
static void ExitGame() {
// Free all memory used by textures.
for (auto &TexIter : TextureList) {
GRRLIB_FreeTexture(TexIter);
}
TextureList.clear();
// Deinitialize GRRLIB & Video
GRRLIB_Exit();
// Exit application
exit(0);
}
static u8 CalculateFrameRate() {
static u8 frameCount = 0;
static u32 lastTime;
static u8 FPS = 0;
u32 currentTime = ticks_to_millisecs(gettime());
frameCount++;
if(currentTime - lastTime > 1000) {
lastTime = currentTime;
FPS = frameCount;
frameCount = 0;
}
return FPS;
}
/**
* A helper function for the YCbCr -> RGB conversion.
* Clamps the given value into a range of 0 - 255 and thus preventing an overflow.
* @param Value The value to clamp. Using float to increase the precision. This makes a full spectrum (0 - 255) possible.
* @return Returns a clean, clamped unsigned char.
*/
static u8 ClampVar8 (f32 Value) {
Value = roundf(Value);
if (Value < 0) Value = 0;
else if (Value > 255) Value = 255;
return (u8)Value;
}
<|endoftext|> |
<commit_before>#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cstdint>
#include <cstdlib>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using std::atof;
using std::count;
using std::cout;
using std::cerr;
using std::endl;
using std::getline;
using std::ifstream;
using std::ios;
using std::string;
using std::stringstream;
using cv::filter2D;
using cv::imread;
using cv::Mat;
using cv::namedWindow;
using cv::Rect;
using cv::waitKey;
namespace {
/*!
\brief ファイルストリームの走査位置を先頭へ戻す。
\param stream ファイルストリーム
\return ファイルストリーム
*/
ifstream& Rewind(ifstream& stream) {
stream.clear();
stream.seekg(0, ios::beg);
return stream;
}
/*
\brief カーネルへオペレータをセット。
\param row カーネルの行
\param line ファイルから読み込まれた文字列
\param size カーネルのサイズ
*/
void SetOperator(Mat row, const string& line, uint64_t size) {
stringstream line_stream(line);
for (uint64_t i = 0; i < size; ++i) {
if (line_stream.good() && !line_stream.eof()) {
string op;
getline(line_stream, op, ',');
// オペレータをセット
row.at<double>(i) = static_cast<double>(atof(op.c_str()));
} else { break; }
}
}
/*!
\brief カーネルのサイズを取得。
\param stream カーネルのファイルストリーム
\return カーネルのサイズ
*/
int GetKernelSize(ifstream& stream) {
string line;
getline(stream, line);
// 最初の行からフィルタサイズを取得。
uint64_t size = count(line.begin(), line.end(), ',') + 1;
return size;
}
/*!
\brief ファイルを読み込み、カーネルを取得する。
\param filename カーネルを表したCSVのファイル名
\return カーネル。エラーが起きた場合は空の画像
*/
Mat GetKernel(const string& filename) {
ifstream stream(filename);
if (stream.good()) {
int size = ::GetKernelSize(stream);
// カーネルの領域を確保
Mat kernel = Mat::zeros(size, size, cv::DataType<double>::type);
if (kernel.data == NULL) {
return Mat();
} else {
::Rewind(stream);
for (int i = 0; i < size; ++i) {
string line;
if (stream.good() && !stream.eof()) {
getline(stream, line);
SetOperator(kernel.row(i), line, size);
} else { break; }
}
return kernel;
}
} else { return Mat(); }
}
/*!
\brief 画像をカーネルに基づいた線形フィルタをかける。
\param src 元画像
\param kernel カーネル
\return フィルタされた画像。元画像かカーネルにエラーがある場合、空の画像
*/
Mat Filter(const Mat& src, const Mat& kernel) {
if (src.data != NULL && kernel.data != NULL) {
Mat filtered;
src.copyTo(filtered);
filter2D(src, filtered, src.depth(), kernel, cv::Point(0, 0));
return filtered;
} else { return Mat(); }
}
/*!
\brief エラーメッセージをウィンドウ名として表示。
ウィンドウが閉じられた時、標準エラー出力にもエラーメッセージを出力する。
\TODO もっといいエラーの表示方法はないものか...
\param error_message エラーメッセージ
\return 常ににEXIT_FAILURE
*/
int ShowErrorWindow(const std::string& error_message) {
namedWindow(error_message, CV_WINDOW_AUTOSIZE);
waitKey(0);
cerr << error_message << endl;
return EXIT_FAILURE;
}
/*!
\brief 元画像をフィルタされた画像を表示。
\param original 元画像
\param filtered フィルタされた画像
\return 常にEXIT_SUCCESS
*/
int ShowImageWindow(const Mat& original, const Mat& filtered) {
Mat output = Mat::zeros(
original.size().height,
original.size().width * 2,
original.type());
// 元画像とフィルタされた画像を結合
original.copyTo(Mat(output, Rect(0, 0, original.cols, original.rows)));
filtered.copyTo(
Mat(output, Rect(original.cols, 0, original.cols, original.rows)));
string window_name("linear_filter");
namedWindow(window_name, CV_WINDOW_AUTOSIZE);
imshow(window_name, output);
waitKey(0);
return EXIT_SUCCESS;
}
/*!
\brief ウィンドウを表示し、結果を出力。
'original'か'filtered'にエラーがある場合、エラーウィンドウを表示する。それ以
外の場合はフィルタされた画像を表示する。
\param original 元画像
\param filtered フィルタされた画像
\param エラーコード
*/
int ShowWindow(const cv::Mat& original, const cv::Mat& filtered) {
if (original.data == NULL) {
return ShowErrorWindow(string("failed to open the image."));
} else if (filtered.data == NULL) {
return ShowErrorWindow(string("failed to filter the image."));
} else { return ShowImageWindow(original, filtered); }
}
/*!
\brief 画像のファイル名を取得。
プログラム引数が2つの時はデフォルトの値'input.jpg'を、それ以上の場合は第二引
数をファイル名として返す。
\param agrc argc
\param argv argv
\return 画像のファイル名
*/
std::string GetImageFilename(int argc, char** argv)
{ return (argc == 2)? string("input.jpg"): string(argv[1]); }
/*!
\brief カーネルを記述したファイル名を取得。
プログラム引数が2つの場合は第二引数を、それ以上の場合は第三引数をファイル名と
して返す。
\param argc argc
\param argv argv
\return カーネルを記述したファイル名
*/
std::string GetKernelFilename(int argc, char** argv)
{ return (argc == 2)? string(argv[1]): string(argv[2]); }
} // namespace
int main(int argc, char** argv) {
if (argc == 2 || argc == 3) {
Mat original = imread(::GetImageFilename(argc, argv),
CV_LOAD_IMAGE_GRAYSCALE);
exit(
::ShowWindow(
original,
::Filter(original, ::GetKernel(::GetKernelFilename(argc, argv)))));
} else {
exit(
::ShowErrorWindow(
string("Usage: linear_filter image_file filter_csv")));
}
return 0;
}
<commit_msg>::GetKernelSize関数がサイズの取得に失敗した場合、0を返すよう変更。<commit_after>#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cstdint>
#include <cstdlib>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using std::atof;
using std::count;
using std::cout;
using std::cerr;
using std::endl;
using std::getline;
using std::ifstream;
using std::ios;
using std::string;
using std::stringstream;
using cv::filter2D;
using cv::imread;
using cv::Mat;
using cv::namedWindow;
using cv::Rect;
using cv::waitKey;
namespace {
/*!
\brief ファイルストリームの走査位置を先頭へ戻す。
\param stream ファイルストリーム
\return ファイルストリーム
*/
ifstream& Rewind(ifstream& stream) {
stream.clear();
stream.seekg(0, ios::beg);
return stream;
}
/*
\brief カーネルへオペレータをセット。
\param row カーネルの行
\param line ファイルから読み込まれた文字列
\param size カーネルのサイズ
*/
void SetOperator(Mat row, const string& line, uint64_t size) {
stringstream line_stream(line);
for (uint64_t i = 0; i < size; ++i) {
if (line_stream.good() && !line_stream.eof()) {
string op;
getline(line_stream, op, ',');
// オペレータをセット
row.at<double>(i) = static_cast<double>(atof(op.c_str()));
} else { break; }
}
}
/*!
\brief カーネルのサイズを取得。
\param stream カーネルのファイルストリーム
\return カーネルのサイズ。取得に失敗した場合は0
*/
int GetKernelSize(ifstream& stream) {
string line;
return (getline(stream, line).good())?
count(line.begin(), line.end(), ',') + 1: 0;
}
/*!
\brief ファイルを読み込み、カーネルを取得する。
\param filename カーネルを表したCSVのファイル名
\return カーネル。エラーが起きた場合は空の画像
*/
Mat GetKernel(const string& filename) {
ifstream stream(filename);
if (stream.good()) {
int size = ::GetKernelSize(stream);
// カーネルの領域を確保
Mat kernel = Mat::zeros(size, size, cv::DataType<double>::type);
if (size <= 0 || kernel.data == NULL) {
return Mat();
} else {
::Rewind(stream);
for (int i = 0; i < size; ++i) {
string line;
if (stream.good() && !stream.eof()) {
getline(stream, line);
SetOperator(kernel.row(i), line, size);
} else { break; }
}
return kernel;
}
} else { return Mat(); }
}
/*!
\brief 画像をカーネルに基づいた線形フィルタをかける。
\param src 元画像
\param kernel カーネル
\return フィルタされた画像。元画像かカーネルにエラーがある場合、空の画像
*/
Mat Filter(const Mat& src, const Mat& kernel) {
if (src.data != NULL && kernel.data != NULL) {
Mat filtered;
src.copyTo(filtered);
filter2D(src, filtered, src.depth(), kernel, cv::Point(0, 0));
return filtered;
} else { return Mat(); }
}
/*!
\brief エラーメッセージをウィンドウ名として表示。
ウィンドウが閉じられた時、標準エラー出力にもエラーメッセージを出力する。
\TODO もっといいエラーの表示方法はないものか...
\param error_message エラーメッセージ
\return 常ににEXIT_FAILURE
*/
int ShowErrorWindow(const std::string& error_message) {
namedWindow(error_message, CV_WINDOW_AUTOSIZE);
waitKey(0);
cerr << error_message << endl;
return EXIT_FAILURE;
}
/*!
\brief 元画像をフィルタされた画像を表示。
\param original 元画像
\param filtered フィルタされた画像
\return 常にEXIT_SUCCESS
*/
int ShowImageWindow(const Mat& original, const Mat& filtered) {
Mat output = Mat::zeros(
original.size().height,
original.size().width * 2,
original.type());
// 元画像とフィルタされた画像を結合
original.copyTo(Mat(output, Rect(0, 0, original.cols, original.rows)));
filtered.copyTo(
Mat(output, Rect(original.cols, 0, original.cols, original.rows)));
string window_name("linear_filter");
namedWindow(window_name, CV_WINDOW_AUTOSIZE);
imshow(window_name, output);
waitKey(0);
return EXIT_SUCCESS;
}
/*!
\brief ウィンドウを表示し、結果を出力。
'original'か'filtered'にエラーがある場合、エラーウィンドウを表示する。それ以
外の場合はフィルタされた画像を表示する。
\param original 元画像
\param filtered フィルタされた画像
\param エラーコード
*/
int ShowWindow(const cv::Mat& original, const cv::Mat& filtered) {
if (original.data == NULL) {
return ShowErrorWindow(string("failed to open the image."));
} else if (filtered.data == NULL) {
return ShowErrorWindow(string("failed to filter the image."));
} else { return ShowImageWindow(original, filtered); }
}
/*!
\brief 画像のファイル名を取得。
プログラム引数が2つの時はデフォルトの値'input.jpg'を、それ以上の場合は第二引
数をファイル名として返す。
\param agrc argc
\param argv argv
\return 画像のファイル名
*/
std::string GetImageFilename(int argc, char** argv)
{ return (argc == 2)? string("input.jpg"): string(argv[1]); }
/*!
\brief カーネルを記述したファイル名を取得。
プログラム引数が2つの場合は第二引数を、それ以上の場合は第三引数をファイル名と
して返す。
\param argc argc
\param argv argv
\return カーネルを記述したファイル名
*/
std::string GetKernelFilename(int argc, char** argv)
{ return (argc == 2)? string(argv[1]): string(argv[2]); }
} // namespace
int main(int argc, char** argv) {
if (argc == 2 || argc == 3) {
Mat original = imread(::GetImageFilename(argc, argv),
CV_LOAD_IMAGE_GRAYSCALE);
exit(
::ShowWindow(
original,
::Filter(original, ::GetKernel(::GetKernelFilename(argc, argv)))));
} else {
exit(
::ShowErrorWindow(
string("Usage: linear_filter image_file filter_csv")));
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 University of Basel
* 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 project's author 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 <boost/program_options.hpp>
#include <itkDataManager.h>
#include <itkDirectory.h>
#include <itkImageFileReader.h>
#include <itkPCAModelBuilder.h>
#include <itkStandardImageRepresenter.h>
#include <itkStatisticalModel.h>
#include "utils/statismo-build-models-utils.h"
namespace po = boost::program_options;
using namespace std;
struct programOptions {
bool bDisplayHelp;
string strDataListFile;
string strOutputFileName;
float fNoiseVariance;
unsigned uNumberOfDimensions;
};
po::options_description initializeProgramOptions(programOptions& poParameters);
bool isOptionsConflictPresent(programOptions& opt);
template<unsigned Dimensions>
void buildAndSaveDeformationModel(programOptions opt);
int main(int argc, char** argv) {
programOptions poParameters;
po::positional_options_description optPositional;
optPositional.add("output-file", 1);
po::options_description optAllOptions = initializeProgramOptions(poParameters);
po::variables_map vm;
try {
po::parsed_options parsedOptions = po::command_line_parser(argc, argv).options(optAllOptions).positional(optPositional).run();
po::store(parsedOptions, vm);
po::notify(vm);
} catch (po::error& e) {
cerr << "An exception occurred while parsing the Command line:"<<endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
}
if (poParameters.bDisplayHelp == true) {
cout << optAllOptions << endl;
return EXIT_SUCCESS;
}
if (isOptionsConflictPresent(poParameters) == true) {
cerr << "A conflict in the options exists or insufficient options were set." << endl;
cout << optAllOptions << endl;
return EXIT_FAILURE;
}
try {
if (poParameters.uNumberOfDimensions == 2) {
buildAndSaveDeformationModel<2>(poParameters);
} else {
buildAndSaveDeformationModel<3>(poParameters);
}
} catch (ifstream::failure & e) {
cerr << "Could not read the data-list:" << endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
} catch (itk::ExceptionObject & e) {
cerr << "Could not build the model:" << endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool isOptionsConflictPresent(programOptions& opt) {
if (opt.strDataListFile == "" || opt.strOutputFileName == "" ) {
return true;
}
if (opt.strDataListFile == opt.strOutputFileName) {
return true;
}
if (opt.fNoiseVariance < 0) {
return true;
}
if (opt.uNumberOfDimensions != 2 && opt.uNumberOfDimensions != 3) {
return true;
}
return false;
}
template<unsigned Dimensions>
void buildAndSaveDeformationModel(programOptions opt) {
typedef itk::Vector<float, Dimensions> VectorPixelType;
typedef itk::Image<VectorPixelType, Dimensions> ImageType;
typedef itk::StandardImageRepresenter<VectorPixelType, Dimensions > RepresenterType;
typename RepresenterType::Pointer representer = RepresenterType::New();
typedef itk::DataManager<ImageType> DataManagerType;
typename DataManagerType::Pointer dataManager = DataManagerType::New();
StringList fileNames = getFileList(opt.strDataListFile);
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef vector<typename ImageReaderType::Pointer> ImageReaderList;
ImageReaderList images;
images.reserve(fileNames.size());
// for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
// typename ImageReaderType::Pointer reader = ImageReaderType::New();
// reader->SetFileName(it->c_str());
// reader->Update();
// //itk::PCAModelBuilder is not a Filter in the ITK world, so the pipeline would not get executed if its main method is called. So the pipeline before calling itk::PCAModelBuilder must be executed by the means of calls to Update() (at least for last elements needed by itk::PCAModelBuilder).
// images.push_back(reader);
// }
if (fileNames.size() == 0) {
itkGenericExceptionMacro( << "No Data was loaded and thus the model can't be built.");
}
// typename ImageReaderType::Pointer referenceReader = *images.begin();
// representer->SetReference(referenceReader->GetOutput());
// dataManager->SetRepresenter(representer);
int cc = 0;
for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
typename ImageReaderType::Pointer reader = ImageReaderType::New();
reader->SetFileName(it->c_str());
reader->Update();
if ( cc == 0) {
representer->SetReference(reader->GetOutput());
dataManager->SetRepresenter(representer);
}
dataManager->AddDataset(reader->GetOutput(), reader->GetFileName().c_str());
cc += 1;
}
typedef itk::StatisticalModel<ImageType> StatisticalModelType;
typename StatisticalModelType::Pointer model;
typedef itk::PCAModelBuilder<ImageType> ModelBuilderType;
typename ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New();
model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), opt.fNoiseVariance);
model->Save(opt.strOutputFileName.c_str());
}
po::options_description initializeProgramOptions(programOptions& poParameters) {
po::options_description optMandatory("Mandatory options");
optMandatory.add_options()
("data-list,l", po::value<string>(&poParameters.strDataListFile), "File containing a list of meshes to build the deformation model from")
("output-file,o", po::value<string>(&poParameters.strOutputFileName), "Name of the output file")
("dimensionality,d", po::value<unsigned>(&poParameters.uNumberOfDimensions)->default_value(3), "Dimensionality of the input images in the data list")
;
po::options_description optAdditional("Optional options");
optAdditional.add_options()
("noise,n", po::value<float>(&poParameters.fNoiseVariance)->default_value(0), "Noise variance of the PPCA model")
("help,h", po::bool_switch(&poParameters.bDisplayHelp), "Display this help message")
;
po::options_description optAllOptions;
optAllOptions.add(optMandatory).add(optAdditional);
return optAllOptions;
}
<commit_msg>uncommented obsolete lines<commit_after>/*
* Copyright (c) 2015 University of Basel
* 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 project's author 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 <boost/program_options.hpp>
#include <itkDataManager.h>
#include <itkDirectory.h>
#include <itkImageFileReader.h>
#include <itkPCAModelBuilder.h>
#include <itkStandardImageRepresenter.h>
#include <itkStatisticalModel.h>
#include "utils/statismo-build-models-utils.h"
namespace po = boost::program_options;
using namespace std;
struct programOptions {
bool bDisplayHelp;
string strDataListFile;
string strOutputFileName;
float fNoiseVariance;
unsigned uNumberOfDimensions;
};
po::options_description initializeProgramOptions(programOptions& poParameters);
bool isOptionsConflictPresent(programOptions& opt);
template<unsigned Dimensions>
void buildAndSaveDeformationModel(programOptions opt);
int main(int argc, char** argv) {
programOptions poParameters;
po::positional_options_description optPositional;
optPositional.add("output-file", 1);
po::options_description optAllOptions = initializeProgramOptions(poParameters);
po::variables_map vm;
try {
po::parsed_options parsedOptions = po::command_line_parser(argc, argv).options(optAllOptions).positional(optPositional).run();
po::store(parsedOptions, vm);
po::notify(vm);
} catch (po::error& e) {
cerr << "An exception occurred while parsing the Command line:"<<endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
}
if (poParameters.bDisplayHelp == true) {
cout << optAllOptions << endl;
return EXIT_SUCCESS;
}
if (isOptionsConflictPresent(poParameters) == true) {
cerr << "A conflict in the options exists or insufficient options were set." << endl;
cout << optAllOptions << endl;
return EXIT_FAILURE;
}
try {
if (poParameters.uNumberOfDimensions == 2) {
buildAndSaveDeformationModel<2>(poParameters);
} else {
buildAndSaveDeformationModel<3>(poParameters);
}
} catch (ifstream::failure & e) {
cerr << "Could not read the data-list:" << endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
} catch (itk::ExceptionObject & e) {
cerr << "Could not build the model:" << endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool isOptionsConflictPresent(programOptions& opt) {
if (opt.strDataListFile == "" || opt.strOutputFileName == "" ) {
return true;
}
if (opt.strDataListFile == opt.strOutputFileName) {
return true;
}
if (opt.fNoiseVariance < 0) {
return true;
}
if (opt.uNumberOfDimensions != 2 && opt.uNumberOfDimensions != 3) {
return true;
}
return false;
}
template<unsigned Dimensions>
void buildAndSaveDeformationModel(programOptions opt) {
typedef itk::Vector<float, Dimensions> VectorPixelType;
typedef itk::Image<VectorPixelType, Dimensions> ImageType;
typedef itk::StandardImageRepresenter<VectorPixelType, Dimensions > RepresenterType;
typename RepresenterType::Pointer representer = RepresenterType::New();
typedef itk::DataManager<ImageType> DataManagerType;
typename DataManagerType::Pointer dataManager = DataManagerType::New();
StringList fileNames = getFileList(opt.strDataListFile);
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef vector<typename ImageReaderType::Pointer> ImageReaderList;
// ImageReaderList images;
// images.reserve(fileNames.size());
// for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
// typename ImageReaderType::Pointer reader = ImageReaderType::New();
// reader->SetFileName(it->c_str());
// reader->Update();
// //itk::PCAModelBuilder is not a Filter in the ITK world, so the pipeline would not get executed if its main method is called. So the pipeline before calling itk::PCAModelBuilder must be executed by the means of calls to Update() (at least for last elements needed by itk::PCAModelBuilder).
// images.push_back(reader);
// }
if (fileNames.size() == 0) {
itkGenericExceptionMacro( << "No Data was loaded and thus the model can't be built.");
}
// typename ImageReaderType::Pointer referenceReader = *images.begin();
// representer->SetReference(referenceReader->GetOutput());
// dataManager->SetRepresenter(representer);
int cc = 0;
for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
typename ImageReaderType::Pointer reader = ImageReaderType::New();
reader->SetFileName(it->c_str());
reader->Update();
if ( cc == 0) {
representer->SetReference(reader->GetOutput());
dataManager->SetRepresenter(representer);
}
dataManager->AddDataset(reader->GetOutput(), reader->GetFileName().c_str());
cc += 1;
}
typedef itk::StatisticalModel<ImageType> StatisticalModelType;
typename StatisticalModelType::Pointer model;
typedef itk::PCAModelBuilder<ImageType> ModelBuilderType;
typename ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New();
model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), opt.fNoiseVariance);
model->Save(opt.strOutputFileName.c_str());
}
po::options_description initializeProgramOptions(programOptions& poParameters) {
po::options_description optMandatory("Mandatory options");
optMandatory.add_options()
("data-list,l", po::value<string>(&poParameters.strDataListFile), "File containing a list of meshes to build the deformation model from")
("output-file,o", po::value<string>(&poParameters.strOutputFileName), "Name of the output file")
("dimensionality,d", po::value<unsigned>(&poParameters.uNumberOfDimensions)->default_value(3), "Dimensionality of the input images in the data list")
;
po::options_description optAdditional("Optional options");
optAdditional.add_options()
("noise,n", po::value<float>(&poParameters.fNoiseVariance)->default_value(0), "Noise variance of the PPCA model")
("help,h", po::bool_switch(&poParameters.bDisplayHelp), "Display this help message")
;
po::options_description optAllOptions;
optAllOptions.add(optMandatory).add(optAdditional);
return optAllOptions;
}
<|endoftext|> |
<commit_before>//===-- IntelJITEventListener.cpp - Tell Intel profiler about JITed code --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a JITEventListener object to tell Intel(R) VTune(TM)
// Amplifier XE 2011 about JITted functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#include "IntelJITEventsWrapper.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/SymbolSize.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "amplifier-jit-event-listener"
namespace {
class IntelJITEventListener : public JITEventListener {
typedef DenseMap<void*, unsigned int> MethodIDMap;
std::unique_ptr<IntelJITEventsWrapper> Wrapper;
MethodIDMap MethodIDs;
typedef SmallVector<const void *, 64> MethodAddressVector;
typedef DenseMap<const void *, MethodAddressVector> ObjectMap;
ObjectMap LoadedObjectMap;
std::map<const char*, OwningBinary<ObjectFile>> DebugObjects;
public:
IntelJITEventListener(IntelJITEventsWrapper* libraryWrapper) {
Wrapper.reset(libraryWrapper);
}
~IntelJITEventListener() {
}
void NotifyObjectEmitted(const ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) override;
void NotifyFreeingObject(const ObjectFile &Obj) override;
};
static LineNumberInfo DILineInfoToIntelJITFormat(uintptr_t StartAddress,
uintptr_t Address,
DILineInfo Line) {
LineNumberInfo Result;
Result.Offset = Address - StartAddress;
Result.LineNumber = Line.Line;
return Result;
}
static iJIT_Method_Load FunctionDescToIntelJITFormat(
IntelJITEventsWrapper& Wrapper,
const char* FnName,
uintptr_t FnStart,
size_t FnSize) {
iJIT_Method_Load Result;
memset(&Result, 0, sizeof(iJIT_Method_Load));
Result.method_id = Wrapper.iJIT_GetNewMethodID();
Result.method_name = const_cast<char*>(FnName);
Result.method_load_address = reinterpret_cast<void*>(FnStart);
Result.method_size = FnSize;
Result.class_id = 0;
Result.class_file_name = NULL;
Result.user_data = NULL;
Result.user_data_size = 0;
Result.env = iJDE_JittingAPI;
return Result;
}
void IntelJITEventListener::NotifyObjectEmitted(
const ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) {
OwningBinary<ObjectFile> DebugObjOwner = L.getObjectForDebug(Obj);
const ObjectFile &DebugObj = *DebugObjOwner.getBinary();
// Get the address of the object image for use as a unique identifier
const void* ObjData = DebugObj.getData().data();
DIContext* Context = new DWARFContextInMemory(DebugObj);
MethodAddressVector Functions;
// Use symbol info to iterate functions in the object.
for (const std::pair<SymbolRef, uint64_t> &P : computeSymbolSizes(DebugObj)) {
SymbolRef Sym = P.first;
std::vector<LineNumberInfo> LineInfo;
std::string SourceFileName;
if (Sym.getType() != SymbolRef::ST_Function)
continue;
ErrorOr<StringRef> Name = Sym.getName();
if (!Name)
continue;
ErrorOr<uint64_t> AddrOrErr = Sym.getAddress();
if (AddrOrErr.getError())
continue;
uint64_t Addr = *AddrOrErr;
uint64_t Size = P.second;
// Record this address in a local vector
Functions.push_back((void*)Addr);
// Build the function loaded notification message
iJIT_Method_Load FunctionMessage =
FunctionDescToIntelJITFormat(*Wrapper, Name->data(), Addr, Size);
DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
DILineInfoTable::iterator Begin = Lines.begin();
DILineInfoTable::iterator End = Lines.end();
for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
LineInfo.push_back(
DILineInfoToIntelJITFormat((uintptr_t)Addr, It->first, It->second));
}
if (LineInfo.size() == 0) {
FunctionMessage.source_file_name = 0;
FunctionMessage.line_number_size = 0;
FunctionMessage.line_number_table = 0;
} else {
// Source line information for the address range is provided as
// a code offset for the start of the corresponding sub-range and
// a source line. JIT API treats offsets in LineNumberInfo structures
// as the end of the corresponding code region. The start of the code
// is taken from the previous element. Need to shift the elements.
LineNumberInfo last = LineInfo.back();
last.Offset = FunctionMessage.method_size;
LineInfo.push_back(last);
for (size_t i = LineInfo.size() - 2; i > 0; --i)
LineInfo[i].LineNumber = LineInfo[i - 1].LineNumber;
SourceFileName = Lines.front().second.FileName;
FunctionMessage.source_file_name =
const_cast<char *>(SourceFileName.c_str());
FunctionMessage.line_number_size = LineInfo.size();
FunctionMessage.line_number_table = &*LineInfo.begin();
}
Wrapper->iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED,
&FunctionMessage);
MethodIDs[(void*)Addr] = FunctionMessage.method_id;
}
// To support object unload notification, we need to keep a list of
// registered function addresses for each loaded object. We will
// use the MethodIDs map to get the registered ID for each function.
LoadedObjectMap[ObjData] = Functions;
DebugObjects[Obj.getData().data()] = std::move(DebugObjOwner);
}
void IntelJITEventListener::NotifyFreeingObject(const ObjectFile &Obj) {
// This object may not have been registered with the listener. If it wasn't,
// bail out.
if (DebugObjects.find(Obj.getData().data()) == DebugObjects.end())
return;
// Get the address of the object image for use as a unique identifier
const ObjectFile &DebugObj = *DebugObjects[Obj.getData().data()].getBinary();
const void* ObjData = DebugObj.getData().data();
// Get the object's function list from LoadedObjectMap
ObjectMap::iterator OI = LoadedObjectMap.find(ObjData);
if (OI == LoadedObjectMap.end())
return;
MethodAddressVector& Functions = OI->second;
// Walk the function list, unregistering each function
for (MethodAddressVector::iterator FI = Functions.begin(),
FE = Functions.end();
FI != FE;
++FI) {
void* FnStart = const_cast<void*>(*FI);
MethodIDMap::iterator MI = MethodIDs.find(FnStart);
if (MI != MethodIDs.end()) {
Wrapper->iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_UNLOAD_START,
&MI->second);
MethodIDs.erase(MI);
}
}
// Erase the object from LoadedObjectMap
LoadedObjectMap.erase(OI);
DebugObjects.erase(Obj.getData().data());
}
} // anonymous namespace.
namespace llvm {
JITEventListener *JITEventListener::createIntelJITEventListener() {
return new IntelJITEventListener(new IntelJITEventsWrapper);
}
// for testing
JITEventListener *JITEventListener::createIntelJITEventListener(
IntelJITEventsWrapper* TestImpl) {
return new IntelJITEventListener(TestImpl);
}
} // namespace llvm
<commit_msg>More more change need as part of r264187 where ErrorOr<> was added to getSymbolType().<commit_after>//===-- IntelJITEventListener.cpp - Tell Intel profiler about JITed code --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a JITEventListener object to tell Intel(R) VTune(TM)
// Amplifier XE 2011 about JITted functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#include "IntelJITEventsWrapper.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/SymbolSize.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "amplifier-jit-event-listener"
namespace {
class IntelJITEventListener : public JITEventListener {
typedef DenseMap<void*, unsigned int> MethodIDMap;
std::unique_ptr<IntelJITEventsWrapper> Wrapper;
MethodIDMap MethodIDs;
typedef SmallVector<const void *, 64> MethodAddressVector;
typedef DenseMap<const void *, MethodAddressVector> ObjectMap;
ObjectMap LoadedObjectMap;
std::map<const char*, OwningBinary<ObjectFile>> DebugObjects;
public:
IntelJITEventListener(IntelJITEventsWrapper* libraryWrapper) {
Wrapper.reset(libraryWrapper);
}
~IntelJITEventListener() {
}
void NotifyObjectEmitted(const ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) override;
void NotifyFreeingObject(const ObjectFile &Obj) override;
};
static LineNumberInfo DILineInfoToIntelJITFormat(uintptr_t StartAddress,
uintptr_t Address,
DILineInfo Line) {
LineNumberInfo Result;
Result.Offset = Address - StartAddress;
Result.LineNumber = Line.Line;
return Result;
}
static iJIT_Method_Load FunctionDescToIntelJITFormat(
IntelJITEventsWrapper& Wrapper,
const char* FnName,
uintptr_t FnStart,
size_t FnSize) {
iJIT_Method_Load Result;
memset(&Result, 0, sizeof(iJIT_Method_Load));
Result.method_id = Wrapper.iJIT_GetNewMethodID();
Result.method_name = const_cast<char*>(FnName);
Result.method_load_address = reinterpret_cast<void*>(FnStart);
Result.method_size = FnSize;
Result.class_id = 0;
Result.class_file_name = NULL;
Result.user_data = NULL;
Result.user_data_size = 0;
Result.env = iJDE_JittingAPI;
return Result;
}
void IntelJITEventListener::NotifyObjectEmitted(
const ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) {
OwningBinary<ObjectFile> DebugObjOwner = L.getObjectForDebug(Obj);
const ObjectFile &DebugObj = *DebugObjOwner.getBinary();
// Get the address of the object image for use as a unique identifier
const void* ObjData = DebugObj.getData().data();
DIContext* Context = new DWARFContextInMemory(DebugObj);
MethodAddressVector Functions;
// Use symbol info to iterate functions in the object.
for (const std::pair<SymbolRef, uint64_t> &P : computeSymbolSizes(DebugObj)) {
SymbolRef Sym = P.first;
std::vector<LineNumberInfo> LineInfo;
std::string SourceFileName;
ErrorOr<SymbolRef::Type> SymTypeOrErr = Sym.getType();
if (!SymTypeOrErr)
continue;
SymbolRef::Type SymType = *SymTypeOrErr;
if (SymType != SymbolRef::ST_Function)
continue;
ErrorOr<StringRef> Name = Sym.getName();
if (!Name)
continue;
ErrorOr<uint64_t> AddrOrErr = Sym.getAddress();
if (AddrOrErr.getError())
continue;
uint64_t Addr = *AddrOrErr;
uint64_t Size = P.second;
// Record this address in a local vector
Functions.push_back((void*)Addr);
// Build the function loaded notification message
iJIT_Method_Load FunctionMessage =
FunctionDescToIntelJITFormat(*Wrapper, Name->data(), Addr, Size);
DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
DILineInfoTable::iterator Begin = Lines.begin();
DILineInfoTable::iterator End = Lines.end();
for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
LineInfo.push_back(
DILineInfoToIntelJITFormat((uintptr_t)Addr, It->first, It->second));
}
if (LineInfo.size() == 0) {
FunctionMessage.source_file_name = 0;
FunctionMessage.line_number_size = 0;
FunctionMessage.line_number_table = 0;
} else {
// Source line information for the address range is provided as
// a code offset for the start of the corresponding sub-range and
// a source line. JIT API treats offsets in LineNumberInfo structures
// as the end of the corresponding code region. The start of the code
// is taken from the previous element. Need to shift the elements.
LineNumberInfo last = LineInfo.back();
last.Offset = FunctionMessage.method_size;
LineInfo.push_back(last);
for (size_t i = LineInfo.size() - 2; i > 0; --i)
LineInfo[i].LineNumber = LineInfo[i - 1].LineNumber;
SourceFileName = Lines.front().second.FileName;
FunctionMessage.source_file_name =
const_cast<char *>(SourceFileName.c_str());
FunctionMessage.line_number_size = LineInfo.size();
FunctionMessage.line_number_table = &*LineInfo.begin();
}
Wrapper->iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED,
&FunctionMessage);
MethodIDs[(void*)Addr] = FunctionMessage.method_id;
}
// To support object unload notification, we need to keep a list of
// registered function addresses for each loaded object. We will
// use the MethodIDs map to get the registered ID for each function.
LoadedObjectMap[ObjData] = Functions;
DebugObjects[Obj.getData().data()] = std::move(DebugObjOwner);
}
void IntelJITEventListener::NotifyFreeingObject(const ObjectFile &Obj) {
// This object may not have been registered with the listener. If it wasn't,
// bail out.
if (DebugObjects.find(Obj.getData().data()) == DebugObjects.end())
return;
// Get the address of the object image for use as a unique identifier
const ObjectFile &DebugObj = *DebugObjects[Obj.getData().data()].getBinary();
const void* ObjData = DebugObj.getData().data();
// Get the object's function list from LoadedObjectMap
ObjectMap::iterator OI = LoadedObjectMap.find(ObjData);
if (OI == LoadedObjectMap.end())
return;
MethodAddressVector& Functions = OI->second;
// Walk the function list, unregistering each function
for (MethodAddressVector::iterator FI = Functions.begin(),
FE = Functions.end();
FI != FE;
++FI) {
void* FnStart = const_cast<void*>(*FI);
MethodIDMap::iterator MI = MethodIDs.find(FnStart);
if (MI != MethodIDs.end()) {
Wrapper->iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_UNLOAD_START,
&MI->second);
MethodIDs.erase(MI);
}
}
// Erase the object from LoadedObjectMap
LoadedObjectMap.erase(OI);
DebugObjects.erase(Obj.getData().data());
}
} // anonymous namespace.
namespace llvm {
JITEventListener *JITEventListener::createIntelJITEventListener() {
return new IntelJITEventListener(new IntelJITEventsWrapper);
}
// for testing
JITEventListener *JITEventListener::createIntelJITEventListener(
IntelJITEventsWrapper* TestImpl) {
return new IntelJITEventListener(TestImpl);
}
} // namespace llvm
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/aec3/subtractor.h"
#include <algorithm>
#include <memory>
#include <numeric>
#include <string>
#include "modules/audio_processing/aec3/aec_state.h"
#include "modules/audio_processing/aec3/render_delay_buffer.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "modules/audio_processing/utility/cascaded_biquad_filter.h"
#include "rtc_base/random.h"
#include "rtc_base/strings/string_builder.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
std::vector<float> RunSubtractorTest(
size_t num_render_channels,
size_t num_capture_channels,
int num_blocks_to_process,
int delay_samples,
int main_filter_length_blocks,
int shadow_filter_length_blocks,
bool uncorrelated_inputs,
const std::vector<int>& blocks_with_echo_path_changes) {
ApmDataDumper data_dumper(42);
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
EchoCanceller3Config config;
config.filter.main.length_blocks = main_filter_length_blocks;
config.filter.shadow.length_blocks = shadow_filter_length_blocks;
Subtractor subtractor(config, num_render_channels, num_capture_channels,
&data_dumper, DetectOptimization());
absl::optional<DelayEstimate> delay_estimate;
std::vector<std::vector<std::vector<float>>> x(
kNumBands, std::vector<std::vector<float>>(
num_render_channels, std::vector<float>(kBlockSize, 0.f)));
std::vector<std::vector<float>> y(num_capture_channels,
std::vector<float>(kBlockSize, 0.f));
std::array<float, kBlockSize> x_old;
std::vector<SubtractorOutput> output(num_capture_channels);
config.delay.default_delay = 1;
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, num_render_channels));
RenderSignalAnalyzer render_signal_analyzer(config);
Random random_generator(42U);
Aec3Fft fft;
std::vector<std::array<float, kFftLengthBy2Plus1>> Y2(num_capture_channels);
std::vector<std::array<float, kFftLengthBy2Plus1>> E2_main(
num_capture_channels);
std::array<float, kFftLengthBy2Plus1> E2_shadow;
AecState aec_state(config, num_capture_channels);
x_old.fill(0.f);
for (auto& Y2_ch : Y2) {
Y2_ch.fill(0.f);
}
for (auto& E2_main_ch : E2_main) {
E2_main_ch.fill(0.f);
}
E2_shadow.fill(0.f);
std::vector<std::vector<std::unique_ptr<DelayBuffer<float>>>> delay_buffer(
num_capture_channels);
for (size_t capture_ch = 0; capture_ch < num_capture_channels; ++capture_ch) {
delay_buffer[capture_ch].resize(num_render_channels);
for (size_t render_ch = 0; render_ch < num_render_channels; ++render_ch) {
delay_buffer[capture_ch][render_ch] =
std::make_unique<DelayBuffer<float>>(delay_samples);
}
}
// [B,A] = butter(2,100/8000,'high')
constexpr CascadedBiQuadFilter::BiQuadCoefficients
kHighPassFilterCoefficients = {{0.97261f, -1.94523f, 0.97261f},
{-1.94448f, 0.94598f}};
std::vector<std::unique_ptr<CascadedBiQuadFilter>> x_hp_filter(
num_render_channels);
for (size_t ch = 0; ch < num_render_channels; ++ch) {
x_hp_filter[ch] =
std::make_unique<CascadedBiQuadFilter>(kHighPassFilterCoefficients, 1);
}
std::vector<std::unique_ptr<CascadedBiQuadFilter>> y_hp_filter(
num_capture_channels);
for (size_t ch = 0; ch < num_capture_channels; ++ch) {
y_hp_filter[ch] =
std::make_unique<CascadedBiQuadFilter>(kHighPassFilterCoefficients, 1);
}
for (int k = 0; k < num_blocks_to_process; ++k) {
for (size_t render_ch = 0; render_ch < num_render_channels; ++render_ch) {
RandomizeSampleVector(&random_generator, x[0][render_ch]);
}
if (uncorrelated_inputs) {
for (size_t capture_ch = 0; capture_ch < num_capture_channels;
++capture_ch) {
RandomizeSampleVector(&random_generator, y[capture_ch]);
}
} else {
for (size_t capture_ch = 0; capture_ch < num_capture_channels;
++capture_ch) {
for (size_t render_ch = 0; render_ch < num_render_channels;
++render_ch) {
std::array<float, kBlockSize> y_channel;
delay_buffer[capture_ch][render_ch]->Delay(x[0][render_ch],
y_channel);
for (size_t k = 0; k < y.size(); ++k) {
y[capture_ch][k] += y_channel[k] / num_render_channels;
}
}
}
}
for (size_t ch = 0; ch < num_render_channels; ++ch) {
x_hp_filter[ch]->Process(x[0][ch]);
}
for (size_t ch = 0; ch < num_capture_channels; ++ch) {
y_hp_filter[ch]->Process(y[ch]);
}
render_delay_buffer->Insert(x);
if (k == 0) {
render_delay_buffer->Reset();
}
render_delay_buffer->PrepareCaptureProcessing();
render_signal_analyzer.Update(*render_delay_buffer->GetRenderBuffer(),
aec_state.MinDirectPathFilterDelay());
// Handle echo path changes.
if (std::find(blocks_with_echo_path_changes.begin(),
blocks_with_echo_path_changes.end(),
k) != blocks_with_echo_path_changes.end()) {
subtractor.HandleEchoPathChange(EchoPathVariability(
true, EchoPathVariability::DelayAdjustment::kNewDetectedDelay,
false));
}
subtractor.Process(*render_delay_buffer->GetRenderBuffer(), y,
render_signal_analyzer, aec_state, output);
aec_state.HandleEchoPathChange(EchoPathVariability(
false, EchoPathVariability::DelayAdjustment::kNone, false));
aec_state.Update(delay_estimate, subtractor.FilterFrequencyResponses(),
subtractor.FilterImpulseResponses(),
*render_delay_buffer->GetRenderBuffer(), E2_main, Y2,
output);
}
std::vector<float> results(num_capture_channels);
for (size_t ch = 0; ch < num_capture_channels; ++ch) {
const float output_power =
std::inner_product(output[ch].e_main.begin(), output[ch].e_main.end(),
output[ch].e_main.begin(), 0.f);
const float y_power =
std::inner_product(y[ch].begin(), y[ch].end(), y[ch].begin(), 0.f);
if (y_power == 0.f) {
ADD_FAILURE();
results[ch] = -1.f;
}
results[ch] = output_power / y_power;
}
return results;
}
std::string ProduceDebugText(size_t num_render_channels,
size_t num_capture_channels,
size_t delay,
int filter_length_blocks) {
rtc::StringBuilder ss;
ss << "delay: " << delay << ", ";
ss << "filter_length_blocks:" << filter_length_blocks << ", ";
ss << "num_render_channels:" << num_render_channels << ", ";
ss << "num_capture_channels:" << num_capture_channels;
return ss.Release();
}
} // namespace
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// Verifies that the check for non data dumper works.
TEST(Subtractor, NullDataDumper) {
EXPECT_DEATH(
Subtractor(EchoCanceller3Config(), 1, 1, nullptr, DetectOptimization()),
"");
}
// Verifies the check for the capture signal size.
TEST(Subtractor, WrongCaptureSize) {
ApmDataDumper data_dumper(42);
EchoCanceller3Config config;
Subtractor subtractor(config, 1, 1, &data_dumper, DetectOptimization());
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, 48000, 1));
RenderSignalAnalyzer render_signal_analyzer(config);
std::vector<std::vector<float>> y(1, std::vector<float>(kBlockSize - 1, 0.f));
std::array<SubtractorOutput, 1> output;
EXPECT_DEATH(
subtractor.Process(*render_delay_buffer->GetRenderBuffer(), y,
render_signal_analyzer, AecState(config, 1), output),
"");
}
#endif
// Verifies that the subtractor is able to converge on correlated data.
TEST(Subtractor, Convergence) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t filter_length_blocks : {12, 20, 30}) {
for (size_t delay_samples : {0, 64, 150, 200, 301}) {
SCOPED_TRACE(ProduceDebugText(1, 1, delay_samples, filter_length_blocks));
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 2500, delay_samples, filter_length_blocks, filter_length_blocks,
false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.1f, echo_to_nearend_power);
}
}
}
}
// Verifies that the subtractor is able to converge on correlated data.
TEST(Subtractor, ConvergenceMultiChannel) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t num_render_channels : {1, 2, 4, 8}) {
for (size_t num_capture_channels : {1, 2, 4}) {
SCOPED_TRACE(
ProduceDebugText(num_render_channels, num_render_channels, 64, 20));
size_t num_blocks_to_process = 2500 * num_render_channels;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
num_render_channels, num_capture_channels, num_blocks_to_process, 64,
20, 20, false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.1f, echo_to_nearend_power);
}
}
}
}
// Verifies that the subtractor is able to handle the case when the main filter
// is longer than the shadow filter.
TEST(Subtractor, MainFilterLongerThanShadowFilter) {
std::vector<int> blocks_with_echo_path_changes;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 400, 64, 20, 15, false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.5f, echo_to_nearend_power);
}
}
// Verifies that the subtractor is able to handle the case when the shadow
// filter is longer than the main filter.
TEST(Subtractor, ShadowFilterLongerThanMainFilter) {
std::vector<int> blocks_with_echo_path_changes;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 400, 64, 15, 20, false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.5f, echo_to_nearend_power);
}
}
// Verifies that the subtractor does not converge on uncorrelated signals.
TEST(Subtractor, NonConvergenceOnUncorrelatedSignals) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t filter_length_blocks : {12, 20, 30}) {
for (size_t delay_samples : {0, 64, 150, 200, 301}) {
SCOPED_TRACE(ProduceDebugText(1, 1, delay_samples, filter_length_blocks));
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 3000, delay_samples, filter_length_blocks, filter_length_blocks,
true, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_NEAR(1.f, echo_to_nearend_power, 0.1);
}
}
}
}
// Verifies that the subtractor does not converge on uncorrelated signals.
TEST(Subtractor, NonConvergenceOnUncorrelatedSignalsMultiChannel) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t num_render_channels : {1, 2, 4}) {
for (size_t num_capture_channels : {1, 2, 4}) {
SCOPED_TRACE(
ProduceDebugText(num_render_channels, num_render_channels, 64, 20));
size_t num_blocks_to_process = 5000 * num_render_channels;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
num_render_channels, num_capture_channels, num_blocks_to_process, 64,
20, 20, true, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_LT(.8f, echo_to_nearend_power);
EXPECT_NEAR(1.f, echo_to_nearend_power, 0.25f);
}
}
}
}
} // namespace webrtc
<commit_msg>Reduce the complexity of the multichannel echo subtractor test<commit_after>/*
* Copyright (c) 2017 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/aec3/subtractor.h"
#include <algorithm>
#include <memory>
#include <numeric>
#include <string>
#include "modules/audio_processing/aec3/aec_state.h"
#include "modules/audio_processing/aec3/render_delay_buffer.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "modules/audio_processing/utility/cascaded_biquad_filter.h"
#include "rtc_base/random.h"
#include "rtc_base/strings/string_builder.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
std::vector<float> RunSubtractorTest(
size_t num_render_channels,
size_t num_capture_channels,
int num_blocks_to_process,
int delay_samples,
int main_filter_length_blocks,
int shadow_filter_length_blocks,
bool uncorrelated_inputs,
const std::vector<int>& blocks_with_echo_path_changes) {
ApmDataDumper data_dumper(42);
constexpr int kSampleRateHz = 48000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
EchoCanceller3Config config;
config.filter.main.length_blocks = main_filter_length_blocks;
config.filter.shadow.length_blocks = shadow_filter_length_blocks;
Subtractor subtractor(config, num_render_channels, num_capture_channels,
&data_dumper, DetectOptimization());
absl::optional<DelayEstimate> delay_estimate;
std::vector<std::vector<std::vector<float>>> x(
kNumBands, std::vector<std::vector<float>>(
num_render_channels, std::vector<float>(kBlockSize, 0.f)));
std::vector<std::vector<float>> y(num_capture_channels,
std::vector<float>(kBlockSize, 0.f));
std::array<float, kBlockSize> x_old;
std::vector<SubtractorOutput> output(num_capture_channels);
config.delay.default_delay = 1;
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, num_render_channels));
RenderSignalAnalyzer render_signal_analyzer(config);
Random random_generator(42U);
Aec3Fft fft;
std::vector<std::array<float, kFftLengthBy2Plus1>> Y2(num_capture_channels);
std::vector<std::array<float, kFftLengthBy2Plus1>> E2_main(
num_capture_channels);
std::array<float, kFftLengthBy2Plus1> E2_shadow;
AecState aec_state(config, num_capture_channels);
x_old.fill(0.f);
for (auto& Y2_ch : Y2) {
Y2_ch.fill(0.f);
}
for (auto& E2_main_ch : E2_main) {
E2_main_ch.fill(0.f);
}
E2_shadow.fill(0.f);
std::vector<std::vector<std::unique_ptr<DelayBuffer<float>>>> delay_buffer(
num_capture_channels);
for (size_t capture_ch = 0; capture_ch < num_capture_channels; ++capture_ch) {
delay_buffer[capture_ch].resize(num_render_channels);
for (size_t render_ch = 0; render_ch < num_render_channels; ++render_ch) {
delay_buffer[capture_ch][render_ch] =
std::make_unique<DelayBuffer<float>>(delay_samples);
}
}
// [B,A] = butter(2,100/8000,'high')
constexpr CascadedBiQuadFilter::BiQuadCoefficients
kHighPassFilterCoefficients = {{0.97261f, -1.94523f, 0.97261f},
{-1.94448f, 0.94598f}};
std::vector<std::unique_ptr<CascadedBiQuadFilter>> x_hp_filter(
num_render_channels);
for (size_t ch = 0; ch < num_render_channels; ++ch) {
x_hp_filter[ch] =
std::make_unique<CascadedBiQuadFilter>(kHighPassFilterCoefficients, 1);
}
std::vector<std::unique_ptr<CascadedBiQuadFilter>> y_hp_filter(
num_capture_channels);
for (size_t ch = 0; ch < num_capture_channels; ++ch) {
y_hp_filter[ch] =
std::make_unique<CascadedBiQuadFilter>(kHighPassFilterCoefficients, 1);
}
for (int k = 0; k < num_blocks_to_process; ++k) {
for (size_t render_ch = 0; render_ch < num_render_channels; ++render_ch) {
RandomizeSampleVector(&random_generator, x[0][render_ch]);
}
if (uncorrelated_inputs) {
for (size_t capture_ch = 0; capture_ch < num_capture_channels;
++capture_ch) {
RandomizeSampleVector(&random_generator, y[capture_ch]);
}
} else {
for (size_t capture_ch = 0; capture_ch < num_capture_channels;
++capture_ch) {
for (size_t render_ch = 0; render_ch < num_render_channels;
++render_ch) {
std::array<float, kBlockSize> y_channel;
delay_buffer[capture_ch][render_ch]->Delay(x[0][render_ch],
y_channel);
for (size_t k = 0; k < y.size(); ++k) {
y[capture_ch][k] += y_channel[k] / num_render_channels;
}
}
}
}
for (size_t ch = 0; ch < num_render_channels; ++ch) {
x_hp_filter[ch]->Process(x[0][ch]);
}
for (size_t ch = 0; ch < num_capture_channels; ++ch) {
y_hp_filter[ch]->Process(y[ch]);
}
render_delay_buffer->Insert(x);
if (k == 0) {
render_delay_buffer->Reset();
}
render_delay_buffer->PrepareCaptureProcessing();
render_signal_analyzer.Update(*render_delay_buffer->GetRenderBuffer(),
aec_state.MinDirectPathFilterDelay());
// Handle echo path changes.
if (std::find(blocks_with_echo_path_changes.begin(),
blocks_with_echo_path_changes.end(),
k) != blocks_with_echo_path_changes.end()) {
subtractor.HandleEchoPathChange(EchoPathVariability(
true, EchoPathVariability::DelayAdjustment::kNewDetectedDelay,
false));
}
subtractor.Process(*render_delay_buffer->GetRenderBuffer(), y,
render_signal_analyzer, aec_state, output);
aec_state.HandleEchoPathChange(EchoPathVariability(
false, EchoPathVariability::DelayAdjustment::kNone, false));
aec_state.Update(delay_estimate, subtractor.FilterFrequencyResponses(),
subtractor.FilterImpulseResponses(),
*render_delay_buffer->GetRenderBuffer(), E2_main, Y2,
output);
}
std::vector<float> results(num_capture_channels);
for (size_t ch = 0; ch < num_capture_channels; ++ch) {
const float output_power =
std::inner_product(output[ch].e_main.begin(), output[ch].e_main.end(),
output[ch].e_main.begin(), 0.f);
const float y_power =
std::inner_product(y[ch].begin(), y[ch].end(), y[ch].begin(), 0.f);
if (y_power == 0.f) {
ADD_FAILURE();
results[ch] = -1.f;
}
results[ch] = output_power / y_power;
}
return results;
}
std::string ProduceDebugText(size_t num_render_channels,
size_t num_capture_channels,
size_t delay,
int filter_length_blocks) {
rtc::StringBuilder ss;
ss << "delay: " << delay << ", ";
ss << "filter_length_blocks:" << filter_length_blocks << ", ";
ss << "num_render_channels:" << num_render_channels << ", ";
ss << "num_capture_channels:" << num_capture_channels;
return ss.Release();
}
} // namespace
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// Verifies that the check for non data dumper works.
TEST(Subtractor, NullDataDumper) {
EXPECT_DEATH(
Subtractor(EchoCanceller3Config(), 1, 1, nullptr, DetectOptimization()),
"");
}
// Verifies the check for the capture signal size.
TEST(Subtractor, WrongCaptureSize) {
ApmDataDumper data_dumper(42);
EchoCanceller3Config config;
Subtractor subtractor(config, 1, 1, &data_dumper, DetectOptimization());
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, 48000, 1));
RenderSignalAnalyzer render_signal_analyzer(config);
std::vector<std::vector<float>> y(1, std::vector<float>(kBlockSize - 1, 0.f));
std::array<SubtractorOutput, 1> output;
EXPECT_DEATH(
subtractor.Process(*render_delay_buffer->GetRenderBuffer(), y,
render_signal_analyzer, AecState(config, 1), output),
"");
}
#endif
// Verifies that the subtractor is able to converge on correlated data.
TEST(Subtractor, Convergence) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t filter_length_blocks : {12, 20, 30}) {
for (size_t delay_samples : {0, 64, 150, 200, 301}) {
SCOPED_TRACE(ProduceDebugText(1, 1, delay_samples, filter_length_blocks));
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 2500, delay_samples, filter_length_blocks, filter_length_blocks,
false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.1f, echo_to_nearend_power);
}
}
}
}
// Verifies that the subtractor is able to converge on correlated data.
TEST(Subtractor, ConvergenceMultiChannel) {
#if defined(NDEBUG)
const size_t kNumRenderChannelsToTest[] = {1, 2, 8};
const size_t kNumCaptureChannelsToTest[] = {1, 2, 4};
#else
const size_t kNumRenderChannelsToTest[] = {1, 2};
const size_t kNumCaptureChannelsToTest[] = {1, 2};
#endif
std::vector<int> blocks_with_echo_path_changes;
for (size_t num_render_channels : kNumRenderChannelsToTest) {
for (size_t num_capture_channels : kNumCaptureChannelsToTest) {
SCOPED_TRACE(
ProduceDebugText(num_render_channels, num_render_channels, 64, 20));
size_t num_blocks_to_process = 2500 * num_render_channels;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
num_render_channels, num_capture_channels, num_blocks_to_process, 64,
20, 20, false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.1f, echo_to_nearend_power);
}
}
}
}
// Verifies that the subtractor is able to handle the case when the main filter
// is longer than the shadow filter.
TEST(Subtractor, MainFilterLongerThanShadowFilter) {
std::vector<int> blocks_with_echo_path_changes;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 400, 64, 20, 15, false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.5f, echo_to_nearend_power);
}
}
// Verifies that the subtractor is able to handle the case when the shadow
// filter is longer than the main filter.
TEST(Subtractor, ShadowFilterLongerThanMainFilter) {
std::vector<int> blocks_with_echo_path_changes;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 400, 64, 15, 20, false, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_GT(0.5f, echo_to_nearend_power);
}
}
// Verifies that the subtractor does not converge on uncorrelated signals.
TEST(Subtractor, NonConvergenceOnUncorrelatedSignals) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t filter_length_blocks : {12, 20, 30}) {
for (size_t delay_samples : {0, 64, 150, 200, 301}) {
SCOPED_TRACE(ProduceDebugText(1, 1, delay_samples, filter_length_blocks));
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
1, 1, 3000, delay_samples, filter_length_blocks, filter_length_blocks,
true, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_NEAR(1.f, echo_to_nearend_power, 0.1);
}
}
}
}
// Verifies that the subtractor does not converge on uncorrelated signals.
TEST(Subtractor, NonConvergenceOnUncorrelatedSignalsMultiChannel) {
std::vector<int> blocks_with_echo_path_changes;
for (size_t num_render_channels : {1, 2, 4}) {
for (size_t num_capture_channels : {1, 2, 4}) {
SCOPED_TRACE(
ProduceDebugText(num_render_channels, num_render_channels, 64, 20));
size_t num_blocks_to_process = 5000 * num_render_channels;
std::vector<float> echo_to_nearend_powers = RunSubtractorTest(
num_render_channels, num_capture_channels, num_blocks_to_process, 64,
20, 20, true, blocks_with_echo_path_changes);
for (float echo_to_nearend_power : echo_to_nearend_powers) {
EXPECT_LT(.8f, echo_to_nearend_power);
EXPECT_NEAR(1.f, echo_to_nearend_power, 0.25f);
}
}
}
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <google/protobuf/descriptor.h>
#include <boost/asio.hpp>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-endpoint-iface.h"
#include "vtrc-server/vtrc-endpoint-tcp.h"
#include "vtrc-server/vtrc-endpoint-unix-local.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-sizepack-policy.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-condition-queues.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-protocol-layer.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "protocol/vtrc-service.pb.h"
#include "vtrc-memory.h"
#include "vtrc-chrono.h"
#include "vtrc-thread.h"
#include "vtrc-server/vtrc-channels.h"
namespace ba = boost::asio;
using namespace vtrc;
struct work_time {
typedef boost::chrono::high_resolution_clock::time_point time_point;
time_point start_;
work_time( )
:start_(boost::chrono::high_resolution_clock::now( ))
{}
~work_time( )
{
time_point stop(boost::chrono::high_resolution_clock::now( ));
std::cout << "call time: " << stop - start_ << "\n";
}
};
void test_send( common::connection_iface *connection,
vtrc::server::application &app )
{
common::connection_iface_sptr s(connection->shared_from_this());
vtrc::shared_ptr<google::protobuf::RpcChannel> ev(
vtrc::server
::channels::unicast
::create_event_channel( s, false ));
const vtrc_rpc_lowlevel::lowlevel_unit *pllu =
common::call_context::get( s )->get_lowlevel_message( );
// vtrc_rpc_lowlevel::lowlevel_unit llu;
// s->get_protocol( ).send_message( llu );
vtrc_service::internal::Stub ping( ev.get( ));
vtrc_service::ping_req preq;
vtrc_service::pong_res pres;
// for( int i=0; i<100; ++i )
// ping.ping( NULL, &preq, &pres, NULL );
try {
//for( ;; )
{
// std::cout << "ping 2 " << vtrc::this_thread::get_id( ) << "\n";
ping.ping( NULL, &preq, &pres, NULL );
}
} catch( std::exception const &ex ) {
// std::cout << "png error " << ex.what( ) << "\n";
}
}
class teat_impl: public vtrc_service::test_rpc {
common::connection_iface *c_;
vtrc::server::application &app_;
unsigned id_;
public:
teat_impl( common::connection_iface *c, vtrc::server::application &app )
:c_(c)
,app_(app)
,id_(0)
{ }
void test(::google::protobuf::RpcController* controller,
const ::vtrc_rpc_lowlevel::message_info* request,
::vtrc_rpc_lowlevel::message_info* response,
::google::protobuf::Closure* done)
{
response->set_message_type( id_++ );
if( (id_ % 100) == 0 )
throw std::runtime_error( "oops 10 =)" );
// vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(200) );
// connection_->get_io_service( ).dispatch(
// vtrc::bind(test_send, connection_));
// boost::thread(test_send, connection_).detach( );
// test_send(c_, app_);
if( done ) done->Run( );
}
virtual void test2(::google::protobuf::RpcController* controller,
const ::vtrc_rpc_lowlevel::message_info* request,
::vtrc_rpc_lowlevel::message_info* response,
::google::protobuf::Closure* done)
{
const vtrc::common::call_context *cc =
vtrc::common::call_context::get( c_ );
// std::cout << "test 2 " << vtrc::this_thread::get_id( ) << "\n\n";
std::cout << std::setw(8) << id_ << " stack: ";
while (cc) {
std::cout << cc->get_lowlevel_message( )->call( ).method_id( )
<< " <- ";
cc = cc->next( );
}
std::cout << "\n";
if( done ) done->Run( );
}
};
class main_app: public vtrc::server::application
{
public:
main_app( common::pool_pair &pp )
:application(pp)
{ }
private:
void on_endpoint_started( vtrc::server::endpoint_iface *ep )
{
std::cout << "Start endpoint: " << ep->string( ) << "\n";
}
void on_endpoint_stopped( vtrc::server::endpoint_iface *ep )
{
std::cout << "Stop endpoint: " << ep->string( ) << "\n";
}
void on_endpoint_exception( vtrc::server::endpoint_iface *ep )
{
try {
throw;
} catch( const std::exception &ex ) {
std::cout << "Endpoint exception '" << ep->string( )
<< "': " << ex.what( ) << "\n";
} catch( ... ) {
throw;
}
}
vtrc::common::rpc_service_wrapper_sptr get_service_by_name(
vtrc::common::connection_iface *connection,
const std::string &service_name)
{
if( service_name == teat_impl::descriptor( )->full_name( ) ) {
return common::rpc_service_wrapper_sptr(
new common::rpc_service_wrapper(
new teat_impl(connection, *this) ) );
}
return common::rpc_service_wrapper_sptr( );
}
};
int main( ) try {
common::pool_pair pp(2, 4);
main_app app(pp);
vtrc::shared_ptr<vtrc::server::endpoint_iface> tcp4_ep
(vtrc::server::endpoints::tcp::create(app, "0.0.0.0", 44667));
vtrc::shared_ptr<vtrc::server::endpoint_iface> tcp6_ep
(vtrc::server::endpoints::tcp::create(app, "::", 44668));
#ifndef _WIN32
std::string file_name("/tmp/test");
::unlink( file_name.c_str( ) );
vtrc::shared_ptr<vtrc::server::endpoint_iface> tcp_ul
(vtrc::server::endpoints::unix_local::create(app, file_name));
::chmod(file_name.c_str( ), 0xFFFFFF );
tcp_ul->start( );
#endif
tcp4_ep->start( );
tcp6_ep->start( );
boost::this_thread::sleep_for( vtrc::chrono::milliseconds(12000) );
std::cout << "Stoppped. Wait ... \n";
#ifndef _WIN32
tcp_ul->stop( );
#endif
tcp4_ep->stop( );
tcp6_ep->stop( );
app.stop_all_clients( );
std::cout << "Stoppped. Wait ... \n";
pp.stop_all( );
pp.join_all( );
google::protobuf::ShutdownProtobufLibrary( );
return 0;
} catch( const std::exception &ex ) {
std::cout << "general error: " << ex.what( ) << "\n";
return 0;
}
<commit_msg>call stack<commit_after>#include <iostream>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <google/protobuf/descriptor.h>
#include <boost/asio.hpp>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-endpoint-iface.h"
#include "vtrc-server/vtrc-endpoint-tcp.h"
#include "vtrc-server/vtrc-endpoint-unix-local.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-sizepack-policy.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-condition-queues.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-protocol-layer.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "protocol/vtrc-service.pb.h"
#include "vtrc-memory.h"
#include "vtrc-chrono.h"
#include "vtrc-thread.h"
#include "vtrc-server/vtrc-channels.h"
namespace ba = boost::asio;
using namespace vtrc;
struct work_time {
typedef boost::chrono::high_resolution_clock::time_point time_point;
time_point start_;
work_time( )
:start_(boost::chrono::high_resolution_clock::now( ))
{}
~work_time( )
{
time_point stop(boost::chrono::high_resolution_clock::now( ));
std::cout << "call time: " << stop - start_ << "\n";
}
};
void test_send( common::connection_iface *connection,
vtrc::server::application &app )
{
common::connection_iface_sptr s(connection->shared_from_this());
vtrc::shared_ptr<google::protobuf::RpcChannel> ev(
vtrc::server
::channels::unicast
::create_event_channel( s, false ));
const vtrc_rpc_lowlevel::lowlevel_unit *pllu =
common::call_context::get( s )->get_lowlevel_message( );
// vtrc_rpc_lowlevel::lowlevel_unit llu;
// s->get_protocol( ).send_message( llu );
vtrc_service::internal::Stub ping( ev.get( ));
vtrc_service::ping_req preq;
vtrc_service::pong_res pres;
// for( int i=0; i<100; ++i )
// ping.ping( NULL, &preq, &pres, NULL );
try {
//for( ;; )
{
// std::cout << "ping 2 " << vtrc::this_thread::get_id( ) << "\n";
ping.ping( NULL, &preq, &pres, NULL );
}
} catch( std::exception const &ex ) {
// std::cout << "png error " << ex.what( ) << "\n";
}
}
class teat_impl: public vtrc_service::test_rpc {
common::connection_iface *c_;
vtrc::server::application &app_;
unsigned id_;
public:
teat_impl( common::connection_iface *c, vtrc::server::application &app )
:c_(c)
,app_(app)
,id_(0)
{ }
void test(::google::protobuf::RpcController* controller,
const ::vtrc_rpc_lowlevel::message_info* request,
::vtrc_rpc_lowlevel::message_info* response,
::google::protobuf::Closure* done)
{
response->set_message_type( id_++ );
if( (id_ % 100) == 0 )
throw std::runtime_error( "oops 10 =)" );
// connection_->get_io_service( ).dispatch(
// vtrc::bind(test_send, connection_));
// boost::thread(test_send, connection_).detach( );
// test_send(c_, app_);
if( done ) done->Run( );
}
virtual void test2(::google::protobuf::RpcController* controller,
const ::vtrc_rpc_lowlevel::message_info* request,
::vtrc_rpc_lowlevel::message_info* response,
::google::protobuf::Closure* done)
{
const vtrc::common::call_context *cc =
vtrc::common::call_context::get( c_ );
// std::cout << "test 2 " << vtrc::this_thread::get_id( ) << "\n\n";
std::cout << std::setw(8) << id_ << " stack: ";
while (cc) {
std::cout << cc->get_lowlevel_message( )->call( ).method_id( )
<< " <- ";
cc = cc->next( );
}
std::cout << "\n";
if( done ) done->Run( );
}
};
class main_app: public vtrc::server::application
{
public:
main_app( common::pool_pair &pp )
:application(pp)
{ }
private:
void on_endpoint_started( vtrc::server::endpoint_iface *ep )
{
std::cout << "Start endpoint: " << ep->string( ) << "\n";
}
void on_endpoint_stopped( vtrc::server::endpoint_iface *ep )
{
std::cout << "Stop endpoint: " << ep->string( ) << "\n";
}
void on_endpoint_exception( vtrc::server::endpoint_iface *ep )
{
try {
throw;
} catch( const std::exception &ex ) {
std::cout << "Endpoint exception '" << ep->string( )
<< "': " << ex.what( ) << "\n";
} catch( ... ) {
throw;
}
}
vtrc::common::rpc_service_wrapper_sptr get_service_by_name(
vtrc::common::connection_iface *connection,
const std::string &service_name)
{
if( service_name == teat_impl::descriptor( )->full_name( ) ) {
return common::rpc_service_wrapper_sptr(
new common::rpc_service_wrapper(
new teat_impl(connection, *this) ) );
}
return common::rpc_service_wrapper_sptr( );
}
};
int main( ) try {
common::pool_pair pp(2, 4);
main_app app(pp);
vtrc::shared_ptr<vtrc::server::endpoint_iface> tcp4_ep
(vtrc::server::endpoints::tcp::create(app, "0.0.0.0", 44667));
vtrc::shared_ptr<vtrc::server::endpoint_iface> tcp6_ep
(vtrc::server::endpoints::tcp::create(app, "::", 44668));
#ifndef _WIN32
std::string file_name("/tmp/test");
::unlink( file_name.c_str( ) );
vtrc::shared_ptr<vtrc::server::endpoint_iface> tcp_ul
(vtrc::server::endpoints::unix_local::create(app, file_name));
::chmod(file_name.c_str( ), 0xFFFFFF );
tcp_ul->start( );
#endif
tcp4_ep->start( );
tcp6_ep->start( );
boost::this_thread::sleep_for( vtrc::chrono::milliseconds(12000) );
std::cout << "Stoppped. Wait ... \n";
#ifndef _WIN32
tcp_ul->stop( );
#endif
tcp4_ep->stop( );
tcp6_ep->stop( );
app.stop_all_clients( );
std::cout << "Stoppped. Wait ... \n";
pp.stop_all( );
pp.join_all( );
google::protobuf::ShutdownProtobufLibrary( );
return 0;
} catch( const std::exception &ex ) {
std::cout << "general error: " << ex.what( ) << "\n";
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Program to draw EE diagrams. *
* This module redraw/draw all structs. *
*****************************************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "class_drawpanel.h"
#include "appl_wxstruct.h"
#include "program.h"
#include "general.h"
#include "protos.h"
#include "class_library.h"
#include "build_version.h"
static EDA_BaseStruct* HighLightStruct = NULL;
void DrawDanglingSymbol( WinEDA_DrawPanel* panel, wxDC* DC,
const wxPoint& pos, int Color )
{
BASE_SCREEN* screen = panel->GetScreen();
if( !screen->m_IsPrinting ) /* Draw but do not print the Dangling Symbol */
{
GRRect( &panel->m_ClipBox, DC,
pos.x - DANGLING_SYMBOL_SIZE, pos.y - DANGLING_SYMBOL_SIZE,
pos.x + DANGLING_SYMBOL_SIZE, pos.y + DANGLING_SYMBOL_SIZE,
0, Color );
}
}
void SetHighLightStruct( EDA_BaseStruct* HighLight )
{
HighLightStruct = HighLight;
}
/*
* Redraws only the active window which is assumed to be whole visible.
*/
void WinEDA_SchematicFrame::RedrawActiveWindow( wxDC* DC, bool EraseBg )
{
wxString title;
if( GetScreen() == NULL )
return;
ActiveScreen = GetScreen();
DrawPanel->DrawBackGround( DC );
RedrawStructList( DrawPanel, DC, GetScreen()->EEDrawList,
GR_DEFAULT_DRAWMODE );
TraceWorkSheet( DC, GetScreen(), g_DrawDefaultLineThickness );
GetScreen()->ClrRefreshReq();
if( DrawPanel->ManageCurseur )
DrawPanel->ManageCurseur( DrawPanel, DC, FALSE );
DrawPanel->DrawCursor( DC );
// Display the sheet filename, and the sheet path, for non root sheets
if( GetScreen()->m_FileName == m_DefaultSchematicFileName )
{
wxString msg = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion();
title.Printf( wxT( "%s [%s]" ), msg.GetData(),
GetScreen()->m_FileName.GetData() );
SetTitle( title );
}
else
{
title = wxT( "[" );
title << GetScreen()->m_FileName << wxT( "] " ) << _( "Sheet" );
title << wxT( " " ) << m_CurrentSheet->PathHumanReadable();
SetTitle( title );
}
}
/**
* PrintPage
* used to print a page.
* Print the page pointed by ActiveScreen, set by the calling print function
* @param aDC = wxDC given by the calling print function
* @param aPrint_Sheet_Ref = true to print page references
* @param aPrintMask = not used here
* @param aPrintMirrorMode = not used here (Set when printing in mirror mode)
* @param aData = a pointer on an auxiliary data (not used here)
*/
void WinEDA_SchematicFrame::PrintPage( wxDC* aDC, bool aPrint_Sheet_Ref,
int aPrintMask, bool aPrintMirrorMode,
void * aData)
{
wxBeginBusyCursor();
RedrawStructList( DrawPanel, aDC, ActiveScreen->EEDrawList, GR_COPY );
if( aPrint_Sheet_Ref )
TraceWorkSheet( aDC, ActiveScreen, g_DrawDefaultLineThickness );
wxEndBusyCursor();
}
/*****************************************************************************
* Routine to redraw list of structs. *
* If the list is of DrawPickStruct types then the picked item are drawn. *
*****************************************************************************/
void RedrawStructList( WinEDA_DrawPanel* panel, wxDC* DC,
SCH_ITEM* Structlist, int DrawMode, int Color )
{
while( Structlist )
{
if( !(Structlist->m_Flags & IS_MOVED) )
{
// uncomment line below when there is a virtual
// EDA_BaseStruct::GetBoundingBox()
// if( panel->m_ClipBox.Intersects( Structs->GetBoundingBox()
// ) )
RedrawOneStruct( panel, DC, Structlist, DrawMode, Color );
}
Structlist = Structlist->Next();
}
}
/*****************************************************************************
* Routine to redraw list of structs. *
*****************************************************************************/
void RedrawOneStruct( WinEDA_DrawPanel* panel, wxDC* DC,
SCH_ITEM* Struct, int DrawMode, int Color )
{
if( Struct == NULL )
return;
if( HighLightStruct == Struct )
Color = HIGHLIGHT_COLOR;
Struct->Draw( panel, DC, wxPoint( 0, 0 ), DrawMode, Color );
}
/* Routine for repainting item in ghost mode. Used in the block moves. */
void DrawStructsInGhost( WinEDA_DrawPanel* aPanel,
wxDC* aDC,
SCH_ITEM* aItem,
const wxPoint& aOffset )
{
int DrawMode = g_XorMode;
int width = g_DrawDefaultLineThickness;
GRSetDrawMode( aDC, DrawMode );
switch( aItem->Type() )
{
case DRAW_POLYLINE_STRUCT_TYPE:
{
SCH_POLYLINE* Struct = (SCH_POLYLINE*) aItem;
GRMoveTo( Struct->m_PolyPoints[0].x + aOffset.x,
Struct->m_PolyPoints[0].y + aOffset.y );
for( unsigned ii = 1; ii < Struct->GetCornerCount(); ii++ )
GRLineTo( &aPanel->m_ClipBox,
aDC,
Struct->m_PolyPoints[ii].x + aOffset.x,
Struct->m_PolyPoints[ii].y + aOffset.y,
width,
g_GhostColor );
break;
}
case DRAW_SEGMENT_STRUCT_TYPE:
{
SCH_LINE* Struct;
Struct = (SCH_LINE*) aItem;
if( (Struct->m_Flags & STARTPOINT) == 0 )
{
GRMoveTo( Struct->m_Start.x + aOffset.x,
Struct->m_Start.y + aOffset.y );
}
else
{
GRMoveTo( Struct->m_Start.x, Struct->m_Start.y );
}
if( (Struct->m_Flags & ENDPOINT) == 0 )
{
GRLineTo( &aPanel->m_ClipBox, aDC, Struct->m_End.x + aOffset.x,
Struct->m_End.y + aOffset.y, width, g_GhostColor );
}
else
{
GRLineTo( &aPanel->m_ClipBox, aDC, Struct->m_End.x,
Struct->m_End.y, width, g_GhostColor );
}
break;
}
case DRAW_BUSENTRY_STRUCT_TYPE:
{
SCH_BUS_ENTRY* Struct = (SCH_BUS_ENTRY*) aItem;
wxPoint start = Struct->m_Pos + aOffset;
GRMoveTo( start.x, start.y );
GRLineTo( &aPanel->m_ClipBox, aDC, Struct->m_Size.x + start.x,
Struct->m_Size.y + start.y, width, g_GhostColor );
break;
}
case DRAW_JUNCTION_STRUCT_TYPE:
{
SCH_JUNCTION* Struct;
Struct = (SCH_JUNCTION*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case TYPE_SCH_TEXT:
{
SCH_TEXT* Struct;
Struct = (SCH_TEXT*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case TYPE_SCH_LABEL:
case TYPE_SCH_GLOBALLABEL:
case TYPE_SCH_HIERLABEL:
{
SCH_LABEL* Struct;
Struct = (SCH_LABEL*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case DRAW_NOCONNECT_STRUCT_TYPE:
{
SCH_NO_CONNECT* Struct;
Struct = (SCH_NO_CONNECT*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case TYPE_SCH_COMPONENT:
{
SCH_COMPONENT* Component = (SCH_COMPONENT*) aItem;
if( Component == NULL )
break;
Component->Draw( aPanel, aDC, aOffset, g_XorMode, g_GhostColor, false );
break;
}
case DRAW_SHEET_STRUCT_TYPE:
{
SCH_SHEET* Struct = (SCH_SHEET*) aItem;
GRRect( &aPanel->m_ClipBox,
aDC,
Struct->m_Pos.x + aOffset.x,
Struct->m_Pos.y + aOffset.y,
Struct->m_Pos.x + Struct->m_Size.x + aOffset.x,
Struct->m_Pos.y + Struct->m_Size.y + aOffset.y,
width,
g_GhostColor );
break;
}
case DRAW_HIERARCHICAL_PIN_SHEET_STRUCT_TYPE:
case TYPE_SCH_MARKER:
break;
default:
break;
}
}
<commit_msg>https://lists.launchpad.net/kicad-developers/msg05013.html<commit_after>/*****************************************************************************
* Program to draw EE diagrams. *
* This module redraw/draw all structs. *
*****************************************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "class_drawpanel.h"
#include "appl_wxstruct.h"
#include "program.h"
#include "general.h"
#include "protos.h"
#include "class_library.h"
#include "build_version.h"
static EDA_BaseStruct* HighLightStruct = NULL;
void DrawDanglingSymbol( WinEDA_DrawPanel* panel, wxDC* DC,
const wxPoint& pos, int Color )
{
BASE_SCREEN* screen = panel->GetScreen();
if( !screen->m_IsPrinting ) /* Draw but do not print the Dangling Symbol */
{
GRRect( &panel->m_ClipBox, DC,
pos.x - DANGLING_SYMBOL_SIZE, pos.y - DANGLING_SYMBOL_SIZE,
pos.x + DANGLING_SYMBOL_SIZE, pos.y + DANGLING_SYMBOL_SIZE,
0, Color );
}
}
void SetHighLightStruct( EDA_BaseStruct* HighLight )
{
HighLightStruct = HighLight;
}
/*
* Redraws only the active window which is assumed to be whole visible.
*/
void WinEDA_SchematicFrame::RedrawActiveWindow( wxDC* DC, bool EraseBg )
{
wxString title;
if( GetScreen() == NULL )
return;
ActiveScreen = GetScreen();
DrawPanel->DrawBackGround( DC );
RedrawStructList( DrawPanel, DC, GetScreen()->EEDrawList,
GR_DEFAULT_DRAWMODE );
TraceWorkSheet( DC, GetScreen(), g_DrawDefaultLineThickness );
GetScreen()->ClrRefreshReq();
if( DrawPanel->ManageCurseur )
DrawPanel->ManageCurseur( DrawPanel, DC, FALSE );
DrawPanel->DrawCursor( DC );
// Display the sheet filename, and the sheet path, for non root sheets
if( GetScreen()->m_FileName == m_DefaultSchematicFileName )
{
wxString msg = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion();
title.Printf( wxT( "%s [%s]" ), msg.GetData(),
GetScreen()->m_FileName.GetData() );
SetTitle( title );
}
else
{
#if 0
title = wxT( "[" );
title << GetScreen()->m_FileName << wxT( "] " ) << _( "Sheet" );
title << wxT( " " ) << m_CurrentSheet->PathHumanReadable();
#else
// Window title format:
// [filename sheetpath] (/path/to/filedir)
// Often the /path/to/filedir is blank because of the FullFileName argument
// passed to LoadOneEEFile() which currently omits the path on non-root schematics.
wxFileName t( GetScreen()->m_FileName );
title = wxChar( '[' );
title << t.GetName() << wxChar( ' ' );
title << m_CurrentSheet->PathHumanReadable() << wxChar( ']' );
title << wxChar( ' ' );
title << wxChar( '(' ) << t.GetPath() << wxChar( ')' );
#endif
SetTitle( title );
}
}
/**
* PrintPage
* used to print a page.
* Print the page pointed by ActiveScreen, set by the calling print function
* @param aDC = wxDC given by the calling print function
* @param aPrint_Sheet_Ref = true to print page references
* @param aPrintMask = not used here
* @param aPrintMirrorMode = not used here (Set when printing in mirror mode)
* @param aData = a pointer on an auxiliary data (not used here)
*/
void WinEDA_SchematicFrame::PrintPage( wxDC* aDC, bool aPrint_Sheet_Ref,
int aPrintMask, bool aPrintMirrorMode,
void * aData)
{
wxBeginBusyCursor();
RedrawStructList( DrawPanel, aDC, ActiveScreen->EEDrawList, GR_COPY );
if( aPrint_Sheet_Ref )
TraceWorkSheet( aDC, ActiveScreen, g_DrawDefaultLineThickness );
wxEndBusyCursor();
}
/*****************************************************************************
* Routine to redraw list of structs. *
* If the list is of DrawPickStruct types then the picked item are drawn. *
*****************************************************************************/
void RedrawStructList( WinEDA_DrawPanel* panel, wxDC* DC,
SCH_ITEM* Structlist, int DrawMode, int Color )
{
while( Structlist )
{
if( !(Structlist->m_Flags & IS_MOVED) )
{
// uncomment line below when there is a virtual
// EDA_BaseStruct::GetBoundingBox()
// if( panel->m_ClipBox.Intersects( Structs->GetBoundingBox()
// ) )
RedrawOneStruct( panel, DC, Structlist, DrawMode, Color );
}
Structlist = Structlist->Next();
}
}
/*****************************************************************************
* Routine to redraw list of structs. *
*****************************************************************************/
void RedrawOneStruct( WinEDA_DrawPanel* panel, wxDC* DC,
SCH_ITEM* Struct, int DrawMode, int Color )
{
if( Struct == NULL )
return;
if( HighLightStruct == Struct )
Color = HIGHLIGHT_COLOR;
Struct->Draw( panel, DC, wxPoint( 0, 0 ), DrawMode, Color );
}
/* Routine for repainting item in ghost mode. Used in the block moves. */
void DrawStructsInGhost( WinEDA_DrawPanel* aPanel,
wxDC* aDC,
SCH_ITEM* aItem,
const wxPoint& aOffset )
{
int DrawMode = g_XorMode;
int width = g_DrawDefaultLineThickness;
GRSetDrawMode( aDC, DrawMode );
switch( aItem->Type() )
{
case DRAW_POLYLINE_STRUCT_TYPE:
{
SCH_POLYLINE* Struct = (SCH_POLYLINE*) aItem;
GRMoveTo( Struct->m_PolyPoints[0].x + aOffset.x,
Struct->m_PolyPoints[0].y + aOffset.y );
for( unsigned ii = 1; ii < Struct->GetCornerCount(); ii++ )
GRLineTo( &aPanel->m_ClipBox,
aDC,
Struct->m_PolyPoints[ii].x + aOffset.x,
Struct->m_PolyPoints[ii].y + aOffset.y,
width,
g_GhostColor );
break;
}
case DRAW_SEGMENT_STRUCT_TYPE:
{
SCH_LINE* Struct;
Struct = (SCH_LINE*) aItem;
if( (Struct->m_Flags & STARTPOINT) == 0 )
{
GRMoveTo( Struct->m_Start.x + aOffset.x,
Struct->m_Start.y + aOffset.y );
}
else
{
GRMoveTo( Struct->m_Start.x, Struct->m_Start.y );
}
if( (Struct->m_Flags & ENDPOINT) == 0 )
{
GRLineTo( &aPanel->m_ClipBox, aDC, Struct->m_End.x + aOffset.x,
Struct->m_End.y + aOffset.y, width, g_GhostColor );
}
else
{
GRLineTo( &aPanel->m_ClipBox, aDC, Struct->m_End.x,
Struct->m_End.y, width, g_GhostColor );
}
break;
}
case DRAW_BUSENTRY_STRUCT_TYPE:
{
SCH_BUS_ENTRY* Struct = (SCH_BUS_ENTRY*) aItem;
wxPoint start = Struct->m_Pos + aOffset;
GRMoveTo( start.x, start.y );
GRLineTo( &aPanel->m_ClipBox, aDC, Struct->m_Size.x + start.x,
Struct->m_Size.y + start.y, width, g_GhostColor );
break;
}
case DRAW_JUNCTION_STRUCT_TYPE:
{
SCH_JUNCTION* Struct;
Struct = (SCH_JUNCTION*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case TYPE_SCH_TEXT:
{
SCH_TEXT* Struct;
Struct = (SCH_TEXT*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case TYPE_SCH_LABEL:
case TYPE_SCH_GLOBALLABEL:
case TYPE_SCH_HIERLABEL:
{
SCH_LABEL* Struct;
Struct = (SCH_LABEL*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case DRAW_NOCONNECT_STRUCT_TYPE:
{
SCH_NO_CONNECT* Struct;
Struct = (SCH_NO_CONNECT*) aItem;
Struct->Draw( aPanel, aDC, aOffset, DrawMode, g_GhostColor );
break;
}
case TYPE_SCH_COMPONENT:
{
SCH_COMPONENT* Component = (SCH_COMPONENT*) aItem;
if( Component == NULL )
break;
Component->Draw( aPanel, aDC, aOffset, g_XorMode, g_GhostColor, false );
break;
}
case DRAW_SHEET_STRUCT_TYPE:
{
SCH_SHEET* Struct = (SCH_SHEET*) aItem;
GRRect( &aPanel->m_ClipBox,
aDC,
Struct->m_Pos.x + aOffset.x,
Struct->m_Pos.y + aOffset.y,
Struct->m_Pos.x + Struct->m_Size.x + aOffset.x,
Struct->m_Pos.y + Struct->m_Size.y + aOffset.y,
width,
g_GhostColor );
break;
}
case DRAW_HIERARCHICAL_PIN_SHEET_STRUCT_TYPE:
case TYPE_SCH_MARKER:
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "schema_fwd.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
#include "partition_version.hh"
#include "tracing/tracing.hh"
#include "row_cache.hh"
namespace cache {
/*
* Represent a flat reader to the underlying source.
* This reader automatically makes sure that it's up to date with all cache updates
*/
class autoupdating_underlying_reader final {
row_cache& _cache;
read_context& _read_context;
flat_mutation_reader_opt _reader;
utils::phased_barrier::phase_type _reader_creation_phase = 0;
dht::partition_range _range = { };
std::optional<dht::decorated_key> _last_key;
std::optional<dht::decorated_key> _new_last_key;
future<> close_reader() noexcept {
return _reader ? _reader->close() : make_ready_future<>();
}
public:
autoupdating_underlying_reader(row_cache& cache, read_context& context)
: _cache(cache)
, _read_context(context)
{ }
future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) {
_last_key = std::move(_new_last_key);
auto start = population_range_start();
auto phase = _cache.phase_of(start);
auto refresh_reader = make_ready_future<>();
if (!_reader || _reader_creation_phase != phase) {
if (_last_key) {
auto cmp = dht::ring_position_comparator(*_cache._schema);
auto&& new_range = _range.split_after(*_last_key, cmp);
if (!new_range) {
return close_reader().then([] {
return make_ready_future<mutation_fragment_opt>();
});
}
_range = std::move(*new_range);
_last_key = {};
}
if (_reader) {
++_cache._tracker._stats.underlying_recreations;
}
refresh_reader = close_reader().then([this, phase] {
_reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range);
_reader_creation_phase = phase;
});
}
return refresh_reader.then([this, timeout] {
return _reader->next_partition().then([this, timeout] {
if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) {
return make_ready_future<mutation_fragment_opt>();
}
return (*_reader)(timeout).then([this] (auto&& mfopt) {
if (mfopt) {
assert(mfopt->is_partition_start());
_new_last_key = mfopt->as_partition_start().key();
}
return std::move(mfopt);
});
});
});
}
future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) {
auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range));
return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout);
}
future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) {
_range = std::move(range);
_last_key = { };
_new_last_key = { };
if (_reader) {
if (_reader_creation_phase == phase) {
++_cache._tracker._stats.underlying_partition_skips;
return _reader->fast_forward_to(_range, timeout);
} else {
++_cache._tracker._stats.underlying_recreations;
}
}
return close_reader().then([this, &snapshot, phase] {
_reader = _cache.create_underlying_reader(_read_context, snapshot, _range);
_reader_creation_phase = phase;
});
}
future<> close() noexcept {
return close_reader();
}
utils::phased_barrier::phase_type creation_phase() const {
return _reader_creation_phase;
}
const dht::partition_range& range() const {
return _range;
}
flat_mutation_reader& underlying() { return *_reader; }
dht::ring_position_view population_range_start() const {
return _last_key ? dht::ring_position_view::for_after_key(*_last_key)
: dht::ring_position_view::for_range_start(_range);
}
};
class read_context final : public enable_lw_shared_from_this<read_context> {
row_cache& _cache;
schema_ptr _schema;
reader_permit _permit;
const dht::partition_range& _range;
const query::partition_slice& _slice;
const io_priority_class& _pc;
tracing::trace_state_ptr _trace_state;
mutation_reader::forwarding _fwd_mr;
bool _range_query;
// When reader enters a partition, it must be set up for reading that
// partition from the underlying mutation source (_underlying) in one of two ways:
//
// 1) either _underlying is already in that partition
//
// 2) _underlying is before the partition, then _underlying_snapshot and _key
// are set so that _underlying_flat can be fast forwarded to the right partition.
//
autoupdating_underlying_reader _underlying;
uint64_t _underlying_created = 0;
mutation_source_opt _underlying_snapshot;
dht::partition_range _sm_range;
std::optional<dht::decorated_key> _key;
bool _partition_exists;
row_cache::phase_type _phase;
public:
read_context(row_cache& cache,
schema_ptr schema,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
mutation_reader::forwarding fwd_mr)
: _cache(cache)
, _schema(std::move(schema))
, _permit(std::move(permit))
, _range(range)
, _slice(slice)
, _pc(pc)
, _trace_state(std::move(trace_state))
, _fwd_mr(fwd_mr)
, _range_query(!query::is_single_partition(range))
, _underlying(_cache, *this)
{
++_cache._tracker._stats.reads;
if (!_range_query) {
_key = range.start()->value().as_decorated_key();
}
}
~read_context() {
++_cache._tracker._stats.reads_done;
if (_underlying_created) {
_cache._stats.reads_with_misses.mark();
++_cache._tracker._stats.reads_with_misses;
} else {
_cache._stats.reads_with_no_misses.mark();
}
}
read_context(const read_context&) = delete;
row_cache& cache() { return _cache; }
const schema_ptr& schema() const { return _schema; }
reader_permit permit() const { return _permit; }
const dht::partition_range& range() const { return _range; }
const query::partition_slice& slice() const { return _slice; }
const io_priority_class& pc() const { return _pc; }
tracing::trace_state_ptr trace_state() const { return _trace_state; }
mutation_reader::forwarding fwd_mr() const { return _fwd_mr; }
bool is_range_query() const { return _range_query; }
autoupdating_underlying_reader& underlying() { return _underlying; }
row_cache::phase_type phase() const { return _phase; }
const dht::decorated_key& key() const { return *_key; }
bool partition_exists() const { return _partition_exists; }
void on_underlying_created() { ++_underlying_created; }
bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); }
public:
future<> ensure_underlying(db::timeout_clock::time_point timeout) {
if (_underlying_snapshot) {
return create_underlying(timeout).then([this, timeout] {
return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) {
_partition_exists = bool(mfopt);
});
});
}
// We know that partition exists because all the callers of
// enter_partition(const dht::decorated_key&, row_cache::phase_type)
// check that and there's no other way of setting _underlying_snapshot
// to empty. Except for calling create_underlying.
_partition_exists = true;
return make_ready_future<>();
}
public:
future<> create_underlying(db::timeout_clock::time_point timeout);
void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = snapshot;
_key = dk;
}
// Precondition: each caller needs to make sure that partition with |dk| key
// exists in underlying before calling this function.
void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = {};
_key = dk;
}
future<> close() noexcept {
return _underlying.close();
}
};
}
<commit_msg>read_context: move_to_next_partition(): make reader creation atomic<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "schema_fwd.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
#include "partition_version.hh"
#include "tracing/tracing.hh"
#include "row_cache.hh"
namespace cache {
/*
* Represent a flat reader to the underlying source.
* This reader automatically makes sure that it's up to date with all cache updates
*/
class autoupdating_underlying_reader final {
row_cache& _cache;
read_context& _read_context;
flat_mutation_reader_opt _reader;
utils::phased_barrier::phase_type _reader_creation_phase = 0;
dht::partition_range _range = { };
std::optional<dht::decorated_key> _last_key;
std::optional<dht::decorated_key> _new_last_key;
future<> close_reader() noexcept {
return _reader ? _reader->close() : make_ready_future<>();
}
public:
autoupdating_underlying_reader(row_cache& cache, read_context& context)
: _cache(cache)
, _read_context(context)
{ }
future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) {
_last_key = std::move(_new_last_key);
auto start = population_range_start();
auto phase = _cache.phase_of(start);
auto refresh_reader = make_ready_future<>();
if (!_reader || _reader_creation_phase != phase) {
if (_last_key) {
auto cmp = dht::ring_position_comparator(*_cache._schema);
auto&& new_range = _range.split_after(*_last_key, cmp);
if (!new_range) {
return close_reader().then([] {
return make_ready_future<mutation_fragment_opt>();
});
}
_range = std::move(*new_range);
_last_key = {};
}
if (_reader) {
++_cache._tracker._stats.underlying_recreations;
}
auto old_reader = std::move(*_reader);
refresh_reader = futurize_invoke([this, phase] () {
_reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range);
_reader_creation_phase = phase;
}).finally([rd = std::move(old_reader)] () mutable {
return rd.close();
});
}
return refresh_reader.then([this, timeout] {
return _reader->next_partition().then([this, timeout] {
if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) {
return make_ready_future<mutation_fragment_opt>();
}
return (*_reader)(timeout).then([this] (auto&& mfopt) {
if (mfopt) {
assert(mfopt->is_partition_start());
_new_last_key = mfopt->as_partition_start().key();
}
return std::move(mfopt);
});
});
});
}
future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) {
auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range));
return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout);
}
future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) {
_range = std::move(range);
_last_key = { };
_new_last_key = { };
if (_reader) {
if (_reader_creation_phase == phase) {
++_cache._tracker._stats.underlying_partition_skips;
return _reader->fast_forward_to(_range, timeout);
} else {
++_cache._tracker._stats.underlying_recreations;
}
}
return close_reader().then([this, &snapshot, phase] {
_reader = _cache.create_underlying_reader(_read_context, snapshot, _range);
_reader_creation_phase = phase;
});
}
future<> close() noexcept {
return close_reader();
}
utils::phased_barrier::phase_type creation_phase() const {
return _reader_creation_phase;
}
const dht::partition_range& range() const {
return _range;
}
flat_mutation_reader& underlying() { return *_reader; }
dht::ring_position_view population_range_start() const {
return _last_key ? dht::ring_position_view::for_after_key(*_last_key)
: dht::ring_position_view::for_range_start(_range);
}
};
class read_context final : public enable_lw_shared_from_this<read_context> {
row_cache& _cache;
schema_ptr _schema;
reader_permit _permit;
const dht::partition_range& _range;
const query::partition_slice& _slice;
const io_priority_class& _pc;
tracing::trace_state_ptr _trace_state;
mutation_reader::forwarding _fwd_mr;
bool _range_query;
// When reader enters a partition, it must be set up for reading that
// partition from the underlying mutation source (_underlying) in one of two ways:
//
// 1) either _underlying is already in that partition
//
// 2) _underlying is before the partition, then _underlying_snapshot and _key
// are set so that _underlying_flat can be fast forwarded to the right partition.
//
autoupdating_underlying_reader _underlying;
uint64_t _underlying_created = 0;
mutation_source_opt _underlying_snapshot;
dht::partition_range _sm_range;
std::optional<dht::decorated_key> _key;
bool _partition_exists;
row_cache::phase_type _phase;
public:
read_context(row_cache& cache,
schema_ptr schema,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
mutation_reader::forwarding fwd_mr)
: _cache(cache)
, _schema(std::move(schema))
, _permit(std::move(permit))
, _range(range)
, _slice(slice)
, _pc(pc)
, _trace_state(std::move(trace_state))
, _fwd_mr(fwd_mr)
, _range_query(!query::is_single_partition(range))
, _underlying(_cache, *this)
{
++_cache._tracker._stats.reads;
if (!_range_query) {
_key = range.start()->value().as_decorated_key();
}
}
~read_context() {
++_cache._tracker._stats.reads_done;
if (_underlying_created) {
_cache._stats.reads_with_misses.mark();
++_cache._tracker._stats.reads_with_misses;
} else {
_cache._stats.reads_with_no_misses.mark();
}
}
read_context(const read_context&) = delete;
row_cache& cache() { return _cache; }
const schema_ptr& schema() const { return _schema; }
reader_permit permit() const { return _permit; }
const dht::partition_range& range() const { return _range; }
const query::partition_slice& slice() const { return _slice; }
const io_priority_class& pc() const { return _pc; }
tracing::trace_state_ptr trace_state() const { return _trace_state; }
mutation_reader::forwarding fwd_mr() const { return _fwd_mr; }
bool is_range_query() const { return _range_query; }
autoupdating_underlying_reader& underlying() { return _underlying; }
row_cache::phase_type phase() const { return _phase; }
const dht::decorated_key& key() const { return *_key; }
bool partition_exists() const { return _partition_exists; }
void on_underlying_created() { ++_underlying_created; }
bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); }
public:
future<> ensure_underlying(db::timeout_clock::time_point timeout) {
if (_underlying_snapshot) {
return create_underlying(timeout).then([this, timeout] {
return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) {
_partition_exists = bool(mfopt);
});
});
}
// We know that partition exists because all the callers of
// enter_partition(const dht::decorated_key&, row_cache::phase_type)
// check that and there's no other way of setting _underlying_snapshot
// to empty. Except for calling create_underlying.
_partition_exists = true;
return make_ready_future<>();
}
public:
future<> create_underlying(db::timeout_clock::time_point timeout);
void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = snapshot;
_key = dk;
}
// Precondition: each caller needs to make sure that partition with |dk| key
// exists in underlying before calling this function.
void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) {
_phase = phase;
_underlying_snapshot = {};
_key = dk;
}
future<> close() noexcept {
return _underlying.close();
}
};
}
<|endoftext|> |
<commit_before>// TODO: add BSD license. This code should be BSD licensed beacuse it uses
// some BSD licensed code, so making it BSD is the simplest thing.
#include <stdio.h>
#include <string.h>
#include <x86intrin.h>
#include <assert.h>
#include "../rdtsc.h"
#define MIN_LEN 256/8
#define MIN_LEN 1048576*16
#define DELTA 4
#define LINE_SIZE 128
#define ITERATIONS 10000
// Mula's SSSE3 implementation core dumps on Mac OS unless it's modified.
#define USE_SOFT
uint64_t buffer[MAX_LEN] __attribute__((aligned(LINE_SIZE)));
void setup_buffer(int len) {
buffer[0] = 1;
buffer[len-1] = 3;
}
// Note: this emits a popcnt with clang 3.4 but not with clang 3.0
uint32_t builtin_popcnt(const uint64_t* buf, int len) {
int cnt = 0;
for (int i = 0; i < len; ++i) {
cnt += __builtin_popcountll(buf[i]);
}
return cnt;
}
uint32_t builtin_popcnt32(const uint64_t* buf64, int len64) {
int cnt = 0;
const uint32_t* buf = (const uint32_t*) buf64;
int len = len64 * 2;
for (int i = 0; i < len; ++i) {
cnt += __builtin_popcount(buf[i]);
}
return cnt;
}
uint32_t builtin_popcnt_unrolled(const uint64_t* buf, int len) {
assert(len % 4 == 0);
int cnt = 0;
for (int i = 0; i < len; i+=4) {
cnt += __builtin_popcountll(buf[i]);
cnt += __builtin_popcountll(buf[i+1]);
cnt += __builtin_popcountll(buf[i+2]);
cnt += __builtin_popcountll(buf[i+3]);
}
return cnt;
}
uint32_t builtin_popcnt_unrolled32(const uint64_t* buf64, int len64) {
const uint32_t* buf = (const uint32_t*) buf64;
int len = len64 * 2;
assert(len % 4 == 0);
int cnt = 0;
for (int i = 0; i < len; i+=4) {
cnt += __builtin_popcount(buf[i]);
cnt += __builtin_popcount(buf[i+1]);
cnt += __builtin_popcount(buf[i+2]);
cnt += __builtin_popcount(buf[i+3]);
}
return cnt;
}
// Attempt to work around false depdency errata.
// gcc is too smart to fall for this and re-creates the dependency unless
// compiled with -funroll-loops or something similar.
// This works with clang, though.
uint32_t builtin_popcnt_unrolled_errata(const uint64_t* buf, int len) {
assert(len % 4 == 0);
int cnt[4];
for (int i = 0; i < 4; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
cnt[0] += __builtin_popcountll(buf[i]);
cnt[1] += __builtin_popcountll(buf[i+1]);
cnt[2] += __builtin_popcountll(buf[i+2]);
cnt[3] += __builtin_popcountll(buf[i+3]);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
// Here's a version that doesn't rely on the compiler not doing
// bad optimizations.
// This code is from Alex Yee.
uint32_t builtin_popcnt_unrolled_errata_manual(const uint64_t* buf, int len) {
assert(len % 4 == 0);
uint64_t cnt[4];
for (int i = 0; i < 4; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
__asm__(
"popcnt %4, %4 \n\t"
"add %4, %0 \n\t"
"popcnt %5, %5 \n\t"
"add %5, %1 \n\t"
"popcnt %6, %6 \n\t"
"add %6, %2 \n\t"
"popcnt %7, %7 \n\t"
"add %7, %3 \n\t"
: "+r" (cnt[0]), "+r" (cnt[1]), "+r" (cnt[2]), "+r" (cnt[3])
: "r" (buf[i]), "r" (buf[i+1]), "r" (buf[i+2]), "r" (buf[i+3])
);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
// This works as intended with clang, but gcc turns the MOVQ intrinsic into an xmm->mem
// operation which defeats the purpose of using MOVQ.
uint32_t builtin_popcnt_movdq(const uint64_t* buf, int len) {
int cnt = 0;
__m128i temp;
__m128i temp2;
uint64_t lower64;
uint64_t upper64;
for (int i = 0; i < len; i+=2) {
temp = _mm_load_si128((__m128i*)&buf[i]);
lower64 = _mm_cvtsi128_si64(temp);
cnt += __builtin_popcountll(lower64);
temp2 = (__m128i)_mm_movehl_ps((__m128)temp, (__m128)temp);
upper64 = _mm_cvtsi128_si64(temp2);
cnt += __builtin_popcountll(upper64);
}
return cnt;
}
// With gcc, this code has the same problem as the previous fn, where movq
// gets translated into an xmm->mem movq.
// Clang handles the movq correctly but it optimizes away the seperate cnt
// variables, causing the popcnt false register dependcy to reduce performance.
uint32_t builtin_popcnt_movdq_unrolled(const uint64_t* buf, int len) {
int cnt[4];
__m128i temp[2];
__m128i temp_upper[2];
uint64_t lower64[2];
uint64_t upper64[2];
for (int i = 0; i < 2; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
temp[0] = _mm_load_si128((__m128i*)&buf[i]);
temp[1] = _mm_load_si128((__m128i*)&buf[i+2]);
lower64[0] = _mm_cvtsi128_si64(temp[0]);
lower64[1] = _mm_cvtsi128_si64(temp[1]);
cnt[0] += __builtin_popcountll(lower64[0]);
cnt[1] += __builtin_popcountll(lower64[1]);
temp_upper[0] = (__m128i)_mm_movehl_ps((__m128)temp[0], (__m128)temp[0]);
temp_upper[1] = (__m128i)_mm_movehl_ps((__m128)temp[1], (__m128)temp[1]);
upper64[0] = _mm_cvtsi128_si64(temp_upper[0]);
upper64[1] = _mm_cvtsi128_si64(temp_upper[1]);
cnt[2] += __builtin_popcountll(upper64[0]);
cnt[3] += __builtin_popcountll(upper64[1]);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
uint32_t builtin_popcnt_movdq_unrolled_manual(const uint64_t* buf, int len) {
uint64_t cnt[4];
__m128i temp_upper[2];
uint64_t lower64[2];
uint64_t upper64[2];
for (int i = 0; i < 2; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
__m128i x0 = _mm_load_si128((__m128i*)&buf[i]);
__m128i x1 = _mm_load_si128((__m128i*)&buf[i+2]);
__m128i x0_upper;
__m128i x1_upper;
uint64_t dummy0;
uint64_t dummy1;
uint64_t dummy0_upper;
uint64_t dummy1_upper;
__asm__(
"movhlps %10, %6 \n\t"
"movhlps %11, %7 \n\t"
"movq %10, %4 \n\t"
"movq %11, %5 \n\t"
"popcnt %4, %4 \n\t"
"add %4, %0 \n\t"
"popcnt %5, %5 \n\t"
"add %5, %1 \n\t"
"movq %6, %8 \n\t"
"movq %7, %9 \n\t"
"popcnt %8, %8 \n\t"
"add %8, %2 \n\t"
"popcnt %9, %9 \n\t"
"add %9, %3 \n\t"
: "+r" (cnt[0]), "+r" (cnt[1]), "+r" (cnt[2]), "+r" (cnt[3]),
"=&r" (dummy0), "=&r" (dummy1), "=x" (x0_upper), "=x" (x1_upper),
"=&r" (dummy0_upper), "=&r" (dummy1_upper)
: "x" (x0), "x" (x1)
);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
int run_and_time_fn(int len, int iterations, uint32_t(*fn)(const uint64_t* buf, int)) {
uint32_t total = 0;
uint64_t tsc_before, tsc_after, tsc, min_tsc;
min_tsc = 0;
min_tsc--;
for (int i = 0; i < iterations; ++i) {
for (int i = 0; i < len; ++i) {
asm volatile("" :: "m" (buffer[i]));
}
RDTSC_START(tsc_before);
total += fn(buffer, len);
RDTSC_STOP(tsc_after);
tsc = tsc_after - tsc_before;
min_tsc = min_tsc < tsc ? min_tsc : tsc;
}
// assert(total == iterations * 3); // Check that we don't have an off by one error.
asm volatile("" :: "m" (total));
return min_tsc;
}
// Code from Wojciech Mula.
// lookup for SSE
uint8_t POPCOUNT_4bit[16] __attribute__((aligned(16))) = {
/* 0 */ 0,
/* 1 */ 1,
/* 2 */ 1,
/* 3 */ 2,
/* 4 */ 1,
/* 5 */ 2,
/* 6 */ 2,
/* 7 */ 3,
/* 8 */ 1,
/* 9 */ 2,
/* a */ 2,
/* b */ 3,
/* c */ 2,
/* d */ 3,
/* e */ 3,
/* f */ 4
};
// ---- SSSE3 - better alorithm, inner loop unrolled ----------------------
uint32_t ssse3_popcount3(uint8_t* buffer, int chunks16) {
static char MASK_4bit[16] = {0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf};
uint32_t result;
#ifdef DEBUG
assert(chunks16 % 4 == 0);
#endif
__asm__ volatile ("movdqu (%%eax), %%xmm7" : : "a" (POPCOUNT_4bit));
__asm__ volatile ("movdqu (%%eax), %%xmm6" : : "a" (MASK_4bit));
__asm__ volatile ("pxor %%xmm5, %%xmm5" : : ); // xmm5 -- global accumulator
result = 0;
int k, n, i;
i = 0;
while (chunks16 > 0) {
// max(POPCOUNT_8bit) = 8, thus byte-wise addition could be done
// for floor(255/8) = 31 iterations
#define MAX (7*4)
if (chunks16 > MAX) {
k = MAX;
chunks16 -= MAX;
}
else {
k = chunks16;
chunks16 = 0;
}
#undef MAX
__asm__ volatile ("pxor %xmm4, %xmm4"); // xmm4 -- local accumulator
for (n=0; n < k; n+=4) {
#define body(index) \
__asm__ volatile( \
"movdqa (%%eax), %%xmm0\n" \
"movdqa %%xmm0, %%xmm1\n" \
"psrlw $4, %%xmm1\n" \
"pand %%xmm6, %%xmm0\n" \
"pand %%xmm6, %%xmm1\n" \
"movdqa %%xmm7, %%xmm2\n" \
"movdqa %%xmm7, %%xmm3\n" \
"pshufb %%xmm0, %%xmm2\n" \
"pshufb %%xmm1, %%xmm3\n" \
"paddb %%xmm2, %%xmm4\n" \
"paddb %%xmm3, %%xmm4\n" \
: : "a" (&buffer[index]));
body(i);
body(i + 1*16);
body(i + 2*16);
body(i + 3*16);
#undef body
i += 4*16;
}
// update global accumulator (two 32-bits counters)
__asm__ volatile (
"pxor %xmm0, %xmm0\n"
"psadbw %xmm0, %xmm4\n"
"paddd %xmm4, %xmm5\n"
);
}
// finally add together 32-bits counters stored in global accumulator
__asm__ volatile (
"movhlps %%xmm5, %%xmm0\n"
"paddd %%xmm5, %%xmm0\n"
"movd %%xmm0, %%eax\n"
: "=a" (result)
);
return result;
}
// End imported code.
int run_mula_popcnt(int len, int iterations) {
// uint8_t buffer[LEN*8] __attribute__((aligned(LINE_SIZE)));
uint32_t total = 0;
uint64_t tsc_before, tsc_after, tsc, min_tsc;
min_tsc = 0;
min_tsc--;
asm volatile("" :: "m" (buffer[0]));
for (int i = 0; i < 1000; ++i) {
RDTSC_START(tsc_before);
total += ssse3_popcount3((uint8_t*)buffer, len/2);
RDTSC_STOP(tsc_after);
tsc = tsc_after - tsc_before;
min_tsc = min_tsc < tsc ? min_tsc : tsc;
}
// assert(total == iterations * 3); // Check that we don't have an off by 1 error.
asm volatile("" :: "m" (total));
return min_tsc;
}
int adjusted_iterations(int len, int iterations) {
int adjusted = iterations * DELTA / len;
return adjusted > 10 ? adjusted : 10;
}
double gb_per_s(int cycles, int len) {
double bytes = len * 8;
return (double) 3.4 * bytes / (double) cycles;
// this 3.4 constant depends on the chip.
}
int main() {
for (int len = MIN_LEN; len <= MAX_LEN; len *= DELTA) {
// int iterations = adjusted_iterations(len, ITERATIONS);
// printf("int %lu long long %lu\n", sizeof(int), sizeof(long long));
int iterations = ITERATIONS;
// printf("builtin32: %.2f\n", run_and_time_fn(len, iterations, &builtin_popcnt32));
printf("bytes: %i\n", 8*len);
printf("builtin: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt), len));
printf("builtin unrolled: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_unrolled), len));
// printf("builtin unrolled32: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_unrolled32));
printf("builtin errata: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_unrolled_errata), len));
printf("builtin manual: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_unrolled_errata_manual), len));
// printf("builtin movdq: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_movdq), len));
// printf("builtin movdq unrolled: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_movdq_unrolled), len));
// printf("builtin movdq manual: %.2f\n", gb_per_s(run_and_time_fn(len, iterations, &builtin_popcnt_movdq_unrolled_manual));
#ifdef USE_SOFT
printf("SSSE3: %.2f\n", gb_per_s(run_mula_popcnt(len, iterations), len));
#endif
}
}
<commit_msg>removed benchmark code from the imported file<commit_after>#include <x86intrin.h>
#include <assert.h>
// Note: this emits a popcnt with clang 3.4 but not with clang 3.0
uint32_t builtin_popcnt(const uint64_t* buf, int len) {
int cnt = 0;
for (int i = 0; i < len; ++i) {
cnt += __builtin_popcountll(buf[i]);
}
return cnt;
}
uint32_t builtin_popcnt32(const uint64_t* buf64, int len64) {
int cnt = 0;
const uint32_t* buf = (const uint32_t*) buf64;
int len = len64 * 2;
for (int i = 0; i < len; ++i) {
cnt += __builtin_popcount(buf[i]);
}
return cnt;
}
uint32_t builtin_popcnt_unrolled(const uint64_t* buf, int len) {
assert(len % 4 == 0);
int cnt = 0;
for (int i = 0; i < len; i+=4) {
cnt += __builtin_popcountll(buf[i]);
cnt += __builtin_popcountll(buf[i+1]);
cnt += __builtin_popcountll(buf[i+2]);
cnt += __builtin_popcountll(buf[i+3]);
}
return cnt;
}
uint32_t builtin_popcnt_unrolled32(const uint64_t* buf64, int len64) {
const uint32_t* buf = (const uint32_t*) buf64;
int len = len64 * 2;
assert(len % 4 == 0);
int cnt = 0;
for (int i = 0; i < len; i+=4) {
cnt += __builtin_popcount(buf[i]);
cnt += __builtin_popcount(buf[i+1]);
cnt += __builtin_popcount(buf[i+2]);
cnt += __builtin_popcount(buf[i+3]);
}
return cnt;
}
// Attempt to work around false depdency errata.
// gcc is too smart to fall for this and re-creates the dependency unless
// compiled with -funroll-loops or something similar.
// This works with clang, though.
uint32_t builtin_popcnt_unrolled_errata(const uint64_t* buf, int len) {
assert(len % 4 == 0);
int cnt[4];
for (int i = 0; i < 4; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
cnt[0] += __builtin_popcountll(buf[i]);
cnt[1] += __builtin_popcountll(buf[i+1]);
cnt[2] += __builtin_popcountll(buf[i+2]);
cnt[3] += __builtin_popcountll(buf[i+3]);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
// Here's a version that doesn't rely on the compiler not doing
// bad optimizations.
// This code is from Alex Yee.
uint32_t builtin_popcnt_unrolled_errata_manual(const uint64_t* buf, int len) {
assert(len % 4 == 0);
uint64_t cnt[4];
for (int i = 0; i < 4; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
__asm__(
"popcnt %4, %4 \n\t"
"add %4, %0 \n\t"
"popcnt %5, %5 \n\t"
"add %5, %1 \n\t"
"popcnt %6, %6 \n\t"
"add %6, %2 \n\t"
"popcnt %7, %7 \n\t"
"add %7, %3 \n\t"
: "+r" (cnt[0]), "+r" (cnt[1]), "+r" (cnt[2]), "+r" (cnt[3])
: "r" (buf[i]), "r" (buf[i+1]), "r" (buf[i+2]), "r" (buf[i+3])
);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
// This works as intended with clang, but gcc turns the MOVQ intrinsic into an xmm->mem
// operation which defeats the purpose of using MOVQ.
uint32_t builtin_popcnt_movdq(const uint64_t* buf, int len) {
int cnt = 0;
__m128i temp;
__m128i temp2;
uint64_t lower64;
uint64_t upper64;
for (int i = 0; i < len; i+=2) {
temp = _mm_load_si128((__m128i*)&buf[i]);
lower64 = _mm_cvtsi128_si64(temp);
cnt += __builtin_popcountll(lower64);
temp2 = (__m128i)_mm_movehl_ps((__m128)temp, (__m128)temp);
upper64 = _mm_cvtsi128_si64(temp2);
cnt += __builtin_popcountll(upper64);
}
return cnt;
}
// With gcc, this code has the same problem as the previous fn, where movq
// gets translated into an xmm->mem movq.
// Clang handles the movq correctly but it optimizes away the seperate cnt
// variables, causing the popcnt false register dependcy to reduce performance.
uint32_t builtin_popcnt_movdq_unrolled(const uint64_t* buf, int len) {
int cnt[4];
__m128i temp[2];
__m128i temp_upper[2];
uint64_t lower64[2];
uint64_t upper64[2];
for (int i = 0; i < 2; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
temp[0] = _mm_load_si128((__m128i*)&buf[i]);
temp[1] = _mm_load_si128((__m128i*)&buf[i+2]);
lower64[0] = _mm_cvtsi128_si64(temp[0]);
lower64[1] = _mm_cvtsi128_si64(temp[1]);
cnt[0] += __builtin_popcountll(lower64[0]);
cnt[1] += __builtin_popcountll(lower64[1]);
temp_upper[0] = (__m128i)_mm_movehl_ps((__m128)temp[0], (__m128)temp[0]);
temp_upper[1] = (__m128i)_mm_movehl_ps((__m128)temp[1], (__m128)temp[1]);
upper64[0] = _mm_cvtsi128_si64(temp_upper[0]);
upper64[1] = _mm_cvtsi128_si64(temp_upper[1]);
cnt[2] += __builtin_popcountll(upper64[0]);
cnt[3] += __builtin_popcountll(upper64[1]);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
uint32_t builtin_popcnt_movdq_unrolled_manual(const uint64_t* buf, int len) {
uint64_t cnt[4];
__m128i temp_upper[2];
uint64_t lower64[2];
uint64_t upper64[2];
for (int i = 0; i < 2; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < len; i+=4) {
__m128i x0 = _mm_load_si128((__m128i*)&buf[i]);
__m128i x1 = _mm_load_si128((__m128i*)&buf[i+2]);
__m128i x0_upper;
__m128i x1_upper;
uint64_t dummy0;
uint64_t dummy1;
uint64_t dummy0_upper;
uint64_t dummy1_upper;
__asm__(
"movhlps %10, %6 \n\t"
"movhlps %11, %7 \n\t"
"movq %10, %4 \n\t"
"movq %11, %5 \n\t"
"popcnt %4, %4 \n\t"
"add %4, %0 \n\t"
"popcnt %5, %5 \n\t"
"add %5, %1 \n\t"
"movq %6, %8 \n\t"
"movq %7, %9 \n\t"
"popcnt %8, %8 \n\t"
"add %8, %2 \n\t"
"popcnt %9, %9 \n\t"
"add %9, %3 \n\t"
: "+r" (cnt[0]), "+r" (cnt[1]), "+r" (cnt[2]), "+r" (cnt[3]),
"=&r" (dummy0), "=&r" (dummy1), "=x" (x0_upper), "=x" (x1_upper),
"=&r" (dummy0_upper), "=&r" (dummy1_upper)
: "x" (x0), "x" (x1)
);
}
return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/dreamview/backend/sim_control/sim_control.h"
#include <cmath>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "modules/canbus/proto/chassis.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/time/time.h"
using apollo::canbus::Chassis;
using apollo::common::math::HeadingToQuaternion;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
using apollo::routing::RoutingResponse;
namespace apollo {
namespace dreamview {
class SimControlTest : public ::testing::Test {
public:
static void SetUpTestCase() {
// init cybertron framework
apollo::cybertron::Init("simulation_world_service_test");
}
virtual void SetUp() {
FLAGS_map_dir = "modules/dreamview/backend/testdata";
FLAGS_base_map_filename = "garage.bin";
map_service_.reset(new MapService(false));
sim_control_.reset(new SimControl(map_service_.get()));
node_ = cybertron::CreateNode("sim_control_test");
chassis_reader_ = node_->CreateReader<Chassis>(FLAGS_chassis_topic);
localization_reader_ =
node_->CreateReader<LocalizationEstimate>(FLAGS_localization_topic);
}
protected:
std::shared_ptr<cybertron::Node> node_;
std::shared_ptr<cybertron::Reader<Chassis>> chassis_reader_;
std::shared_ptr<cybertron::Reader<LocalizationEstimate>> localization_reader_;
std::unique_ptr<MapService> map_service_;
std::unique_ptr<SimControl> sim_control_;
};
void SetTrajectory(const std::vector<double> &xs, const std::vector<double> &ys,
const std::vector<double> &ss, const std::vector<double> &vs,
const std::vector<double> &as,
const std::vector<double> &ths,
const std::vector<double> &ks, const std::vector<double> &ts,
planning::ADCTrajectory *adc_trajectory) {
for (size_t i = 0; i < xs.size(); ++i) {
auto *point = adc_trajectory->add_trajectory_point();
point->mutable_path_point()->set_x(xs[i]);
point->mutable_path_point()->set_y(ys[i]);
point->mutable_path_point()->set_s(ss[i]);
point->set_v(vs[i]);
point->set_a(as[i]);
point->mutable_path_point()->set_theta(ths[i]);
point->mutable_path_point()->set_kappa(ks[i]);
point->set_relative_time(ts[i]);
}
}
TEST_F(SimControlTest, Test) {
sim_control_->Init(false);
sim_control_->enabled_ = true;
planning::ADCTrajectory adc_trajectory;
std::vector<double> xs(5);
std::vector<double> ys(5);
std::vector<double> ss(5);
std::vector<double> vs(5);
std::vector<double> as = {0.0, 0.0, 0.0, 0.0, 0.0};
std::vector<double> ths = {M_PI / 4.0, M_PI / 4.0, M_PI / 4.0, M_PI / 4.0,
M_PI / 4.0};
std::vector<double> kappa_s = {0.0, 0.0, 0.0, 0.0, 0.0};
std::vector<double> ts = {0.0, 0.1, 0.2, 0.3, 0.4};
ss[0] = 0.0;
xs[0] = 0.0;
ys[0] = 0.0;
vs[0] = 10.0;
for (std::size_t i = 1; i < ts.size(); ++i) {
vs[i] = vs[i - 1] + as[i - 1] * ts[i];
ss[i] = (vs[i - 1] + 0.5 * vs[i]) * ts[i];
xs[i] = std::sqrt(ss[i] * ss[i] / 2.0);
ys[i] = std::sqrt(ss[i] * ss[i] / 2.0);
}
SetTrajectory(xs, ys, ss, vs, as, ths, kappa_s, ts, &adc_trajectory);
const double timestamp = 100.0;
adc_trajectory.mutable_header()->set_timestamp_sec(timestamp);
sim_control_->SetStartPoint(adc_trajectory.trajectory_point(0));
sim_control_->OnPlanning(std::make_shared<ADCTrajectory>(adc_trajectory));
{
Clock::SetMode(Clock::MOCK);
const auto timestamp = apollo::common::time::From(100.01);
Clock::SetNow(timestamp.time_since_epoch());
sim_control_->RunOnce();
node_->Observe();
const auto chassis = chassis_reader_->GetLatestObserved();
const auto localization = localization_reader_->GetLatestObserved();
EXPECT_TRUE(chassis->engine_started());
EXPECT_EQ(Chassis::COMPLETE_AUTO_DRIVE, chassis->driving_mode());
EXPECT_EQ(Chassis::GEAR_DRIVE, chassis->gear_location());
EXPECT_NEAR(chassis->speed_mps(), 10.0, 1e-6);
EXPECT_NEAR(chassis->throttle_percentage(), 0.0, 1e-6);
EXPECT_NEAR(chassis->brake_percentage(), 0.0, 1e-6);
const auto &pose = localization->pose();
EXPECT_NEAR(pose.position().x(), 0.10606601717803638, 1e-6);
EXPECT_NEAR(pose.position().y(), 0.10606601717803638, 1e-6);
EXPECT_NEAR(pose.position().z(), 0.0, 1e-6);
const double theta = M_PI / 4.0;
EXPECT_NEAR(pose.heading(), theta, 1e-6);
const Eigen::Quaternion<double> orientation =
HeadingToQuaternion<double>(theta);
EXPECT_NEAR(pose.orientation().qw(), orientation.w(), 1e-6);
EXPECT_NEAR(pose.orientation().qx(), orientation.x(), 1e-6);
EXPECT_NEAR(pose.orientation().qy(), orientation.y(), 1e-6);
EXPECT_NEAR(pose.orientation().qz(), orientation.z(), 1e-6);
const double speed = 10.0;
EXPECT_NEAR(pose.linear_velocity().x(), std::cos(theta) * speed, 1e-6);
EXPECT_NEAR(pose.linear_velocity().y(), std::sin(theta) * speed, 1e-6);
EXPECT_NEAR(pose.linear_velocity().z(), 0.0, 1e-6);
const double curvature = 0.0;
EXPECT_NEAR(pose.angular_velocity().x(), 0.0, 1e-6);
EXPECT_NEAR(pose.angular_velocity().y(), 0.0, 1e-6);
EXPECT_NEAR(pose.angular_velocity().z(), speed * curvature, 1e-6);
const double acceleration_s = 0.0;
EXPECT_NEAR(pose.linear_acceleration().x(),
std::cos(theta) * acceleration_s, 1e-6);
EXPECT_NEAR(pose.linear_acceleration().y(),
std::sin(theta) * acceleration_s, 1e-6);
EXPECT_NEAR(pose.linear_acceleration().z(), 0.0, 1e-6);
}
}
} // namespace dreamview
} // namespace apollo
<commit_msg>fix test with new caros api<commit_after>/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/dreamview/backend/sim_control/sim_control.h"
#include <cmath>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "modules/canbus/proto/chassis.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/time/time.h"
using apollo::canbus::Chassis;
using apollo::common::math::HeadingToQuaternion;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
using apollo::routing::RoutingResponse;
namespace apollo {
namespace dreamview {
class SimControlTest : public ::testing::Test {
public:
static void SetUpTestCase() {
// init cybertron framework
apollo::cybertron::Init("simulation_world_service_test");
}
virtual void SetUp() {
FLAGS_map_dir = "modules/dreamview/backend/testdata";
FLAGS_base_map_filename = "garage.bin";
map_service_.reset(new MapService(false));
sim_control_.reset(new SimControl(map_service_.get()));
node_ = cybertron::CreateNode("sim_control_test");
chassis_reader_ = node_->CreateReader<Chassis>(FLAGS_chassis_topic);
localization_reader_ =
node_->CreateReader<LocalizationEstimate>(FLAGS_localization_topic);
}
protected:
std::shared_ptr<cybertron::Node> node_;
std::shared_ptr<cybertron::Reader<Chassis>> chassis_reader_;
std::shared_ptr<cybertron::Reader<LocalizationEstimate>> localization_reader_;
std::unique_ptr<MapService> map_service_;
std::unique_ptr<SimControl> sim_control_;
};
void SetTrajectory(const std::vector<double> &xs, const std::vector<double> &ys,
const std::vector<double> &ss, const std::vector<double> &vs,
const std::vector<double> &as,
const std::vector<double> &ths,
const std::vector<double> &ks, const std::vector<double> &ts,
planning::ADCTrajectory *adc_trajectory) {
for (size_t i = 0; i < xs.size(); ++i) {
auto *point = adc_trajectory->add_trajectory_point();
point->mutable_path_point()->set_x(xs[i]);
point->mutable_path_point()->set_y(ys[i]);
point->mutable_path_point()->set_s(ss[i]);
point->set_v(vs[i]);
point->set_a(as[i]);
point->mutable_path_point()->set_theta(ths[i]);
point->mutable_path_point()->set_kappa(ks[i]);
point->set_relative_time(ts[i]);
}
}
TEST_F(SimControlTest, Test) {
sim_control_->Init(false);
sim_control_->enabled_ = true;
planning::ADCTrajectory adc_trajectory;
std::vector<double> xs(5);
std::vector<double> ys(5);
std::vector<double> ss(5);
std::vector<double> vs(5);
std::vector<double> as = {0.0, 0.0, 0.0, 0.0, 0.0};
std::vector<double> ths = {M_PI / 4.0, M_PI / 4.0, M_PI / 4.0, M_PI / 4.0,
M_PI / 4.0};
std::vector<double> kappa_s = {0.0, 0.0, 0.0, 0.0, 0.0};
std::vector<double> ts = {0.0, 0.1, 0.2, 0.3, 0.4};
ss[0] = 0.0;
xs[0] = 0.0;
ys[0] = 0.0;
vs[0] = 10.0;
for (std::size_t i = 1; i < ts.size(); ++i) {
vs[i] = vs[i - 1] + as[i - 1] * ts[i];
ss[i] = (vs[i - 1] + 0.5 * vs[i]) * ts[i];
xs[i] = std::sqrt(ss[i] * ss[i] / 2.0);
ys[i] = std::sqrt(ss[i] * ss[i] / 2.0);
}
SetTrajectory(xs, ys, ss, vs, as, ths, kappa_s, ts, &adc_trajectory);
const double timestamp = 100.0;
adc_trajectory.mutable_header()->set_timestamp_sec(timestamp);
sim_control_->SetStartPoint(adc_trajectory.trajectory_point(0));
sim_control_->OnPlanning(std::make_shared<ADCTrajectory>(adc_trajectory));
{
Clock::SetMode(Clock::MOCK);
const auto timestamp = apollo::common::time::From(100.01);
Clock::SetNow(timestamp.time_since_epoch());
sim_control_->RunOnce();
node_->Observe();
int32_t count = 100;
while (count-- > 0 && nullptr == chassis_reader_->GetLatestObserved()) {
usleep(10000);
continue;
}
count = 100;
while (count-- > 0 && nullptr == localization_reader_->GetLatestObserved()) {
usleep(10000);
continue;
}
const auto chassis = chassis_reader_->GetLatestObserved();
const auto localization = localization_reader_->GetLatestObserved();
ASSERT_TRUE(chassis != nullptr);
ASSERT_TRUE(localization != nullptr);
EXPECT_TRUE(chassis->engine_started());
EXPECT_EQ(Chassis::COMPLETE_AUTO_DRIVE, chassis->driving_mode());
EXPECT_EQ(Chassis::GEAR_DRIVE, chassis->gear_location());
EXPECT_NEAR(chassis->speed_mps(), 10.0, 1e-6);
EXPECT_NEAR(chassis->throttle_percentage(), 0.0, 1e-6);
EXPECT_NEAR(chassis->brake_percentage(), 0.0, 1e-6);
const auto &pose = localization->pose();
EXPECT_NEAR(pose.position().x(), 0.10606601717803638, 1e-6);
EXPECT_NEAR(pose.position().y(), 0.10606601717803638, 1e-6);
EXPECT_NEAR(pose.position().z(), 0.0, 1e-6);
const double theta = M_PI / 4.0;
EXPECT_NEAR(pose.heading(), theta, 1e-6);
const Eigen::Quaternion<double> orientation =
HeadingToQuaternion<double>(theta);
EXPECT_NEAR(pose.orientation().qw(), orientation.w(), 1e-6);
EXPECT_NEAR(pose.orientation().qx(), orientation.x(), 1e-6);
EXPECT_NEAR(pose.orientation().qy(), orientation.y(), 1e-6);
EXPECT_NEAR(pose.orientation().qz(), orientation.z(), 1e-6);
const double speed = 10.0;
EXPECT_NEAR(pose.linear_velocity().x(), std::cos(theta) * speed, 1e-6);
EXPECT_NEAR(pose.linear_velocity().y(), std::sin(theta) * speed, 1e-6);
EXPECT_NEAR(pose.linear_velocity().z(), 0.0, 1e-6);
const double curvature = 0.0;
EXPECT_NEAR(pose.angular_velocity().x(), 0.0, 1e-6);
EXPECT_NEAR(pose.angular_velocity().y(), 0.0, 1e-6);
EXPECT_NEAR(pose.angular_velocity().z(), speed * curvature, 1e-6);
const double acceleration_s = 0.0;
EXPECT_NEAR(pose.linear_acceleration().x(),
std::cos(theta) * acceleration_s, 1e-6);
EXPECT_NEAR(pose.linear_acceleration().y(),
std::sin(theta) * acceleration_s, 1e-6);
EXPECT_NEAR(pose.linear_acceleration().z(), 0.0, 1e-6);
}
}
} // namespace dreamview
} // namespace apollo
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/webbrowser/processors/webbrowserprocessor.h>
#include <modules/webbrowser/interaction/cefinteractionhandler.h>
#include <modules/webbrowser/webbrowsermodule.h>
#include <modules/opengl/image/layergl.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/utilities.h>
#include <warn/push>
#include <warn/ignore/all>
#include <include/cef_app.h>
#include <warn/pop>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo WebBrowserProcessor::processorInfo_{
"org.inviwo.webbrowser", // Class identifier
"Web browser", // Display name
"Web", // Category
CodeState::Stable, // Code state
"GL, Web Browser", // Tags
};
const ProcessorInfo WebBrowserProcessor::getProcessorInfo() const { return processorInfo_; }
WebBrowserProcessor::WebBrowserProcessor()
: Processor()
// Output from CEF is 8-bits per channel
, background_("background")
, outport_("webpage", DataVec4UInt8::get())
, fileName_("fileName", "HTML file", "")
, url_("URL", "URL", "http://www.inviwo.org")
, reload_("reload", "Reload")
, addPropertyGroup_("addProperty", "Add property to synchronize")
, type_("property", "Property")
, propertyHtmlId_("propertyHtmlId", "Html id")
, add_("add", "Add")
, sourceType_("sourceType", "Source",
{{"localFile", "Local File", SourceType::LocalFile},
{"webAddress", "Web Address", SourceType::WebAddress}})
, picking_(this, 1, [&](PickingEvent* p) { cefInteractionHandler_.handlePickingEvent(p); })
, cefToInviwoImageConverter_(picking_.getColor())
, renderHandler_(new RenderHandlerGL([&]() {
// Called as soon as new content is available
// Queue an invalidation
// Note: no need to queue invalidation using dispathFront since
// RenderHandler calls will be made from the same thread.
// dispatchFront([&] {
invalidate(InvalidationLevel::InvalidOutput);
//});
}))
, browserClient_(new WebBrowserClient(renderHandler_)) {
addPort(background_);
background_.setOptional(true);
addPort(outport_);
addProperty(sourceType_);
addProperty(fileName_);
addProperty(url_);
url_.setVisible(false);
addProperty(reload_);
sourceType_.onChange([&]() {
switch (sourceType_.get()) {
default:
case SourceType::LocalFile:
fileName_.setVisible(true);
url_.setVisible(false);
break;
case SourceType::WebAddress:
fileName_.setVisible(false);
url_.setVisible(true);
break;
}
invalidate(InvalidationLevel::InvalidResources);
});
// Do not serialize options, they are generated in code
type_.setSerializationMode(PropertySerializationMode::None);
addPropertyGroup_.addProperty(type_);
addPropertyGroup_.addProperty(propertyHtmlId_);
addPropertyGroup_.addProperty(add_);
addProperty(addPropertyGroup_);
// Setup CEF browser
CefWindowInfo window_info;
CefBrowserSettings browserSettings;
browserSettings.windowless_frame_rate = 30; // Must be between 1-60, 30 is default
// in linux set a gtk widget, in windows a hwnd. If not available set nullptr - may cause
// some render errors, in context-menu and plugins.
window_info.SetAsWindowless(nullptr); // nullptr means no transparency (site background colour)
// Note that browserClient_ outlives this class so make sure to remove renderHandler_ in
// destructor
browser_ = CefBrowserHost::CreateBrowserSync(window_info, browserClient_, getSource(),
browserSettings, nullptr);
// Inject events into CEF browser_
cefInteractionHandler_.setHost(browser_->GetHost());
cefInteractionHandler_.setRenderHandler(renderHandler_);
addInteractionHandler(&cefInteractionHandler_);
// Add all supported properties
auto app = InviwoApplication::getPtr();
for (auto propKey : app->getPropertyFactory()->getKeys()) {
auto prop = app->getPropertyFactory()->create(propKey);
if (browserClient_->propertyCefSynchronizer_->htmlWidgetFactory_.hasKey(prop.get())) {
type_.addOption(prop->getClassIdentifier(),
filesystem::getFileExtension(prop->getClassIdentifier()), type_.size());
}
}
propertyHtmlId_ = type_.getSelectedDisplayName();
type_.onChange([&]() { propertyHtmlId_ = type_.getSelectedDisplayName(); });
add_.onChange([&]() {
auto key = type_.getSelectedIdentifier();
auto p = getInviwoApplication()->getPropertyFactory()->create(key);
auto id = propertyHtmlId_.get();
try {
util::validateIdentifier(id, "Property", IvwContext);
} catch (Exception& ex) {
LogError(ex.getMessage());
return;
}
if (getPropertyByIdentifier(id) != nullptr) {
LogError("Property with same id already added");
return;
}
p->setIdentifier(id);
p->setDisplayName(id);
p->setSerializationMode(PropertySerializationMode::All);
// InvalidationLevel::Valid is used to not get
// invalidations from both CEF (html) and Qt
p->setInvalidationLevel(InvalidationLevel::Valid);
// Add property to processor before propertyCefSynchronizer to
// include processor in property path
addProperty(p.get(), true);
browserClient_->propertyCefSynchronizer_->startSynchronize(p.get(), id);
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
p.release();
});
}
std::string WebBrowserProcessor::getSource() {
std::string sourceString;
if (sourceType_.get() == SourceType::LocalFile) {
sourceString = "file://" + fileName_.get();
} else if (sourceType_.get() == SourceType::WebAddress) {
sourceString = url_.get();
}
#ifndef NDEBUG
// CEF does not allow empty urls in debug mode
if (sourceString.empty()) {
sourceString = "https://www.inviwo.org";
}
#endif
return sourceString;
}
WebBrowserProcessor::~WebBrowserProcessor() {
// Force close browser
browser_->GetHost()->CloseBrowser(true);
// Remove render handler since browserClient_ might not be destroyed until CefShutdown() is
// called
browserClient_->SetRenderHandler(NULL);
}
void WebBrowserProcessor::deserialize(Deserializer& d) {
Processor::deserialize(d);
for (auto prop : *this) {
if (prop == &sourceType_ || prop == &fileName_ || prop == &url_ || prop == &reload_ ||
prop == &addPropertyGroup_ || prop == &type_ || prop == &propertyHtmlId_ ||
prop == &add_) {
continue;
}
browserClient_->propertyCefSynchronizer_->startSynchronize(prop, prop->getIdentifier());
}
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
}
void WebBrowserProcessor::process() {
if (fileName_.isModified() || url_.isModified() || reload_.isModified() ||
sourceType_.isModified()) {
browser_->GetMainFrame()->LoadURL(getSource());
}
// Vertical flip of CEF output image
cefToInviwoImageConverter_.convert(renderHandler_->getTexture2D(), outport_, &background_);
}
} // namespace inviwo
<commit_msg>Webbrowser: Enable loading files from other locations than where the .html file is<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/webbrowser/processors/webbrowserprocessor.h>
#include <modules/webbrowser/interaction/cefinteractionhandler.h>
#include <modules/webbrowser/webbrowsermodule.h>
#include <modules/opengl/image/layergl.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/utilities.h>
#include <warn/push>
#include <warn/ignore/all>
#include <include/cef_app.h>
#include <warn/pop>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo WebBrowserProcessor::processorInfo_{
"org.inviwo.webbrowser", // Class identifier
"Web browser", // Display name
"Web", // Category
CodeState::Stable, // Code state
"GL, Web Browser", // Tags
};
const ProcessorInfo WebBrowserProcessor::getProcessorInfo() const { return processorInfo_; }
WebBrowserProcessor::WebBrowserProcessor()
: Processor()
// Output from CEF is 8-bits per channel
, background_("background")
, outport_("webpage", DataVec4UInt8::get())
, fileName_("fileName", "HTML file", "")
, url_("URL", "URL", "http://www.inviwo.org")
, reload_("reload", "Reload")
, addPropertyGroup_("addProperty", "Add property to synchronize")
, type_("property", "Property")
, propertyHtmlId_("propertyHtmlId", "Html id")
, add_("add", "Add")
, sourceType_("sourceType", "Source",
{{"localFile", "Local File", SourceType::LocalFile},
{"webAddress", "Web Address", SourceType::WebAddress}})
, picking_(this, 1, [&](PickingEvent* p) { cefInteractionHandler_.handlePickingEvent(p); })
, cefToInviwoImageConverter_(picking_.getColor())
, renderHandler_(new RenderHandlerGL([&]() {
// Called as soon as new content is available
// Queue an invalidation
// Note: no need to queue invalidation using dispathFront since
// RenderHandler calls will be made from the same thread.
// dispatchFront([&] {
invalidate(InvalidationLevel::InvalidOutput);
//});
}))
, browserClient_(new WebBrowserClient(renderHandler_)) {
addPort(background_);
background_.setOptional(true);
addPort(outport_);
addProperty(sourceType_);
addProperty(fileName_);
addProperty(url_);
url_.setVisible(false);
addProperty(reload_);
sourceType_.onChange([&]() {
switch (sourceType_.get()) {
default:
case SourceType::LocalFile:
fileName_.setVisible(true);
url_.setVisible(false);
break;
case SourceType::WebAddress:
fileName_.setVisible(false);
url_.setVisible(true);
break;
}
invalidate(InvalidationLevel::InvalidResources);
});
// Do not serialize options, they are generated in code
type_.setSerializationMode(PropertySerializationMode::None);
addPropertyGroup_.addProperty(type_);
addPropertyGroup_.addProperty(propertyHtmlId_);
addPropertyGroup_.addProperty(add_);
addProperty(addPropertyGroup_);
// Setup CEF browser
CefWindowInfo window_info;
CefBrowserSettings browserSettings;
// Enable loading files from other locations than where the .html file is
browserSettings.file_access_from_file_urls = STATE_ENABLED;
browserSettings.windowless_frame_rate = 30; // Must be between 1-60, 30 is default
// in linux set a gtk widget, in windows a hwnd. If not available set nullptr - may cause
// some render errors, in context-menu and plugins.
window_info.SetAsWindowless(nullptr); // nullptr means no transparency (site background colour)
// Note that browserClient_ outlives this class so make sure to remove renderHandler_ in
// destructor
browser_ = CefBrowserHost::CreateBrowserSync(window_info, browserClient_, getSource(),
browserSettings, nullptr);
// Inject events into CEF browser_
cefInteractionHandler_.setHost(browser_->GetHost());
cefInteractionHandler_.setRenderHandler(renderHandler_);
addInteractionHandler(&cefInteractionHandler_);
// Add all supported properties
auto app = InviwoApplication::getPtr();
for (auto propKey : app->getPropertyFactory()->getKeys()) {
auto prop = app->getPropertyFactory()->create(propKey);
if (browserClient_->propertyCefSynchronizer_->htmlWidgetFactory_.hasKey(prop.get())) {
type_.addOption(prop->getClassIdentifier(),
filesystem::getFileExtension(prop->getClassIdentifier()), type_.size());
}
}
propertyHtmlId_ = type_.getSelectedDisplayName();
type_.onChange([&]() { propertyHtmlId_ = type_.getSelectedDisplayName(); });
add_.onChange([&]() {
auto key = type_.getSelectedIdentifier();
auto p = getInviwoApplication()->getPropertyFactory()->create(key);
auto id = propertyHtmlId_.get();
try {
util::validateIdentifier(id, "Property", IvwContext);
} catch (Exception& ex) {
LogError(ex.getMessage());
return;
}
if (getPropertyByIdentifier(id) != nullptr) {
LogError("Property with same id already added");
return;
}
p->setIdentifier(id);
p->setDisplayName(id);
p->setSerializationMode(PropertySerializationMode::All);
// InvalidationLevel::Valid is used to not get
// invalidations from both CEF (html) and Qt
p->setInvalidationLevel(InvalidationLevel::Valid);
// Add property to processor before propertyCefSynchronizer to
// include processor in property path
addProperty(p.get(), true);
browserClient_->propertyCefSynchronizer_->startSynchronize(p.get(), id);
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
p.release();
});
}
std::string WebBrowserProcessor::getSource() {
std::string sourceString;
if (sourceType_.get() == SourceType::LocalFile) {
sourceString = "file://" + fileName_.get();
} else if (sourceType_.get() == SourceType::WebAddress) {
sourceString = url_.get();
}
#ifndef NDEBUG
// CEF does not allow empty urls in debug mode
if (sourceString.empty()) {
sourceString = "https://www.inviwo.org";
}
#endif
return sourceString;
}
WebBrowserProcessor::~WebBrowserProcessor() {
// Force close browser
browser_->GetHost()->CloseBrowser(true);
// Remove render handler since browserClient_ might not be destroyed until CefShutdown() is
// called
browserClient_->SetRenderHandler(NULL);
}
void WebBrowserProcessor::deserialize(Deserializer& d) {
Processor::deserialize(d);
for (auto prop : *this) {
if (prop == &sourceType_ || prop == &fileName_ || prop == &url_ || prop == &reload_ ||
prop == &addPropertyGroup_ || prop == &type_ || prop == &propertyHtmlId_ ||
prop == &add_) {
continue;
}
browserClient_->propertyCefSynchronizer_->startSynchronize(prop, prop->getIdentifier());
}
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
}
void WebBrowserProcessor::process() {
if (fileName_.isModified() || url_.isModified() || reload_.isModified() ||
sourceType_.isModified()) {
browser_->GetMainFrame()->LoadURL(getSource());
}
// Vertical flip of CEF output image
cefToInviwoImageConverter_.convert(renderHandler_->getTexture2D(), outport_, &background_);
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*
* This file contains code that is part of the OpenKinect Project.
* http://www.openkinect.org
*
* Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file
* for details.
* Additional code is copyright (c) 2011 Jeff Kramer ([email protected]).
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*
*
*/
#include <iostream>
#include "freenect_fix.hpp"
#include <libfreenect/libfreenect_registration.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <vector>
#include <ctime>
#include <boost/thread/thread.hpp>
#include "pcl/common/common_headers.h"
#include "pcl/common/eigen.h"
#include "pcl/common/transforms.h"
#include "pcl/features/normal_3d.h"
#include "pcl/io/pcd_io.h"
#include "pcl/visualization/pcl_visualizer.h"
#include "pcl/console/parse.h"
#include "pcl/point_types.h"
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>
#include "boost/lexical_cast.hpp"
#include "pcl/filters/voxel_grid.h"
#include <pcl/segmentation/region_growing_rgb.h>
#include <pcl/segmentation/region_growing.h>
#include <boost/thread/mutex.hpp>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/point_types.h>
///Kinect Hardware Connection Class
/* thanks to Yoda---- from IRC */
class MyFreenectDevice : public FreenectFix::FreenectDevice {
public:
MyFreenectDevice(freenect_context *_ctx, int _index)
: FreenectFix::FreenectDevice(_ctx, _index), depth(freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_REGISTERED).bytes),m_buffer_video(freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB).bytes), m_new_rgb_frame(false), m_new_depth_frame(false)
{
}
//~MyFreenectDevice(){}
// Do not call directly even in child
void VideoCallback(void* _rgb, uint32_t timestamp) {
boost::mutex::scoped_lock lock(m_rgb_mutex);
uint8_t* rgb = static_cast<uint8_t*>(_rgb);
std::copy(rgb, rgb+getVideoBufferSize(), m_buffer_video.begin());
m_new_rgb_frame = true;
};
// Do not call directly even in child
void DepthCallback(void* _depth, uint32_t timestamp) {
boost::mutex::scoped_lock lock(m_depth_mutex);
depth.clear();
uint16_t* call_depth = static_cast<uint16_t*>(_depth);
for (size_t i = 0; i < 640*480 ; i++) {
depth.push_back(call_depth[i]);
}
m_new_depth_frame = true;
}
bool getRGB(std::vector<uint8_t> &buffer) {
boost::mutex::scoped_lock lock(m_rgb_mutex);
if (!m_new_rgb_frame)
return false;
buffer.swap(m_buffer_video);
m_new_rgb_frame = false;
return true;
}
bool getDepth(std::vector<uint16_t> &buffer) {
boost::mutex::scoped_lock lock(m_depth_mutex);
if (!m_new_depth_frame)
return false;
buffer.swap(depth);
m_new_depth_frame = false;
return true;
}
private:
std::vector<uint16_t> depth;
std::vector<uint8_t> m_buffer_video;
boost::mutex m_depth_mutex;
boost::mutex m_rgb_mutex;
bool m_new_rgb_frame;
bool m_new_depth_frame;
};
FreenectFix::Freenect freenect;
MyFreenectDevice* device;
//PCL
// --------------
// -----Main-----
// --------------
pcl::PointCloud<pcl::PointXYZRGB>::Ptr vis_cloud;
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
void visualizerThread()
{
while (!viewer->wasStopped ())
{
if(vis_cloud){
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
vis_cloud.swap(cloud);
if(!viewer->updatePointCloud (cloud, "Kinect Cloud")){
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, "Kinect Cloud");
viewer->setPointCloudRenderingProperties
(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "Kinect Cloud");
}
}
viewer->spinOnce ();
}
}
int main (int argc, char** argv)
{
//More Kinect Setup
static std::vector<uint16_t> mdepth(640*480);
static std::vector<uint8_t> mrgb(640*480*4);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::search::Search <pcl::PointXYZRGB>::Ptr tree = boost::shared_ptr<pcl::search::Search<pcl::PointXYZRGB> > (new pcl::search::KdTree<pcl::PointXYZRGB>);
// Fill in the cloud data
cloud->width = 640;
cloud->height = 480;
cloud->is_dense = false;
cloud->points.resize (cloud->width * cloud->height);
// Create and setup the viewer
printf("Create the viewer.\n");
viewer->setBackgroundColor (0, 0, 0);
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
//Voxelizer Setup
printf("Create the devices.\n");
device = &freenect.createDevice<MyFreenectDevice>(0);
//devicetwo = &freenect.createDevice<MyFreenectDevice>(1);
device->startVideo();
device->startDepth();
pcl::VoxelGrid<pcl::PointXYZRGB> vox;
vox.setLeafSize (30.0f, 30.0f, 30.0f);
// Some region growing stuff
/*
pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;
reg.setSearchMethod (tree);
reg.setDistanceThreshold (10);
reg.setPointColorThreshold (6);
reg.setRegionColorThreshold (6);
reg.setMinClusterSize (600);
*/
pcl::PointCloud <pcl::Normal>::Ptr normals (new pcl::PointCloud <pcl::Normal>);
pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> normal_estimator;
normal_estimator.setSearchMethod (tree);
normal_estimator.setKSearch (50);
pcl::RegionGrowing<pcl::PointXYZRGB, pcl::Normal> reg;
reg.setMinClusterSize (500);
// reg.setMaxClusterSize (1000000);
reg.setSearchMethod (tree);
reg.setNumberOfNeighbours (30);
//reg.setIndices (indices);
reg.setSmoothnessThreshold (5.0 / 180.0 * M_PI);
reg.setCurvatureThreshold (2.0);
pcl::SACSegmentation<pcl::PointXYZRGB> seg_plane;
seg_plane.setOptimizeCoefficients (true);
seg_plane.setModelType (pcl::SACMODEL_PLANE);
seg_plane.setMethodType (pcl::SAC_RANSAC);
seg_plane.setDistanceThreshold (10);
seg_plane.setMaxIterations (100);
pcl::SACSegmentationFromNormals<pcl::PointXYZRGB, pcl::Normal> seg_cylinder;
seg_cylinder.setModelType (pcl::SACMODEL_CYLINDER);
seg_cylinder.setMethodType (pcl::SAC_RANSAC);
seg_cylinder.setNormalDistanceWeight (0.1);
seg_cylinder.setMaxIterations (100);
seg_cylinder.setDistanceThreshold (0.05);
seg_cylinder.setRadiusLimits (0, 0.1);
boost::thread thrd1(
boost::bind(&visualizerThread));
//--------------------
// -----Main loop-----
//--------------------
double x = 0;
double y = 0;
double tx = 0;
double ty = 0;
int iRealDepth = 0;
int iTDepth = 0;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::ModelCoefficients::Ptr coefficients_plane (new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers_plane (new pcl::PointIndices);
pcl::ModelCoefficients::Ptr coefficients_cylinder (new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers_cylinder (new pcl::PointIndices);
printf("Start the main loop.\n");
while (!viewer->wasStopped ()){
device->updateState();
device->getDepth(mdepth);
device->getRGB(mrgb);
size_t i = 0;
for (size_t v=0 ; v<480 ; v++)
{
for ( size_t u=0 ; u<640 ; u++, i++)
{
iRealDepth = mdepth[i];
freenect_camera_to_world(device->getDevice(), u, v, iRealDepth, &x, &y);
cloud->points[i].x = x;
cloud->points[i].y = y;
cloud->points[i].z = iRealDepth;
cloud->points[i].r = mrgb[i*3];
cloud->points[i].g = mrgb[(i*3)+1];
cloud->points[i].b = mrgb[(i*3)+2];
}
}
vox.setInputCloud (cloud);
vox.filter (*cloud_filtered);
std::vector <pcl::PointIndices> clusters;
normal_estimator.setInputCloud (cloud_filtered);
normal_estimator.compute (*normals);
reg.setInputCloud (cloud_filtered);
reg.setInputNormals (normals);
reg.extract (clusters);
seg_cylinder.setInputCloud(cloud_filtered);
seg_cylinder.setInputNormals (normals);
seg_plane.setInputCloud(cloud_filtered);
i = 0;
for(std::vector<pcl::PointIndices>::iterator
cluster = clusters.begin();
cluster != clusters.end();
cluster++, i++){
pcl::PointIndices::Ptr clust(new pcl::PointIndices(*cluster));
seg_cylinder.setIndices(clust);
seg_plane.setIndices(clust);
float fsize = clust->indices.size();
seg_cylinder.segment (*inliers_cylinder, *coefficients_cylinder);
seg_plane.segment (*inliers_plane, *coefficients_plane);
cout << "Cluster: "<< i << "Size: " << clust->indices.size() << endl
<< "Cylinder: "
<< float(inliers_cylinder->indices.size())/fsize << endl
<< "Plane "
<< float(inliers_plane->indices.size())/fsize
<< endl;
}
pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();
vis_cloud = colored_cloud;
// cloud_filtered.reset(new pcl::PointCloud<pcl::PointXYZRGB>);
}
thrd1.join();
device->stopVideo();
device->stopDepth();
//devicetwo->stopVideo();
//devicetwo->stopDepth();
return 0;
}
<commit_msg>Color based segmentation works better and added some surfaces<commit_after>/*
* This file contains code that is part of the OpenKinect Project.
* http://www.openkinect.org
*
* Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file
* for details.
* Additional code is copyright (c) 2011 Jeff Kramer ([email protected]).
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*
*
*/
#include <iostream>
#include "freenect_fix.hpp"
#include <libfreenect/libfreenect_registration.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <vector>
#include <ctime>
#include <boost/thread/thread.hpp>
#include "pcl/common/common_headers.h"
#include "pcl/common/eigen.h"
#include "pcl/common/transforms.h"
#include "pcl/features/normal_3d.h"
#include "pcl/io/pcd_io.h"
#include "pcl/visualization/pcl_visualizer.h"
#include "pcl/console/parse.h"
#include "pcl/point_types.h"
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>
#include "boost/lexical_cast.hpp"
#include "pcl/filters/voxel_grid.h"
#include <pcl/segmentation/region_growing_rgb.h>
#include <pcl/segmentation/region_growing.h>
#include <boost/thread/mutex.hpp>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/point_types.h>
#include <pcl/filters/fast_bilateral.h>
#include <pcl/filters/project_inliers.h>
#include <pcl/surface/convex_hull.h>
#include <sstream>
///Kinect Hardware Connection Class
/* thanks to Yoda---- from IRC */
class MyFreenectDevice : public FreenectFix::FreenectDevice {
public:
MyFreenectDevice(freenect_context *_ctx, int _index)
: FreenectFix::FreenectDevice(_ctx, _index), depth(freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_REGISTERED).bytes),m_buffer_video(freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB).bytes), m_new_rgb_frame(false), m_new_depth_frame(false)
{
}
//~MyFreenectDevice(){}
// Do not call directly even in child
void VideoCallback(void* _rgb, uint32_t timestamp) {
boost::mutex::scoped_lock lock(m_rgb_mutex);
uint8_t* rgb = static_cast<uint8_t*>(_rgb);
std::copy(rgb, rgb+getVideoBufferSize(), m_buffer_video.begin());
m_new_rgb_frame = true;
};
// Do not call directly even in child
void DepthCallback(void* _depth, uint32_t timestamp) {
boost::mutex::scoped_lock lock(m_depth_mutex);
depth.clear();
uint16_t* call_depth = static_cast<uint16_t*>(_depth);
for (size_t i = 0; i < 640*480 ; i++) {
depth.push_back(call_depth[i]);
}
m_new_depth_frame = true;
}
bool getRGB(std::vector<uint8_t> &buffer) {
boost::mutex::scoped_lock lock(m_rgb_mutex);
if (!m_new_rgb_frame)
return false;
buffer.swap(m_buffer_video);
m_new_rgb_frame = false;
return true;
}
bool getDepth(std::vector<uint16_t> &buffer) {
boost::mutex::scoped_lock lock(m_depth_mutex);
if (!m_new_depth_frame)
return false;
buffer.swap(depth);
m_new_depth_frame = false;
return true;
}
private:
std::vector<uint16_t> depth;
std::vector<uint8_t> m_buffer_video;
boost::mutex m_depth_mutex;
boost::mutex m_rgb_mutex;
bool m_new_rgb_frame;
bool m_new_depth_frame;
};
FreenectFix::Freenect freenect;
MyFreenectDevice* device;
//PCL
// --------------
// -----Main-----
// --------------
pcl::PointCloud<pcl::PointXYZRGB>::Ptr vis_cloud;
boost::shared_ptr<std::vector<pcl::PolygonMesh::Ptr> > vis_meshes;
void visualizerThread()
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
std::vector<std::string> meshnames;
while (!viewer->wasStopped ())
{
viewer->spinOnce ();
if(vis_cloud){
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
vis_cloud.swap(cloud);
if(!viewer->updatePointCloud (cloud, "Kinect Cloud")){
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, "Kinect Cloud");
viewer->setPointCloudRenderingProperties
(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "Kinect Cloud");
}
}
if(vis_meshes){
boost::shared_ptr<std::vector<pcl::PolygonMesh::Ptr> > meshes;
vis_meshes.swap(meshes);
int i = 0;
for(std::vector<std::string>::iterator it = meshnames.begin();
it != meshnames.end(); it++)
viewer->removePolygonMesh(*it);
meshnames.clear();
for(std::vector<pcl::PolygonMesh::Ptr>::iterator it = meshes->begin();
it != meshes->end();
it++){
//viewer->removePolygonMesh("polygon"+i);
std::stringstream ss;
ss << "polygon"<< i++;
meshnames.push_back(ss.str());
viewer->addPolygonMesh(**it, ss.str());
}
}
}
}
int main (int argc, char** argv)
{
//More Kinect Setup
static std::vector<uint16_t> mdepth(640*480);
static std::vector<uint8_t> mrgb(640*480*4);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::search::Search <pcl::PointXYZRGB>::Ptr tree = boost::shared_ptr<pcl::search::Search<pcl::PointXYZRGB> > (new pcl::search::KdTree<pcl::PointXYZRGB>);
// Fill in the cloud data
cloud->width = 640;
cloud->height = 480;
cloud->is_dense = false;
cloud->points.resize (cloud->width * cloud->height);
// Create and setup the viewer
printf("Create the viewer.\n");
//Voxelizer Setup
printf("Create the devices.\n");
device = &freenect.createDevice<MyFreenectDevice>(0);
//devicetwo = &freenect.createDevice<MyFreenectDevice>(1);
device->startVideo();
device->startDepth();
pcl::VoxelGrid<pcl::PointXYZRGB> vox;
vox.setLeafSize (30.0f, 30.0f, 30.0f);
// Some region growing stuff
pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;
reg.setSearchMethod (tree);
reg.setDistanceThreshold (10);
reg.setPointColorThreshold (6);
reg.setRegionColorThreshold (6);
reg.setMinClusterSize (600);
pcl::PointCloud <pcl::Normal>::Ptr normals (new pcl::PointCloud <pcl::Normal>);
pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> normal_estimator;
normal_estimator.setSearchMethod (tree);
normal_estimator.setKSearch (8);
/*
pcl::RegionGrowing<pcl::PointXYZRGB, pcl::Normal> reg;
reg.setMinClusterSize (50);
reg.setSearchMethod (tree);
reg.setNumberOfNeighbours (8);
reg.setSmoothnessThreshold (30 / 180.0 * M_PI);
reg.setCurvatureThreshold (0.001);
*/
pcl::SACSegmentation<pcl::PointXYZRGB> seg_plane;
seg_plane.setOptimizeCoefficients (true);
seg_plane.setModelType (pcl::SACMODEL_PLANE);
seg_plane.setMethodType (pcl::SAC_RANSAC);
seg_plane.setDistanceThreshold (10);
seg_plane.setMaxIterations (100);
pcl::SACSegmentationFromNormals<pcl::PointXYZRGB, pcl::Normal> seg_cylinder;
seg_cylinder.setModelType (pcl::SACMODEL_CYLINDER);
seg_cylinder.setMethodType (pcl::SAC_RANSAC);
seg_cylinder.setNormalDistanceWeight (0.1);
seg_cylinder.setMaxIterations (100);
seg_cylinder.setDistanceThreshold (0.05);
seg_cylinder.setRadiusLimits (0, 0.1);
boost::thread thrd1(
boost::bind(&visualizerThread));
//--------------------
// -----Main loop-----
//--------------------
double x = 0;
double y = 0;
double tx = 0;
double ty = 0;
int iRealDepth = 0;
int iTDepth = 0;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::ModelCoefficients::Ptr coefficients_plane (new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers_plane (new pcl::PointIndices);
pcl::ModelCoefficients::Ptr coefficients_cylinder (new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers_cylinder (new pcl::PointIndices);
pcl::ConvexHull<pcl::PointXYZRGB> cHull;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_proj (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_hull (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::ProjectInliers<pcl::PointXYZRGB> proj;
proj.setModelType (pcl::SACMODEL_PLANE);
printf("Start the main loop.\n");
while (1){
device->updateState();
device->getDepth(mdepth);
device->getRGB(mrgb);
size_t i = 0;
for (size_t v=0 ; v<480 ; v++)
{
for ( size_t u=0 ; u<640 ; u++, i++)
{
iRealDepth = mdepth[i];
freenect_camera_to_world(device->getDevice(), u, v, iRealDepth, &x, &y);
cloud->points[i].x = x;
cloud->points[i].y = y;
cloud->points[i].z = iRealDepth;
cloud->points[i].r = mrgb[i*3];
cloud->points[i].g = mrgb[(i*3)+1];
cloud->points[i].b = mrgb[(i*3)+2];
}
}
/*
pcl::FastBilateralFilter<pcl::PointXYZRGB> fbf;
fbf.setSigmaS (10.0f);
fbf.setSigmaR (10.0f);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_bfiltered (new pcl::PointCloud<pcl::PointXYZRGB> ());
fbf.setInputCloud (cloud);
fbf.applyFilter (*cloud_bfiltered);
*/
vox.setInputCloud (cloud);
vox.filter (*cloud_filtered);
std::vector <pcl::PointIndices> clusters;
normal_estimator.setInputCloud (cloud_filtered);
normal_estimator.compute (*normals);
reg.setInputCloud (cloud_filtered);
reg.setInputNormals (normals);
reg.extract (clusters);
seg_cylinder.setInputCloud(cloud_filtered);
seg_cylinder.setInputNormals (normals);
seg_plane.setInputCloud(cloud_filtered);
proj.setInputCloud (cloud_filtered);
i = 0;
boost::shared_ptr<std::vector<pcl::PolygonMesh::Ptr> >
meshes(new std::vector<pcl::PolygonMesh::Ptr>());
for(std::vector<pcl::PointIndices>::iterator
cluster = clusters.begin();
cluster != clusters.end();
cluster++, i++){
pcl::PolygonMesh::Ptr mesh(new pcl::PolygonMesh);
pcl::PointIndices::Ptr clust(new pcl::PointIndices(*cluster));
//seg_cylinder.setIndices(clust);
seg_plane.setIndices(clust);
float fsize = clust->indices.size();
seg_plane.segment (*inliers_plane, *coefficients_plane);
proj.setIndices(inliers_plane);
proj.setModelCoefficients (coefficients_plane);
proj.filter (*cloud_proj);
cHull.setInputCloud(cloud_proj);
cHull.reconstruct (*mesh);
meshes->push_back(mesh);
cout << "Cluster: "<< i << "Size: " << clust->indices.size() << endl
<< "Cylinder: "
<< float(inliers_cylinder->indices.size())/fsize << endl
<< "Plane "
<< float(inliers_plane->indices.size())/fsize
<< endl;
}
pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();
vis_cloud = colored_cloud;
vis_meshes = meshes;
// cloud_filtered.reset(new pcl::PointCloud<pcl::PointXYZRGB>);
}
thrd1.join();
device->stopVideo();
device->stopDepth();
//devicetwo->stopVideo();
//devicetwo->stopDepth();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix compiler warning<commit_after><|endoftext|> |
<commit_before><commit_msg>Removing debugging lines<commit_after><|endoftext|> |
<commit_before>// Simple keogram composition program using OpenCV
// Copyright 2018 Jarno Paananen <[email protected]>
// Based on a script by Thomas Jacquin
// SPDX-License-Identifier: MIT
#include <cstdlib>
#include <glob.h>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <vector>
#include <stdio.h>
#ifdef OPENCV_C_HEADERS
#include <opencv2/core/types_c.h>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/imgcodecs/legacy/constants_c.h>
#endif
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
if (argc < 4)
{
std::cout << KRED << "You need to pass 3 arguments: source directory, "
"image extension, output file"
<< std::endl;
std::cout << "Optionally you can pass after them: " << std::endl;
std::cout << " -no-label - Disable hour labels" << std::endl;
std::cout << " -fontname = Font Name - Default = 0 - Font Types "
"(0-7), Ex. 0 = simplex, 4 = triplex, 7 = script"
<< std::endl;
std::cout << " -fontcolor = Font Color - Default = 255 0 0 - Text "
"blue (BRG)"
<< std::endl;
std::cout << " -fonttype = Font Type - Default = 8 - Font Line "
"Type,(0-2), 0 = AA, 1 = 8, 2 = 4"
<< std::endl;
std::cout << " -fontsize - Default = 2.0 - Text Font Size" << std::endl;
std::cout << " -fontline - Default = 3 - Text Font "
"Line Thickness"
<< std::endl;
std::cout << " ex: keogram ../images/current/ jpg keogram.jpg -fontsize 2" << std::endl;
std::cout << " ex: keogram . png /home/pi/allsky/keogram.jpg -no-label" << KNRM << std::endl;
return 3;
}
std::string directory = argv[1];
std::string extension = argv[2];
std::string outputfile = argv[3];
bool labelsEnabled = true;
int fontFace = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
double fontScale = 2;
int fontType = 8;
int thickness = 3;
unsigned char fontColor[3] = { 255, 0, 0 };
// Handle optional parameters
for (int a = 4; a < argc; ++a)
{
if (!strcmp(argv[a], "-no-label"))
{
labelsEnabled = false;
}
else if (!strcmp(argv[a], "-fontname"))
{
fontFace = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-fonttype"))
{
fontType = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-fontsize"))
{
fontScale = atof(argv[++a]);
}
else if (!strcmp(argv[a], "-fontline"))
{
thickness = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-fontcolor"))
{
fontColor[0] = atoi(argv[++a]);
fontColor[1] = atoi(argv[++a]);
fontColor[2] = atoi(argv[++a]);
}
}
glob_t files;
std::string wildcard = directory + "/*." + extension;
glob(wildcard.c_str(), 0, NULL, &files);
if (files.gl_pathc == 0)
{
globfree(&files);
std::cout << "No images found, exiting." << std::endl;
return 0;
}
cv::Mat accumulated;
int prevHour = -1;
for (size_t f = 0; f < files.gl_pathc; f++)
{
cv::Mat image = cv::imread(files.gl_pathv[f], cv::IMREAD_UNCHANGED);
if (!image.data)
{
std::cout << "Error reading file " << basename(files.gl_pathv[f]) << std::endl;
continue;
}
std::cout << "[" << f + 1 << "/" << files.gl_pathc << "] " << basename(files.gl_pathv[f]) << std::endl;
// If we don't have image yet, create one using height and format from
// the source image and width from number of files
if (accumulated.empty())
{
accumulated.create(image.rows, files.gl_pathc, image.type());
}
// Copy middle column to destination
image.col(image.cols / 2).copyTo(accumulated.col(f));
if (labelsEnabled)
{
struct stat s;
stat(files.gl_pathv[f], &s);
struct tm *t = localtime(&s.st_mtime);
if (t->tm_hour != prevHour)
{
if (prevHour != -1)
{
// Draw a dashed line and label for hour
cv::LineIterator it(accumulated, cv::Point(f, 0), cv::Point(f, accumulated.rows));
for (int i = 0; i < it.count; i++, ++it)
{
// 4 pixel dashed line
if (i & 4)
{
uchar *p = *it;
for (int c = 0; c < it.elemSize; c++)
{
*p = ~(*p);
p++;
}
}
}
// Draw text label to the left of the dash
char hour[3];
snprintf(hour, 3, "%02d", t->tm_hour);
std::string text(hour);
int baseline = 0;
cv::Size textSize = cv::getTextSize(text, fontFace, fontScale, thickness, &baseline);
if (f - textSize.width >= 0)
{
cv::putText(accumulated, text,
cv::Point(f - textSize.width, accumulated.rows - textSize.height), fontFace,
fontScale, cv::Scalar(fontColor[0], fontColor[1], fontColor[2]), thickness,
fontType);
}
}
prevHour = t->tm_hour;
}
}
}
globfree(&files);
std::vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
cv::imwrite(outputfile, accumulated, compression_params);
}
<commit_msg>Added a new -rotate optional argument to keogram to compensate camera orientation N-S<commit_after>// Simple keogram composition program using OpenCV
// Copyright 2018 Jarno Paananen <[email protected]>
// Based on a script by Thomas Jacquin
// Rotation added by Agustin Nunez @agnunez
// SPDX-License-Identifier: MIT
#include <cstdlib>
#include <glob.h>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <vector>
#include <stdio.h>
#ifdef OPENCV_C_HEADERS
#include <opencv2/core/types_c.h>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/imgcodecs/legacy/constants_c.h>
#endif
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
if (argc < 4)
{
std::cout << KRED << "You need to pass 3 arguments: source directory, "
"image extension, output file"
<< std::endl;
std::cout << "Optionally you can pass after them: " << std::endl;
std::cout << " -no-label - Disable hour labels" << std::endl;
std::cout << " -fontname = Font Name - Default = 0 - Font Types "
"(0-7), Ex. 0 = simplex, 4 = triplex, 7 = script"
<< std::endl;
std::cout << " -fontcolor = Font Color - Default = 255 0 0 - Text "
"blue (BRG)"
<< std::endl;
std::cout << " -fonttype = Font Type - Default = 8 - Font Line "
"Type,(0-2), 0 = AA, 1 = 8, 2 = 4"
<< std::endl;
std::cout << " -fontsize - Default = 2.0 - Text Font Size" << std::endl;
std::cout << " -fontline - Default = 3 - Text Font "
"Line Thickness"
<< std::endl;
std::cout << " -rotate - Default = 0 - Rotation angle anticlockwise (deg)" << std::endl;
std::cout << " ex: keogram ../images/current/ jpg keogram.jpg -fontsize 2" << std::endl;
std::cout << " ex: keogram . png /home/pi/allsky/keogram.jpg -no-label" << KNRM << std::endl;
return 3;
}
std::string directory = argv[1];
std::string extension = argv[2];
std::string outputfile = argv[3];
bool labelsEnabled = true;
int fontFace = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
double fontScale = 2;
int fontType = 8;
int thickness = 3;
unsigned char fontColor[3] = { 255, 0, 0 };
double angle = 0;
// Handle optional parameters
for (int a = 4; a < argc; ++a)
{
if (!strcmp(argv[a], "-no-label"))
{
labelsEnabled = false;
}
else if (!strcmp(argv[a], "-fontname"))
{
fontFace = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-fonttype"))
{
fontType = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-fontsize"))
{
fontScale = atof(argv[++a]);
}
else if (!strcmp(argv[a], "-fontline"))
{
thickness = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-fontcolor"))
{
fontColor[0] = atoi(argv[++a]);
fontColor[1] = atoi(argv[++a]);
fontColor[2] = atoi(argv[++a]);
}
else if (!strcmp(argv[a], "-rotate"))
{
angle = atoi(argv[++a]);
}
}
glob_t files;
std::string wildcard = directory + "/*." + extension;
glob(wildcard.c_str(), 0, NULL, &files);
if (files.gl_pathc == 0)
{
globfree(&files);
std::cout << "No images found, exiting." << std::endl;
return 0;
}
cv::Mat accumulated;
int prevHour = -1;
for (size_t f = 0; f < files.gl_pathc; f++)
{
cv::Mat imagesrc = cv::imread(files.gl_pathv[f], cv::IMREAD_UNCHANGED);
if (!imagesrc.data)
{
std::cout << "Error reading file " << basename(files.gl_pathv[f]) << std::endl;
continue;
}
std::cout << "[" << f + 1 << "/" << files.gl_pathc << "] " << basename(files.gl_pathv[f]) << std::endl;
//double angle = -36;
cv::Point2f center((imagesrc.cols-1)/2.0, (imagesrc.rows-1)/2.0);
cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
cv::Rect2f bbox = cv::RotatedRect(cv::Point2f(), imagesrc.size(), angle).boundingRect2f();
rot.at<double>(0,2) += bbox.width/2.0 - imagesrc.cols/2.0;
rot.at<double>(1,2) += bbox.height/2.0 - imagesrc.rows/2.0;
cv::Mat imagedst;
cv::warpAffine(imagesrc, imagedst, rot, bbox.size());
if (accumulated.empty())
{
accumulated.create(imagedst.rows, files.gl_pathc, imagesrc.type());
}
// Copy middle column to destination
imagedst.col(imagedst.cols / 2).copyTo(accumulated.col(f));
if (labelsEnabled)
{
struct stat s;
stat(files.gl_pathv[f], &s);
struct tm *t = localtime(&s.st_mtime);
if (t->tm_hour != prevHour)
{
if (prevHour != -1)
{
// Draw a dashed line and label for hour
cv::LineIterator it(accumulated, cv::Point(f, 0), cv::Point(f, accumulated.rows));
for (int i = 0; i < it.count; i++, ++it)
{
// 4 pixel dashed line
if (i & 4)
{
uchar *p = *it;
for (int c = 0; c < it.elemSize; c++)
{
*p = ~(*p);
p++;
}
}
}
// Draw text label to the left of the dash
char hour[3];
snprintf(hour, 3, "%02d", t->tm_hour);
std::string text(hour);
int baseline = 0;
cv::Size textSize = cv::getTextSize(text, fontFace, fontScale, thickness, &baseline);
if (f - textSize.width >= 0)
{
cv::putText(accumulated, text,
cv::Point(f - textSize.width, accumulated.rows - textSize.height), fontFace,
fontScale, cv::Scalar(fontColor[0], fontColor[1], fontColor[2]), thickness,
fontType);
}
}
prevHour = t->tm_hour;
}
}
}
globfree(&files);
std::vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
cv::imwrite(outputfile, accumulated, compression_params);
}
<|endoftext|> |
<commit_before>#ifndef KD_TREE_H
#define KD_TREE_H
#include <list>
#include <queue>
#include <vector>
struct feature {
float x;
float y;
std::vector<float> key;
feature ();
feature (float x, float y, int n);
};
struct kd_node {
kd_node *left;
kd_node *right;
int ki;
float kv;
std::list<int> idx_list; // the list of the feature index
kd_node ();
};
struct mq_node {
kd_node *node;
float dist;
mq_node(kd_node *, float);
};
struct mq_node_comparator {
inline bool operator() (const mq_node& a, const mq_node& b)
{
return a.dist > b.dist;
}
};
class kd_tree {
private :
kd_node *root;
int nKey;
std::vector<feature> feat_list;
void set_partition(kd_node *);
void divide_kd_node(kd_node *);
public :
kd_tree(std::vector<feature> feat_list,gint nKey);
int bbf_search(const feature &feat, const int M=5);
};
#endif
<commit_msg>constructor modified<commit_after>#ifndef KD_TREE_H
#define KD_TREE_H
#include <list>
#include <queue>
#include <vector>
struct feature {
float x;
float y;
std::vector<float> key;
feature ();
feature (float x, float y, int n);
};
struct kd_node {
kd_node *left;
kd_node *right;
int ki;
float kv;
std::list<int> idx_list; // the list of the feature index
kd_node ();
};
struct mq_node {
kd_node *node;
float dist;
mq_node(kd_node *, float);
};
struct mq_node_comparator {
inline bool operator() (const mq_node& a, const mq_node& b)
{
return a.dist > b.dist;
}
};
class kd_tree {
private :
kd_node *root;
int nKey;
std::vector<feature> feat_list;
void set_partition(kd_node *);
void divide_kd_node(kd_node *);
public :
kd_tree(std::vector<feature> feat_list, int nKey);
int bbf_search(const feature &feat, const int M=5);
};
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - T.Feuvrier
Language : C++
Date : 11 janvier 2005
Version :
Role : Test l'extraction d'une ROI dans une image mono canal
$Id$
=========================================================================*/
#include "itkExceptionObject.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "otbExtractImageFilter.h"
#include "itkImage.h"
int otbExtractROIImage( int argc, char ** argv )
{
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
unsigned int startX((unsigned int)::atoi(argv[3]));
unsigned int startY((unsigned int)::atoi(argv[4]));
unsigned int sizeX((unsigned int)::atoi(argv[5]));
unsigned int sizeY((unsigned int)::atoi(argv[6]));
typedef unsigned char InputPixelType;
typedef unsigned char OutputPixelType;
const unsigned int Dimension = 2;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
typedef otb::ExtractImageFilter< InputImageType,
OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetStartX( startX );
filter->SetStartY( startY );
filter->SetSizeX( sizeX );
filter->SetSizeY( sizeY );
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
filter->SetInput( reader->GetOutput() );
writer->SetInput( filter->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<commit_msg>Renommage de la classe d'extraction d'une ROI<commit_after>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - T.Feuvrier
Language : C++
Date : 11 janvier 2005
Version :
Role : Test l'extraction d'une ROI dans une image mono canal, dont les valeurs sont codes en "unsigned char"
$Id$
=========================================================================*/
#include "itkExceptionObject.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "otbExtractROI.h"
#include "itkImage.h"
int otbExtractROI( int argc, char ** argv )
{
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
unsigned int startX((unsigned int)::atoi(argv[3]));
unsigned int startY((unsigned int)::atoi(argv[4]));
unsigned int sizeX((unsigned int)::atoi(argv[5]));
unsigned int sizeY((unsigned int)::atoi(argv[6]));
typedef unsigned char InputPixelType;
typedef unsigned char OutputPixelType;
const unsigned int Dimension = 2;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
typedef otb::ExtractROI< InputImageType,
OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetStartX( startX );
filter->SetStartY( startY );
filter->SetSizeX( sizeX );
filter->SetSizeY( sizeY );
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
filter->SetInput( reader->GetOutput() );
writer->SetInput( filter->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "SSDMetric3rdPartyComponent.h"
#include "GDOptimizer3rdPartyComponent.h"
#include "SSDMetric4thPartyComponent.h"
#include "GDOptimizer4thPartyComponent.h"
#include "gtest/gtest.h"
namespace elx {
class InterfaceTest : public ::testing::Test {
public:
virtual void SetUp() {
metric3p = new SSDMetric3rdPartyComponent();
optimizer3p = new GDOptimizer3rdPartyComponent();
metric4p = new SSDMetric4thPartyComponent();
optimizer4p = new GDOptimizer4thPartyComponent();
}
virtual void TearDown() {
delete metric3p;
delete optimizer3p;
delete metric4p;
delete optimizer4p;
}
// types as if returned by our component factory
ComponentBase* metric3p;
ComponentBase* optimizer3p;
ComponentBase* metric4p;
ComponentBase* optimizer4p;
};
TEST_F( InterfaceTest, InterfaceNameTraits )
{
EXPECT_STREQ(InterfaceName<MetricValueInterface>::Get(), "MetricValueInterface");
EXPECT_STREQ(InterfaceName<InterfaceAcceptor<MetricValueInterface> >::Get(), "MetricValueInterface");
}
TEST_F( InterfaceTest, DynamicCast )
{
int returnval;
//metric3p should have a MetricValueInterface
MetricValueInterface* valueIF = dynamic_cast<MetricValueInterface*> (metric3p);
ASSERT_NE(valueIF, nullptr);
EXPECT_NO_THROW(returnval = valueIF->GetValue());
//metric3p should have a MetricDerivativeInterface
MetricDerivativeInterface* derivativeIF = dynamic_cast<MetricDerivativeInterface*> (metric3p);
ASSERT_NE(derivativeIF, nullptr);
EXPECT_NO_THROW(returnval = derivativeIF->GetDerivative());
//optimizer3p should have a OptimizerUpdateInterface
OptimizerUpdateInterface* updateIF = dynamic_cast<OptimizerUpdateInterface*> (optimizer3p);
ASSERT_NE(updateIF, nullptr);
EXPECT_NO_THROW(returnval = updateIF->Update());
//optimizer3p should have a InterfaceAcceptor<MetricValueInterface>
InterfaceAcceptor<MetricValueInterface>* valueAcceptorIF = dynamic_cast<InterfaceAcceptor<MetricValueInterface>*> (optimizer3p);
ASSERT_NE(valueAcceptorIF, nullptr);
//optimizer3p should have a InterfaceAcceptor<MetricDerivativeInterface>
InterfaceAcceptor<MetricDerivativeInterface>* derivativeAcceptorIF = dynamic_cast<InterfaceAcceptor<MetricDerivativeInterface>*> (optimizer3p);
ASSERT_NE(derivativeAcceptorIF, nullptr);
}
TEST_F( InterfaceTest, ComponentConnecting )
{
interfaceStatus IFstatus;
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricValueInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricValueInterface", metric4p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer4p->ConnectFrom("MetricValueInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer4p->ConnectFrom("MetricValueInterface", metric4p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricDerivativeInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricDerivativeInterface", metric4p));
EXPECT_EQ(IFstatus, interfaceStatus::noprovider);
EXPECT_NO_THROW(IFstatus = optimizer4p->ConnectFrom("MetricDerivativeInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::noaccepter);
}
} // namespace elx
<commit_msg>FIX: some tests<commit_after>#include "SSDMetric3rdPartyComponent.h"
#include "GDOptimizer3rdPartyComponent.h"
#include "SSDMetric4thPartyComponent.h"
#include "GDOptimizer4thPartyComponent.h"
#include "gtest/gtest.h"
namespace elx {
class InterfaceTest : public ::testing::Test {
public:
virtual void SetUp() {
metric3p = new SSDMetric3rdPartyComponent();
optimizer3p = new GDOptimizer3rdPartyComponent();
metric4p = new SSDMetric4thPartyComponent();
optimizer4p = new GDOptimizer4thPartyComponent();
}
virtual void TearDown() {
delete metric3p;
delete optimizer3p;
delete metric4p;
delete optimizer4p;
}
// types as if returned by our component factory
ComponentBase* metric3p;
ComponentBase* optimizer3p;
ComponentBase* metric4p;
ComponentBase* optimizer4p;
};
TEST_F( InterfaceTest, InterfaceNameTraits )
{
EXPECT_STREQ(InterfaceName<MetricValueInterface>::Get(), "MetricValueInterface");
EXPECT_STREQ(InterfaceName<InterfaceAcceptor<MetricValueInterface> >::Get(), "MetricValueInterface");
}
TEST_F( InterfaceTest, DynamicCast )
{
int returnval;
//metric3p should have a MetricValueInterface
MetricValueInterface* valueIF = dynamic_cast<MetricValueInterface*> (metric3p);
ASSERT_NE(valueIF, nullptr);
EXPECT_NO_THROW(returnval = valueIF->GetValue());
//metric3p should have a MetricDerivativeInterface
MetricDerivativeInterface* derivativeIF = dynamic_cast<MetricDerivativeInterface*> (metric3p);
ASSERT_NE(derivativeIF, nullptr);
EXPECT_NO_THROW(returnval = derivativeIF->GetDerivative());
//optimizer3p should have a OptimizerUpdateInterface
OptimizerUpdateInterface* updateIF = dynamic_cast<OptimizerUpdateInterface*> (optimizer3p);
ASSERT_NE(updateIF, nullptr);
//EXPECT_NO_THROW(returnval = updateIF->Update()); // Update can only be called if metric and optimizer are connected
//optimizer3p should have a InterfaceAcceptor<MetricValueInterface>
InterfaceAcceptor<MetricValueInterface>* valueAcceptorIF = dynamic_cast<InterfaceAcceptor<MetricValueInterface>*> (optimizer3p);
ASSERT_NE(valueAcceptorIF, nullptr);
//optimizer3p should have a InterfaceAcceptor<MetricDerivativeInterface>
InterfaceAcceptor<MetricDerivativeInterface>* derivativeAcceptorIF = dynamic_cast<InterfaceAcceptor<MetricDerivativeInterface>*> (optimizer3p);
ASSERT_NE(derivativeAcceptorIF, nullptr);
}
TEST_F( InterfaceTest, ConnectByName )
{
interfaceStatus IFstatus;
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricValueInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricValueInterface", metric4p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer4p->ConnectFrom("MetricValueInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer4p->ConnectFrom("MetricValueInterface", metric4p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricDerivativeInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::success);
EXPECT_NO_THROW(IFstatus = optimizer3p->ConnectFrom("MetricDerivativeInterface", metric4p));
EXPECT_EQ(IFstatus, interfaceStatus::noprovider);
EXPECT_NO_THROW(IFstatus = optimizer4p->ConnectFrom("MetricDerivativeInterface", metric3p));
EXPECT_EQ(IFstatus, interfaceStatus::noaccepter);
}
TEST_F(InterfaceTest, ConnectAll)
{
int connectionCount = 0;
EXPECT_NO_THROW(connectionCount = optimizer3p->ConnectFrom(metric3p));
EXPECT_EQ(connectionCount, 2); // both MetricValueInterface and MetricDerivativeInterface are connected
EXPECT_NO_THROW(connectionCount = optimizer3p->ConnectFrom(metric4p));
EXPECT_EQ(connectionCount, 1); // only MetricValueInterface is connected
EXPECT_NO_THROW(connectionCount = optimizer4p->ConnectFrom(metric3p));
EXPECT_EQ(connectionCount, 1); // only MetricValueInterface is connected
EXPECT_NO_THROW(connectionCount = optimizer4p->ConnectFrom(metric4p));
EXPECT_EQ(connectionCount, 1); // only MetricValueInterface is connected
EXPECT_NO_THROW(connectionCount = metric4p->ConnectFrom(optimizer4p));
EXPECT_EQ(connectionCount, 0); // cannot connect in this direction
}
} // namespace elx
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2015 PX4 Development Team. 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 PX4 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.
*
****************************************************************************/
/**
* @file FixedwingLandDetector.cpp
* Land detection algorithm for fixedwings
*
* @author Johan Jansen <[email protected]>
*/
#include "FixedwingLandDetector.h"
#include <cmath>
#include <drivers/drv_hrt.h>
FixedwingLandDetector::FixedwingLandDetector() : LandDetector(),
_paramHandle(),
_params(),
_vehicleLocalPositionSub(-1),
_vehicleLocalPosition({}),
_airspeedSub(-1),
_airspeed({}),
_parameterSub(-1),
_velocity_xy_filtered(0.0f),
_velocity_z_filtered(0.0f),
_airspeed_filtered(0.0f),
_landDetectTrigger(0)
{
_paramHandle.maxVelocity = param_find("LNDFW_VEL_XY_MAX");
_paramHandle.maxClimbRate = param_find("LNDFW_VEL_Z_MAX");
_paramHandle.maxAirSpeed = param_find("LNDFW_AIRSPD_MAX");
}
void FixedwingLandDetector::initialize()
{
// Subscribe to local position and airspeed data
_vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position));
_airspeedSub = orb_subscribe(ORB_ID(airspeed));
updateParameterCache(true);
}
void FixedwingLandDetector::updateSubscriptions()
{
orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition);
orb_update(ORB_ID(airspeed), _airspeedSub, &_airspeed);
}
bool FixedwingLandDetector::update()
{
// First poll for new data from our subscriptions
updateSubscriptions();
const uint64_t now = hrt_absolute_time();
bool landDetected = false;
if (hrt_elapsed_time(&_vehicleLocalPosition.timestamp) < 500 * 1000) {
float val = 0.95f * _velocity_xy_filtered + 0.05f * sqrtf(_vehicleLocalPosition.vx *
_vehicleLocalPosition.vx + _vehicleLocalPosition.vy * _vehicleLocalPosition.vy);
if (isfinite(val)) {
_velocity_xy_filtered = val;
}
val = 0.95f * _velocity_z_filtered + 0.05f * fabsf(_vehicleLocalPosition.vz);
if (isfinite(val)) {
_velocity_z_filtered = val;
}
}
if (hrt_elapsed_time(&_airspeed.timestamp) < 500 * 1000) {
_airspeed_filtered = 0.95f * _airspeed_filtered + 0.05f * _airspeed.true_airspeed_m_s;
}
// crude land detector for fixedwing
if (_velocity_xy_filtered < _params.maxVelocity
&& _velocity_z_filtered < _params.maxClimbRate
&& _airspeed_filtered < _params.maxAirSpeed) {
// these conditions need to be stable for a period of time before we trust them
if (now > _landDetectTrigger) {
landDetected = true;
}
} else {
// reset land detect trigger
_landDetectTrigger = now + LAND_DETECTOR_TRIGGER_TIME;
}
return landDetected;
}
void FixedwingLandDetector::updateParameterCache(const bool force)
{
bool updated;
parameter_update_s paramUpdate;
orb_check(_parameterSub, &updated);
if (updated) {
orb_copy(ORB_ID(parameter_update), _parameterSub, ¶mUpdate);
}
if (updated || force) {
param_get(_paramHandle.maxVelocity, &_params.maxVelocity);
param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate);
param_get(_paramHandle.maxAirSpeed, &_params.maxAirSpeed);
}
}
<commit_msg>Fixed wing land detector: Filter GPS speeds more since they are unreliable, leave airspeed filter where it was<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2015 PX4 Development Team. 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 PX4 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.
*
****************************************************************************/
/**
* @file FixedwingLandDetector.cpp
* Land detection algorithm for fixedwings
*
* @author Johan Jansen <[email protected]>
*/
#include "FixedwingLandDetector.h"
#include <cmath>
#include <drivers/drv_hrt.h>
FixedwingLandDetector::FixedwingLandDetector() : LandDetector(),
_paramHandle(),
_params(),
_vehicleLocalPositionSub(-1),
_vehicleLocalPosition({}),
_airspeedSub(-1),
_airspeed({}),
_parameterSub(-1),
_velocity_xy_filtered(0.0f),
_velocity_z_filtered(0.0f),
_airspeed_filtered(0.0f),
_landDetectTrigger(0)
{
_paramHandle.maxVelocity = param_find("LNDFW_VEL_XY_MAX");
_paramHandle.maxClimbRate = param_find("LNDFW_VEL_Z_MAX");
_paramHandle.maxAirSpeed = param_find("LNDFW_AIRSPD_MAX");
}
void FixedwingLandDetector::initialize()
{
// Subscribe to local position and airspeed data
_vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position));
_airspeedSub = orb_subscribe(ORB_ID(airspeed));
updateParameterCache(true);
}
void FixedwingLandDetector::updateSubscriptions()
{
orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition);
orb_update(ORB_ID(airspeed), _airspeedSub, &_airspeed);
}
bool FixedwingLandDetector::update()
{
// First poll for new data from our subscriptions
updateSubscriptions();
const uint64_t now = hrt_absolute_time();
bool landDetected = false;
if (hrt_elapsed_time(&_vehicleLocalPosition.timestamp) < 500 * 1000) {
float val = 0.97f * _velocity_xy_filtered + 0.03f * sqrtf(_vehicleLocalPosition.vx *
_vehicleLocalPosition.vx + _vehicleLocalPosition.vy * _vehicleLocalPosition.vy);
if (isfinite(val)) {
_velocity_xy_filtered = val;
}
val = 0.99f * _velocity_z_filtered + 0.01f * fabsf(_vehicleLocalPosition.vz);
if (isfinite(val)) {
_velocity_z_filtered = val;
}
}
if (hrt_elapsed_time(&_airspeed.timestamp) < 500 * 1000) {
_airspeed_filtered = 0.95f * _airspeed_filtered + 0.05f * _airspeed.true_airspeed_m_s;
}
// crude land detector for fixedwing
if (_velocity_xy_filtered < _params.maxVelocity
&& _velocity_z_filtered < _params.maxClimbRate
&& _airspeed_filtered < _params.maxAirSpeed) {
// these conditions need to be stable for a period of time before we trust them
if (now > _landDetectTrigger) {
landDetected = true;
}
} else {
// reset land detect trigger
_landDetectTrigger = now + LAND_DETECTOR_TRIGGER_TIME;
}
return landDetected;
}
void FixedwingLandDetector::updateParameterCache(const bool force)
{
bool updated;
parameter_update_s paramUpdate;
orb_check(_parameterSub, &updated);
if (updated) {
orb_copy(ORB_ID(parameter_update), _parameterSub, ¶mUpdate);
}
if (updated || force) {
param_get(_paramHandle.maxVelocity, &_params.maxVelocity);
param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate);
param_get(_paramHandle.maxAirSpeed, &_params.maxAirSpeed);
}
}
<|endoftext|> |
<commit_before>
#include "Common.h"
#include "BaseLocationManager.h"
#include "InformationManager.h"
#include "MapTools.h"
#include "Global.h"
#include "UnitData.h"
using namespace UAlbertaBot;
BaseLocationManager::BaseLocationManager()
{
onStart();
}
BWAPI::Position BaseLocationManager::calcCenter(const std::vector<BWAPI::Unit> & units)
{
if (units.empty())
{
return BWAPI::Position(0, 0);
}
int cx = 0;
int cy = 0;
for (auto & unit : units)
{
cx += unit->getPosition().x;
cy += unit->getPosition().y;
}
return BWAPI::Position(cx / units.size(), cy / units.size());
}
void BaseLocationManager::onStart()
{
PROFILE_FUNCTION();
m_tileBaseLocations = std::vector<std::vector<BaseLocation *>>(BWAPI::Broodwar->mapWidth(), std::vector<BaseLocation *>(BWAPI::Broodwar->mapHeight(), nullptr));
m_playerStartingBaseLocations[BWAPI::Broodwar->self()] = nullptr;
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = nullptr;
// Use StarDraft to find the borders of the bases on the map
m_baseBorders = BaseBorderFinder(Global::Map().getStarDraftMap());
for (size_t baseID = 0; baseID < m_baseBorders.getBaseBorders().size(); baseID++)
{
const auto & border = m_baseBorders.getBaseBorders()[baseID];
// fill a vector with all the resource units in the border
std::vector<BWAPI::Unit> resources;
// for each static unit on the map
for (auto unit : BWAPI::Broodwar->getStaticNeutralUnits())
{
// if it's a resource
if (unit->getType().isMineralField() || unit->getType() == BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
BWAPI::TilePosition tile(unit->getPosition());
// if it's inside the border, add it to the vector
if (border.contains(tile.x, tile.y))
{
resources.push_back(unit);
}
}
}
// add a baselocation containing these resources
m_baseLocationData.push_back(BaseLocation(baseID, resources));
}
// construct the vectors of base location pointers, this is safe since they will never change
for (auto & baseLocation : m_baseLocationData)
{
m_baseLocationPtrs.push_back(&baseLocation);
// if it's a start location, add it to the start locations
if (baseLocation.isStartLocation())
{
m_startingBaseLocations.push_back(&baseLocation);
}
// if it's our starting location, set the pointer
if (baseLocation.isPlayerStartLocation(BWAPI::Broodwar->self()))
{
m_playerStartingBaseLocations[BWAPI::Broodwar->self()] = &baseLocation;
}
if (baseLocation.isPlayerStartLocation(BWAPI::Broodwar->enemy()))
{
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = &baseLocation;
}
}
// construct the map of tile positions to base locations
for (int x=0; x < BWAPI::Broodwar->mapWidth(); ++x)
{
for (int y = 0; y < BWAPI::Broodwar->mapHeight(); ++y)
{
for (auto & baseLocation : m_baseLocationData)
{
BWAPI::Position pos(BWAPI::TilePosition(x, y));
if (baseLocation.containsPosition(pos))
{
m_tileBaseLocations[x][y] = &baseLocation;
break;
}
}
}
}
// construct the sets of occupied base locations
m_occupiedBaseLocations[BWAPI::Broodwar->self()] = std::set<const BaseLocation *>();
m_occupiedBaseLocations[BWAPI::Broodwar->enemy()] = std::set<const BaseLocation *>();
}
void BaseLocationManager::onFrame()
{
PROFILE_FUNCTION();
drawBaseLocations();
// reset the player occupation information for each location
for (auto & baseLocation : m_baseLocationData)
{
baseLocation.setPlayerOccupying(BWAPI::Broodwar->self(), false);
baseLocation.setPlayerOccupying(BWAPI::Broodwar->self(), false);
}
// for each unit on the map, update which base location it may be occupying
for (auto & unit : BWAPI::Broodwar->self()->getUnits())
{
// we only care about buildings on the ground
if (!unit->getType().isBuilding() || unit->isFlying())
{
continue;
}
BaseLocation * baseLocation = getBaseLocation(unit->getPosition());
if (baseLocation != nullptr)
{
baseLocation->setPlayerOccupying(unit->getPlayer(), true);
}
}
// update enemy base occupations
for (const auto & kv : Global::Info().getUnitInfo(BWAPI::Broodwar->enemy()))
{
const UnitInfo & ui = kv.second;
if (ui.type.isBuilding())
{
continue;
}
BaseLocation * baseLocation = getBaseLocation(ui.lastPosition);
if (baseLocation != nullptr)
{
baseLocation->setPlayerOccupying(BWAPI::Broodwar->enemy(), true);
}
}
// update the starting locations of the enemy player
// this will happen one of two ways:
// 1. we've seen the enemy base directly, so the baselocation will know
if (m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] == nullptr)
{
for (auto & baseLocation : m_baseLocationData)
{
if (baseLocation.isPlayerStartLocation(BWAPI::Broodwar->enemy()))
{
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = &baseLocation;
}
}
}
// 2. we've explored every other start location and haven't seen the enemy yet
if (m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] == nullptr)
{
const int numStartLocations = (int)getStartingBaseLocations().size();
int numExploredLocations = 0;
BaseLocation * unexplored = nullptr;
for (auto & baseLocation : m_baseLocationData)
{
if (!baseLocation.isStartLocation())
{
continue;
}
if (baseLocation.isExplored())
{
numExploredLocations++;
}
else
{
unexplored = &baseLocation;
}
}
// if we have explored all but one location, then the unexplored one is the enemy start location
if (numExploredLocations == numStartLocations - 1 && unexplored != nullptr)
{
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = unexplored;
unexplored->setPlayerOccupying(BWAPI::Broodwar->enemy(), true);
}
}
// update the occupied base locations for each player
m_occupiedBaseLocations[BWAPI::Broodwar->self()] = std::set<const BaseLocation *>();
m_occupiedBaseLocations[BWAPI::Broodwar->enemy()] = std::set<const BaseLocation *>();
for (auto & baseLocation : m_baseLocationData)
{
if (baseLocation.isOccupiedByPlayer(BWAPI::Broodwar->self()))
{
m_occupiedBaseLocations[BWAPI::Broodwar->self()].insert(&baseLocation);
}
if (baseLocation.isOccupiedByPlayer(BWAPI::Broodwar->enemy()))
{
m_occupiedBaseLocations[BWAPI::Broodwar->enemy()].insert(&baseLocation);
}
}
// sanity check: make sure we have as many starting locations as BWAPI says
if (getStartingBaseLocations().size() != BWAPI::Broodwar->getStartLocations().size())
{
std::cout << "\nWARNING: BaseLocationManager start location mismatch\n";
std::cout << " BaseLocationManager found " << getStartingBaseLocations().size() << " starting locations\n";
std::cout << " BWAPI says that there are " << BWAPI::Broodwar->getStartLocations().size() << " starting locations\n\n";
for (auto tp : BWAPI::Broodwar->getStartLocations())
{
BWAPI::Broodwar->drawCircleMap(BWAPI::Position(tp), 64, BWAPI::Colors::Red, true);
}
}
}
BaseLocation * BaseLocationManager::getBaseLocation(const BWAPI::Position & pos) const
{
if (!pos.isValid()) { return nullptr; }
return m_tileBaseLocations[pos.x / 32][pos.y / 32];
}
void BaseLocationManager::drawBaseLocations()
{
for (auto & baseLocation : m_baseLocationData)
{
baseLocation.draw();
}
// draw a purple sphere at the next expansion location
//BWAPI::TilePosition nextExpansionPosition = getNextExpansion(BWAPI::Broodwar->self());
//BWAPI::Broodwar->drawCircleMap(BWAPI::Position(nextExpansionPosition), 32, BWAPI::Color(255, 0, 255), true);
//BWAPI::Broodwar->drawTextMap(BWAPI::Position(nextExpansionPosition), "Next Expansion Location", BWAPI::Color(255, 0, 255));
}
const std::vector<const BaseLocation *> & BaseLocationManager::getBaseLocations() const
{
return m_baseLocationPtrs;
}
const std::vector<const BaseLocation *> & BaseLocationManager::getStartingBaseLocations() const
{
return m_startingBaseLocations;
}
const BaseLocation * BaseLocationManager::getPlayerStartingBaseLocation(BWAPI::Player player) const
{
return m_playerStartingBaseLocations.at(player);
}
const std::set<const BaseLocation *> & BaseLocationManager::getOccupiedBaseLocations(BWAPI::Player player) const
{
return m_occupiedBaseLocations.at(player);
}
BWAPI::TilePosition BaseLocationManager::getNextExpansion(BWAPI::Player player) const
{
PROFILE_FUNCTION();
const BaseLocation * homeBase = getPlayerStartingBaseLocation(player);
const BaseLocation * closestBase = nullptr;
int minDistance = std::numeric_limits<int>::max();
BWAPI::TilePosition homeTile(homeBase->getPosition());
for (auto & base : getBaseLocations())
{
// skip mineral only and starting locations (TODO: fix this)
if (base->isMineralOnly() || base->isStartLocation())
{
continue;
}
// get the tile position of the base
BWAPI::TilePosition tile = base->getDepotPosition();
bool buildingInTheWay = false; // TODO: check if there are any units on the tile
if (buildingInTheWay)
{
continue;
}
// the base's distance from our main nexus
int distanceFromHome = homeBase->getGroundDistance(tile);
// if it is not connected, continue
if (distanceFromHome < 0)
{
continue;
}
if (!closestBase || distanceFromHome < minDistance)
{
closestBase = base;
minDistance = distanceFromHome;
}
}
return closestBase ? closestBase->getDepotPosition() : BWAPI::TilePosition(0, 0);
}
<commit_msg>Update BaseLocationManager.cpp<commit_after>
#include "Common.h"
#include "BaseLocationManager.h"
#include "InformationManager.h"
#include "MapTools.h"
#include "Global.h"
#include "UnitData.h"
using namespace UAlbertaBot;
BaseLocationManager::BaseLocationManager()
{
onStart();
}
BWAPI::Position BaseLocationManager::calcCenter(const std::vector<BWAPI::Unit> & units)
{
if (units.empty())
{
return BWAPI::Position(0, 0);
}
int cx = 0;
int cy = 0;
for (auto & unit : units)
{
cx += unit->getPosition().x;
cy += unit->getPosition().y;
}
return BWAPI::Position(cx / units.size(), cy / units.size());
}
void BaseLocationManager::onStart()
{
PROFILE_FUNCTION();
m_tileBaseLocations = std::vector<std::vector<BaseLocation *>>(BWAPI::Broodwar->mapWidth(), std::vector<BaseLocation *>(BWAPI::Broodwar->mapHeight(), nullptr));
m_playerStartingBaseLocations[BWAPI::Broodwar->self()] = nullptr;
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = nullptr;
// Use StarDraft to find the borders of the bases on the map
m_baseBorders = BaseBorderFinder(Global::Map().getStarDraftMap());
for (size_t baseID = 0; baseID < m_baseBorders.getBaseBorders().size(); baseID++)
{
const auto & border = m_baseBorders.getBaseBorders()[baseID];
// fill a vector with all the resource units in the border
std::vector<BWAPI::Unit> resources;
// for each static unit on the map
for (auto unit : BWAPI::Broodwar->getStaticNeutralUnits())
{
// if it's a resource
if (unit->getType().isMineralField() || unit->getType() == BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
BWAPI::TilePosition tile(unit->getPosition());
// if it's inside the border, add it to the vector
if (border.contains(tile.x, tile.y))
{
resources.push_back(unit);
}
}
}
// add a baselocation containing these resources
m_baseLocationData.push_back(BaseLocation(baseID, resources));
}
// construct the vectors of base location pointers, this is safe since they will never change
for (auto & baseLocation : m_baseLocationData)
{
m_baseLocationPtrs.push_back(&baseLocation);
// if it's a start location, add it to the start locations
if (baseLocation.isStartLocation())
{
m_startingBaseLocations.push_back(&baseLocation);
}
// if it's our starting location, set the pointer
if (baseLocation.isPlayerStartLocation(BWAPI::Broodwar->self()))
{
m_playerStartingBaseLocations[BWAPI::Broodwar->self()] = &baseLocation;
}
if (baseLocation.isPlayerStartLocation(BWAPI::Broodwar->enemy()))
{
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = &baseLocation;
}
}
// construct the map of tile positions to base locations
for (int x=0; x < BWAPI::Broodwar->mapWidth(); ++x)
{
for (int y = 0; y < BWAPI::Broodwar->mapHeight(); ++y)
{
for (auto & baseLocation : m_baseLocationData)
{
BWAPI::Position pos(BWAPI::TilePosition(x, y));
if (baseLocation.containsPosition(pos))
{
m_tileBaseLocations[x][y] = &baseLocation;
break;
}
}
}
}
// construct the sets of occupied base locations
m_occupiedBaseLocations[BWAPI::Broodwar->self()] = std::set<const BaseLocation *>();
m_occupiedBaseLocations[BWAPI::Broodwar->enemy()] = std::set<const BaseLocation *>();
}
void BaseLocationManager::onFrame()
{
PROFILE_FUNCTION();
drawBaseLocations();
// reset the player occupation information for each location
for (auto & baseLocation : m_baseLocationData)
{
baseLocation.setPlayerOccupying(BWAPI::Broodwar->self(), false);
baseLocation.setPlayerOccupying(BWAPI::Broodwar->self(), false);
}
// for each unit on the map, update which base location it may be occupying
for (auto & unit : BWAPI::Broodwar->self()->getUnits())
{
// we only care about buildings on the ground
if (!unit->getType().isBuilding() || unit->isFlying())
{
continue;
}
BaseLocation * baseLocation = getBaseLocation(unit->getPosition());
if (baseLocation != nullptr)
{
baseLocation->setPlayerOccupying(unit->getPlayer(), true);
}
}
// update enemy base occupations
for (const auto & kv : Global::Info().getUnitInfo(BWAPI::Broodwar->enemy()))
{
const UnitInfo & ui = kv.second;
if (ui.type.isBuilding())
{
continue;
}
BaseLocation * baseLocation = getBaseLocation(ui.lastPosition);
if (baseLocation != nullptr)
{
baseLocation->setPlayerOccupying(BWAPI::Broodwar->enemy(), true);
}
}
// update the starting locations of the enemy player
// this will happen one of two ways:
// 1. we've seen the enemy base directly, so the baselocation will know
if (m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] == nullptr)
{
for (auto & baseLocation : m_baseLocationData)
{
if (baseLocation.isPlayerStartLocation(BWAPI::Broodwar->enemy()))
{
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = &baseLocation;
}
}
}
// 2. we've explored every other start location and haven't seen the enemy yet
if (m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] == nullptr)
{
const int numStartLocations = (int)getStartingBaseLocations().size();
int numExploredLocations = 0;
BaseLocation * unexplored = nullptr;
for (auto & baseLocation : m_baseLocationData)
{
if (!baseLocation.isStartLocation())
{
continue;
}
if (baseLocation.isExplored())
{
numExploredLocations++;
}
else
{
unexplored = &baseLocation;
}
}
// if we have explored all but one location, then the unexplored one is the enemy start location
if (numExploredLocations == numStartLocations - 1 && unexplored != nullptr)
{
m_playerStartingBaseLocations[BWAPI::Broodwar->enemy()] = unexplored;
unexplored->setPlayerOccupying(BWAPI::Broodwar->enemy(), true);
}
}
// update the occupied base locations for each player
m_occupiedBaseLocations[BWAPI::Broodwar->self()] = std::set<const BaseLocation *>();
m_occupiedBaseLocations[BWAPI::Broodwar->enemy()] = std::set<const BaseLocation *>();
for (auto & baseLocation : m_baseLocationData)
{
if (baseLocation.isOccupiedByPlayer(BWAPI::Broodwar->self()))
{
m_occupiedBaseLocations[BWAPI::Broodwar->self()].insert(&baseLocation);
}
if (baseLocation.isOccupiedByPlayer(BWAPI::Broodwar->enemy()))
{
m_occupiedBaseLocations[BWAPI::Broodwar->enemy()].insert(&baseLocation);
}
}
// sanity check: make sure we have as many starting locations as BWAPI says
if (getStartingBaseLocations().size() != BWAPI::Broodwar->getStartLocations().size())
{
std::cout << "\nWARNING: BaseLocationManager start location mismatch: " << BWAPI::Broodwar->mapFileName() << "\n";
std::cout << " BaseLocationManager found " << getStartingBaseLocations().size() << " starting locations\n";
std::cout << " BWAPI says that there are " << BWAPI::Broodwar->getStartLocations().size() << " starting locations\n\n";
for (auto tp : BWAPI::Broodwar->getStartLocations())
{
BWAPI::Broodwar->drawCircleMap(BWAPI::Position(tp), 64, BWAPI::Colors::Red, true);
}
}
}
BaseLocation * BaseLocationManager::getBaseLocation(const BWAPI::Position & pos) const
{
if (!pos.isValid()) { return nullptr; }
return m_tileBaseLocations[pos.x / 32][pos.y / 32];
}
void BaseLocationManager::drawBaseLocations()
{
for (auto & baseLocation : m_baseLocationData)
{
baseLocation.draw();
}
// draw a purple sphere at the next expansion location
//BWAPI::TilePosition nextExpansionPosition = getNextExpansion(BWAPI::Broodwar->self());
//BWAPI::Broodwar->drawCircleMap(BWAPI::Position(nextExpansionPosition), 32, BWAPI::Color(255, 0, 255), true);
//BWAPI::Broodwar->drawTextMap(BWAPI::Position(nextExpansionPosition), "Next Expansion Location", BWAPI::Color(255, 0, 255));
}
const std::vector<const BaseLocation *> & BaseLocationManager::getBaseLocations() const
{
return m_baseLocationPtrs;
}
const std::vector<const BaseLocation *> & BaseLocationManager::getStartingBaseLocations() const
{
return m_startingBaseLocations;
}
const BaseLocation * BaseLocationManager::getPlayerStartingBaseLocation(BWAPI::Player player) const
{
return m_playerStartingBaseLocations.at(player);
}
const std::set<const BaseLocation *> & BaseLocationManager::getOccupiedBaseLocations(BWAPI::Player player) const
{
return m_occupiedBaseLocations.at(player);
}
BWAPI::TilePosition BaseLocationManager::getNextExpansion(BWAPI::Player player) const
{
PROFILE_FUNCTION();
const BaseLocation * homeBase = getPlayerStartingBaseLocation(player);
const BaseLocation * closestBase = nullptr;
int minDistance = std::numeric_limits<int>::max();
BWAPI::TilePosition homeTile(homeBase->getPosition());
for (auto & base : getBaseLocations())
{
// skip mineral only and starting locations (TODO: fix this)
if (base->isMineralOnly() || base->isStartLocation())
{
continue;
}
// get the tile position of the base
BWAPI::TilePosition tile = base->getDepotPosition();
bool buildingInTheWay = false; // TODO: check if there are any units on the tile
if (buildingInTheWay)
{
continue;
}
// the base's distance from our main nexus
int distanceFromHome = homeBase->getGroundDistance(tile);
// if it is not connected, continue
if (distanceFromHome < 0)
{
continue;
}
if (!closestBase || distanceFromHome < minDistance)
{
closestBase = base;
minDistance = distanceFromHome;
}
}
return closestBase ? closestBase->getDepotPosition() : BWAPI::TilePosition(0, 0);
}
<|endoftext|> |
<commit_before>// csastil_includeorder.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// Copyright 2012 Dietmar Kuehl http://www.dietmar-kuehl.de
// Distributed under the Boost Software License, Version 1.0. (See file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
// ----------------------------------------------------------------------------
#include <csabase_analyser.h>
#include <csabase_location.h>
#include <csabase_ppobserver.h>
#include <csabase_registercheck.h>
#include <csabase_util.h>
#include <cctype>
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
namespace CB = cool::csabase;
// ----------------------------------------------------------------------------
static std::string const check_name("include-order");
// ----------------------------------------------------------------------------
namespace
{
struct include_order
{
typedef std::vector<std::pair<std::string, clang::SourceLocation> > headers_t;
headers_t d_header;
headers_t d_source;
void add_include(bool in_header,
std::string header,
clang::SourceLocation const& where)
{
std::string::size_type pos(header.find('.'));
if (pos != header.npos) {
header = header.substr(0u, pos);
}
headers_t& headers(in_header? d_header: d_source);
if (headers.empty() || headers.back().first != header) {
headers.push_back(std::make_pair(header, where));
}
}
};
}
// ----------------------------------------------------------------------------
namespace
{
struct has_prefix
{
typedef std::pair<std::string, clang::SourceLocation> const& argument_type;
has_prefix(std::string const& prefix)
: d_prefix(prefix)
{
}
bool operator()(argument_type entry) const
{
return entry.first.find(d_prefix) == 0;
}
std::string d_prefix;
};
}
// ----------------------------------------------------------------------------
static bool
first_is_greater(std::pair<std::string, clang::SourceLocation> const& entry0,
std::pair<std::string, clang::SourceLocation> const& entry1)
{
return entry1.first < entry0.first;
}
// ----------------------------------------------------------------------------
static bool
is_component(std::pair<std::string, clang::SourceLocation> const& entry)
{
std::string const& header(entry.first);
std::string::size_type start(header.find("a_") == 0 || header.find("e_") == 0? 2: 0);
std::string::size_type under(header.find('_', 0));
return under != header.npos && 4 < under - start && under - start < 8;
}
// ----------------------------------------------------------------------------
static void
check_order(CB::Analyser* analyser,
std::string const& message,
include_order::headers_t::const_iterator it,
include_order::headers_t::const_iterator end)
{
for (; end != (it = std::adjacent_find(it, end, &first_is_greater));
++it) {
analyser->report(it[1].second, check_name, "SHO01",
"%0 header out of order")
<< message;
}
}
static void
check_order(CB::Analyser* analyser,
std::string const& message,
include_order::headers_t::const_iterator it,
include_order::headers_t::const_iterator section_end,
include_order::headers_t::const_iterator end)
{
check_order(analyser, message, it, section_end);
for (it = section_end;
end != (it = std::find_if(it, end, has_prefix(analyser->package() + "_")));
++it) {
analyser->report(it->second, check_name, "SHO02",
"%0 header coming late")
<< message;
}
}
static clang::SourceLocation const*
check_order(CB::Analyser* analyser,
include_order::headers_t const& headers,
bool header)
{
clang::SourceLocation const* bdes_ident_location(0);
if (headers.empty()) {
analyser->report(clang::SourceLocation(), check_name, "SH003",
header
? "Header without include guard included"
: "Source without component include");
return bdes_ident_location;
}
include_order::headers_t::const_iterator it(headers.begin());
if (it->first != analyser->component() || it++ == headers.end()) {
analyser->report(headers[0].second, check_name, "SHO04",
header
? "Header without or with wrong include guard"
: "Source doesn't include component header first");
}
std::string ident =
analyser->group() == "bsl" ? "bsls_ident" : "bdes_ident";
if (analyser->component() == ident ||
(analyser->is_test_driver() && !header)) {
if (it != headers.end()) {
if (it->first == "bdes_ident") {
bdes_ident_location = &it->second;
}
if (it->first == ident) {
++it;
}
}
}
else if (it == headers.end() || it->first != ident) {
analyser->report((it == headers.end() ? it - 1: it)->second,
check_name, "SHO06",
"Missing include for %0.h")
<< ident;
}
else {
if (it->first == "bdes_ident") {
bdes_ident_location = &it->second;
}
++it;
}
std::string version = analyser->group() + "scm_version";
if ( analyser->component() != version
&& header
&& (it == headers.end()
|| it->first != version
|| it++ == headers.end())) {
analyser->report((it == headers.end() ? it - 1 : it)->second,
check_name, "SHO07",
"Missing include for %0.h")
<< version;
}
include_order::headers_t::const_iterator end
= std::find_if(it, headers.end(),
std::not1(std::ptr_fun(&is_component)));
include_order::headers_t::const_iterator package_end
= std::find_if(it, end, std::not1(has_prefix(analyser->package() + "_")));
check_order(analyser, "Package", it, package_end, end);
include_order::headers_t::const_iterator group_end
= std::find_if(it, end, std::not1(has_prefix(analyser->group())));
check_order(analyser, "Group", package_end, group_end, end);
check_order(analyser, "Component", group_end, end);
return bdes_ident_location;
}
// ----------------------------------------------------------------------------
static inline bool
is_space(unsigned char c)
{
return std::isspace(c);
}
// ----------------------------------------------------------------------------
namespace
{
std::string const prefix0("included_");
std::string const prefix1("!defined(included_");
std::string const prefix2("!definedincluded_");
struct binder
{
binder(cool::csabase::Analyser* analyser)
: d_analyser(analyser)
{
}
void operator()(clang::SourceLocation,
clang::SourceRange range) const // onIf
{
if (!d_analyser->is_component(range.getBegin())) {
return;
}
include_order& data(d_analyser->attachment<include_order>());
char const* begin(d_analyser->manager().getCharacterData(range.getBegin()));
char const* end(d_analyser->manager().getCharacterData(range.getEnd()));
std::string value(begin, end);
value.erase(std::remove_if(value.begin(), value.end(),
&is_space), value.end());
value = cool::csabase::to_lower(value);
if (value.find(prefix1) == 0 && value[value.size() - 1] == ')') {
data.add_include(d_analyser->is_component_header(range.getBegin()),
value.substr(prefix1.size(), value.size() - prefix1.size() - 1),
range.getBegin());
}
else if (value.find(prefix2) == 0) {
data.add_include(d_analyser->is_component_header(range.getBegin()),
value.substr(prefix2.size()),
range.getBegin());
}
}
void operator()(clang::SourceLocation where,
clang::Token const& token) const // onIfndef
{
if (!d_analyser->is_component(token.getLocation())) {
return;
}
include_order& data(d_analyser->attachment<include_order>());
if (clang::IdentifierInfo const* id = token.getIdentifierInfo())
{
std::string value(id->getNameStart());
value = cool::csabase::to_lower(value);
if (value.find(prefix0) == 0) {
data.add_include(d_analyser->is_component_header(token.getLocation()),
value.substr(prefix0.size()),
token.getLocation());
}
}
}
void operator()(clang::SourceLocation where,
bool,
std::string const& name)
{
if (d_analyser->is_component(where)) {
include_order& data(d_analyser->attachment<include_order>());
bool in_header(d_analyser->is_component_header(where));
data.add_include(in_header, name, where);
}
}
void operator()() // translation unit done
{
include_order& data(d_analyser->attachment<include_order>());
clang::SourceLocation const* header_bdes_ident(
check_order(d_analyser, data.d_header, true));
clang::SourceLocation const* source_bdes_ident(
check_order(d_analyser, data.d_source, false));
if ((header_bdes_ident == 0) != (source_bdes_ident == 0)) {
d_analyser->report(*(header_bdes_ident ? header_bdes_ident :
source_bdes_ident),
check_name, "SHO08",
"bdes_ident.h is used inconsistently with "
"the %0")
<< (header_bdes_ident ? "source" : "header");
}
}
cool::csabase::Analyser* d_analyser;
};
}
// ----------------------------------------------------------------------------
static void
subscribe(cool::csabase::Analyser& analyser, cool::csabase::Visitor&, cool::csabase::PPObserver& observer)
{
analyser.onTranslationUnitDone += binder(&analyser);
observer.onInclude += binder(&analyser);
observer.onIfndef += binder(&analyser);
observer.onIf += binder(&analyser);
}
// ----------------------------------------------------------------------------
static cool::csabase::RegisterCheck register_observer(check_name, &subscribe);
<commit_msg>Typo 0 => O<commit_after>// csastil_includeorder.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// Copyright 2012 Dietmar Kuehl http://www.dietmar-kuehl.de
// Distributed under the Boost Software License, Version 1.0. (See file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
// ----------------------------------------------------------------------------
#include <csabase_analyser.h>
#include <csabase_location.h>
#include <csabase_ppobserver.h>
#include <csabase_registercheck.h>
#include <csabase_util.h>
#include <cctype>
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
namespace CB = cool::csabase;
// ----------------------------------------------------------------------------
static std::string const check_name("include-order");
// ----------------------------------------------------------------------------
namespace
{
struct include_order
{
typedef std::vector<std::pair<std::string, clang::SourceLocation> > headers_t;
headers_t d_header;
headers_t d_source;
void add_include(bool in_header,
std::string header,
clang::SourceLocation const& where)
{
std::string::size_type pos(header.find('.'));
if (pos != header.npos) {
header = header.substr(0u, pos);
}
headers_t& headers(in_header? d_header: d_source);
if (headers.empty() || headers.back().first != header) {
headers.push_back(std::make_pair(header, where));
}
}
};
}
// ----------------------------------------------------------------------------
namespace
{
struct has_prefix
{
typedef std::pair<std::string, clang::SourceLocation> const& argument_type;
has_prefix(std::string const& prefix)
: d_prefix(prefix)
{
}
bool operator()(argument_type entry) const
{
return entry.first.find(d_prefix) == 0;
}
std::string d_prefix;
};
}
// ----------------------------------------------------------------------------
static bool
first_is_greater(std::pair<std::string, clang::SourceLocation> const& entry0,
std::pair<std::string, clang::SourceLocation> const& entry1)
{
return entry1.first < entry0.first;
}
// ----------------------------------------------------------------------------
static bool
is_component(std::pair<std::string, clang::SourceLocation> const& entry)
{
std::string const& header(entry.first);
std::string::size_type start(header.find("a_") == 0 || header.find("e_") == 0? 2: 0);
std::string::size_type under(header.find('_', 0));
return under != header.npos && 4 < under - start && under - start < 8;
}
// ----------------------------------------------------------------------------
static void
check_order(CB::Analyser* analyser,
std::string const& message,
include_order::headers_t::const_iterator it,
include_order::headers_t::const_iterator end)
{
for (; end != (it = std::adjacent_find(it, end, &first_is_greater));
++it) {
analyser->report(it[1].second, check_name, "SHO01",
"%0 header out of order")
<< message;
}
}
static void
check_order(CB::Analyser* analyser,
std::string const& message,
include_order::headers_t::const_iterator it,
include_order::headers_t::const_iterator section_end,
include_order::headers_t::const_iterator end)
{
check_order(analyser, message, it, section_end);
for (it = section_end;
end != (it = std::find_if(it, end, has_prefix(analyser->package() + "_")));
++it) {
analyser->report(it->second, check_name, "SHO02",
"%0 header coming late")
<< message;
}
}
static clang::SourceLocation const*
check_order(CB::Analyser* analyser,
include_order::headers_t const& headers,
bool header)
{
clang::SourceLocation const* bdes_ident_location(0);
if (headers.empty()) {
analyser->report(clang::SourceLocation(), check_name, "SHO03",
header
? "Header without include guard included"
: "Source without component include");
return bdes_ident_location;
}
include_order::headers_t::const_iterator it(headers.begin());
if (it->first != analyser->component() || it++ == headers.end()) {
analyser->report(headers[0].second, check_name, "SHO04",
header
? "Header without or with wrong include guard"
: "Source doesn't include component header first");
}
std::string ident =
analyser->group() == "bsl" ? "bsls_ident" : "bdes_ident";
if (analyser->component() == ident ||
(analyser->is_test_driver() && !header)) {
if (it != headers.end()) {
if (it->first == "bdes_ident") {
bdes_ident_location = &it->second;
}
if (it->first == ident) {
++it;
}
}
}
else if (it == headers.end() || it->first != ident) {
analyser->report((it == headers.end() ? it - 1: it)->second,
check_name, "SHO06",
"Missing include for %0.h")
<< ident;
}
else {
if (it->first == "bdes_ident") {
bdes_ident_location = &it->second;
}
++it;
}
std::string version = analyser->group() + "scm_version";
if ( analyser->component() != version
&& header
&& (it == headers.end()
|| it->first != version
|| it++ == headers.end())) {
analyser->report((it == headers.end() ? it - 1 : it)->second,
check_name, "SHO07",
"Missing include for %0.h")
<< version;
}
include_order::headers_t::const_iterator end
= std::find_if(it, headers.end(),
std::not1(std::ptr_fun(&is_component)));
include_order::headers_t::const_iterator package_end
= std::find_if(it, end, std::not1(has_prefix(analyser->package() + "_")));
check_order(analyser, "Package", it, package_end, end);
include_order::headers_t::const_iterator group_end
= std::find_if(it, end, std::not1(has_prefix(analyser->group())));
check_order(analyser, "Group", package_end, group_end, end);
check_order(analyser, "Component", group_end, end);
return bdes_ident_location;
}
// ----------------------------------------------------------------------------
static inline bool
is_space(unsigned char c)
{
return std::isspace(c);
}
// ----------------------------------------------------------------------------
namespace
{
std::string const prefix0("included_");
std::string const prefix1("!defined(included_");
std::string const prefix2("!definedincluded_");
struct binder
{
binder(cool::csabase::Analyser* analyser)
: d_analyser(analyser)
{
}
void operator()(clang::SourceLocation,
clang::SourceRange range) const // onIf
{
if (!d_analyser->is_component(range.getBegin())) {
return;
}
include_order& data(d_analyser->attachment<include_order>());
char const* begin(d_analyser->manager().getCharacterData(range.getBegin()));
char const* end(d_analyser->manager().getCharacterData(range.getEnd()));
std::string value(begin, end);
value.erase(std::remove_if(value.begin(), value.end(),
&is_space), value.end());
value = cool::csabase::to_lower(value);
if (value.find(prefix1) == 0 && value[value.size() - 1] == ')') {
data.add_include(d_analyser->is_component_header(range.getBegin()),
value.substr(prefix1.size(), value.size() - prefix1.size() - 1),
range.getBegin());
}
else if (value.find(prefix2) == 0) {
data.add_include(d_analyser->is_component_header(range.getBegin()),
value.substr(prefix2.size()),
range.getBegin());
}
}
void operator()(clang::SourceLocation where,
clang::Token const& token) const // onIfndef
{
if (!d_analyser->is_component(token.getLocation())) {
return;
}
include_order& data(d_analyser->attachment<include_order>());
if (clang::IdentifierInfo const* id = token.getIdentifierInfo())
{
std::string value(id->getNameStart());
value = cool::csabase::to_lower(value);
if (value.find(prefix0) == 0) {
data.add_include(d_analyser->is_component_header(token.getLocation()),
value.substr(prefix0.size()),
token.getLocation());
}
}
}
void operator()(clang::SourceLocation where,
bool,
std::string const& name)
{
if (d_analyser->is_component(where)) {
include_order& data(d_analyser->attachment<include_order>());
bool in_header(d_analyser->is_component_header(where));
data.add_include(in_header, name, where);
}
}
void operator()() // translation unit done
{
include_order& data(d_analyser->attachment<include_order>());
clang::SourceLocation const* header_bdes_ident(
check_order(d_analyser, data.d_header, true));
clang::SourceLocation const* source_bdes_ident(
check_order(d_analyser, data.d_source, false));
if ((header_bdes_ident == 0) != (source_bdes_ident == 0)) {
d_analyser->report(*(header_bdes_ident ? header_bdes_ident :
source_bdes_ident),
check_name, "SHO08",
"bdes_ident.h is used inconsistently with "
"the %0")
<< (header_bdes_ident ? "source" : "header");
}
}
cool::csabase::Analyser* d_analyser;
};
}
// ----------------------------------------------------------------------------
static void
subscribe(cool::csabase::Analyser& analyser, cool::csabase::Visitor&, cool::csabase::PPObserver& observer)
{
analyser.onTranslationUnitDone += binder(&analyser);
observer.onInclude += binder(&analyser);
observer.onIfndef += binder(&analyser);
observer.onIf += binder(&analyser);
}
// ----------------------------------------------------------------------------
static cool::csabase::RegisterCheck register_observer(check_name, &subscribe);
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "resource_provider/storage/uri_disk_profile_adaptor.hpp"
#include <map>
#include <string>
#include <tuple>
#include <csi/spec.hpp>
#include <mesos/module/disk_profile_adaptor.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/socket.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/json.hpp>
#include <stout/option.hpp>
#include <stout/protobuf.hpp>
#include <stout/result.hpp>
#include <stout/strings.hpp>
#include "csi/utils.hpp"
#include "resource_provider/storage/disk_profile_utils.hpp"
using namespace mesos;
using namespace process;
using std::map;
using std::string;
using std::tuple;
using google::protobuf::Map;
using mesos::resource_provider::DiskProfileMapping;
namespace mesos {
namespace internal {
namespace storage {
bool operator==(
const Map<string, string>& left,
const Map<string, string>& right) {
if (left.size() != right.size()) {
return false;
}
typename Map<string, string>::const_iterator iterator = left.begin();
while (iterator != left.end()) {
if (right.count(iterator->first) != 1) {
return false;
}
if (iterator->second != right.at(iterator->first)) {
return false;
}
}
return true;
}
UriDiskProfileAdaptor::UriDiskProfileAdaptor(const Flags& _flags)
: flags(_flags),
process(new UriDiskProfileAdaptorProcess(flags))
{
spawn(process.get());
}
UriDiskProfileAdaptor::~UriDiskProfileAdaptor()
{
terminate(process.get());
wait(process.get());
}
Future<DiskProfileAdaptor::ProfileInfo> UriDiskProfileAdaptor::translate(
const string& profile,
const ResourceProviderInfo& resourceProviderInfo)
{
return dispatch(
process.get(),
&UriDiskProfileAdaptorProcess::translate,
profile,
resourceProviderInfo);
}
Future<hashset<string>> UriDiskProfileAdaptor::watch(
const hashset<string>& knownProfiles,
const ResourceProviderInfo& resourceProviderInfo)
{
return dispatch(
process.get(),
&UriDiskProfileAdaptorProcess::watch,
knownProfiles,
resourceProviderInfo);
}
UriDiskProfileAdaptorProcess::UriDiskProfileAdaptorProcess(
const UriDiskProfileAdaptor::Flags& _flags)
: ProcessBase(ID::generate("uri-disk-profile-adaptor")),
flags(_flags),
watchPromise(new Promise<Nothing>()) {}
void UriDiskProfileAdaptorProcess::initialize()
{
poll();
}
Future<DiskProfileAdaptor::ProfileInfo>
UriDiskProfileAdaptorProcess::translate(
const string& profile,
const ResourceProviderInfo& resourceProviderInfo)
{
if (!profileMatrix.contains(profile) || !profileMatrix.at(profile).active) {
return Failure("Profile '" + profile + "' not found");
}
const DiskProfileMapping::CSIManifest& manifest =
profileMatrix.at(profile).manifest;
if (!isSelectedResourceProvider(manifest, resourceProviderInfo)) {
return Failure(
"Profile '" + profile + "' does not apply to resource provider with "
"type '" + resourceProviderInfo.type() + "' and name '" +
resourceProviderInfo.name() + "'");
}
return DiskProfileAdaptor::ProfileInfo{
manifest.volume_capabilities(),
manifest.create_parameters()
};
}
Future<hashset<string>> UriDiskProfileAdaptorProcess::watch(
const hashset<string>& knownProfiles,
const ResourceProviderInfo& resourceProviderInfo)
{
// Calculate the new set of profiles for the resource provider.
hashset<string> newProfiles;
foreachpair (const string& profile,
const ProfileRecord& record,
profileMatrix) {
if (record.active &&
isSelectedResourceProvider(record.manifest, resourceProviderInfo)) {
newProfiles.insert(profile);
}
}
if (newProfiles != knownProfiles) {
return newProfiles;
}
// Wait for the next update if there is no change.
return watchPromise->future()
.then(defer(self(), &Self::watch, knownProfiles, resourceProviderInfo));
}
void UriDiskProfileAdaptorProcess::poll()
{
// NOTE: The flags do not allow relative paths, so this is guaranteed to
// be either 'http://' or 'https://'.
if (strings::startsWith(flags.uri, "http")) {
// NOTE: We already validated that this URI is parsable in the flags.
Try<http::URL> url = http::URL::parse(flags.uri.string());
CHECK_SOME(url);
http::get(url.get())
.onAny(defer(self(), &Self::_poll, lambda::_1));
} else {
__poll(os::read(flags.uri.string()));
}
}
void UriDiskProfileAdaptorProcess::_poll(const Future<http::Response>& response)
{
if (response.isReady()) {
if (response->code == http::Status::OK) {
__poll(response->body);
} else {
__poll(Error("Unexpected HTTP response '" + response->status + "'"));
}
} else if (response.isFailed()) {
__poll(Error(response.failure()));
} else {
__poll(Error("Future discarded or abandoned"));
}
}
void UriDiskProfileAdaptorProcess::__poll(const Try<string>& fetched)
{
if (fetched.isSome()) {
Try<DiskProfileMapping> parsed = parseDiskProfileMapping(fetched.get());
if (parsed.isSome()) {
notify(parsed.get());
} else {
LOG(ERROR) << "Failed to parse result: " << parsed.error();
}
} else {
LOG(WARNING) << "Failed to poll URI: " << fetched.error();
}
// TODO(josephw): Do we want to retry if polling fails and no polling
// interval is set? Or perhaps we should exit in that case?
if (flags.poll_interval.isSome()) {
delay(flags.poll_interval.get(), self(), &Self::poll);
}
}
void UriDiskProfileAdaptorProcess::notify(
const DiskProfileMapping& parsed)
{
bool hasErrors = false;
foreach (const auto& entry, parsed.profile_matrix()) {
if (!profileMatrix.contains(entry.first)) {
continue;
}
bool matchingCapability =
entry.second.volume_capabilities() ==
profileMatrix.at(entry.first).manifest.volume_capabilities();
bool matchingParameters =
entry.second.create_parameters() ==
profileMatrix.at(entry.first).manifest.create_parameters();
if (!matchingCapability || !matchingParameters) {
hasErrors = true;
LOG(WARNING)
<< "Fetched profile mapping for profile '" << entry.first
<< "' does not match earlier data. "
<< "The fetched mapping will be ignored entirely";
}
}
// When encountering a data conflict, this module assumes there is a
// problem upstream (i.e. in the `--uri`). It is up to the operator
// to notice and resolve this.
if (hasErrors) {
return;
}
// TODO(chhsiao): No need to update the profile matrix and send notifications
// if the parsed mapping has the same size and profile selectors.
// The fetched mapping satisfies our invariants.
// Mark disappeared profiles as inactive.
foreachpair (const string& profile, ProfileRecord& record, profileMatrix) {
if (parsed.profile_matrix().count(profile) != 1) {
record.active = false;
LOG(INFO)
<< "Profile '" << profile << "' is marked inactive "
<< "because it is not in the fetched profile mapping";
}
}
// Save the fetched profile mapping.
foreach (const auto& entry, parsed.profile_matrix()) {
profileMatrix.put(entry.first, {entry.second, true});
}
// Notify any watchers and then prepare a new promise for the next
// iteration of polling.
//
// TODO(josephw): Delay this based on the `--max_random_wait` option.
watchPromise->set(Nothing());
watchPromise.reset(new Promise<Nothing>());
LOG(INFO)
<< "Updated disk profile mapping to " << parsed.profile_matrix().size()
<< " active profiles";
}
} // namespace storage {
} // namespace internal {
} // namespace mesos {
mesos::modules::Module<DiskProfileAdaptor>
org_apache_mesos_UriDiskProfileAdaptor(
MESOS_MODULE_API_VERSION,
MESOS_VERSION,
"Apache Mesos",
"[email protected]",
"URI Disk Profile Adaptor module.",
nullptr,
[](const Parameters& parameters) -> DiskProfileAdaptor* {
// Convert `parameters` into a map.
map<string, string> values;
foreach (const Parameter& parameter, parameters.parameter()) {
values[parameter.key()] = parameter.value();
}
// Load and validate flags from the map.
mesos::internal::storage::UriDiskProfileAdaptor::Flags flags;
Try<flags::Warnings> load = flags.load(values);
if (load.isError()) {
LOG(ERROR) << "Failed to parse parameters: " << load.error();
return nullptr;
}
// Log any flag warnings.
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
return new mesos::internal::storage::UriDiskProfileAdaptor(flags);
});
<commit_msg>Fixed protobuf map equality check in the URI disk profile adaptor.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "resource_provider/storage/uri_disk_profile_adaptor.hpp"
#include <map>
#include <string>
#include <tuple>
#include <csi/spec.hpp>
#include <mesos/module/disk_profile_adaptor.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/socket.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/json.hpp>
#include <stout/option.hpp>
#include <stout/protobuf.hpp>
#include <stout/result.hpp>
#include <stout/strings.hpp>
#include "csi/utils.hpp"
#include "resource_provider/storage/disk_profile_utils.hpp"
using namespace mesos;
using namespace process;
using std::map;
using std::string;
using std::tuple;
using google::protobuf::Map;
using mesos::resource_provider::DiskProfileMapping;
namespace mesos {
namespace internal {
namespace storage {
bool operator==(
const Map<string, string>& left,
const Map<string, string>& right) {
if (left.size() != right.size()) {
return false;
}
typename Map<string, string>::const_iterator iterator = left.begin();
while (iterator != left.end()) {
if (right.count(iterator->first) != 1) {
return false;
}
if (iterator->second != right.at(iterator->first)) {
return false;
}
++iterator;
}
return true;
}
UriDiskProfileAdaptor::UriDiskProfileAdaptor(const Flags& _flags)
: flags(_flags),
process(new UriDiskProfileAdaptorProcess(flags))
{
spawn(process.get());
}
UriDiskProfileAdaptor::~UriDiskProfileAdaptor()
{
terminate(process.get());
wait(process.get());
}
Future<DiskProfileAdaptor::ProfileInfo> UriDiskProfileAdaptor::translate(
const string& profile,
const ResourceProviderInfo& resourceProviderInfo)
{
return dispatch(
process.get(),
&UriDiskProfileAdaptorProcess::translate,
profile,
resourceProviderInfo);
}
Future<hashset<string>> UriDiskProfileAdaptor::watch(
const hashset<string>& knownProfiles,
const ResourceProviderInfo& resourceProviderInfo)
{
return dispatch(
process.get(),
&UriDiskProfileAdaptorProcess::watch,
knownProfiles,
resourceProviderInfo);
}
UriDiskProfileAdaptorProcess::UriDiskProfileAdaptorProcess(
const UriDiskProfileAdaptor::Flags& _flags)
: ProcessBase(ID::generate("uri-disk-profile-adaptor")),
flags(_flags),
watchPromise(new Promise<Nothing>()) {}
void UriDiskProfileAdaptorProcess::initialize()
{
poll();
}
Future<DiskProfileAdaptor::ProfileInfo>
UriDiskProfileAdaptorProcess::translate(
const string& profile,
const ResourceProviderInfo& resourceProviderInfo)
{
if (!profileMatrix.contains(profile) || !profileMatrix.at(profile).active) {
return Failure("Profile '" + profile + "' not found");
}
const DiskProfileMapping::CSIManifest& manifest =
profileMatrix.at(profile).manifest;
if (!isSelectedResourceProvider(manifest, resourceProviderInfo)) {
return Failure(
"Profile '" + profile + "' does not apply to resource provider with "
"type '" + resourceProviderInfo.type() + "' and name '" +
resourceProviderInfo.name() + "'");
}
return DiskProfileAdaptor::ProfileInfo{
manifest.volume_capabilities(),
manifest.create_parameters()
};
}
Future<hashset<string>> UriDiskProfileAdaptorProcess::watch(
const hashset<string>& knownProfiles,
const ResourceProviderInfo& resourceProviderInfo)
{
// Calculate the new set of profiles for the resource provider.
hashset<string> newProfiles;
foreachpair (const string& profile,
const ProfileRecord& record,
profileMatrix) {
if (record.active &&
isSelectedResourceProvider(record.manifest, resourceProviderInfo)) {
newProfiles.insert(profile);
}
}
if (newProfiles != knownProfiles) {
return newProfiles;
}
// Wait for the next update if there is no change.
return watchPromise->future()
.then(defer(self(), &Self::watch, knownProfiles, resourceProviderInfo));
}
void UriDiskProfileAdaptorProcess::poll()
{
// NOTE: The flags do not allow relative paths, so this is guaranteed to
// be either 'http://' or 'https://'.
if (strings::startsWith(flags.uri, "http")) {
// NOTE: We already validated that this URI is parsable in the flags.
Try<http::URL> url = http::URL::parse(flags.uri.string());
CHECK_SOME(url);
http::get(url.get())
.onAny(defer(self(), &Self::_poll, lambda::_1));
} else {
__poll(os::read(flags.uri.string()));
}
}
void UriDiskProfileAdaptorProcess::_poll(const Future<http::Response>& response)
{
if (response.isReady()) {
if (response->code == http::Status::OK) {
__poll(response->body);
} else {
__poll(Error("Unexpected HTTP response '" + response->status + "'"));
}
} else if (response.isFailed()) {
__poll(Error(response.failure()));
} else {
__poll(Error("Future discarded or abandoned"));
}
}
void UriDiskProfileAdaptorProcess::__poll(const Try<string>& fetched)
{
if (fetched.isSome()) {
Try<DiskProfileMapping> parsed = parseDiskProfileMapping(fetched.get());
if (parsed.isSome()) {
notify(parsed.get());
} else {
LOG(ERROR) << "Failed to parse result: " << parsed.error();
}
} else {
LOG(WARNING) << "Failed to poll URI: " << fetched.error();
}
// TODO(josephw): Do we want to retry if polling fails and no polling
// interval is set? Or perhaps we should exit in that case?
if (flags.poll_interval.isSome()) {
delay(flags.poll_interval.get(), self(), &Self::poll);
}
}
void UriDiskProfileAdaptorProcess::notify(
const DiskProfileMapping& parsed)
{
bool hasErrors = false;
foreach (const auto& entry, parsed.profile_matrix()) {
if (!profileMatrix.contains(entry.first)) {
continue;
}
bool matchingCapability =
entry.second.volume_capabilities() ==
profileMatrix.at(entry.first).manifest.volume_capabilities();
bool matchingParameters =
entry.second.create_parameters() ==
profileMatrix.at(entry.first).manifest.create_parameters();
if (!matchingCapability || !matchingParameters) {
hasErrors = true;
LOG(WARNING)
<< "Fetched profile mapping for profile '" << entry.first
<< "' does not match earlier data. "
<< "The fetched mapping will be ignored entirely";
}
}
// When encountering a data conflict, this module assumes there is a
// problem upstream (i.e. in the `--uri`). It is up to the operator
// to notice and resolve this.
if (hasErrors) {
return;
}
// TODO(chhsiao): No need to update the profile matrix and send notifications
// if the parsed mapping has the same size and profile selectors.
// The fetched mapping satisfies our invariants.
// Mark disappeared profiles as inactive.
foreachpair (const string& profile, ProfileRecord& record, profileMatrix) {
if (parsed.profile_matrix().count(profile) != 1) {
record.active = false;
LOG(INFO)
<< "Profile '" << profile << "' is marked inactive "
<< "because it is not in the fetched profile mapping";
}
}
// Save the fetched profile mapping.
foreach (const auto& entry, parsed.profile_matrix()) {
profileMatrix.put(entry.first, {entry.second, true});
}
// Notify any watchers and then prepare a new promise for the next
// iteration of polling.
//
// TODO(josephw): Delay this based on the `--max_random_wait` option.
watchPromise->set(Nothing());
watchPromise.reset(new Promise<Nothing>());
LOG(INFO)
<< "Updated disk profile mapping to " << parsed.profile_matrix().size()
<< " active profiles";
}
} // namespace storage {
} // namespace internal {
} // namespace mesos {
mesos::modules::Module<DiskProfileAdaptor>
org_apache_mesos_UriDiskProfileAdaptor(
MESOS_MODULE_API_VERSION,
MESOS_VERSION,
"Apache Mesos",
"[email protected]",
"URI Disk Profile Adaptor module.",
nullptr,
[](const Parameters& parameters) -> DiskProfileAdaptor* {
// Convert `parameters` into a map.
map<string, string> values;
foreach (const Parameter& parameter, parameters.parameter()) {
values[parameter.key()] = parameter.value();
}
// Load and validate flags from the map.
mesos::internal::storage::UriDiskProfileAdaptor::Flags flags;
Try<flags::Warnings> load = flags.load(values);
if (load.isError()) {
LOG(ERROR) << "Failed to parse parameters: " << load.error();
return nullptr;
}
// Log any flag warnings.
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
return new mesos::internal::storage::UriDiskProfileAdaptor(flags);
});
<|endoftext|> |
<commit_before>#include <src/servers/Server_Common/Common.h>
#include <src/servers/Server_Common/Network/CommonNetwork.h>
#include <src/servers/Server_Common/Database/Database.h>
#include <src/servers/Server_Common/Network/GamePacketNew.h>
#include <src/servers/Server_Common/Logging/Logger.h>
#include <src/servers/Server_Common/Exd/ExdData.h>
#include <src/servers/Server_Common/Network/PacketContainer.h>
#include <boost/format.hpp>
#include "src/servers/Server_Zone/Network/GameConnection.h"
#include "src/servers/Server_Zone/Session.h"
#include "src/servers/Server_Zone/Zone/Zone.h"
#include "src/servers/Server_Zone/Zone/ZonePosition.h"
#include "src/servers/Server_Zone/ServerZone.h"
#include "src/servers/Server_Zone/Zone/ZoneMgr.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/InitUIPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/PingPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/MoveActorPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ChatPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ServerNoticePacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ActorControlPacket142.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ActorControlPacket143.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ActorControlPacket144.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/EventStartPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/EventFinishPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/PlayerStateFlagsPacket.h"
#include "src/servers/Server_Zone/DebugCommand/DebugCommandHandler.h"
#include "src/servers/Server_Zone/Actor/Player.h"
#include "src/servers/Server_Zone/Inventory/Inventory.h"
#include "src/servers/Server_Zone/Forwards.h"
#include "src/servers/Server_Zone/Event/EventHelper.h"
#include "src/servers/Server_Zone/Action/Action.h"
#include "src/servers/Server_Zone/Action/ActionTeleport.h"
extern Core::Logger g_log;
extern Core::Db::Database g_database;
extern Core::ServerZone g_serverZone;
extern Core::ZoneMgr g_zoneMgr;
extern Core::Data::ExdData g_exdData;
extern Core::DebugCommandHandler g_gameCommandMgr;
using namespace Core::Common;
using namespace Core::Network::Packets;
using namespace Core::Network::Packets::Server;
void Core::Network::GameConnection::actionHandler( const Packets::GamePacket& inPacket,
Entity::PlayerPtr pPlayer )
{
uint16_t commandId = inPacket.getValAt< uint16_t >( 0x20 );
uint64_t param1 = inPacket.getValAt< uint64_t >( 0x24 );
uint32_t param11 = inPacket.getValAt< uint32_t >( 0x24 );
uint32_t param12 = inPacket.getValAt< uint32_t >( 0x28 );
uint32_t param2 = inPacket.getValAt< uint32_t >( 0x2c );
uint64_t param3 = inPacket.getValAt< uint64_t >( 0x38 );
g_log.debug( "[" + std::to_string( m_pSession->getId() ) + "] Incoming action: " +
boost::str( boost::format( "%|04X|" ) % ( uint32_t ) ( commandId & 0xFFFF ) ) +
"\nparam1: " + boost::str( boost::format( "%|016X|" ) % ( uint64_t ) ( param1 & 0xFFFFFFFFFFFFFFF ) ) +
"\nparam2: " + boost::str( boost::format( "%|08X|" ) % ( uint32_t ) ( param2 & 0xFFFFFFFF ) ) +
"\nparam3: " + boost::str( boost::format( "%|016X|" ) % ( uint64_t ) ( param3 & 0xFFFFFFFFFFFFFFF ) )
);
//g_log.Log(LoggingSeverity::debug, "[" + std::to_string(m_pSession->getId()) + "] " + pInPacket->toString());
switch( commandId )
{
case 0x01: // Toggle sheathe
{
if ( param11 == 1 )
pPlayer->setStance( Entity::Actor::Stance::Active );
else
{
pPlayer->setStance( Entity::Actor::Stance::Passive );
pPlayer->setAutoattack( false );
}
pPlayer->sendToInRangeSet( ActorControlPacket142( pPlayer->getId(), 0, param11, 1 ) );
break;
}
case 0x02: // Toggle auto-attack
{
if ( param11 == 1 )
{
pPlayer->setAutoattack( true );
pPlayer->setStance( Entity::Actor::Stance::Active );
}
else
pPlayer->setAutoattack( false );
pPlayer->sendToInRangeSet( ActorControlPacket142( pPlayer->getId(), 1, param11, 1 ) );
break;
}
case 0x03: // Change target
{
uint64_t targetId = inPacket.getValAt< uint64_t >( 0x24 );
pPlayer->changeTarget( targetId );
break;
}
case 0x65:
{
pPlayer->dismount();
break;
}
case 0x68: // Remove status (clicking it off)
{
// todo: check if status can be removed by client from exd
pPlayer->removeSingleStatusEffectFromId( static_cast< uint32_t >( param1 ) );
break;
}
case 0x69: // Cancel cast
{
if( pPlayer->getCurrentAction() != nullptr )
pPlayer->getCurrentAction()->setInterrupted();
break;
}
case 0x12E: // Set player title
{
pPlayer->setTitle( param1 );
break;
}
case 0x12F: // Get title list
{
GamePacketNew< FFXIVIpcPlayerTitleList, ServerZoneIpcType > titleListPacket( pPlayer->getId() );
memcpy( titleListPacket.data().titleList, pPlayer->getTitleList(), sizeof( titleListPacket.data().titleList ) );
pPlayer->queuePacket( titleListPacket );
break;
}
case 0x133: // Update howtos seen
{
uint32_t howToId = static_cast< uint32_t >( param1 );
pPlayer->updateHowtosSeen( howToId );
break;
}
case 0x1F4: // emote
{
uint64_t targetId = pPlayer->getTargetId();
uint32_t emoteId = inPacket.getValAt< uint32_t >( 0x24 );
pPlayer->sendToInRangeSet( ActorControlPacket144( pPlayer->getId(), Emote, emoteId, 0, 0, 0, targetId ) );
break;
}
case 0xC8: // return dead
{
switch ( static_cast < ResurrectType >( param1 ) )
{
case ResurrectType::RaiseSpell:
// todo: handle raise case (set position to raiser, apply weakness status, set hp/mp/tp as well as packet)
pPlayer->returnToHomepoint();
break;
case ResurrectType::Return:
pPlayer->returnToHomepoint();
break;
default:
break;
}
}
case 0xC9: // Finish zoning
{
switch( pPlayer->getZoningType() )
{
case ZoneingType::None:
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01 ), true );
break;
case ZoneingType::Teleport:
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01, 0, 0, 110 ), true );
break;
case ZoneingType::Return:
case ZoneingType::ReturnDead:
{
if( pPlayer->getStatus() == Entity::Actor::ActorStatus::Dead )
{
pPlayer->resetHp();
pPlayer->resetMp();
pPlayer->setStatus( Entity::Actor::ActorStatus::Idle );
pPlayer->setSyncFlag( Status );
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01, 0x01, 0, 111 ), true );
pPlayer->sendToInRangeSet( ActorControlPacket142( pPlayer->getId(), SetStatus, static_cast< uint8_t >( Entity::Actor::ActorStatus::Idle ) ), true );
}
else
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01, 0x00, 0, 111 ), true );
}
break;
case ZoneingType::FadeIn:
break;
default:
break;
}
pPlayer->setZoningType( Common::ZoneingType::None );
pPlayer->unsetStateFlag( PlayerStateFlag::BetweenAreas );
pPlayer->unsetStateFlag( PlayerStateFlag::BetweenAreas1 );
pPlayer->sendStateFlags();
break;
}
case 0xCA: // Teleport
{
// TODO: only register this action if enough gil is in possession
auto targetAetheryte = g_exdData.getAetheryteInfo( param11 );
if( targetAetheryte )
{
auto fromAetheryte = g_exdData.getAetheryteInfo( g_exdData.m_zoneInfoMap[pPlayer->getZoneId()].aetheryte_index );
// calculate cost - does not apply for favorite points or homepoints neither checks for aether tickets
auto cost = static_cast< uint16_t > ( ( sqrt( pow( fromAetheryte->map_coord_x - targetAetheryte->map_coord_x, 2 ) +
pow( fromAetheryte->map_coord_y - targetAetheryte->map_coord_y, 2 ) ) / 2 ) + 100 );
// cap at 999 gil
cost = cost > 999 ? 999 : cost;
bool insufficientGil = pPlayer->getCurrency( Inventory::CurrencyType::Gil ) < cost;
// todo: figure out what param1 really does
pPlayer->queuePacket( ActorControlPacket143( pPlayer->getId(), TeleportStart, insufficientGil ? 2 : 0, param11 ) );
if( !insufficientGil )
{
Action::ActionTeleportPtr pActionTeleport( new Action::ActionTeleport( pPlayer, param11, cost ) );
pPlayer->setCurrentAction( pActionTeleport );
}
}
break;
}
default:
{
g_log.debug( "[" + std::to_string( m_pSession->getId() ) + "] Unhandled action: " +
boost::str( boost::format( "%|04X|" ) % (uint32_t) ( commandId & 0xFFFF ) ) );
}
}
}
<commit_msg>compiler warning fix<commit_after>#include <src/servers/Server_Common/Common.h>
#include <src/servers/Server_Common/Network/CommonNetwork.h>
#include <src/servers/Server_Common/Database/Database.h>
#include <src/servers/Server_Common/Network/GamePacketNew.h>
#include <src/servers/Server_Common/Logging/Logger.h>
#include <src/servers/Server_Common/Exd/ExdData.h>
#include <src/servers/Server_Common/Network/PacketContainer.h>
#include <boost/format.hpp>
#include "src/servers/Server_Zone/Network/GameConnection.h"
#include "src/servers/Server_Zone/Session.h"
#include "src/servers/Server_Zone/Zone/Zone.h"
#include "src/servers/Server_Zone/Zone/ZonePosition.h"
#include "src/servers/Server_Zone/ServerZone.h"
#include "src/servers/Server_Zone/Zone/ZoneMgr.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/InitUIPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/PingPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/MoveActorPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ChatPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ServerNoticePacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ActorControlPacket142.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ActorControlPacket143.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/ActorControlPacket144.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/EventStartPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/EventFinishPacket.h"
#include "src/servers/Server_Zone/Network/PacketWrappers/PlayerStateFlagsPacket.h"
#include "src/servers/Server_Zone/DebugCommand/DebugCommandHandler.h"
#include "src/servers/Server_Zone/Actor/Player.h"
#include "src/servers/Server_Zone/Inventory/Inventory.h"
#include "src/servers/Server_Zone/Forwards.h"
#include "src/servers/Server_Zone/Event/EventHelper.h"
#include "src/servers/Server_Zone/Action/Action.h"
#include "src/servers/Server_Zone/Action/ActionTeleport.h"
extern Core::Logger g_log;
extern Core::Db::Database g_database;
extern Core::ServerZone g_serverZone;
extern Core::ZoneMgr g_zoneMgr;
extern Core::Data::ExdData g_exdData;
extern Core::DebugCommandHandler g_gameCommandMgr;
using namespace Core::Common;
using namespace Core::Network::Packets;
using namespace Core::Network::Packets::Server;
void Core::Network::GameConnection::actionHandler( const Packets::GamePacket& inPacket,
Entity::PlayerPtr pPlayer )
{
uint16_t commandId = inPacket.getValAt< uint16_t >( 0x20 );
uint64_t param1 = inPacket.getValAt< uint64_t >( 0x24 );
uint32_t param11 = inPacket.getValAt< uint32_t >( 0x24 );
uint32_t param12 = inPacket.getValAt< uint32_t >( 0x28 );
uint32_t param2 = inPacket.getValAt< uint32_t >( 0x2c );
uint64_t param3 = inPacket.getValAt< uint64_t >( 0x38 );
g_log.debug( "[" + std::to_string( m_pSession->getId() ) + "] Incoming action: " +
boost::str( boost::format( "%|04X|" ) % ( uint32_t ) ( commandId & 0xFFFF ) ) +
"\nparam1: " + boost::str( boost::format( "%|016X|" ) % ( uint64_t ) ( param1 & 0xFFFFFFFFFFFFFFF ) ) +
"\nparam2: " + boost::str( boost::format( "%|08X|" ) % ( uint32_t ) ( param2 & 0xFFFFFFFF ) ) +
"\nparam3: " + boost::str( boost::format( "%|016X|" ) % ( uint64_t ) ( param3 & 0xFFFFFFFFFFFFFFF ) )
);
//g_log.Log(LoggingSeverity::debug, "[" + std::to_string(m_pSession->getId()) + "] " + pInPacket->toString());
switch( commandId )
{
case 0x01: // Toggle sheathe
{
if ( param11 == 1 )
pPlayer->setStance( Entity::Actor::Stance::Active );
else
{
pPlayer->setStance( Entity::Actor::Stance::Passive );
pPlayer->setAutoattack( false );
}
pPlayer->sendToInRangeSet( ActorControlPacket142( pPlayer->getId(), 0, param11, 1 ) );
break;
}
case 0x02: // Toggle auto-attack
{
if ( param11 == 1 )
{
pPlayer->setAutoattack( true );
pPlayer->setStance( Entity::Actor::Stance::Active );
}
else
pPlayer->setAutoattack( false );
pPlayer->sendToInRangeSet( ActorControlPacket142( pPlayer->getId(), 1, param11, 1 ) );
break;
}
case 0x03: // Change target
{
uint64_t targetId = inPacket.getValAt< uint64_t >( 0x24 );
pPlayer->changeTarget( targetId );
break;
}
case 0x65:
{
pPlayer->dismount();
break;
}
case 0x68: // Remove status (clicking it off)
{
// todo: check if status can be removed by client from exd
pPlayer->removeSingleStatusEffectFromId( static_cast< uint32_t >( param1 ) );
break;
}
case 0x69: // Cancel cast
{
if( pPlayer->getCurrentAction() != nullptr )
pPlayer->getCurrentAction()->setInterrupted();
break;
}
case 0x12E: // Set player title
{
pPlayer->setTitle( static_cast< uint16_t >( param1 ) );
break;
}
case 0x12F: // Get title list
{
GamePacketNew< FFXIVIpcPlayerTitleList, ServerZoneIpcType > titleListPacket( pPlayer->getId() );
memcpy( titleListPacket.data().titleList, pPlayer->getTitleList(), sizeof( titleListPacket.data().titleList ) );
pPlayer->queuePacket( titleListPacket );
break;
}
case 0x133: // Update howtos seen
{
uint32_t howToId = static_cast< uint32_t >( param1 );
pPlayer->updateHowtosSeen( howToId );
break;
}
case 0x1F4: // emote
{
uint64_t targetId = pPlayer->getTargetId();
uint32_t emoteId = inPacket.getValAt< uint32_t >( 0x24 );
pPlayer->sendToInRangeSet( ActorControlPacket144( pPlayer->getId(), Emote, emoteId, 0, 0, 0, targetId ) );
break;
}
case 0xC8: // return dead
{
switch ( static_cast < ResurrectType >( param1 ) )
{
case ResurrectType::RaiseSpell:
// todo: handle raise case (set position to raiser, apply weakness status, set hp/mp/tp as well as packet)
pPlayer->returnToHomepoint();
break;
case ResurrectType::Return:
pPlayer->returnToHomepoint();
break;
default:
break;
}
}
case 0xC9: // Finish zoning
{
switch( pPlayer->getZoningType() )
{
case ZoneingType::None:
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01 ), true );
break;
case ZoneingType::Teleport:
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01, 0, 0, 110 ), true );
break;
case ZoneingType::Return:
case ZoneingType::ReturnDead:
{
if( pPlayer->getStatus() == Entity::Actor::ActorStatus::Dead )
{
pPlayer->resetHp();
pPlayer->resetMp();
pPlayer->setStatus( Entity::Actor::ActorStatus::Idle );
pPlayer->setSyncFlag( Status );
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01, 0x01, 0, 111 ), true );
pPlayer->sendToInRangeSet( ActorControlPacket142( pPlayer->getId(), SetStatus, static_cast< uint8_t >( Entity::Actor::ActorStatus::Idle ) ), true );
}
else
pPlayer->sendToInRangeSet( ActorControlPacket143( pPlayer->getId(), ZoneIn, 0x01, 0x00, 0, 111 ), true );
}
break;
case ZoneingType::FadeIn:
break;
default:
break;
}
pPlayer->setZoningType( Common::ZoneingType::None );
pPlayer->unsetStateFlag( PlayerStateFlag::BetweenAreas );
pPlayer->unsetStateFlag( PlayerStateFlag::BetweenAreas1 );
pPlayer->sendStateFlags();
break;
}
case 0xCA: // Teleport
{
// TODO: only register this action if enough gil is in possession
auto targetAetheryte = g_exdData.getAetheryteInfo( param11 );
if( targetAetheryte )
{
auto fromAetheryte = g_exdData.getAetheryteInfo( g_exdData.m_zoneInfoMap[pPlayer->getZoneId()].aetheryte_index );
// calculate cost - does not apply for favorite points or homepoints neither checks for aether tickets
auto cost = static_cast< uint16_t > ( ( sqrt( pow( fromAetheryte->map_coord_x - targetAetheryte->map_coord_x, 2 ) +
pow( fromAetheryte->map_coord_y - targetAetheryte->map_coord_y, 2 ) ) / 2 ) + 100 );
// cap at 999 gil
cost = cost > 999 ? 999 : cost;
bool insufficientGil = pPlayer->getCurrency( Inventory::CurrencyType::Gil ) < cost;
// todo: figure out what param1 really does
pPlayer->queuePacket( ActorControlPacket143( pPlayer->getId(), TeleportStart, insufficientGil ? 2 : 0, param11 ) );
if( !insufficientGil )
{
Action::ActionTeleportPtr pActionTeleport( new Action::ActionTeleport( pPlayer, param11, cost ) );
pPlayer->setCurrentAction( pActionTeleport );
}
}
break;
}
default:
{
g_log.debug( "[" + std::to_string( m_pSession->getId() ) + "] Unhandled action: " +
boost::str( boost::format( "%|04X|" ) % (uint32_t) ( commandId & 0xFFFF ) ) );
}
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <string.h>
#include "MeshMaterial.h"
#include "Pack.h"
void MeshMaterial::reset()
{
texture = "";
textureMatrix = -1;
dynamicColor = -1;
const float defAmbient[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
const float defDiffuse[4] = { 0.8f, 0.8f, 0.8f, 1.0f };
const float defSpecular[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
const float defEmission[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
memcpy (ambient, defAmbient, sizeof(ambient));
memcpy (diffuse, defDiffuse, sizeof(diffuse));
memcpy (specular, defSpecular, sizeof(specular));
memcpy (emission, defEmission, sizeof(emission));
shininess = 0.0f;
useTexture = true;
useTextureAlpha = true;
useColorOnTexture = true;
return;
}
MeshMaterial::MeshMaterial()
{
reset();
return;
}
MeshMaterial::MeshMaterial(const MeshMaterial& m)
{
texture = m.texture;
textureMatrix = m.textureMatrix;
dynamicColor = m.dynamicColor;
memcpy (ambient, m.ambient, sizeof(ambient));
memcpy (diffuse, m.diffuse, sizeof(diffuse));
memcpy (specular, m.specular, sizeof(specular));
memcpy (emission, m.emission, sizeof(emission));
shininess = m.shininess;
useTexture = m.useTexture;
useTexture = m.useTextureAlpha;
useColorOnTexture = m.useColorOnTexture;
return;
}
MeshMaterial& MeshMaterial::operator=(const MeshMaterial& m)
{
texture = m.texture;
textureMatrix = m.textureMatrix;
dynamicColor = m.dynamicColor;
memcpy (ambient, m.ambient, sizeof(ambient));
memcpy (diffuse, m.diffuse, sizeof(diffuse));
memcpy (specular, m.specular, sizeof(specular));
memcpy (emission, m.emission, sizeof(emission));
shininess = m.shininess;
useTexture = m.useTexture;
useTexture = m.useTextureAlpha;
useColorOnTexture = m.useColorOnTexture;
return *this;
}
bool MeshMaterial::operator==(const MeshMaterial& m)
{
if ((texture != m.texture) ||
(textureMatrix != m.textureMatrix) ||
(dynamicColor != m.dynamicColor) ||
(shininess != m.shininess) ||
(memcmp (ambient, m.ambient, sizeof(float[4])) != 0) ||
(memcmp (diffuse, m.diffuse, sizeof(float[4])) != 0) ||
(memcmp (specular, m.specular, sizeof(float[4])) != 0) ||
(memcmp (emission, m.emission, sizeof(float[4])) != 0) ||
(useTexture != m.useTexture) ||
(useTextureAlpha != m.useTextureAlpha) ||
(useColorOnTexture != m.useColorOnTexture)) {
return false;
}
return true;
}
bool MeshMaterial::copyDiffs(const MeshMaterial& moded,
const MeshMaterial& orig)
{
bool changed = false;
if (orig.texture != moded.texture) {
texture = moded.texture;
changed = true;
}
if (orig.textureMatrix != moded.textureMatrix) {
textureMatrix = moded.textureMatrix;
changed = true;
}
if (orig.dynamicColor != moded.dynamicColor) {
dynamicColor = moded.dynamicColor;
changed = true;
}
if (orig.shininess != moded.shininess) {
shininess = moded.shininess;
changed = true;
}
if (memcmp (orig.ambient, moded.ambient, sizeof(float[4])) != 0) {
memcpy (ambient, moded.ambient, sizeof(float[4]));
changed = true;
}
if (memcmp (orig.diffuse, moded.diffuse, sizeof(float[4])) != 0) {
memcpy (diffuse, moded.diffuse, sizeof(float[4]));
changed = true;
}
if (memcmp (orig.specular, moded.specular, sizeof(float[4])) != 0) {
memcpy (specular, moded.specular, sizeof(float[4]));
changed = true;
}
if (memcmp (orig.emission, moded.emission, sizeof(float[4])) != 0) {
memcpy (emission, moded.emission, sizeof(float[4]));
changed = true;
}
if (orig.useTexture != moded.useTexture) {
useTexture = moded.useTexture;
changed = true;
}
if (orig.useTextureAlpha != moded.useTextureAlpha) {
useTextureAlpha = moded.useTextureAlpha;
changed = true;
}
if (orig.useColorOnTexture != moded.useColorOnTexture) {
useColorOnTexture = moded.useColorOnTexture;
changed = true;
}
return changed;
}
static void* pack4Float(void *buf, const float values[4])
{
int i;
for (i = 0; i < 4; i++) {
buf = nboPackFloat(buf, values[i]);
}
return buf;
}
static void* unpack4Float(void *buf, float values[4])
{
int i;
for (i = 0; i < 4; i++) {
buf = nboUnpackFloat(buf, values[i]);
}
return buf;
}
void* MeshMaterial::pack(void* buf)
{
unsigned char stateByte = 0;
if (useTexture) {
stateByte = stateByte | (1 << 0);
}
if (useTextureAlpha) {
stateByte = stateByte | (1 << 1);
}
if (useColorOnTexture) {
stateByte = stateByte | (1 << 2);
}
buf = nboPackUByte(buf, stateByte);
unsigned char len = (unsigned char)texture.size();
buf = nboPackUByte(buf, len);
buf = nboPackString(buf, texture.c_str(), len);
buf = nboPackInt(buf, textureMatrix);
buf = nboPackInt(buf, dynamicColor);
buf = pack4Float(buf, ambient);
buf = pack4Float(buf, diffuse);
buf = pack4Float(buf, specular);
buf = pack4Float(buf, emission);
buf = nboPackFloat(buf, shininess);
return buf;
}
void* MeshMaterial::unpack(void* buf)
{
unsigned char stateByte;
buf = nboUnpackUByte(buf, stateByte);
useTexture = useTextureAlpha= useColorOnTexture = false;
if (stateByte & (1 << 0)) {
useTexture = true;
}
if (stateByte & (1 << 1)) {
useTextureAlpha = true;
}
if (stateByte & (1 << 2)) {
useColorOnTexture = true;
}
char textureStr[256];
unsigned char len;
buf = nboUnpackUByte(buf, len);
buf = nboUnpackString(buf, textureStr, len);
textureStr[len] = '\0';
texture = textureStr;
buf = nboUnpackInt(buf, textureMatrix);
buf = nboUnpackInt(buf, dynamicColor);
buf = unpack4Float(buf, ambient);
buf = unpack4Float(buf, diffuse);
buf = unpack4Float(buf, specular);
buf = unpack4Float(buf, emission);
buf = nboUnpackFloat(buf, shininess);
return buf;
}
int MeshMaterial::packSize()
{
const int basicSize = (2 * sizeof(unsigned char)) +
sizeof(int) + sizeof(int) +
(4 * sizeof(float[4])) + sizeof(float);
unsigned char len = (unsigned char)texture.size();
return basicSize + len;
}
void MeshMaterial::print(std::ostream& out, int /*level*/)
{
if (texture.size() > 0) {
out << " texture " << texture << std::endl;
}
out << " texmat " << textureMatrix << std::endl;
if (!useTexture) {
out << " notexture" << std::endl;
}
if (!useTextureAlpha) {
out << " notexalpha" << std::endl;
}
if (!useColorOnTexture) {
out << " notexcolor" << std::endl;
}
out << " dyncol " << dynamicColor << std::endl;
out << " ambient " << ambient[0] << " " << ambient[1] << " "
<< ambient[2] << " " << ambient[3] << std::endl;
out << " diffuse " << diffuse[0] << " " << diffuse[1] << " "
<< diffuse[2] << " " << diffuse[3] << std::endl;
out << " specular " << specular[0] << " " << specular[1] << " "
<< specular[2] << " " << specular[3] << std::endl;
out << " emission " << emission[0] << " " << emission[1] << " "
<< emission[2] << " " << emission[3] << std::endl;
out << " shininess " << shininess << std::endl;
return;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>fix "notexture" material property<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <string.h>
#include "MeshMaterial.h"
#include "Pack.h"
void MeshMaterial::reset()
{
texture = "";
textureMatrix = -1;
dynamicColor = -1;
const float defAmbient[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
const float defDiffuse[4] = { 0.8f, 0.8f, 0.8f, 1.0f };
const float defSpecular[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
const float defEmission[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
memcpy (ambient, defAmbient, sizeof(ambient));
memcpy (diffuse, defDiffuse, sizeof(diffuse));
memcpy (specular, defSpecular, sizeof(specular));
memcpy (emission, defEmission, sizeof(emission));
shininess = 0.0f;
useTexture = true;
useTextureAlpha = true;
useColorOnTexture = true;
return;
}
MeshMaterial::MeshMaterial()
{
reset();
return;
}
MeshMaterial::MeshMaterial(const MeshMaterial& m)
{
texture = m.texture;
textureMatrix = m.textureMatrix;
dynamicColor = m.dynamicColor;
memcpy (ambient, m.ambient, sizeof(ambient));
memcpy (diffuse, m.diffuse, sizeof(diffuse));
memcpy (specular, m.specular, sizeof(specular));
memcpy (emission, m.emission, sizeof(emission));
shininess = m.shininess;
useTexture = m.useTexture;
useTextureAlpha = m.useTextureAlpha;
useColorOnTexture = m.useColorOnTexture;
return;
}
MeshMaterial& MeshMaterial::operator=(const MeshMaterial& m)
{
texture = m.texture;
textureMatrix = m.textureMatrix;
dynamicColor = m.dynamicColor;
memcpy (ambient, m.ambient, sizeof(ambient));
memcpy (diffuse, m.diffuse, sizeof(diffuse));
memcpy (specular, m.specular, sizeof(specular));
memcpy (emission, m.emission, sizeof(emission));
shininess = m.shininess;
useTexture = m.useTexture;
useTextureAlpha = m.useTextureAlpha;
useColorOnTexture = m.useColorOnTexture;
return *this;
}
bool MeshMaterial::operator==(const MeshMaterial& m)
{
if ((texture != m.texture) ||
(textureMatrix != m.textureMatrix) ||
(dynamicColor != m.dynamicColor) ||
(shininess != m.shininess) ||
(memcmp (ambient, m.ambient, sizeof(float[4])) != 0) ||
(memcmp (diffuse, m.diffuse, sizeof(float[4])) != 0) ||
(memcmp (specular, m.specular, sizeof(float[4])) != 0) ||
(memcmp (emission, m.emission, sizeof(float[4])) != 0) ||
(useTexture != m.useTexture) ||
(useTextureAlpha != m.useTextureAlpha) ||
(useColorOnTexture != m.useColorOnTexture)) {
return false;
}
return true;
}
bool MeshMaterial::copyDiffs(const MeshMaterial& moded,
const MeshMaterial& orig)
{
bool changed = false;
if (orig.texture != moded.texture) {
texture = moded.texture;
changed = true;
}
if (orig.textureMatrix != moded.textureMatrix) {
textureMatrix = moded.textureMatrix;
changed = true;
}
if (orig.dynamicColor != moded.dynamicColor) {
dynamicColor = moded.dynamicColor;
changed = true;
}
if (orig.shininess != moded.shininess) {
shininess = moded.shininess;
changed = true;
}
if (memcmp (orig.ambient, moded.ambient, sizeof(float[4])) != 0) {
memcpy (ambient, moded.ambient, sizeof(float[4]));
changed = true;
}
if (memcmp (orig.diffuse, moded.diffuse, sizeof(float[4])) != 0) {
memcpy (diffuse, moded.diffuse, sizeof(float[4]));
changed = true;
}
if (memcmp (orig.specular, moded.specular, sizeof(float[4])) != 0) {
memcpy (specular, moded.specular, sizeof(float[4]));
changed = true;
}
if (memcmp (orig.emission, moded.emission, sizeof(float[4])) != 0) {
memcpy (emission, moded.emission, sizeof(float[4]));
changed = true;
}
if (orig.useTexture != moded.useTexture) {
useTexture = moded.useTexture;
changed = true;
}
if (orig.useTextureAlpha != moded.useTextureAlpha) {
useTextureAlpha = moded.useTextureAlpha;
changed = true;
}
if (orig.useColorOnTexture != moded.useColorOnTexture) {
useColorOnTexture = moded.useColorOnTexture;
changed = true;
}
return changed;
}
static void* pack4Float(void *buf, const float values[4])
{
int i;
for (i = 0; i < 4; i++) {
buf = nboPackFloat(buf, values[i]);
}
return buf;
}
static void* unpack4Float(void *buf, float values[4])
{
int i;
for (i = 0; i < 4; i++) {
buf = nboUnpackFloat(buf, values[i]);
}
return buf;
}
void* MeshMaterial::pack(void* buf)
{
unsigned char stateByte = 0;
if (useTexture) {
stateByte = stateByte | (1 << 0);
}
if (useTextureAlpha) {
stateByte = stateByte | (1 << 1);
}
if (useColorOnTexture) {
stateByte = stateByte | (1 << 2);
}
buf = nboPackUByte(buf, stateByte);
unsigned char len = (unsigned char)texture.size();
buf = nboPackUByte(buf, len);
buf = nboPackString(buf, texture.c_str(), len);
buf = nboPackInt(buf, textureMatrix);
buf = nboPackInt(buf, dynamicColor);
buf = pack4Float(buf, ambient);
buf = pack4Float(buf, diffuse);
buf = pack4Float(buf, specular);
buf = pack4Float(buf, emission);
buf = nboPackFloat(buf, shininess);
return buf;
}
void* MeshMaterial::unpack(void* buf)
{
unsigned char stateByte;
buf = nboUnpackUByte(buf, stateByte);
useTexture = useTextureAlpha = useColorOnTexture = false;
if (stateByte & (1 << 0)) {
useTexture = true;
}
if (stateByte & (1 << 1)) {
useTextureAlpha = true;
}
if (stateByte & (1 << 2)) {
useColorOnTexture = true;
}
char textureStr[256];
unsigned char len;
buf = nboUnpackUByte(buf, len);
buf = nboUnpackString(buf, textureStr, len);
textureStr[len] = '\0';
texture = textureStr;
buf = nboUnpackInt(buf, textureMatrix);
buf = nboUnpackInt(buf, dynamicColor);
buf = unpack4Float(buf, ambient);
buf = unpack4Float(buf, diffuse);
buf = unpack4Float(buf, specular);
buf = unpack4Float(buf, emission);
buf = nboUnpackFloat(buf, shininess);
return buf;
}
int MeshMaterial::packSize()
{
const int basicSize = (2 * sizeof(unsigned char)) +
sizeof(int) + sizeof(int) +
(4 * sizeof(float[4])) + sizeof(float);
unsigned char len = (unsigned char)texture.size();
return basicSize + len;
}
void MeshMaterial::print(std::ostream& out, int /*level*/)
{
if (texture.size() > 0) {
out << " texture " << texture << std::endl;
}
out << " texmat " << textureMatrix << std::endl;
if (!useTexture) {
out << " notexture" << std::endl;
}
if (!useTextureAlpha) {
out << " notexalpha" << std::endl;
}
if (!useColorOnTexture) {
out << " notexcolor" << std::endl;
}
out << " dyncol " << dynamicColor << std::endl;
out << " ambient " << ambient[0] << " " << ambient[1] << " "
<< ambient[2] << " " << ambient[3] << std::endl;
out << " diffuse " << diffuse[0] << " " << diffuse[1] << " "
<< diffuse[2] << " " << diffuse[3] << std::endl;
out << " specular " << specular[0] << " " << specular[1] << " "
<< specular[2] << " " << specular[3] << std::endl;
out << " emission " << emission[0] << " " << emission[1] << " "
<< emission[2] << " " << emission[3] << std::endl;
out << " shininess " << shininess << std::endl;
return;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
namespace stan {
namespace prob {
/**
* The log of the normal density for the specified scalar(s) given
* the specified mean(s) and deviation(s). y, mu, or sigma can
* each be either a scalar or a std::vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/mean/deviation triple.
* @param y (Sequence of) scalar(s).
* @param mu (Sequence of) location parameter(s)
* for the normal distribution.
* @param sigma (Sequence of) scale parameters for the normal
* distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if the scale is not positive.
* @tparam T_y Underlying type of scalar in sequence.
* @tparam T_loc Type of location parameter.
*/
template <bool propto,
typename T_y, typename T_loc, typename T_scale,
class Policy>
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy& /*policy*/) {
static const char* function = "stan::prob::normal_log(%1%)";
using std::log;
using stan::is_constant_struct;
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
using stan::math::value_of;
using stan::prob::include_summand;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(mu)
&& stan::length(sigma)))
return 0.0;
// set up return value accumulator
double logp(0.0);
// validate args (here done over var, which should be OK)
if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
return logp;
if (!check_finite(function, mu, "Location parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, sigma, "Scale parameter",
&logp, Policy()))
return logp;
if (!(check_consistent_sizes(function,
y,mu,sigma,
"Random variable","Location parameter","Scale parameter",
&logp, Policy())))
return logp;
// check if no variables are involved and prop-to
if (!include_summand<propto,T_y,T_loc,T_scale>::value)
return 0.0;
// set up template expressions wrapping scalars into vector views
agrad::OperandsAndPartials<T_y, T_loc, T_scale> operands_and_partials(y, mu, sigma);
VectorView<const T_y> y_vec(y);
VectorView<const T_loc> mu_vec(mu);
VectorView<const T_scale> sigma_vec(sigma);
size_t N = max_size(y, mu, sigma);
DoubleVectorView<true,T_scale> inv_sigma(length(sigma));
DoubleVectorView<include_summand<propto,T_scale>::value,T_scale> log_sigma(length(sigma));
for (size_t i = 0; i < length(sigma); i++) {
inv_sigma[i] = 1.0 / value_of(sigma_vec[i]);
if (include_summand<propto,T_scale>::value)
log_sigma[i] = log(value_of(sigma_vec[i]));
}
for (size_t n = 0; n < N; n++) {
// pull out values of arguments
const double y_dbl = value_of(y_vec[n]);
const double mu_dbl = value_of(mu_vec[n]);
// reusable subexpression values
const double y_minus_mu_over_sigma
= (y_dbl - mu_dbl) * inv_sigma[n];
const double y_minus_mu_over_sigma_squared
= y_minus_mu_over_sigma * y_minus_mu_over_sigma;
static double NEGATIVE_HALF = - 0.5;
// log probability
if (include_summand<propto>::value)
logp += NEG_LOG_SQRT_TWO_PI;
if (include_summand<propto,T_scale>::value)
logp -= log_sigma[n];
if (include_summand<propto,T_y,T_loc,T_scale>::value)
logp += NEGATIVE_HALF * y_minus_mu_over_sigma_squared;
// gradients
double scaled_diff = inv_sigma[n] * y_minus_mu_over_sigma;
if (!is_constant_struct<T_y>::value)
operands_and_partials.d_x1[n] -= scaled_diff;
if (!is_constant_struct<T_loc>::value)
operands_and_partials.d_x2[n] += scaled_diff;
if (!is_constant_struct<T_scale>::value)
operands_and_partials.d_x3[n]
+= -inv_sigma[n] + inv_sigma[n] * y_minus_mu_over_sigma_squared;
}
return operands_and_partials.to_var(logp);
}
template <bool propto,
typename T_y, typename T_loc, typename T_scale>
inline
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<propto>(y,mu,sigma,stan::math::default_policy());
}
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
inline
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
return normal_log<false>(y,mu,sigma,Policy());
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<false>(y,mu,sigma,stan::math::default_policy());
}
/**
* Calculates the normal cumulative distribution function for the given
* variate, location, and scale.
*
* \f$\Phi(x) = \frac{1}{\sqrt{2 \pi}} \int_{-\inf}^x e^{-t^2/2} dt\f$.
*
* Errors are configured by policy. All variables must be finite
* and the scale must be strictly greater than zero.
*
* @param y A scalar variate.
* @param mu The location of the normal distribution.
* @param sigma The scale of the normal distriubtion
* @return The unit normal cdf evaluated at the specified arguments.
* @tparam T_y Type of y.
* @tparam T_loc Type of mean parameter.
* @tparam T_scale Type of standard deviation paramater.
* @tparam Policy Error-handling policy.
*/
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
typename return_type<T_y,T_loc,T_scale>::type
normal_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_cdf(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y, T_loc, T_scale>::type lp;
if (!check_not_nan(function, y, "Random variable", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter", &lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter",
&lp, Policy()))
return lp;
return 0.5 + 0.5 * erf((y - mu) / (sigma * SQRT_2));
// return 0.5 * erfc(-(y - mu)/(sigma * SQRT_2));
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y, T_loc, T_scale>::type
normal_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_cdf(y,mu,sigma,stan::math::default_policy());
}
template <typename T_loc, typename T_scale, class RNG>
inline double
normal_random(const T_loc& mu, const T_scale& sigma, RNG& rng) {
using boost::variate_generator;
using boost::normal_distribution;
using stan::math::value_of;
variate_generator<RNG&, normal_distribution<> >
rng_unit_norm(rng, normal_distribution<>());
return value_of(mu) + value_of(sigma) * rng_unit_norm();
}
}
}
#endif
<commit_msg>vectorized normal_cdf<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
namespace stan {
namespace prob {
/**
* The log of the normal density for the specified scalar(s) given
* the specified mean(s) and deviation(s). y, mu, or sigma can
* each be either a scalar or a std::vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/mean/deviation triple.
* @param y (Sequence of) scalar(s).
* @param mu (Sequence of) location parameter(s)
* for the normal distribution.
* @param sigma (Sequence of) scale parameters for the normal
* distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if the scale is not positive.
* @tparam T_y Underlying type of scalar in sequence.
* @tparam T_loc Type of location parameter.
*/
template <bool propto,
typename T_y, typename T_loc, typename T_scale,
class Policy>
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy& /*policy*/) {
static const char* function = "stan::prob::normal_log(%1%)";
using std::log;
using stan::is_constant_struct;
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
using stan::math::value_of;
using stan::prob::include_summand;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(mu)
&& stan::length(sigma)))
return 0.0;
// set up return value accumulator
double logp(0.0);
// validate args (here done over var, which should be OK)
if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
return logp;
if (!check_finite(function, mu, "Location parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, sigma, "Scale parameter",
&logp, Policy()))
return logp;
if (!(check_consistent_sizes(function,
y,mu,sigma,
"Random variable","Location parameter","Scale parameter",
&logp, Policy())))
return logp;
// check if no variables are involved and prop-to
if (!include_summand<propto,T_y,T_loc,T_scale>::value)
return 0.0;
// set up template expressions wrapping scalars into vector views
agrad::OperandsAndPartials<T_y, T_loc, T_scale> operands_and_partials(y, mu, sigma);
VectorView<const T_y> y_vec(y);
VectorView<const T_loc> mu_vec(mu);
VectorView<const T_scale> sigma_vec(sigma);
size_t N = max_size(y, mu, sigma);
DoubleVectorView<true,T_scale> inv_sigma(length(sigma));
DoubleVectorView<include_summand<propto,T_scale>::value,T_scale> log_sigma(length(sigma));
for (size_t i = 0; i < length(sigma); i++) {
inv_sigma[i] = 1.0 / value_of(sigma_vec[i]);
if (include_summand<propto,T_scale>::value)
log_sigma[i] = log(value_of(sigma_vec[i]));
}
for (size_t n = 0; n < N; n++) {
// pull out values of arguments
const double y_dbl = value_of(y_vec[n]);
const double mu_dbl = value_of(mu_vec[n]);
// reusable subexpression values
const double y_minus_mu_over_sigma
= (y_dbl - mu_dbl) * inv_sigma[n];
const double y_minus_mu_over_sigma_squared
= y_minus_mu_over_sigma * y_minus_mu_over_sigma;
static double NEGATIVE_HALF = - 0.5;
// log probability
if (include_summand<propto>::value)
logp += NEG_LOG_SQRT_TWO_PI;
if (include_summand<propto,T_scale>::value)
logp -= log_sigma[n];
if (include_summand<propto,T_y,T_loc,T_scale>::value)
logp += NEGATIVE_HALF * y_minus_mu_over_sigma_squared;
// gradients
double scaled_diff = inv_sigma[n] * y_minus_mu_over_sigma;
if (!is_constant_struct<T_y>::value)
operands_and_partials.d_x1[n] -= scaled_diff;
if (!is_constant_struct<T_loc>::value)
operands_and_partials.d_x2[n] += scaled_diff;
if (!is_constant_struct<T_scale>::value)
operands_and_partials.d_x3[n]
+= -inv_sigma[n] + inv_sigma[n] * y_minus_mu_over_sigma_squared;
}
return operands_and_partials.to_var(logp);
}
template <bool propto,
typename T_y, typename T_loc, typename T_scale>
inline
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<propto>(y,mu,sigma,stan::math::default_policy());
}
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
inline
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
return normal_log<false>(y,mu,sigma,Policy());
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename return_type<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<false>(y,mu,sigma,stan::math::default_policy());
}
/**
* Calculates the normal cumulative distribution function for the given
* variate, location, and scale.
*
* \f$\Phi(x) = \frac{1}{\sqrt{2 \pi}} \int_{-\inf}^x e^{-t^2/2} dt\f$.
*
* Errors are configured by policy. All variables must be finite
* and the scale must be strictly greater than zero.
*
* @param y A scalar variate.
* @param mu The location of the normal distribution.
* @param sigma The scale of the normal distriubtion
* @return The unit normal cdf evaluated at the specified arguments.
* @tparam T_y Type of y.
* @tparam T_loc Type of mean parameter.
* @tparam T_scale Type of standard deviation paramater.
* @tparam Policy Error-handling policy.
*/
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
typename return_type<T_y,T_loc,T_scale>::type
normal_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_cdf(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
typename return_type<T_y, T_loc, T_scale>::type cdf;
if (!check_not_nan(function, y, "Random variable", &cdf, Policy()))
return cdf;
if (!check_finite(function, mu, "Location parameter", &cdf, Policy()))
return cdf;
if (!check_not_nan(function, sigma, "Scale parameter",
&cdf, Policy()))
return cdf;
if (!check_positive(function, sigma, "Scale parameter",
&cdf, Policy()))
return cdf;
if (!(check_consistent_sizes(function,
y,mu,sigma,
"Random variable","Location parameter","Scale parameter",
&cdf, Policy())))
return cdf;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(mu)
&& stan::length(sigma)))
return 0.0;
VectorView<const T_y> y_vec(y);
VectorView<const T_loc> mu_vec(mu);
VectorView<const T_scale> sigma_vec(sigma);
size_t N = max_size(y, mu, sigma);
for (size_t n = 0; n < N; n++) {
cdf += 0.5 + 0.5 * erf((y_vec[n] - mu_vec[n]) / (sigma_vec[n] * SQRT_2));
}
return cdf;
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename return_type<T_y, T_loc, T_scale>::type
normal_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_cdf(y,mu,sigma,stan::math::default_policy());
}
template <typename T_loc, typename T_scale, class RNG>
inline double
normal_random(const T_loc& mu, const T_scale& sigma, RNG& rng) {
using boost::variate_generator;
using boost::normal_distribution;
using stan::math::value_of;
variate_generator<RNG&, normal_distribution<> >
rng_unit_norm(rng, normal_distribution<>());
return value_of(mu) + value_of(sigma) * rng_unit_norm();
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2010 Martin Schreiber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CPHYSICS_COLLISION_IMPULSE_HPP
#define CPHYSICS_COLLISION_IMPULSE_HPP
#include "cPhysicsCollisionData.hpp"
#include "worksheets_precompiler.hpp"
/*
* this class handles the change of object velocity (linear and angular)
* by applying an impulse
*/
class CPhysicsCollisionImpulse
{
public:
static inline void applyCollisionImpulse(CPhysicsCollisionData &c, double frame_elapsed_time)
{
#if WORKSHEET_6
#endif
if ( (c.physics_object1->no_rotations_and_frictions && c.physics_object2->no_rotations_and_frictions)
#if !WORKSHEET_6
|| 1
#endif
)
{
#if WORKSHEET_3
//no friction or rotations, apply linear impulse
//velocities in direction of collision normal
float collision_velocity1 = (-c.collision_normal).dotProd(c.physics_object1->velocity);
float collision_velocity2 = (-c.collision_normal).dotProd(c.physics_object2->velocity);
float closing_velocity = (collision_velocity1 - collision_velocity2);
//TODO
float coefficient_of_restitution = 0.9;
c.physics_object1->velocity = -c.collision_normal*closing_velocity*(c.physics_object1->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object1->velocity;
c.physics_object2->velocity = c.collision_normal*closing_velocity*(c.physics_object2->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object2->velocity;
#endif
}
else if ((c.physics_object1->friction_disabled && c.physics_object2->friction_disabled)
#if !WORKSHEET_7
|| 1
#endif
)
{
#if WORKSHEET_6
#endif
}
else
{
#if WORKSHEET_7
#endif
}
// DAMPING TEST
#if 0
c.physics_object1->velocity -= c.physics_object1->velocity*frame_elapsed_time*0.5;
c.physics_object2->velocity -= c.physics_object2->velocity*frame_elapsed_time*0.5;
c.physics_object1->angular_velocity -= c.physics_object1->angular_velocity*frame_elapsed_time*0.5;
c.physics_object2->angular_velocity -= c.physics_object2->angular_velocity*frame_elapsed_time*0.5;
#endif
#if 0
if (c.physics_object1->velocity.getLength() < 0.5) c.physics_object1->velocity.setZero();
if (c.physics_object2->velocity.getLength() < 0.5) c.physics_object2->velocity.setZero();
if (c.physics_object1->angular_velocity.getLength() < 0.2) c.physics_object1->angular_velocity.setZero();
if (c.physics_object2->angular_velocity.getLength() < 0.2) c.physics_object2->angular_velocity.setZero();
#endif
}
};
#endif
<commit_msg>Fixed coefficient of restitution for impulses<commit_after>/*
* Copyright 2010 Martin Schreiber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CPHYSICS_COLLISION_IMPULSE_HPP
#define CPHYSICS_COLLISION_IMPULSE_HPP
#include "cPhysicsCollisionData.hpp"
#include "worksheets_precompiler.hpp"
/*
* this class handles the change of object velocity (linear and angular)
* by applying an impulse
*/
class CPhysicsCollisionImpulse
{
public:
static inline void applyCollisionImpulse(CPhysicsCollisionData &c, double frame_elapsed_time)
{
#if WORKSHEET_6
#endif
if ( (c.physics_object1->no_rotations_and_frictions && c.physics_object2->no_rotations_and_frictions)
#if !WORKSHEET_6
|| 1
#endif
)
{
#if WORKSHEET_3
//no friction or rotations, apply linear impulse
//velocities in direction of collision normal
float collision_velocity1 = (-c.collision_normal).dotProd(c.physics_object1->velocity);
float collision_velocity2 = (-c.collision_normal).dotProd(c.physics_object2->velocity);
float closing_velocity = (collision_velocity1 - collision_velocity2);
float coefficient_of_restitution = (c.physics_object1->restitution_coefficient * c.physics_object2->restitution_coefficient)/2.0;
c.physics_object1->velocity = -c.collision_normal*closing_velocity*(c.physics_object1->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object1->velocity;
c.physics_object2->velocity = c.collision_normal*closing_velocity*(c.physics_object2->inv_mass/(c.physics_object1->inv_mass + c.physics_object2->inv_mass))*(-(1+coefficient_of_restitution)) + c.physics_object2->velocity;
#endif
}
else if ((c.physics_object1->friction_disabled && c.physics_object2->friction_disabled)
#if !WORKSHEET_7
|| 1
#endif
)
{
#if WORKSHEET_6
#endif
}
else
{
#if WORKSHEET_7
#endif
}
// DAMPING TEST
#if 0
c.physics_object1->velocity -= c.physics_object1->velocity*frame_elapsed_time*0.5;
c.physics_object2->velocity -= c.physics_object2->velocity*frame_elapsed_time*0.5;
c.physics_object1->angular_velocity -= c.physics_object1->angular_velocity*frame_elapsed_time*0.5;
c.physics_object2->angular_velocity -= c.physics_object2->angular_velocity*frame_elapsed_time*0.5;
#endif
#if 0
if (c.physics_object1->velocity.getLength() < 0.5) c.physics_object1->velocity.setZero();
if (c.physics_object2->velocity.getLength() < 0.5) c.physics_object2->velocity.setZero();
if (c.physics_object1->angular_velocity.getLength() < 0.2) c.physics_object1->angular_velocity.setZero();
if (c.physics_object2->angular_velocity.getLength() < 0.2) c.physics_object2->angular_velocity.setZero();
#endif
}
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFloatingPoint.h"
#include "SkRasterPipeline.h"
#include "SkReadBuffer.h"
#include "SkTwoPointConicalGradient.h"
#include "SkWriteBuffer.h"
#include "../../jumper/SkJumper.h"
// Please see https://skia.org/dev/design/conical for how our shader works.
bool SkTwoPointConicalGradient::FocalData::set(SkScalar r0, SkScalar r1, SkMatrix* matrix) {
fIsSwapped = false;
fFocalX = sk_ieee_float_divide(r0, (r0 - r1));
if (SkScalarNearlyZero(fFocalX - 1)) {
// swap r0, r1
matrix->postTranslate(-1, 0);
matrix->postScale(-1, 1);
std::swap(r0, r1);
fFocalX = 0; // because r0 is now 0
fIsSwapped = true;
}
// Map {focal point, (1, 0)} to {(0, 0), (1, 0)}
const SkPoint from[2] = { {fFocalX, 0}, {1, 0} };
const SkPoint to[2] = { {0, 0}, {1, 0} };
SkMatrix focalMatrix;
if (!focalMatrix.setPolyToPoly(from, to, 2)) {
return false;
}
matrix->postConcat(focalMatrix);
fR1 = r1 / SkScalarAbs(1 - fFocalX); // focalMatrix has a scale of 1/(1-f)
// The following transformations are just to accelerate the shader computation by saving
// some arithmatic operations.
if (this->isFocalOnCircle()) {
matrix->postScale(0.5, 0.5);
} else {
matrix->postScale(fR1 / (fR1 * fR1 - 1), 1 / sqrt(SkScalarAbs(fR1 * fR1 - 1)));
}
matrix->postScale(SkScalarAbs(1 - fFocalX), SkScalarAbs(1 - fFocalX)); // scale |1 - f|
return true;
}
sk_sp<SkShader> SkTwoPointConicalGradient::Create(const SkPoint& c0, SkScalar r0,
const SkPoint& c1, SkScalar r1,
const Descriptor& desc) {
SkMatrix gradientMatrix;
Type gradientType;
if (SkScalarNearlyZero((c0 - c1).length())) {
// Concentric case: we can pretend we're radial (with a tiny twist).
const SkScalar scale = sk_ieee_float_divide(1, SkTMax(r0, r1));
gradientMatrix = SkMatrix::MakeTrans(-c1.x(), -c1.y());
gradientMatrix.postScale(scale, scale);
gradientType = Type::kRadial;
} else {
const SkPoint centers[2] = { c0 , c1 };
const SkPoint unitvec[2] = { {0, 0}, {1, 0} };
if (!gradientMatrix.setPolyToPoly(centers, unitvec, 2)) {
// Degenerate case.
return nullptr;
}
gradientType = SkScalarNearlyZero(r1 - r0) ? Type::kStrip : Type::kFocal;
}
FocalData focalData;
if (gradientType == Type::kFocal) {
const auto dCenter = (c0 - c1).length();
if (!focalData.set(r0 / dCenter, r1 / dCenter, &gradientMatrix)) {
return nullptr;
}
}
return sk_sp<SkShader>(new SkTwoPointConicalGradient(c0, r0, c1, r1, desc,
gradientType, gradientMatrix, focalData));
}
SkTwoPointConicalGradient::SkTwoPointConicalGradient(
const SkPoint& start, SkScalar startRadius,
const SkPoint& end, SkScalar endRadius,
const Descriptor& desc, Type type, const SkMatrix& gradientMatrix, const FocalData& data)
: SkGradientShaderBase(desc, gradientMatrix)
, fCenter1(start)
, fCenter2(end)
, fRadius1(startRadius)
, fRadius2(endRadius)
, fType(type)
{
// this is degenerate, and should be caught by our caller
SkASSERT(fCenter1 != fCenter2 || fRadius1 != fRadius2);
if (type == Type::kFocal) {
fFocalData = data;
}
}
bool SkTwoPointConicalGradient::isOpaque() const {
// Because areas outside the cone are left untouched, we cannot treat the
// shader as opaque even if the gradient itself is opaque.
// TODO(junov): Compute whether the cone fills the plane crbug.com/222380
return false;
}
// Returns the original non-sorted version of the gradient
SkShader::GradientType SkTwoPointConicalGradient::asAGradient(GradientInfo* info) const {
if (info) {
commonAsAGradient(info);
info->fPoint[0] = fCenter1;
info->fPoint[1] = fCenter2;
info->fRadius[0] = fRadius1;
info->fRadius[1] = fRadius2;
}
return kConical_GradientType;
}
sk_sp<SkFlattenable> SkTwoPointConicalGradient::CreateProc(SkReadBuffer& buffer) {
DescriptorScope desc;
if (!desc.unflatten(buffer)) {
return nullptr;
}
SkPoint c1 = buffer.readPoint();
SkPoint c2 = buffer.readPoint();
SkScalar r1 = buffer.readScalar();
SkScalar r2 = buffer.readScalar();
if (buffer.isVersionLT(SkReadBuffer::k2PtConicalNoFlip_Version) && buffer.readBool()) {
// legacy flipped gradient
SkTSwap(c1, c2);
SkTSwap(r1, r2);
SkColor4f* colors = desc.mutableColors();
SkScalar* pos = desc.mutablePos();
const int last = desc.fCount - 1;
const int half = desc.fCount >> 1;
for (int i = 0; i < half; ++i) {
SkTSwap(colors[i], colors[last - i]);
if (pos) {
SkScalar tmp = pos[i];
pos[i] = SK_Scalar1 - pos[last - i];
pos[last - i] = SK_Scalar1 - tmp;
}
}
if (pos) {
if (desc.fCount & 1) {
pos[half] = SK_Scalar1 - pos[half];
}
}
}
return SkGradientShader::MakeTwoPointConical(c1, r1, c2, r2, desc.fColors,
std::move(desc.fColorSpace), desc.fPos,
desc.fCount, desc.fTileMode, desc.fGradFlags,
desc.fLocalMatrix);
}
void SkTwoPointConicalGradient::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writePoint(fCenter1);
buffer.writePoint(fCenter2);
buffer.writeScalar(fRadius1);
buffer.writeScalar(fRadius2);
}
#if SK_SUPPORT_GPU
#include "SkGr.h"
#include "SkTwoPointConicalGradient_gpu.h"
std::unique_ptr<GrFragmentProcessor> SkTwoPointConicalGradient::asFragmentProcessor(
const GrFPArgs& args) const {
SkMatrix matrix;
if (!this->totalLocalMatrix(args.fPreLocalMatrix, args.fPostLocalMatrix)->invert(&matrix)) {
return nullptr;
}
return Gr2PtConicalGradientEffect::Make(
GrGradientEffect::CreateArgs(args.fContext, this, &matrix, fTileMode,
args.fDstColorSpaceInfo->colorSpace()));
}
#endif
sk_sp<SkShader> SkTwoPointConicalGradient::onMakeColorSpace(SkColorSpaceXformer* xformer) const {
const AutoXformColors xformedColors(*this, xformer);
return SkGradientShader::MakeTwoPointConical(fCenter1, fRadius1, fCenter2, fRadius2,
xformedColors.fColors.get(), fOrigPos, fColorCount,
fTileMode, fGradFlags, &this->getLocalMatrix());
}
void SkTwoPointConicalGradient::toString(SkString* str) const {
str->append("SkTwoPointConicalGradient: (");
str->append("center1: (");
str->appendScalar(fCenter1.fX);
str->append(", ");
str->appendScalar(fCenter1.fY);
str->append(") radius1: ");
str->appendScalar(fRadius1);
str->append(" ");
str->append("center2: (");
str->appendScalar(fCenter2.fX);
str->append(", ");
str->appendScalar(fCenter2.fY);
str->append(") radius2: ");
str->appendScalar(fRadius2);
str->append(" ");
this->INHERITED::toString(str);
str->append(")");
}
void SkTwoPointConicalGradient::appendGradientStages(SkArenaAlloc* alloc, SkRasterPipeline* p,
SkRasterPipeline* postPipeline) const {
const auto dRadius = fRadius2 - fRadius1;
if (fType == Type::kRadial) {
p->append(SkRasterPipeline::xy_to_radius);
// Tiny twist: radial computes a t for [0, r2], but we want a t for [r1, r2].
auto scale = SkTMax(fRadius1, fRadius2) / dRadius;
auto bias = -fRadius1 / dRadius;
p->append_matrix(alloc, SkMatrix::Concat(SkMatrix::MakeTrans(bias, 0),
SkMatrix::MakeScale(scale, 1)));
return;
}
if (fType == Type::kStrip) {
auto* ctx = alloc->make<SkJumper_2PtConicalCtx>();
SkScalar scaledR0 = fRadius1 / this->getCenterX1();
ctx->fP0 = scaledR0 * scaledR0;
p->append(SkRasterPipeline::xy_to_2pt_conical_strip, ctx);
p->append(SkRasterPipeline::mask_2pt_conical_nan, ctx);
postPipeline->append(SkRasterPipeline::apply_vector_mask, &ctx->fMask);
return;
}
auto* ctx = alloc->make<SkJumper_2PtConicalCtx>();
ctx->fP0 = 1/fFocalData.fR1;
ctx->fP1 = fFocalData.fFocalX;
if (fFocalData.isFocalOnCircle()) {
p->append(SkRasterPipeline::xy_to_2pt_conical_focal_on_circle);
} else if (fFocalData.isWellBehaved()) {
p->append(SkRasterPipeline::xy_to_2pt_conical_well_behaved, ctx);
} else if (fFocalData.isSwapped() || 1 - fFocalData.fFocalX < 0) {
p->append(SkRasterPipeline::xy_to_2pt_conical_smaller, ctx);
} else {
p->append(SkRasterPipeline::xy_to_2pt_conical_greater, ctx);
}
if (!fFocalData.isWellBehaved()) {
p->append(SkRasterPipeline::mask_2pt_conical_degenerates, ctx);
}
if (1 - fFocalData.fFocalX < 0) {
p->append(SkRasterPipeline::negate_x);
}
if (!fFocalData.isNativelyFocal()) {
p->append(SkRasterPipeline::alter_2pt_conical_compensate_focal, ctx);
}
if (fFocalData.isSwapped()) {
p->append(SkRasterPipeline::alter_2pt_conical_unswap);
}
if (!fFocalData.isWellBehaved()) {
postPipeline->append(SkRasterPipeline::apply_vector_mask, &ctx->fMask);
}
}
<commit_msg>Avoid dividing by zero in SkTwoPointConicalGradient::Create<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFloatingPoint.h"
#include "SkRasterPipeline.h"
#include "SkReadBuffer.h"
#include "SkTwoPointConicalGradient.h"
#include "SkWriteBuffer.h"
#include "../../jumper/SkJumper.h"
// Please see https://skia.org/dev/design/conical for how our shader works.
bool SkTwoPointConicalGradient::FocalData::set(SkScalar r0, SkScalar r1, SkMatrix* matrix) {
fIsSwapped = false;
fFocalX = sk_ieee_float_divide(r0, (r0 - r1));
if (SkScalarNearlyZero(fFocalX - 1)) {
// swap r0, r1
matrix->postTranslate(-1, 0);
matrix->postScale(-1, 1);
std::swap(r0, r1);
fFocalX = 0; // because r0 is now 0
fIsSwapped = true;
}
// Map {focal point, (1, 0)} to {(0, 0), (1, 0)}
const SkPoint from[2] = { {fFocalX, 0}, {1, 0} };
const SkPoint to[2] = { {0, 0}, {1, 0} };
SkMatrix focalMatrix;
if (!focalMatrix.setPolyToPoly(from, to, 2)) {
return false;
}
matrix->postConcat(focalMatrix);
fR1 = r1 / SkScalarAbs(1 - fFocalX); // focalMatrix has a scale of 1/(1-f)
// The following transformations are just to accelerate the shader computation by saving
// some arithmatic operations.
if (this->isFocalOnCircle()) {
matrix->postScale(0.5, 0.5);
} else {
matrix->postScale(fR1 / (fR1 * fR1 - 1), 1 / sqrt(SkScalarAbs(fR1 * fR1 - 1)));
}
matrix->postScale(SkScalarAbs(1 - fFocalX), SkScalarAbs(1 - fFocalX)); // scale |1 - f|
return true;
}
sk_sp<SkShader> SkTwoPointConicalGradient::Create(const SkPoint& c0, SkScalar r0,
const SkPoint& c1, SkScalar r1,
const Descriptor& desc) {
SkMatrix gradientMatrix;
Type gradientType;
if (SkScalarNearlyZero((c0 - c1).length())) {
if (SkScalarNearlyZero(SkTMax(r0, r1))) {
return nullptr; // Degenerate case; avoid dividing by zero.
}
// Concentric case: we can pretend we're radial (with a tiny twist).
const SkScalar scale = sk_ieee_float_divide(1, SkTMax(r0, r1));
gradientMatrix = SkMatrix::MakeTrans(-c1.x(), -c1.y());
gradientMatrix.postScale(scale, scale);
gradientType = Type::kRadial;
} else {
const SkPoint centers[2] = { c0 , c1 };
const SkPoint unitvec[2] = { {0, 0}, {1, 0} };
if (!gradientMatrix.setPolyToPoly(centers, unitvec, 2)) {
// Degenerate case.
return nullptr;
}
gradientType = SkScalarNearlyZero(r1 - r0) ? Type::kStrip : Type::kFocal;
}
FocalData focalData;
if (gradientType == Type::kFocal) {
const auto dCenter = (c0 - c1).length();
if (!focalData.set(r0 / dCenter, r1 / dCenter, &gradientMatrix)) {
return nullptr;
}
}
return sk_sp<SkShader>(new SkTwoPointConicalGradient(c0, r0, c1, r1, desc,
gradientType, gradientMatrix, focalData));
}
SkTwoPointConicalGradient::SkTwoPointConicalGradient(
const SkPoint& start, SkScalar startRadius,
const SkPoint& end, SkScalar endRadius,
const Descriptor& desc, Type type, const SkMatrix& gradientMatrix, const FocalData& data)
: SkGradientShaderBase(desc, gradientMatrix)
, fCenter1(start)
, fCenter2(end)
, fRadius1(startRadius)
, fRadius2(endRadius)
, fType(type)
{
// this is degenerate, and should be caught by our caller
SkASSERT(fCenter1 != fCenter2 || fRadius1 != fRadius2);
if (type == Type::kFocal) {
fFocalData = data;
}
}
bool SkTwoPointConicalGradient::isOpaque() const {
// Because areas outside the cone are left untouched, we cannot treat the
// shader as opaque even if the gradient itself is opaque.
// TODO(junov): Compute whether the cone fills the plane crbug.com/222380
return false;
}
// Returns the original non-sorted version of the gradient
SkShader::GradientType SkTwoPointConicalGradient::asAGradient(GradientInfo* info) const {
if (info) {
commonAsAGradient(info);
info->fPoint[0] = fCenter1;
info->fPoint[1] = fCenter2;
info->fRadius[0] = fRadius1;
info->fRadius[1] = fRadius2;
}
return kConical_GradientType;
}
sk_sp<SkFlattenable> SkTwoPointConicalGradient::CreateProc(SkReadBuffer& buffer) {
DescriptorScope desc;
if (!desc.unflatten(buffer)) {
return nullptr;
}
SkPoint c1 = buffer.readPoint();
SkPoint c2 = buffer.readPoint();
SkScalar r1 = buffer.readScalar();
SkScalar r2 = buffer.readScalar();
if (buffer.isVersionLT(SkReadBuffer::k2PtConicalNoFlip_Version) && buffer.readBool()) {
// legacy flipped gradient
SkTSwap(c1, c2);
SkTSwap(r1, r2);
SkColor4f* colors = desc.mutableColors();
SkScalar* pos = desc.mutablePos();
const int last = desc.fCount - 1;
const int half = desc.fCount >> 1;
for (int i = 0; i < half; ++i) {
SkTSwap(colors[i], colors[last - i]);
if (pos) {
SkScalar tmp = pos[i];
pos[i] = SK_Scalar1 - pos[last - i];
pos[last - i] = SK_Scalar1 - tmp;
}
}
if (pos) {
if (desc.fCount & 1) {
pos[half] = SK_Scalar1 - pos[half];
}
}
}
return SkGradientShader::MakeTwoPointConical(c1, r1, c2, r2, desc.fColors,
std::move(desc.fColorSpace), desc.fPos,
desc.fCount, desc.fTileMode, desc.fGradFlags,
desc.fLocalMatrix);
}
void SkTwoPointConicalGradient::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writePoint(fCenter1);
buffer.writePoint(fCenter2);
buffer.writeScalar(fRadius1);
buffer.writeScalar(fRadius2);
}
#if SK_SUPPORT_GPU
#include "SkGr.h"
#include "SkTwoPointConicalGradient_gpu.h"
std::unique_ptr<GrFragmentProcessor> SkTwoPointConicalGradient::asFragmentProcessor(
const GrFPArgs& args) const {
SkMatrix matrix;
if (!this->totalLocalMatrix(args.fPreLocalMatrix, args.fPostLocalMatrix)->invert(&matrix)) {
return nullptr;
}
return Gr2PtConicalGradientEffect::Make(
GrGradientEffect::CreateArgs(args.fContext, this, &matrix, fTileMode,
args.fDstColorSpaceInfo->colorSpace()));
}
#endif
sk_sp<SkShader> SkTwoPointConicalGradient::onMakeColorSpace(SkColorSpaceXformer* xformer) const {
const AutoXformColors xformedColors(*this, xformer);
return SkGradientShader::MakeTwoPointConical(fCenter1, fRadius1, fCenter2, fRadius2,
xformedColors.fColors.get(), fOrigPos, fColorCount,
fTileMode, fGradFlags, &this->getLocalMatrix());
}
void SkTwoPointConicalGradient::toString(SkString* str) const {
str->append("SkTwoPointConicalGradient: (");
str->append("center1: (");
str->appendScalar(fCenter1.fX);
str->append(", ");
str->appendScalar(fCenter1.fY);
str->append(") radius1: ");
str->appendScalar(fRadius1);
str->append(" ");
str->append("center2: (");
str->appendScalar(fCenter2.fX);
str->append(", ");
str->appendScalar(fCenter2.fY);
str->append(") radius2: ");
str->appendScalar(fRadius2);
str->append(" ");
this->INHERITED::toString(str);
str->append(")");
}
void SkTwoPointConicalGradient::appendGradientStages(SkArenaAlloc* alloc, SkRasterPipeline* p,
SkRasterPipeline* postPipeline) const {
const auto dRadius = fRadius2 - fRadius1;
if (fType == Type::kRadial) {
p->append(SkRasterPipeline::xy_to_radius);
// Tiny twist: radial computes a t for [0, r2], but we want a t for [r1, r2].
auto scale = SkTMax(fRadius1, fRadius2) / dRadius;
auto bias = -fRadius1 / dRadius;
p->append_matrix(alloc, SkMatrix::Concat(SkMatrix::MakeTrans(bias, 0),
SkMatrix::MakeScale(scale, 1)));
return;
}
if (fType == Type::kStrip) {
auto* ctx = alloc->make<SkJumper_2PtConicalCtx>();
SkScalar scaledR0 = fRadius1 / this->getCenterX1();
ctx->fP0 = scaledR0 * scaledR0;
p->append(SkRasterPipeline::xy_to_2pt_conical_strip, ctx);
p->append(SkRasterPipeline::mask_2pt_conical_nan, ctx);
postPipeline->append(SkRasterPipeline::apply_vector_mask, &ctx->fMask);
return;
}
auto* ctx = alloc->make<SkJumper_2PtConicalCtx>();
ctx->fP0 = 1/fFocalData.fR1;
ctx->fP1 = fFocalData.fFocalX;
if (fFocalData.isFocalOnCircle()) {
p->append(SkRasterPipeline::xy_to_2pt_conical_focal_on_circle);
} else if (fFocalData.isWellBehaved()) {
p->append(SkRasterPipeline::xy_to_2pt_conical_well_behaved, ctx);
} else if (fFocalData.isSwapped() || 1 - fFocalData.fFocalX < 0) {
p->append(SkRasterPipeline::xy_to_2pt_conical_smaller, ctx);
} else {
p->append(SkRasterPipeline::xy_to_2pt_conical_greater, ctx);
}
if (!fFocalData.isWellBehaved()) {
p->append(SkRasterPipeline::mask_2pt_conical_degenerates, ctx);
}
if (1 - fFocalData.fFocalX < 0) {
p->append(SkRasterPipeline::negate_x);
}
if (!fFocalData.isNativelyFocal()) {
p->append(SkRasterPipeline::alter_2pt_conical_compensate_focal, ctx);
}
if (fFocalData.isSwapped()) {
p->append(SkRasterPipeline::alter_2pt_conical_unswap);
}
if (!fFocalData.isWellBehaved()) {
postPipeline->append(SkRasterPipeline::apply_vector_mask, &ctx->fMask);
}
}
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Christopher Blauvelt <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/* Based on source code from Mpeg KFile plugin by Allan Sandfeld Jensen
* and libmpeg3.
*/
#include "strigiconfig.h"
#include "mpegendanalyzer.h"
#include "analysisresult.h"
#include "textutils.h"
#include <iostream>
using namespace Strigi;
using namespace std;
void MpegEndAnalyzerFactory::registerFields(FieldRegister& r) {
fields["length"] = r.registerField("media.duration", FieldRegister::integerType, 1, 0);
fields["dimensions.y"] = r.registerField("image.dimensions.y", FieldRegister::integerType, 1, 0);
fields["dimensions.x"] = r.registerField("image.dimensions.x", FieldRegister::integerType, 1, 0);
fields["frame rate"] = r.registerField("video.frame_rate", FieldRegister::floatType, 1, 0);
fields["video codec"] = r.registerField("av.video_codec", FieldRegister::stringType, 1, 0);
fields["audio codec"] = r.registerField("av.audio_codec", FieldRegister::stringType, 1, 0);
fields["aspect ratio"] = r.registerField("image.aspect_ratio", FieldRegister::stringType, 1, 0);
}
bool MpegEndAnalyzer::checkHeader(const char* header, int32_t headersize) const
{
uint32_t dword = 0;
if(headersize < 9)
{
//cerr << "File was less than nine bytes. Not long enough" << endl;
return false;
}
dword = readBigEndianUInt32(header);
if(dword == 0x52494646) // == "RIFF"
{
dword = readBigEndianUInt32(header+5);
if (dword == 0x43445841) { // == "CDXA"
//cerr << "CDXA not yet supported" << endl;
return false;
}
}
else if(dword != 0x000001ba) {
//cerr << "Not a MPEG-PS file" << endl;
return false;
}
return true;
}
char MpegEndAnalyzer::analyze(AnalysisResult& idx, InputStream* in) {
if(!in) {
return -1;
}
if(!this->readMpeg(in) )
{
//cerr << "Error reading mpeg." << endl;
in->reset(0);
return -1;
}
std::map<std::string, const Strigi::RegisteredField*>tempfields = factory->fields;
idx.addValue(tempfields["frame rate"], this->frame_rate);
idx.addValue(tempfields["dimensions.y"], this->vertical_size);
idx.addValue(tempfields["dimensions.x"], this->horizontal_size);
if (this->mpeg_version == 1) idx.addValue(tempfields["video codec"], "MPEG-1");
else idx.addValue(tempfields["video codec"], "MPEG-2");
switch (this->audio_type)
{
case 1:
idx.addValue(tempfields["audio codec"], "MP1");
break;
case 2:
idx.addValue(tempfields["audio codec"], "MP2");
break;
case 3:
idx.addValue(tempfields["audio codec"], "MP3");
break;
case 5:
idx.addValue(tempfields["audio codec"], "AC3");
break;
case 7:
idx.addValue(tempfields["audio codec"], "PCM");
break;
default:
idx.addValue(tempfields["audio codec"], "Unknown");
}
// MPEG 1 also has an aspect ratio setting, but it works differently,
// and I am not sure if it is used.
if (this->mpeg_version == 2) {
switch (this->aspect_ratio) {
case 1:
idx.addValue(tempfields["aspect ratio"], "default");
break;
case 2:
idx.addValue(tempfields["aspect ratio"], "4/3");
break;
case 3:
idx.addValue(tempfields["aspect ratio"], "16/9");
break;
case 4:
idx.addValue(tempfields["aspect ratio"], "2.11/1");
break;
}
}
return 0;
}
bool MpegEndAnalyzer::readMpeg(InputStream* in) {
if(!in) {
return false;
}
const char *buf;
this->mpeg_version = 0;
this->audio_type = 0;
uint32_t dword = 0,nread = 0;
//Now that we've established that this is an mpeg file (almost),
//we search for the audio and video elements
in->reset(0);
uint16_t packet;
bool video_found = false, audio_found = false, read_error = false;
// Start searching for MPEG packets
while((nread = in->read(buf,2,2) ) )
{
if(nread != 2)
{
read_error = true;
break;
}
packet = readBigEndianUInt16(buf);
if(packet == this->sequence_start)
{
if(video_found) break;
if(this->parse_seq(in) ) video_found = true;
}
else if(packet == this->ext_sequence_start)
{
this->parse_seq_ext(in);
}
else if(packet == this->private1_packet || packet == this->private2_packet)
{
this->parse_private(in);
}
else if(packet == this->audio1_packet || packet == this->audio2_packet)
{
if(audio_found) break;
if(this->parse_audio(in) ) audio_found = true;
}
if (video_found && audio_found) break;
}
if(read_error)
{
return false;
}
else if (this->mpeg_version == 0) {
//cerr << "No sequence-start found" << endl;
return false;
}
return true;
}
bool MpegEndAnalyzer::parse_seq(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t dword = 0,nread = 0;
nread = in->read(buf,4,4);
if(nread < 4) return false;
dword = readBigEndianUInt32(buf);
this->horizontal_size = (dword >> 20);
this->vertical_size = (dword >> 8) & ((1<<12)-1);
this->aspect_ratio = (dword >> 4) & ((1<<4)-1);
int framerate_code = dword & ((1<<4)-1);
this->frame_rate = this->frame_rate_table[framerate_code];
nread = in->read(buf,4,4);
if(nread < 4) return false;
dword = readBigEndianUInt32(buf);
this->bitrate = (dword >> 14);
this->mpeg_version = 1;
return true;
}
bool MpegEndAnalyzer::parse_seq_ext(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t dword = 0,nread = 0;
nread = in->read(buf,4,4);
if(nread < 4) return false;
dword = readBigEndianUInt32(buf);
uint8_t type = dword >> 28;
if(type == 1 )
{
this->mpeg_version = 2;
}
return true;
}
bool MpegEndAnalyzer::parse_private(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t nread = 0;
uint8_t subtype = 0;
//skip the first two bytes
in->skip(2);
nread = in->read(buf,1,1);
if(nread < 1) return false;
subtype = (uint8_t)*buf;
subtype = subtype >> 4;
if (subtype == 8) // AC3
this->audio_type = 5;
else
if (subtype == 10) // LPCM
this->audio_type = 7;
return true;
}
bool MpegEndAnalyzer::parse_audio(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t nread = 0;
uint8_t byte = 0;
//skip the first two bytes (16bits)
in->skip(2);
bool sync_found = false;
//anybody know why this is 20?
for(int i=0; i<20; i++) {
nread = in->read(buf,1,1);
if(nread != 1) return false;
byte = (uint8_t)*buf;
if (byte == 0xff) {
nread = in->read(buf,1,1);
if(nread != 1) return false;
byte = (uint8_t)*buf;
if ((byte & 0xe0) == 0xe0)
sync_found = true;
break;
}
}
if(!sync_found)
{
//cerr << "MPEG audio sync not found" << endl;
return false;
}
//the sync code was found so parse the audio type
int layer = ((byte >> 1) & 0x3);
if (layer == 1)
this->audio_type = 3;
else if (layer == 2)
this->audio_type = 2;
else if (layer == 3)
this->audio_type = 1;
else
//cerr << "Invalid MPEG audio layer" << endl;
return true;
}
<commit_msg>you should be more careful when commenting lines of if/else blocks that don't have { This comment moved the return to be the else block so there was no main function return CCMAIL: [email protected]<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Christopher Blauvelt <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/* Based on source code from Mpeg KFile plugin by Allan Sandfeld Jensen
* and libmpeg3.
*/
#include "strigiconfig.h"
#include "mpegendanalyzer.h"
#include "analysisresult.h"
#include "textutils.h"
#include <iostream>
using namespace Strigi;
using namespace std;
void MpegEndAnalyzerFactory::registerFields(FieldRegister& r) {
fields["length"] = r.registerField("media.duration", FieldRegister::integerType, 1, 0);
fields["dimensions.y"] = r.registerField("image.dimensions.y", FieldRegister::integerType, 1, 0);
fields["dimensions.x"] = r.registerField("image.dimensions.x", FieldRegister::integerType, 1, 0);
fields["frame rate"] = r.registerField("video.frame_rate", FieldRegister::floatType, 1, 0);
fields["video codec"] = r.registerField("av.video_codec", FieldRegister::stringType, 1, 0);
fields["audio codec"] = r.registerField("av.audio_codec", FieldRegister::stringType, 1, 0);
fields["aspect ratio"] = r.registerField("image.aspect_ratio", FieldRegister::stringType, 1, 0);
}
bool MpegEndAnalyzer::checkHeader(const char* header, int32_t headersize) const
{
uint32_t dword = 0;
if(headersize < 9)
{
//cerr << "File was less than nine bytes. Not long enough" << endl;
return false;
}
dword = readBigEndianUInt32(header);
if(dword == 0x52494646) // == "RIFF"
{
dword = readBigEndianUInt32(header+5);
if (dword == 0x43445841) { // == "CDXA"
//cerr << "CDXA not yet supported" << endl;
return false;
}
}
else if(dword != 0x000001ba) {
//cerr << "Not a MPEG-PS file" << endl;
return false;
}
return true;
}
char MpegEndAnalyzer::analyze(AnalysisResult& idx, InputStream* in) {
if(!in) {
return -1;
}
if(!this->readMpeg(in) )
{
//cerr << "Error reading mpeg." << endl;
in->reset(0);
return -1;
}
std::map<std::string, const Strigi::RegisteredField*>tempfields = factory->fields;
idx.addValue(tempfields["frame rate"], this->frame_rate);
idx.addValue(tempfields["dimensions.y"], this->vertical_size);
idx.addValue(tempfields["dimensions.x"], this->horizontal_size);
if (this->mpeg_version == 1) idx.addValue(tempfields["video codec"], "MPEG-1");
else idx.addValue(tempfields["video codec"], "MPEG-2");
switch (this->audio_type)
{
case 1:
idx.addValue(tempfields["audio codec"], "MP1");
break;
case 2:
idx.addValue(tempfields["audio codec"], "MP2");
break;
case 3:
idx.addValue(tempfields["audio codec"], "MP3");
break;
case 5:
idx.addValue(tempfields["audio codec"], "AC3");
break;
case 7:
idx.addValue(tempfields["audio codec"], "PCM");
break;
default:
idx.addValue(tempfields["audio codec"], "Unknown");
}
// MPEG 1 also has an aspect ratio setting, but it works differently,
// and I am not sure if it is used.
if (this->mpeg_version == 2) {
switch (this->aspect_ratio) {
case 1:
idx.addValue(tempfields["aspect ratio"], "default");
break;
case 2:
idx.addValue(tempfields["aspect ratio"], "4/3");
break;
case 3:
idx.addValue(tempfields["aspect ratio"], "16/9");
break;
case 4:
idx.addValue(tempfields["aspect ratio"], "2.11/1");
break;
}
}
return 0;
}
bool MpegEndAnalyzer::readMpeg(InputStream* in) {
if(!in) {
return false;
}
const char *buf;
this->mpeg_version = 0;
this->audio_type = 0;
uint32_t dword = 0,nread = 0;
//Now that we've established that this is an mpeg file (almost),
//we search for the audio and video elements
in->reset(0);
uint16_t packet;
bool video_found = false, audio_found = false, read_error = false;
// Start searching for MPEG packets
while((nread = in->read(buf,2,2) ) )
{
if(nread != 2)
{
read_error = true;
break;
}
packet = readBigEndianUInt16(buf);
if(packet == this->sequence_start)
{
if(video_found) break;
if(this->parse_seq(in) ) video_found = true;
}
else if(packet == this->ext_sequence_start)
{
this->parse_seq_ext(in);
}
else if(packet == this->private1_packet || packet == this->private2_packet)
{
this->parse_private(in);
}
else if(packet == this->audio1_packet || packet == this->audio2_packet)
{
if(audio_found) break;
if(this->parse_audio(in) ) audio_found = true;
}
if (video_found && audio_found) break;
}
if(read_error)
{
return false;
}
else if (this->mpeg_version == 0) {
//cerr << "No sequence-start found" << endl;
return false;
}
return true;
}
bool MpegEndAnalyzer::parse_seq(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t dword = 0,nread = 0;
nread = in->read(buf,4,4);
if(nread < 4) return false;
dword = readBigEndianUInt32(buf);
this->horizontal_size = (dword >> 20);
this->vertical_size = (dword >> 8) & ((1<<12)-1);
this->aspect_ratio = (dword >> 4) & ((1<<4)-1);
int framerate_code = dword & ((1<<4)-1);
this->frame_rate = this->frame_rate_table[framerate_code];
nread = in->read(buf,4,4);
if(nread < 4) return false;
dword = readBigEndianUInt32(buf);
this->bitrate = (dword >> 14);
this->mpeg_version = 1;
return true;
}
bool MpegEndAnalyzer::parse_seq_ext(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t dword = 0,nread = 0;
nread = in->read(buf,4,4);
if(nread < 4) return false;
dword = readBigEndianUInt32(buf);
uint8_t type = dword >> 28;
if(type == 1 )
{
this->mpeg_version = 2;
}
return true;
}
bool MpegEndAnalyzer::parse_private(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t nread = 0;
uint8_t subtype = 0;
//skip the first two bytes
in->skip(2);
nread = in->read(buf,1,1);
if(nread < 1) return false;
subtype = (uint8_t)*buf;
subtype = subtype >> 4;
if (subtype == 8) // AC3
this->audio_type = 5;
else
if (subtype == 10) // LPCM
this->audio_type = 7;
return true;
}
bool MpegEndAnalyzer::parse_audio(InputStream* in)
{
if(!in) {
return false;
}
const char *buf;
uint32_t nread = 0;
uint8_t byte = 0;
//skip the first two bytes (16bits)
in->skip(2);
bool sync_found = false;
//anybody know why this is 20?
for(int i=0; i<20; i++) {
nread = in->read(buf,1,1);
if(nread != 1) return false;
byte = (uint8_t)*buf;
if (byte == 0xff) {
nread = in->read(buf,1,1);
if(nread != 1) return false;
byte = (uint8_t)*buf;
if ((byte & 0xe0) == 0xe0)
sync_found = true;
break;
}
}
if(!sync_found)
{
//cerr << "MPEG audio sync not found" << endl;
return false;
}
//the sync code was found so parse the audio type
int layer = ((byte >> 1) & 0x3);
if (layer == 1)
this->audio_type = 3;
else if (layer == 2)
this->audio_type = 2;
else if (layer == 3)
this->audio_type = 1;
else
{
//cerr << "Invalid MPEG audio layer" << endl;
}
return true;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(DATATYPEVALIDATORFACTORY_HPP)
#define DATATYPEVALIDATORFACTORY_HPP
/**
* This class implements a factory of Datatype Validators. Internally the
* DatatypeValidators are kept in a registry.
* There is one instance of DatatypeValidatorFactory per Parser.
* There is one datatype Registry per instance of DatatypeValidatorFactory,
* such registry is first allocated with the number DatatypeValidators needed.
* e.g.
* If Parser finds an XML document with a DTD, a registry of DTD validators (only
* 9 validators) get initialized in the registry.
* The initialization process consist of instantiating the Datatype and
* facets and registering the Datatype into registry table.
* This implementation uses a Hahtable as a registry. The datatype validators created
* by the factory will be deleted by the registry.
*
* As the Parser parses an instance document it knows if validation needs
* to be checked. If no validation is necesary we should not instantiate a
* DatatypeValidatorFactory.
* If validation is needed, we need to instantiate a DatatypeValidatorFactory.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/internal/XSerializable.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// DatatypeValidatorFactory: Local declaration
// ---------------------------------------------------------------------------
typedef RefHashTableOf<KVStringPair> KVStringPairHashTable;
typedef RefHashTableOf<DatatypeValidator> DVHashTable;
typedef RefArrayVectorOf<XMLCh> XMLChRefVector;
class VALIDATORS_EXPORT DatatypeValidatorFactory : public XSerializable, public XMemory
{
public:
// -----------------------------------------------------------------------
// Public Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors */
//@{
DatatypeValidatorFactory
(
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//@}
/** @name Destructor. */
//@{
~DatatypeValidatorFactory();
//@}
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/** @name Getter Functions */
//@{
/**
* Returns the datatype validator
*
* @param dvType Datatype validator name/type
*/
DatatypeValidator* getDatatypeValidator(const XMLCh* const dvType) const;
/**
* Returns the user defined registry of types
**/
DVHashTable* getUserDefinedRegistry() const;
/**
* Returns the built in registry of types
**/
DVHashTable* getBuiltInRegistry() const;
//@}
// -----------------------------------------------------------------------
// Registry Initialization methods
// -----------------------------------------------------------------------
/** @name Registry Initialization Functions */
//@{
/**
* Initializes registry with primitive and derived Simple types.
*
* This method does not clear the registry to clear the registry you
* have to call resetRegistry.
*
* The net effect of this method is to start with the smallest set of
* datatypes needed by the validator.
*
* If we start with Schema's then we initialize to full set of
* validators.
*/
void expandRegistryToFullSchemaSet();
//@}
// -----------------------------------------------------------------------
// Validator Factory methods
// -----------------------------------------------------------------------
/** @name Validator Factory Functions */
//@{
/**
* Creates a new datatype validator of type baseValidator's class and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param baseValidator Base datatype validator
*
* @param facets datatype facets if any
*
* @param enums vector of values for enum facet
*
* @param isDerivedByList Indicates whether the datatype is derived by
* list or not
*
* @param finalSet 'final' values of the simpleType
*
* @param isUserDefined Indicates whether the datatype is built-in or
* user defined
*/
DatatypeValidator* createDatatypeValidator
(
const XMLCh* const typeName
, DatatypeValidator* const baseValidator
, RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const bool isDerivedByList
, const int finalSet = 0
, const bool isUserDefined = true
);
/**
* Creates a new datatype validator of type UnionDatatypeValidator and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param validators Vector of datatype validators
*
* @param finalSet 'final' values of the simpleType
*
* @param isUserDefined Indicates whether the datatype is built-in or
* user defined
*/
DatatypeValidator* createDatatypeValidator
(
const XMLCh* const typeName
, RefVectorOf<DatatypeValidator>* const validators
, const int finalSet
, const bool isUserDefined = true
);
//@}
/**
* Reset datatype validator registry
*/
void resetRegistry();
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
static void reinitRegistry();
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(DatatypeValidatorFactory)
private:
// -----------------------------------------------------------------------
// CleanUp methods
// -----------------------------------------------------------------------
void cleanUp();
// -----------------------------------------------------------------------
// Private data members
//
// fUserDefinedRegistry
// This is a hashtable of user defined dataype validators.
//
// fBuiltInRegistry
// This is a hashtable of built-in primitive datatype validators.
// -----------------------------------------------------------------------
XERCES_CPP_NAMESPACE_QUALIFIER RefHashTableOf<XERCES_CPP_NAMESPACE_QUALIFIER DatatypeValidator>* fUserDefinedRegistry;
static XERCES_CPP_NAMESPACE_QUALIFIER RefHashTableOf<DatatypeValidator>* fBuiltInRegistry;
XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const fMemoryManager;
friend class XPath2ContextImpl;
};
inline DatatypeValidator*
DatatypeValidatorFactory::getDatatypeValidator(const XMLCh* const dvType) const
{
if (dvType) {
if (fBuiltInRegistry && fBuiltInRegistry->containsKey(dvType)) {
return fBuiltInRegistry->get(dvType);
}
if (fUserDefinedRegistry && fUserDefinedRegistry->containsKey(dvType)) {
return fUserDefinedRegistry->get(dvType);
}
}
return 0;
}
inline DVHashTable*
DatatypeValidatorFactory::getUserDefinedRegistry() const {
return fUserDefinedRegistry;
}
inline DVHashTable*
DatatypeValidatorFactory::getBuiltInRegistry() const {
return fBuiltInRegistry;
}
// ---------------------------------------------------------------------------
// DatatypeValidator: CleanUp methods
// ---------------------------------------------------------------------------
inline void DatatypeValidatorFactory::cleanUp() {
delete fUserDefinedRegistry;
fUserDefinedRegistry = 0;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file DatatypeValidatorFactory.hpp
*/
<commit_msg>make getBuiltInRegistry() static<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(DATATYPEVALIDATORFACTORY_HPP)
#define DATATYPEVALIDATORFACTORY_HPP
/**
* This class implements a factory of Datatype Validators. Internally the
* DatatypeValidators are kept in a registry.
* There is one instance of DatatypeValidatorFactory per Parser.
* There is one datatype Registry per instance of DatatypeValidatorFactory,
* such registry is first allocated with the number DatatypeValidators needed.
* e.g.
* If Parser finds an XML document with a DTD, a registry of DTD validators (only
* 9 validators) get initialized in the registry.
* The initialization process consist of instantiating the Datatype and
* facets and registering the Datatype into registry table.
* This implementation uses a Hahtable as a registry. The datatype validators created
* by the factory will be deleted by the registry.
*
* As the Parser parses an instance document it knows if validation needs
* to be checked. If no validation is necesary we should not instantiate a
* DatatypeValidatorFactory.
* If validation is needed, we need to instantiate a DatatypeValidatorFactory.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/internal/XSerializable.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// DatatypeValidatorFactory: Local declaration
// ---------------------------------------------------------------------------
typedef RefHashTableOf<KVStringPair> KVStringPairHashTable;
typedef RefHashTableOf<DatatypeValidator> DVHashTable;
typedef RefArrayVectorOf<XMLCh> XMLChRefVector;
class VALIDATORS_EXPORT DatatypeValidatorFactory : public XSerializable, public XMemory
{
public:
// -----------------------------------------------------------------------
// Public Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors */
//@{
DatatypeValidatorFactory
(
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//@}
/** @name Destructor. */
//@{
~DatatypeValidatorFactory();
//@}
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/** @name Getter Functions */
//@{
/**
* Returns the datatype validator
*
* @param dvType Datatype validator name/type
*/
DatatypeValidator* getDatatypeValidator(const XMLCh* const dvType) const;
/**
* Returns the user defined registry of types
**/
DVHashTable* getUserDefinedRegistry() const;
/**
* Returns the built in registry of types
**/
static DVHashTable* getBuiltInRegistry();
//@}
// -----------------------------------------------------------------------
// Registry Initialization methods
// -----------------------------------------------------------------------
/** @name Registry Initialization Functions */
//@{
/**
* Initializes registry with primitive and derived Simple types.
*
* This method does not clear the registry to clear the registry you
* have to call resetRegistry.
*
* The net effect of this method is to start with the smallest set of
* datatypes needed by the validator.
*
* If we start with Schema's then we initialize to full set of
* validators.
*/
void expandRegistryToFullSchemaSet();
//@}
// -----------------------------------------------------------------------
// Validator Factory methods
// -----------------------------------------------------------------------
/** @name Validator Factory Functions */
//@{
/**
* Creates a new datatype validator of type baseValidator's class and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param baseValidator Base datatype validator
*
* @param facets datatype facets if any
*
* @param enums vector of values for enum facet
*
* @param isDerivedByList Indicates whether the datatype is derived by
* list or not
*
* @param finalSet 'final' values of the simpleType
*
* @param isUserDefined Indicates whether the datatype is built-in or
* user defined
*/
DatatypeValidator* createDatatypeValidator
(
const XMLCh* const typeName
, DatatypeValidator* const baseValidator
, RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const bool isDerivedByList
, const int finalSet = 0
, const bool isUserDefined = true
);
/**
* Creates a new datatype validator of type UnionDatatypeValidator and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param validators Vector of datatype validators
*
* @param finalSet 'final' values of the simpleType
*
* @param isUserDefined Indicates whether the datatype is built-in or
* user defined
*/
DatatypeValidator* createDatatypeValidator
(
const XMLCh* const typeName
, RefVectorOf<DatatypeValidator>* const validators
, const int finalSet
, const bool isUserDefined = true
);
//@}
/**
* Reset datatype validator registry
*/
void resetRegistry();
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
static void reinitRegistry();
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(DatatypeValidatorFactory)
private:
// -----------------------------------------------------------------------
// CleanUp methods
// -----------------------------------------------------------------------
void cleanUp();
// -----------------------------------------------------------------------
// Private data members
//
// fUserDefinedRegistry
// This is a hashtable of user defined dataype validators.
//
// fBuiltInRegistry
// This is a hashtable of built-in primitive datatype validators.
// -----------------------------------------------------------------------
XERCES_CPP_NAMESPACE_QUALIFIER RefHashTableOf<XERCES_CPP_NAMESPACE_QUALIFIER DatatypeValidator>* fUserDefinedRegistry;
static XERCES_CPP_NAMESPACE_QUALIFIER RefHashTableOf<DatatypeValidator>* fBuiltInRegistry;
XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const fMemoryManager;
friend class XPath2ContextImpl;
};
inline DatatypeValidator*
DatatypeValidatorFactory::getDatatypeValidator(const XMLCh* const dvType) const
{
if (dvType) {
if (fBuiltInRegistry && fBuiltInRegistry->containsKey(dvType)) {
return fBuiltInRegistry->get(dvType);
}
if (fUserDefinedRegistry && fUserDefinedRegistry->containsKey(dvType)) {
return fUserDefinedRegistry->get(dvType);
}
}
return 0;
}
inline DVHashTable*
DatatypeValidatorFactory::getUserDefinedRegistry() const {
return fUserDefinedRegistry;
}
inline DVHashTable*
DatatypeValidatorFactory::getBuiltInRegistry() {
return fBuiltInRegistry;
}
// ---------------------------------------------------------------------------
// DatatypeValidator: CleanUp methods
// ---------------------------------------------------------------------------
inline void DatatypeValidatorFactory::cleanUp() {
delete fUserDefinedRegistry;
fUserDefinedRegistry = 0;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file DatatypeValidatorFactory.hpp
*/
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(DATATYPEVALIDATORFACTORY_HPP)
#define DATATYPEVALIDATORFACTORY_HPP
/**
* This class implements a factory of Datatype Validators. Internally the
* DatatypeValidators are kept in a registry.
* There is one instance of DatatypeValidatorFactory per Parser.
* There is one datatype Registry per instance of DatatypeValidatorFactory,
* such registry is first allocated with the number DatatypeValidators needed.
* e.g.
* If Parser finds an XML document with a DTD, a registry of DTD validators (only
* 9 validators) get initialized in the registry.
* The initialization process consist of instantiating the Datatype and
* facets and registering the Datatype into registry table.
* This implementation uses a Hahtable as a registry. The datatype validators created
* by the factory will be deleted by the registry.
*
* As the Parser parses an instance document it knows if validation needs
* to be checked. If no validation is necesary we should not instantiate a
* DatatypeValidatorFactory.
* If validation is needed, we need to instantiate a DatatypeValidatorFactory.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/util/RefVectorOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// DatatypeValidatorFactory: Local declaration
// ---------------------------------------------------------------------------
typedef RefHashTableOf<KVStringPair> KVStringPairHashTable;
typedef RefHashTableOf<DatatypeValidator> DVHashTable;
typedef RefVectorOf<XMLCh> XMLChRefVector;
class VALIDATORS_EXPORT DatatypeValidatorFactory
{
public:
// -----------------------------------------------------------------------
// Public Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors */
//@{
DatatypeValidatorFactory();
//@}
/** @name Destructor. */
//@{
~DatatypeValidatorFactory();
//@}
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/** @name Getter Functions */
//@{
/**
* Returns the datatype validator
*
* @param dvType Datatype validator name/type
*/
DatatypeValidator* getDatatypeValidator(const XMLCh* const dvType) const;
//@}
// -----------------------------------------------------------------------
// Registry Initialization methods
// -----------------------------------------------------------------------
/** @name Registry Initialization Functions */
//@{
/**
* Initializes registry with primitive and derived Simple types.
*
* This method does not clear the registry to clear the registry you
* have to call resetRegistry.
*
* The net effect of this method is to start with the smallest set of
* datatypes needed by the validator.
*
* If we start with Schema's then we initialize to full set of
* validators.
*/
void expandRegistryToFullSchemaSet();
//@}
// -----------------------------------------------------------------------
// Validator Factory methods
// -----------------------------------------------------------------------
/** @name Validator Factory Functions */
//@{
/**
* Creates a new datatype validator of type baseValidator's class and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param baseValidator Base datatype validator
*
* @param facets datatype facets if any
*
* @param enums vector of values for enum facet
*
* @param derivedByList Indicates whether the datatype is derived by
* list or not
*
* @param finalSet 'final' values of the simpleType
*/
DatatypeValidator* createDatatypeValidator(const XMLCh* const,
DatatypeValidator* const,
RefHashTableOf<KVStringPair>* const,
RefVectorOf<XMLCh>* const enums,
const bool,
const int = 0,
const bool = true);
/**
* Creates a new datatype validator of type UnionDatatypeValidator and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param validators Vector of datatype validators
*
*/
DatatypeValidator* createDatatypeValidator(const XMLCh* const,
RefVectorOf<DatatypeValidator>* const,
const int finalSet,
const bool = true);
//@}
/**
* Reset datatype validator registry
*/
void resetRegistry();
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
static void reinitRegistry();
private:
// -----------------------------------------------------------------------
// CleanUp methods
// -----------------------------------------------------------------------
void cleanUp();
// -----------------------------------------------------------------------
// Private data members
//
// fUserDefinedRegistry
// This is a hashtable of user defined dataype validators.
//
// fBuiltInRegistry
// This is a hashtable of built-in primitive datatype validators.
// -----------------------------------------------------------------------
RefHashTableOf<DatatypeValidator>* fUserDefinedRegistry;
static RefHashTableOf<DatatypeValidator>* fBuiltInRegistry;
};
// ---------------------------------------------------------------------------
// DatatypeValidatorFactory: Getters
// ---------------------------------------------------------------------------
inline DatatypeValidator*
DatatypeValidatorFactory::getDatatypeValidator(const XMLCh* const dvType) const
{
if (dvType) {
if (fBuiltInRegistry && fBuiltInRegistry->containsKey(dvType)) {
return fBuiltInRegistry->get(dvType);
}
if (fUserDefinedRegistry && fUserDefinedRegistry->containsKey(dvType)) {
return fUserDefinedRegistry->get(dvType);
}
}
return 0;
}
// ---------------------------------------------------------------------------
// DatatypeValidator: CleanUp methods
// ---------------------------------------------------------------------------
inline void DatatypeValidatorFactory::cleanUp() {
delete fUserDefinedRegistry;
fUserDefinedRegistry = 0;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file DatatypeValidatorFactory.hpp
*/
<commit_msg>Fix for bug #14960. Opened up interface to expose user defined and built in registries. Patch by Peter A. Volchek.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(DATATYPEVALIDATORFACTORY_HPP)
#define DATATYPEVALIDATORFACTORY_HPP
/**
* This class implements a factory of Datatype Validators. Internally the
* DatatypeValidators are kept in a registry.
* There is one instance of DatatypeValidatorFactory per Parser.
* There is one datatype Registry per instance of DatatypeValidatorFactory,
* such registry is first allocated with the number DatatypeValidators needed.
* e.g.
* If Parser finds an XML document with a DTD, a registry of DTD validators (only
* 9 validators) get initialized in the registry.
* The initialization process consist of instantiating the Datatype and
* facets and registering the Datatype into registry table.
* This implementation uses a Hahtable as a registry. The datatype validators created
* by the factory will be deleted by the registry.
*
* As the Parser parses an instance document it knows if validation needs
* to be checked. If no validation is necesary we should not instantiate a
* DatatypeValidatorFactory.
* If validation is needed, we need to instantiate a DatatypeValidatorFactory.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/util/RefVectorOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// DatatypeValidatorFactory: Local declaration
// ---------------------------------------------------------------------------
typedef RefHashTableOf<KVStringPair> KVStringPairHashTable;
typedef RefHashTableOf<DatatypeValidator> DVHashTable;
typedef RefVectorOf<XMLCh> XMLChRefVector;
class VALIDATORS_EXPORT DatatypeValidatorFactory
{
public:
// -----------------------------------------------------------------------
// Public Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors */
//@{
DatatypeValidatorFactory();
//@}
/** @name Destructor. */
//@{
~DatatypeValidatorFactory();
//@}
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/** @name Getter Functions */
//@{
/**
* Returns the datatype validator
*
* @param dvType Datatype validator name/type
*/
DatatypeValidator* getDatatypeValidator(const XMLCh* const dvType) const;
/**
* Returns the user defined registry of types
**/
DVHashTable* getUserDefinedRegistry() const;
/**
* Returns the built in registry of types
**/
DVHashTable* getBuiltInRegistry() const;
//@}
// -----------------------------------------------------------------------
// Registry Initialization methods
// -----------------------------------------------------------------------
/** @name Registry Initialization Functions */
//@{
/**
* Initializes registry with primitive and derived Simple types.
*
* This method does not clear the registry to clear the registry you
* have to call resetRegistry.
*
* The net effect of this method is to start with the smallest set of
* datatypes needed by the validator.
*
* If we start with Schema's then we initialize to full set of
* validators.
*/
void expandRegistryToFullSchemaSet();
//@}
// -----------------------------------------------------------------------
// Validator Factory methods
// -----------------------------------------------------------------------
/** @name Validator Factory Functions */
//@{
/**
* Creates a new datatype validator of type baseValidator's class and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param baseValidator Base datatype validator
*
* @param facets datatype facets if any
*
* @param enums vector of values for enum facet
*
* @param derivedByList Indicates whether the datatype is derived by
* list or not
*
* @param finalSet 'final' values of the simpleType
*/
DatatypeValidator* createDatatypeValidator(const XMLCh* const,
DatatypeValidator* const,
RefHashTableOf<KVStringPair>* const,
RefVectorOf<XMLCh>* const enums,
const bool,
const int = 0,
const bool = true);
/**
* Creates a new datatype validator of type UnionDatatypeValidator and
* adds it to the registry
*
* @param typeName Datatype validator name
*
* @param validators Vector of datatype validators
*
*/
DatatypeValidator* createDatatypeValidator(const XMLCh* const,
RefVectorOf<DatatypeValidator>* const,
const int finalSet,
const bool = true);
//@}
/**
* Reset datatype validator registry
*/
void resetRegistry();
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
static void reinitRegistry();
private:
// -----------------------------------------------------------------------
// CleanUp methods
// -----------------------------------------------------------------------
void cleanUp();
// -----------------------------------------------------------------------
// Private data members
//
// fUserDefinedRegistry
// This is a hashtable of user defined dataype validators.
//
// fBuiltInRegistry
// This is a hashtable of built-in primitive datatype validators.
// -----------------------------------------------------------------------
RefHashTableOf<DatatypeValidator>* fUserDefinedRegistry;
static RefHashTableOf<DatatypeValidator>* fBuiltInRegistry;
};
// ---------------------------------------------------------------------------
// DatatypeValidatorFactory: Getters
// ---------------------------------------------------------------------------
inline DatatypeValidator*
DatatypeValidatorFactory::getDatatypeValidator(const XMLCh* const dvType) const
{
if (dvType) {
if (fBuiltInRegistry && fBuiltInRegistry->containsKey(dvType)) {
return fBuiltInRegistry->get(dvType);
}
if (fUserDefinedRegistry && fUserDefinedRegistry->containsKey(dvType)) {
return fUserDefinedRegistry->get(dvType);
}
}
return 0;
}
inline DVHashTable*
DatatypeValidatorFactory::getUserDefinedRegistry() const {
return fUserDefinedRegistry;
}
inline DVHashTable*
DatatypeValidatorFactory::getBuiltInRegistry() const {
return fBuiltInRegistry;
}
// ---------------------------------------------------------------------------
// DatatypeValidator: CleanUp methods
// ---------------------------------------------------------------------------
inline void DatatypeValidatorFactory::cleanUp() {
delete fUserDefinedRegistry;
fUserDefinedRegistry = 0;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file DatatypeValidatorFactory.hpp
*/
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstring>
#include <iostream>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#include "../include/oasis.h"
#if defined(_MSC_VER)
#include "../wingetopt/wingetopt.h"
#else
#include <unistd.h>
#endif
namespace validatevulnerability {
inline bool ProbabilityCheck(float prob) {
return roundf(prob * 100000) / 100000 != 1.0;
}
inline bool ProbabilityError(Vulnerability v, float prob) {
fprintf(stderr, "Probabilities for vulnerability ID %d", v.vulnerability_id);
fprintf(stderr, " and intensity bin ID %d", v.intensity_bin_id);
fprintf(stderr, " do not sum to 1.\n");
fprintf(stderr, "Probability = %f\n", prob);
return false;
}
inline bool OutOfOrderError(char const * name, int lineno, char * prevLine,
char * line) {
fprintf(stderr, "%s IDs in lines %d and %d", name, lineno-1, lineno);
fprintf(stderr, " not in ascending order:\n");
fprintf(stderr, "%s\n%s\n", prevLine, line);
return false;
}
void doit() {
Vulnerability p = {}, q;
bool dataValid = true;
std::set<int> damageBins;
int maxDamageBin = 0;
char const * sVulnerability = "Vulnerability";
char const * sIntensityBin = "Intensity bin";
float prob = 0.0;
char prevLine[4096], line[4096];
sprintf(prevLine, "%d, %d, %d, %f", p.vulnerability_id, p.intensity_bin_id,
p.damage_bin_id, p.probability);
int lineno = 0;
fgets(line, sizeof(line), stdin); // Skip header line
lineno++;
while(fgets(line, sizeof(line), stdin) != 0) {
// Check for invalid data
if(sscanf(line, "%d,%d,%d,%f", &q.vulnerability_id, &q.intensity_bin_id,
&q.damage_bin_id, &q.probability) != 4) {
fprintf(stderr, "Invalid data in line %d:\n%s\n", lineno, line);
dataValid = false;
}
// New vulnerability ID
if(q.vulnerability_id != p.vulnerability_id) {
// Check total probability for vulnerability-intensity bin combination
// is 1.0
if(ProbabilityCheck(prob) && p.vulnerability_id != 0) {
dataValid = ProbabilityError(p, prob);
}
damageBins.clear();
prob = 0.0;
// Check event IDs listed in ascending order
if(q.vulnerability_id < p.vulnerability_id) {
dataValid = OutOfOrderError(sVulnerability, lineno, prevLine, line);
}
} else if(q.intensity_bin_id != p.intensity_bin_id) {
// Check total probability for vulnerability-intensity bin combination
// is 1.0
if(ProbabilityCheck(prob)) {
dataValid = ProbabilityError(p, prob);
}
damageBins.clear();
prob = 0.0;
// Check intensity bin IDs listed in ascending order
if(q.intensity_bin_id < p.intensity_bin_id) {
dataValid = OutOfOrderError(sIntensityBin, lineno, prevLine, line);
}
}
// Check no duplicate damage bins for each vulnerability-intensity bin
// combination
if(damageBins.find(q.damage_bin_id) == damageBins.end()) {
damageBins.insert(q.damage_bin_id);
prob += q.probability;
// Get maximum value of damage_bin_index
if(q.damage_bin_id > maxDamageBin) {
maxDamageBin = q.damage_bin_id;
}
} else {
fprintf(stderr, "Duplicate intensity bin for");
fprintf(stderr, " vulnerability-intensity bin combination");
fprintf(stderr, "%s\n", line);
dataValid = false;
}
lineno++;
p = q;
memcpy(prevLine, line, strlen(line)+1);
prevLine[strlen(line)-1] = '\0';
}
// Check total probability for last vulnerability-intensity bin combination
// is 1.0
if(ProbabilityCheck(prob)) {
dataValid = ProbabilityError(q, prob);
}
if(dataValid == true) {
fprintf(stderr, "All checks pass.\n");
fprintf(stderr, "Maximum value of damage_bin_index = %d\n", maxDamageBin);
} else {
fprintf(stderr, "Some checks have failed. Please edit input file.\n");
}
}
}
<commit_msg>Add checks for intensity bin IDs<commit_after>#include <cmath>
#include <cstring>
#include <iostream>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#include "../include/oasis.h"
#if defined(_MSC_VER)
#include "../wingetopt/wingetopt.h"
#else
#include <unistd.h>
#endif
namespace validatevulnerability {
inline bool ProbabilityCheck(float prob) {
return roundf(prob * 100000) / 100000 != 1.0;
}
inline bool ProbabilityError(Vulnerability v, float prob) {
fprintf(stderr, "Probabilities for vulnerability ID %d", v.vulnerability_id);
fprintf(stderr, " and intensity bin ID %d", v.intensity_bin_id);
fprintf(stderr, " do not sum to 1.\n");
fprintf(stderr, "Probability = %f\n", prob);
return false;
}
inline bool OutOfOrderError(char const * name, int lineno, char * prevLine,
char * line) {
fprintf(stderr, "%s IDs in lines %d and %d", name, lineno-1, lineno);
fprintf(stderr, " not in ascending order:\n");
fprintf(stderr, "%s\n%s\n", prevLine, line);
return false;
}
void doit() {
Vulnerability p = {}, q;
bool dataValid = true;
std::set<int> damageBins;
int maxDamageBin = 0;
char const * sVulnerability = "Vulnerability";
char const * sIntensityBin = "Intensity bin";
float prob = 0.0;
char prevLine[4096], line[4096];
sprintf(prevLine, "%d, %d, %d, %f", p.vulnerability_id, p.intensity_bin_id,
p.damage_bin_id, p.probability);
int lineno = 0;
fgets(line, sizeof(line), stdin); // Skip header line
lineno++;
while(fgets(line, sizeof(line), stdin) != 0) {
// Check for invalid data
if(sscanf(line, "%d,%d,%d,%f", &q.vulnerability_id, &q.intensity_bin_id,
&q.damage_bin_id, &q.probability) != 4) {
fprintf(stderr, "Invalid data in line %d:\n%s\n", lineno, line);
dataValid = false;
}
// New vulnerability ID
if(q.vulnerability_id != p.vulnerability_id) {
// Check total probability for vulnerability-intensity bin combination
// is 1.0
if(ProbabilityCheck(prob) && p.vulnerability_id != 0) {
dataValid = ProbabilityError(p, prob);
}
damageBins.clear();
prob = 0.0;
// Check event IDs listed in ascending order
if(q.vulnerability_id < p.vulnerability_id) {
dataValid = OutOfOrderError(sVulnerability, lineno, prevLine, line);
}
// Check first intensity bin ID is 1 for new vulnerability ID
if(q.intensity_bin_id != 1) {
fprintf(stderr, "First intensity bin index = %d", q.intensity_bin_id);
fprintf(stderr, " for vulnerability ID %d.", q.vulnerability_id);
fprintf(stderr, " It must be 1.\n");
dataValid = false;
}
} else if(q.intensity_bin_id != p.intensity_bin_id) {
// Check total probability for vulnerability-intensity bin combination
// is 1.0
if(ProbabilityCheck(prob)) {
dataValid = ProbabilityError(p, prob);
}
damageBins.clear();
prob = 0.0;
// Check intensity bin IDs listed in ascending order
if(q.intensity_bin_id < p.intensity_bin_id) {
dataValid = OutOfOrderError(sIntensityBin, lineno, prevLine, line);
// Else check intensity bin IDs are contiguous
} else if (q.intensity_bin_id > p.intensity_bin_id+1) {
fprintf(stderr, "Non-contiguous intensity bin IDs");
fprintf(stderr, " in lines %d and %d", lineno-1, lineno);
fprintf(stderr, "%s\n%s\n", prevLine, line);
dataValid = false;
}
}
// Check no duplicate damage bins for each vulnerability-intensity bin
// combination
if(damageBins.find(q.damage_bin_id) == damageBins.end()) {
damageBins.insert(q.damage_bin_id);
prob += q.probability;
// Get maximum value of damage_bin_index
if(q.damage_bin_id > maxDamageBin) {
maxDamageBin = q.damage_bin_id;
}
} else {
fprintf(stderr, "Duplicate intensity bin for");
fprintf(stderr, " vulnerability-intensity bin combination");
fprintf(stderr, "%s\n", line);
dataValid = false;
}
lineno++;
p = q;
memcpy(prevLine, line, strlen(line)+1);
prevLine[strlen(line)-1] = '\0';
}
// Check total probability for last vulnerability-intensity bin combination
// is 1.0
if(ProbabilityCheck(prob)) {
dataValid = ProbabilityError(q, prob);
}
if(dataValid == true) {
fprintf(stderr, "All checks pass.\n");
fprintf(stderr, "Maximum value of damage_bin_index = %d\n", maxDamageBin);
} else {
fprintf(stderr, "Some checks have failed. Please edit input file.\n");
}
}
}
<|endoftext|> |
<commit_before>/**
* Copyright 2014 Truphone
*/
#include "XmppHarness.h"
#include "CommandFactory.h"
#include "XmppResourceStore.h"
#include "XmppHelpCommand.h"
#include "XmppPresenceCommand.h"
#include "XmppConnectCommand.h"
#include "XmppMessageCommand.h"
namespace truphone
{
namespace test
{
namespace cascades
{
XmppHarness::XmppHarness(QObject *parent) :
QObject(parent)
{
}
XmppHarness::~XmppHarness()
{
}
bool XmppHarness::installHarness()
{
XMPPResourceStore::initialiseStore(this);
CommandFactory::installCommand(
XMPPHelpCommand::getCmd(),
&XMPPHelpCommand::create);
CommandFactory::installCommand(
XMPPConnectCommand::getCmd(),
&XMPPConnectCommand::create);
CommandFactory::installCommand(
XMPPPresenceCommand::getCmd(),
&XMPPPresenceCommand::create);
CommandFactory::installCommand(
XMPPMessageCommand::getCmd(),
&XMPPMessageCommand::create);
return true;
}
} // namespace cascades
} // namespace test
} // namespace truphone
<commit_msg>Add the disconnect command to the factory.<commit_after>/**
* Copyright 2014 Truphone
*/
#include "XmppHarness.h"
#include "CommandFactory.h"
#include "XmppResourceStore.h"
#include "XmppHelpCommand.h"
#include "XmppPresenceCommand.h"
#include "XmppConnectCommand.h"
#include "XmppMessageCommand.h"
#include "XmppDisconnectCommand.h"
namespace truphone
{
namespace test
{
namespace cascades
{
XmppHarness::XmppHarness(QObject *parent) :
QObject(parent)
{
}
XmppHarness::~XmppHarness()
{
}
bool XmppHarness::installHarness()
{
XMPPResourceStore::initialiseStore(this);
CommandFactory::installCommand(
XMPPHelpCommand::getCmd(),
&XMPPHelpCommand::create);
CommandFactory::installCommand(
XMPPConnectCommand::getCmd(),
&XMPPConnectCommand::create);
CommandFactory::installCommand(
XMPPPresenceCommand::getCmd(),
&XMPPPresenceCommand::create);
CommandFactory::installCommand(
XMPPMessageCommand::getCmd(),
&XMPPMessageCommand::create);
CommandFactory::installCommand(
XMPPDisconnectCommand::getCmd(),
&XMPPDisconnectCommand::create);
return true;
}
} // namespace cascades
} // namespace test
} // namespace truphone
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XERCESDOMSUPPORT_HEADER_GUARD_1357924680)
#define XERCESDOMSUPPORT_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp>
#include <xalanc/DOMSupport/DOMSupport.hpp>
XALAN_CPP_NAMESPACE_BEGIN
class XercesParserLiaison;
class XALAN_XERCESPARSERLIAISON_EXPORT XercesDOMSupport : public DOMSupport
{
public:
XercesDOMSupport(XercesParserLiaison& theLiaison);
virtual
~XercesDOMSupport();
// These interfaces are inherited from Resettable...
virtual void
reset();
// These interfaces are inherited from DOMSupport...
virtual const XalanDOMString&
getUnparsedEntityURI(
const XalanDOMString& theName,
const XalanDocument& theDocument) const;
virtual bool
isNodeAfter(
const XalanNode& node1,
const XalanNode& node2) const;
private:
XercesParserLiaison& m_liaison;
};
XALAN_CPP_NAMESPACE_END
#endif // DOMSUPPORT_HEADER_GUARD_1357924680
<commit_msg>Fixed comment in header file.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XERCESDOMSUPPORT_HEADER_GUARD_1357924680)
#define XERCESDOMSUPPORT_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp>
#include <xalanc/DOMSupport/DOMSupport.hpp>
XALAN_CPP_NAMESPACE_BEGIN
class XercesParserLiaison;
class XALAN_XERCESPARSERLIAISON_EXPORT XercesDOMSupport : public DOMSupport
{
public:
XercesDOMSupport(XercesParserLiaison& theLiaison);
virtual
~XercesDOMSupport();
// These interfaces are inherited from DOMSupport...
virtual void
reset();
virtual const XalanDOMString&
getUnparsedEntityURI(
const XalanDOMString& theName,
const XalanDocument& theDocument) const;
virtual bool
isNodeAfter(
const XalanNode& node1,
const XalanNode& node2) const;
private:
XercesParserLiaison& m_liaison;
};
XALAN_CPP_NAMESPACE_END
#endif // DOMSUPPORT_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow 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.
==============================================================================*/
// XLA-specific reduction Ops.
#include "tensorflow/compiler/tf2xla/kernels/reduction_ops.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
namespace tensorflow {
namespace {
class SumOp : public XlaReductionOp {
public:
explicit SumOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx,
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::Zero(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Add(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Sum").CompileTimeConstantInput("reduction_indices"),
SumOp);
class ProdOp : public XlaReductionOp {
public:
explicit ProdOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx,
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::One(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Mul(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Prod").CompileTimeConstantInput("reduction_indices"),
ProdOp);
class MinOp : public XlaReductionOp {
public:
explicit MinOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::MaxValue(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Min(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Min").CompileTimeConstantInput("reduction_indices"),
MinOp);
class MaxOp : public XlaReductionOp {
public:
explicit MaxOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {
OP_REQUIRES_OK(ctx, TypeCheck(xla_reduction_type_));
}
Status TypeCheck(xla::PrimitiveType xla_reduction_type_){
if(xla_reduction_type_ == xla::C64){
return errors::InvalidArgument(
"Unsupported type in xla_reduction_type_");
}else{
return Status::OK();
}
}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::MinValue(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Max(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Max").CompileTimeConstantInput("reduction_indices"),
MaxOp);
class MeanOp : public XlaReductionOp {
public:
explicit MeanOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx,
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::Zero(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Add(scalar_lhs, scalar_rhs);
}
xla::XlaOp BuildFinalizer(
xla::XlaBuilder* /*builder*/, const xla::XlaOp& input,
const xla::XlaOp& reduce_output,
const std::vector<int64>& dimensions_to_reduce) override {
if (dimensions_to_reduce.empty()) {
return reduce_output;
}
auto divisor = xla::GetDimensionSize(input, dimensions_to_reduce[0]);
for (int i = 1; i < dimensions_to_reduce.size(); i++) {
auto size = xla::GetDimensionSize(input, dimensions_to_reduce[i]);
divisor = xla::Mul(divisor, size);
}
divisor = xla::ConvertElementType(divisor, xla_reduction_type_);
return XlaHelpers::ConvertElementType(reduce_output / divisor,
input_type(0));
}
};
REGISTER_XLA_OP(Name("Mean").CompileTimeConstantInput("reduction_indices"),
MeanOp);
class AllOp : public XlaReductionOp {
public:
explicit AllOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::ConstantR0<bool>(builder, true);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::And(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("All").CompileTimeConstantInput("reduction_indices"),
AllOp);
class AnyOp : public XlaReductionOp {
public:
explicit AnyOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::ConstantR0<bool>(builder, false);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Or(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Any").CompileTimeConstantInput("reduction_indices"),
AnyOp);
} // namespace
} // namespace tensorflow
<commit_msg>format error message in create op<commit_after>/* Copyright 2017 The TensorFlow 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.
==============================================================================*/
// XLA-specific reduction Ops.
#include "tensorflow/compiler/tf2xla/kernels/reduction_ops.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
namespace tensorflow {
namespace {
class SumOp : public XlaReductionOp {
public:
explicit SumOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx,
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::Zero(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Add(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Sum").CompileTimeConstantInput("reduction_indices"),
SumOp);
class ProdOp : public XlaReductionOp {
public:
explicit ProdOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx,
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::One(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Mul(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Prod").CompileTimeConstantInput("reduction_indices"),
ProdOp);
class MinOp : public XlaReductionOp {
public:
explicit MinOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::MaxValue(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Min(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Min").CompileTimeConstantInput("reduction_indices"),
MinOp);
class MaxOp : public XlaReductionOp {
public:
explicit MaxOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {
OP_REQUIRES_OK(ctx, TypeCheck(xla_reduction_type_));
}
Status TypeCheck(xla::PrimitiveType xla_reduction_type_) {
if (xla_reduction_type_ == xla::C64) {
return errors::InvalidArgument(
"Unsupported PrimitiveType in MaxOp: '",
xla::PrimitiveType_Name(xla_reduction_type_), "'");
} else {
return Status::OK();
}
}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::MinValue(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Max(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Max").CompileTimeConstantInput("reduction_indices"),
MaxOp);
class MeanOp : public XlaReductionOp {
public:
explicit MeanOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx,
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::Zero(builder, xla_reduction_type_);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Add(scalar_lhs, scalar_rhs);
}
xla::XlaOp BuildFinalizer(
xla::XlaBuilder* /*builder*/, const xla::XlaOp& input,
const xla::XlaOp& reduce_output,
const std::vector<int64>& dimensions_to_reduce) override {
if (dimensions_to_reduce.empty()) {
return reduce_output;
}
auto divisor = xla::GetDimensionSize(input, dimensions_to_reduce[0]);
for (int i = 1; i < dimensions_to_reduce.size(); i++) {
auto size = xla::GetDimensionSize(input, dimensions_to_reduce[i]);
divisor = xla::Mul(divisor, size);
}
divisor = xla::ConvertElementType(divisor, xla_reduction_type_);
return XlaHelpers::ConvertElementType(reduce_output / divisor,
input_type(0));
}
};
REGISTER_XLA_OP(Name("Mean").CompileTimeConstantInput("reduction_indices"),
MeanOp);
class AllOp : public XlaReductionOp {
public:
explicit AllOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::ConstantR0<bool>(builder, true);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::And(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("All").CompileTimeConstantInput("reduction_indices"),
AllOp);
class AnyOp : public XlaReductionOp {
public:
explicit AnyOp(OpKernelConstruction* ctx)
: XlaReductionOp(ctx, ctx->input_type(0)) {}
xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
return xla::ConstantR0<bool>(builder, false);
}
void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs,
const xla::XlaOp& scalar_rhs) override {
xla::Or(scalar_lhs, scalar_rhs);
}
};
REGISTER_XLA_OP(Name("Any").CompileTimeConstantInput("reduction_indices"),
AnyOp);
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow 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 "tensorflow/compiler/xla/service/bfloat16_support.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
namespace xla {
bool BFloat16Support::SupportsBF16Operand(const HloInstruction& hlo,
int64 operand_index) const {
switch (hlo.opcode()) {
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kCustomCall:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
return true;
case HloOpcode::kConvert:
CHECK_EQ(operand_index, 0);
return hlo.operand(0)->shape().element_type() == BF16;
default:
break;
}
return false;
}
bool BFloat16Support::SupportsBF16Output(const HloInstruction& hlo) const {
switch (hlo.opcode()) {
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kCustomCall:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
return true;
case HloOpcode::kConvert:
return hlo.shape().element_type() == BF16;
default:
break;
}
return false;
}
bool BFloat16Support::SupportsMixedPrecisions(const HloInstruction& hlo) const {
switch (hlo.opcode()) {
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kConvert:
case HloOpcode::kCustomCall:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
return true;
default:
break;
}
return false;
}
/* static */
bool BFloat16Support::EffectiveOperandPrecisionIsOutputPrecision(
const HloInstruction& hlo, int64 operand_index) {
switch (hlo.opcode()) {
case HloOpcode::kAbs:
case HloOpcode::kBroadcast:
case HloOpcode::kClamp:
case HloOpcode::kConcatenate:
case HloOpcode::kConvert:
case HloOpcode::kCopy:
case HloOpcode::kGetTupleElement:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kPad:
case HloOpcode::kReshape:
case HloOpcode::kReverse:
case HloOpcode::kSlice:
case HloOpcode::kSort:
case HloOpcode::kTranspose:
case HloOpcode::kTuple:
return true;
case HloOpcode::kDynamicSlice:
return operand_index == 0;
case HloOpcode::kDynamicUpdateSlice:
return operand_index == 0 || operand_index == 1;
case HloOpcode::kSelect:
return operand_index == 1 || operand_index == 2;
default:
break;
}
return false;
}
bool BFloat16Support::EffectiveOperandPrecisionIsBF16(
const HloInstruction& hlo, int64 operand_index) const {
return false;
}
} // namespace xla
<commit_msg>Enable bfloat propagation for bitcast HLO<commit_after>/* Copyright 2018 The TensorFlow 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 "tensorflow/compiler/xla/service/bfloat16_support.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
namespace xla {
bool BFloat16Support::SupportsBF16Operand(const HloInstruction& hlo,
int64 operand_index) const {
switch (hlo.opcode()) {
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kCustomCall:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
return true;
case HloOpcode::kConvert:
CHECK_EQ(operand_index, 0);
return hlo.operand(0)->shape().element_type() == BF16;
default:
break;
}
return false;
}
bool BFloat16Support::SupportsBF16Output(const HloInstruction& hlo) const {
switch (hlo.opcode()) {
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kCustomCall:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
return true;
case HloOpcode::kConvert:
return hlo.shape().element_type() == BF16;
default:
break;
}
return false;
}
bool BFloat16Support::SupportsMixedPrecisions(const HloInstruction& hlo) const {
switch (hlo.opcode()) {
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kConvert:
case HloOpcode::kCustomCall:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
return true;
default:
break;
}
return false;
}
/* static */
bool BFloat16Support::EffectiveOperandPrecisionIsOutputPrecision(
const HloInstruction& hlo, int64 operand_index) {
switch (hlo.opcode()) {
case HloOpcode::kAbs:
case HloOpcode::kBroadcast:
case HloOpcode::kClamp:
case HloOpcode::kConcatenate:
case HloOpcode::kConvert:
case HloOpcode::kCopy:
case HloOpcode::kGetTupleElement:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kPad:
case HloOpcode::kReshape:
case HloOpcode::kReverse:
case HloOpcode::kSlice:
case HloOpcode::kSort:
case HloOpcode::kTranspose:
case HloOpcode::kTuple:
return true;
case HloOpcode::kBitcast:
return hlo.shape().element_type() ==
hlo.operand(0)->shape().element_type();
case HloOpcode::kDynamicSlice:
return operand_index == 0;
case HloOpcode::kDynamicUpdateSlice:
return operand_index == 0 || operand_index == 1;
case HloOpcode::kSelect:
return operand_index == 1 || operand_index == 2;
default:
break;
}
return false;
}
bool BFloat16Support::EffectiveOperandPrecisionIsBF16(
const HloInstruction& hlo, int64 operand_index) const {
return false;
}
} // namespace xla
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow 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 <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/lib/profiler_factory.h"
#include "tensorflow/core/profiler/lib/profiler_interface.h"
#include "tensorflow/core/profiler/profiler_options.pb.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/tpu/tpu_api.h"
#include "tensorflow/core/tpu/tpu_initializer_helper.h"
#include "tensorflow/core/tpu/tpu_ops_c_api.h"
#include "tensorflow/stream_executor/tpu/status_helper.h"
namespace tensorflow {
namespace profiler {
namespace {
// Tpu implementation of ProfilerInterface.
//
// Thread-safety: This class is go/thread-compatible.
class TpuTracer : public ProfilerInterface {
public:
explicit TpuTracer();
~TpuTracer() override;
Status Start() override;
Status Stop() override;
// Unsupported.
Status CollectData(RunMetadata* run_metadata) override;
Status CollectData(XSpace* space) override;
private:
TpuProfiler* tpu_profiler_;
};
TpuTracer::TpuTracer() {
StatusHelper status;
tpu::OpsApiFn()->TpuProfiler_CreateFn(&tpu_profiler_, status.c_status);
if (!status.ok()) {
LOG(ERROR) << status.status().error_message();
}
}
TpuTracer::~TpuTracer() {
tpu::OpsApiFn()->TpuProfiler_DestroyFn(tpu_profiler_);
}
Status TpuTracer::Start() {
StatusHelper status;
tpu::OpsApiFn()->TpuProfiler_StartFn(tpu_profiler_, status.c_status);
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to start.";
return status.status();
}
return Status::OK();
}
Status TpuTracer::Stop() {
StatusHelper status;
tpu::OpsApiFn()->TpuProfiler_StopFn(tpu_profiler_, status.c_status);
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to stop.";
return status.status();
}
return Status::OK();
}
Status TpuTracer::CollectData(RunMetadata* run_metadata) {
// Unsupported
return Status::OK();
}
Status TpuTracer::CollectData(XSpace* space) {
StatusHelper status;
// Get size of buffer required for TPU driver to serialize XSpace into.
size_t size_in_bytes;
tpu::OpsApiFn()->TpuProfiler_CollectDataFn(tpu_profiler_, status.c_status,
/*buffer=*/nullptr,
&size_in_bytes);
// Prepare an appropriately sized buffer.
if (size_in_bytes > 0) {
std::vector<uint8_t> buffer(size_in_bytes);
tpu::OpsApiFn()->TpuProfiler_CollectDataFn(tpu_profiler_, status.c_status,
buffer.data(), &size_in_bytes);
// Deserialize XSpace from the buffer and return it.
XSpace tpu_space;
tpu_space.ParseFromArray(buffer.data(), buffer.size());
for (XPlane& tpu_plane : *tpu_space.mutable_planes()) {
XPlane* plane = space->add_planes();
plane->Swap(&tpu_plane);
}
}
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to collect data.";
return status.status();
}
return Status::OK();
}
} // namespace
// Not in anonymous namespace for testing purposes.
std::unique_ptr<ProfilerInterface> CreateTpuTracer(
const ProfileOptions& options) {
if (options.device_type() != ProfileOptions::TPU &&
options.device_type() != ProfileOptions::UNSPECIFIED) {
return nullptr;
}
// Don't attempt to create a TpuTracer if the TPU C API isn't initialized.
if (tpu::OpsApiFn()->TpuProfiler_CreateFn == nullptr) {
return nullptr;
}
return absl::make_unique<TpuTracer>();
}
auto register_tpu_tracer_factory = [] {
if (tensorflow::tpu::TryAcquireTpuLock()) {
RegisterProfilerFactory(&CreateTpuTracer);
}
return 0;
}();
} // namespace profiler
} // namespace tensorflow
<commit_msg>Remove RunMetadata overload of TpuTracer::CollectData<commit_after>/* Copyright 2018 The TensorFlow 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 <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/lib/profiler_factory.h"
#include "tensorflow/core/profiler/lib/profiler_interface.h"
#include "tensorflow/core/profiler/profiler_options.pb.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/tpu/tpu_api.h"
#include "tensorflow/core/tpu/tpu_initializer_helper.h"
#include "tensorflow/core/tpu/tpu_ops_c_api.h"
#include "tensorflow/stream_executor/tpu/status_helper.h"
namespace tensorflow {
namespace profiler {
namespace {
// Tpu implementation of ProfilerInterface.
//
// Thread-safety: This class is go/thread-compatible.
class TpuTracer : public ProfilerInterface {
public:
explicit TpuTracer();
~TpuTracer() override;
Status Start() override;
Status Stop() override;
Status CollectData(XSpace* space) override;
private:
TpuProfiler* tpu_profiler_;
};
TpuTracer::TpuTracer() {
StatusHelper status;
tpu::OpsApiFn()->TpuProfiler_CreateFn(&tpu_profiler_, status.c_status);
if (!status.ok()) {
LOG(ERROR) << status.status().error_message();
}
}
TpuTracer::~TpuTracer() {
tpu::OpsApiFn()->TpuProfiler_DestroyFn(tpu_profiler_);
}
Status TpuTracer::Start() {
StatusHelper status;
tpu::OpsApiFn()->TpuProfiler_StartFn(tpu_profiler_, status.c_status);
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to start.";
return status.status();
}
return Status::OK();
}
Status TpuTracer::Stop() {
StatusHelper status;
tpu::OpsApiFn()->TpuProfiler_StopFn(tpu_profiler_, status.c_status);
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to stop.";
return status.status();
}
return Status::OK();
}
Status TpuTracer::CollectData(XSpace* space) {
StatusHelper status;
// Get size of buffer required for TPU driver to serialize XSpace into.
size_t size_in_bytes;
tpu::OpsApiFn()->TpuProfiler_CollectDataFn(tpu_profiler_, status.c_status,
/*buffer=*/nullptr,
&size_in_bytes);
// Prepare an appropriately sized buffer.
if (size_in_bytes > 0) {
std::vector<uint8_t> buffer(size_in_bytes);
tpu::OpsApiFn()->TpuProfiler_CollectDataFn(tpu_profiler_, status.c_status,
buffer.data(), &size_in_bytes);
// Deserialize XSpace from the buffer and return it.
XSpace tpu_space;
tpu_space.ParseFromArray(buffer.data(), buffer.size());
for (XPlane& tpu_plane : *tpu_space.mutable_planes()) {
XPlane* plane = space->add_planes();
plane->Swap(&tpu_plane);
}
}
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to collect data.";
return status.status();
}
return Status::OK();
}
} // namespace
// Not in anonymous namespace for testing purposes.
std::unique_ptr<ProfilerInterface> CreateTpuTracer(
const ProfileOptions& options) {
if (options.device_type() != ProfileOptions::TPU &&
options.device_type() != ProfileOptions::UNSPECIFIED) {
return nullptr;
}
// Don't attempt to create a TpuTracer if the TPU C API isn't initialized.
if (tpu::OpsApiFn()->TpuProfiler_CreateFn == nullptr) {
return nullptr;
}
return absl::make_unique<TpuTracer>();
}
auto register_tpu_tracer_factory = [] {
if (tensorflow::tpu::TryAcquireTpuLock()) {
RegisterProfilerFactory(&CreateTpuTracer);
}
return 0;
}();
} // namespace profiler
} // namespace tensorflow
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter_test_suite.hpp
* \date June 2015
* \author Jan Issac ([email protected])
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
namespace fl
{
template <typename TestType>
class GaussianFilterTest
: public ::testing::Test
{
public:
};
}
<commit_msg>Implemented GaussianFilter Testing suit<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter_test_suite.hpp
* \date June 2015
* \author Jan Issac ([email protected])
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <fl/util/math/linear_algebra.hpp>
#include <fl/filter/filter_interface.hpp>
#include <fl/model/process/linear_process_model.hpp>
#include <fl/model/observation/linear_observation_model.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>
template <typename TestType>
class GaussianFilterTest
: public ::testing::Test
{
protected:
enum: signed int
{
StateDim = 10,
InputDim = 5,
ObsrvDim = 20,
StateSize = fl::TestSize<StateDim, TestType>::Value,
InputSize = fl::TestSize<InputDim, TestType>::Value,
ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value
};
typedef Eigen::Matrix<fl::Real, StateSize, 1> State;
typedef Eigen::Matrix<fl::Real, InputSize, 1> Input;
typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv;
typedef fl::LinearStateTransitionModel<State, Input> LinearStateTransition;
typedef fl::LinearObservationModel<Obsrv, State> LinearObservation;
template <typename Filter>
void setup_models(Filter& filter)
{
auto A = filter.process_model().create_dynamics_matrix();
auto Q = filter.process_model().create_noise_matrix();
auto H = filter.obsrv_model().create_sensor_matrix();
auto R = filter.obsrv_model().create_noise_matrix();
A.setRandom();
H.setRandom();
Q.setRandom();
R.setRandom();
filter.process_model().dynamics_matrix(A);
filter.process_model().noise_matrix(Q);
filter.obsrv_model().sensor_matrix(H);
filter.obsrv_model().noise_matrix(R);
}
State zero_state() { return State::Zero(StateDim); }
Input zero_input() { return Input::Zero(InputDim); }
Obsrv zero_obsrv() { return Obsrv::Zero(ObsrvDim); }
State rand_state() { return State::Random(StateDim); }
Input rand_input() { return Input::Random(InputDim); }
Obsrv rand_obsrv() { return Obsrv::Random(ObsrvDim); }
template <typename Filter, typename Belief>
void predict(Filter& filter, Belief& belief)
{
EXPECT_TRUE(belief.mean().isZero());
EXPECT_TRUE(belief.covariance().isIdentity());
filter.predict(belief, zero_input(), belief);
auto Q = filter.process_model().noise_matrix_squared();
EXPECT_TRUE(belief.mean().isZero());
EXPECT_TRUE(fl::are_similar(belief.covariance(), 2. * Q));
}
template <typename Filter, typename Belief>
void predict_update(Filter& filter, Belief& belief)
{
setup_models(filter);
EXPECT_TRUE(belief.covariance().ldlt().isPositive());
for (int i = 0; i < 2000; ++i)
{
filter.predict(belief, zero_input(), belief);
ASSERT_TRUE(belief.covariance().ldlt().isPositive());
filter.update(belief, rand_obsrv(), belief);
ASSERT_TRUE(belief.covariance().ldlt().isPositive());
}
}
template <typename Filter, typename Belief>
void predict_and_update(Filter& filter, Belief& belief_A, Belief& belief_B)
{
setup_models(filter);
EXPECT_TRUE(belief_A.covariance().ldlt().isPositive());
EXPECT_TRUE(belief_B.covariance().ldlt().isPositive());
for (int i = 0; i < 2000; ++i)
{
const auto y = rand_obsrv();
const auto u = zero_input();
filter.predict(belief_A, u, belief_A);
filter.update(belief_A, y, belief_A);
filter.predict_and_update(belief_B, u, y, belief_B);
ASSERT_TRUE(
fl::are_similar(belief_A.mean(), belief_B.mean()));
ASSERT_TRUE(
fl::are_similar(belief_A.covariance(), belief_B.covariance()));
ASSERT_TRUE(belief_A.covariance().ldlt().isPositive());
ASSERT_TRUE(belief_B.covariance().ldlt().isPositive());
}
}
};
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "AT_CellularStack.h"
#include "CellularUtil.h"
#include "CellularLog.h"
using namespace mbed_cellular_util;
using namespace mbed;
AT_CellularStack::AT_CellularStack(ATHandler &at, int cid, nsapi_ip_stack_t stack_type) : AT_CellularBase(at), _socket(NULL), _socket_count(0), _cid(cid), _stack_type(stack_type)
{
memset(_ip, 0, PDP_IPV6_SIZE);
}
AT_CellularStack::~AT_CellularStack()
{
for (int i = 0; i < _socket_count; i++) {
if (_socket[i]) {
delete _socket[i];
_socket[i] = NULL;
}
}
_socket_count = 0;
delete [] _socket;
_socket = NULL;
}
int AT_CellularStack::find_socket_index(nsapi_socket_t handle)
{
int max_socket_count = get_max_socket_count();
for (int i = 0; i < max_socket_count; i++) {
if (_socket[i] == handle) {
return i;
}
}
return -1;
}
/** NetworkStack
*/
const char *AT_CellularStack::get_ip_address()
{
_at.lock();
_at.cmd_start("AT+CGPADDR=");
_at.write_int(_cid);
_at.cmd_stop();
_at.resp_start("+CGPADDR:");
if (_at.info_resp()) {
_at.skip_param();
int len = _at.read_string(_ip, NSAPI_IPv4_SIZE - 1);
if (len == -1) {
_ip[0] = '\0';
_at.resp_stop();
_at.unlock();
// no IPV4 address, return
return NULL;
}
// in case stack type is not IPV4 only, try to look also for IPV6 address
if (_stack_type != IPV4_STACK) {
(void)_at.read_string(_ip, PDP_IPV6_SIZE - 1);
}
}
_at.resp_stop();
_at.unlock();
// we have at least IPV4 address
convert_ipv6(_ip);
return _ip;
}
nsapi_error_t AT_CellularStack::socket_stack_init()
{
return NSAPI_ERROR_OK;
}
nsapi_error_t AT_CellularStack::socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto)
{
if (!is_protocol_supported(proto) || !handle) {
return NSAPI_ERROR_UNSUPPORTED;
}
int max_socket_count = get_max_socket_count();
_socket_mutex.lock();
if (!_socket) {
if (socket_stack_init() != NSAPI_ERROR_OK) {
_socket_mutex.unlock();
return NSAPI_ERROR_NO_SOCKET;
}
_socket = new CellularSocket*[max_socket_count];
if (!_socket) {
tr_error("No memory to open socket!");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_SOCKET;
}
_socket_count = max_socket_count;
for (int i = 0; i < max_socket_count; i++) {
_socket[i] = 0;
}
}
int index = find_socket_index(0);
if (index == -1) {
tr_error("No free sockets!");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_SOCKET;
}
tr_info("Socket %d open", index);
// create local socket structure, socket on modem is created when app calls sendto/recvfrom
_socket[index] = new CellularSocket;
CellularSocket *psock;
psock = _socket[index];
memset(psock, 0, sizeof(CellularSocket));
SocketAddress addr(0, get_dynamic_ip_port());
psock->id = index;
psock->localAddress = addr;
psock->proto = proto;
*handle = psock;
_socket_mutex.unlock();
return NSAPI_ERROR_OK;
}
nsapi_error_t AT_CellularStack::socket_close(nsapi_socket_t handle)
{
int err = NSAPI_ERROR_DEVICE_ERROR;
struct CellularSocket *socket = (struct CellularSocket *)handle;
if (!socket) {
return err;
}
int sock_id = socket->id;
bool sock_created = socket->created;
int index = find_socket_index(handle);
if (index == -1) {
tr_error("No socket found to be closed");
return err;
}
err = NSAPI_ERROR_OK;
// Close the socket on the modem if it was created
_at.lock();
if (sock_created) {
err = socket_close_impl(sock_id);
}
if (!err) {
tr_info("Socket %d closed", index);
} else {
tr_info("Socket %d close (id %d, created %d, started %d, error %d)", index, sock_id, socket->created, socket->started, err);
}
_socket[index] = NULL;
delete socket;
_at.unlock();
return err;
}
nsapi_error_t AT_CellularStack::socket_bind(nsapi_socket_t handle, const SocketAddress &addr)
{
struct CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
if (addr) {
socket->localAddress.set_addr(addr.get_addr());
}
if (addr.get_port()) {
socket->localAddress.set_port(addr.get_port());
}
_at.lock();
if (!socket->created) {
create_socket_impl(socket);
}
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;;
}
nsapi_error_t AT_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &addr)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
socket->remoteAddress = addr;
socket->connected = true;
return NSAPI_ERROR_OK;
}
nsapi_error_t AT_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)
{
return NSAPI_ERROR_UNSUPPORTED;;
}
nsapi_size_or_error_t AT_CellularStack::socket_send(nsapi_socket_t handle, const void *data, unsigned size)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket || !socket->connected) {
return NSAPI_ERROR_DEVICE_ERROR;
}
return socket_sendto(handle, socket->remoteAddress, data, size);
}
nsapi_size_or_error_t AT_CellularStack::socket_sendto(nsapi_socket_t handle, const SocketAddress &addr, const void *data, unsigned size)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
nsapi_size_or_error_t ret_val = NSAPI_ERROR_OK;
if (!socket->created) {
_at.lock();
ret_val = create_socket_impl(socket);
_at.unlock();
if (ret_val != NSAPI_ERROR_OK) {
tr_error("Socket %d create %s error %d", find_socket_index(socket), addr.get_ip_address(), ret_val);
return ret_val;
}
}
/* Check parameters */
if (addr.get_ip_version() == NSAPI_UNSPEC) {
return NSAPI_ERROR_DEVICE_ERROR;
}
_at.lock();
ret_val = socket_sendto_impl(socket, addr, data, size);
_at.unlock();
if (ret_val >= 0) {
tr_info("Socket %d sent %d bytes to %s port %d", find_socket_index(socket), ret_val, addr.get_ip_address(), addr.get_port());
} else if (ret_val != NSAPI_ERROR_WOULD_BLOCK) {
tr_error("Socket %d sendto %s error %d", find_socket_index(socket), addr.get_ip_address(), ret_val);
}
return ret_val;
}
nsapi_size_or_error_t AT_CellularStack::socket_recv(nsapi_socket_t handle, void *data, unsigned size)
{
return socket_recvfrom(handle, NULL, data, size);
}
nsapi_size_or_error_t AT_CellularStack::socket_recvfrom(nsapi_socket_t handle, SocketAddress *addr, void *buffer, unsigned size)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
nsapi_size_or_error_t ret_val = NSAPI_ERROR_OK;
if (!socket->created) {
_at.lock();
ret_val = create_socket_impl(socket);
_at.unlock();
if (ret_val != NSAPI_ERROR_OK) {
tr_error("Socket %d create error %d", find_socket_index(socket), ret_val);
return ret_val;
}
}
_at.lock();
ret_val = socket_recvfrom_impl(socket, addr, buffer, size);
_at.unlock();
if (ret_val >= 0) {
if(addr){
tr_info("Socket %d recv %d bytes from %s port %d", find_socket_index(socket), ret_val, addr->get_ip_address(), addr->get_port());
}
else{
tr_info("Socket %d recv %d bytes", find_socket_index(socket), ret_val);
}
} else if (ret_val != NSAPI_ERROR_WOULD_BLOCK) {
tr_error("Socket %d recv error %d", find_socket_index(socket), ret_val);
}
return ret_val;
}
void AT_CellularStack::socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return;
}
socket->_cb = callback;
socket->_data = data;
}
<commit_msg>Formatted via astyle.<commit_after>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "AT_CellularStack.h"
#include "CellularUtil.h"
#include "CellularLog.h"
using namespace mbed_cellular_util;
using namespace mbed;
AT_CellularStack::AT_CellularStack(ATHandler &at, int cid, nsapi_ip_stack_t stack_type) : AT_CellularBase(at), _socket(NULL), _socket_count(0), _cid(cid), _stack_type(stack_type)
{
memset(_ip, 0, PDP_IPV6_SIZE);
}
AT_CellularStack::~AT_CellularStack()
{
for (int i = 0; i < _socket_count; i++) {
if (_socket[i]) {
delete _socket[i];
_socket[i] = NULL;
}
}
_socket_count = 0;
delete [] _socket;
_socket = NULL;
}
int AT_CellularStack::find_socket_index(nsapi_socket_t handle)
{
int max_socket_count = get_max_socket_count();
for (int i = 0; i < max_socket_count; i++) {
if (_socket[i] == handle) {
return i;
}
}
return -1;
}
/** NetworkStack
*/
const char *AT_CellularStack::get_ip_address()
{
_at.lock();
_at.cmd_start("AT+CGPADDR=");
_at.write_int(_cid);
_at.cmd_stop();
_at.resp_start("+CGPADDR:");
if (_at.info_resp()) {
_at.skip_param();
int len = _at.read_string(_ip, NSAPI_IPv4_SIZE - 1);
if (len == -1) {
_ip[0] = '\0';
_at.resp_stop();
_at.unlock();
// no IPV4 address, return
return NULL;
}
// in case stack type is not IPV4 only, try to look also for IPV6 address
if (_stack_type != IPV4_STACK) {
(void)_at.read_string(_ip, PDP_IPV6_SIZE - 1);
}
}
_at.resp_stop();
_at.unlock();
// we have at least IPV4 address
convert_ipv6(_ip);
return _ip;
}
nsapi_error_t AT_CellularStack::socket_stack_init()
{
return NSAPI_ERROR_OK;
}
nsapi_error_t AT_CellularStack::socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto)
{
if (!is_protocol_supported(proto) || !handle) {
return NSAPI_ERROR_UNSUPPORTED;
}
int max_socket_count = get_max_socket_count();
_socket_mutex.lock();
if (!_socket) {
if (socket_stack_init() != NSAPI_ERROR_OK) {
_socket_mutex.unlock();
return NSAPI_ERROR_NO_SOCKET;
}
_socket = new CellularSocket*[max_socket_count];
if (!_socket) {
tr_error("No memory to open socket!");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_SOCKET;
}
_socket_count = max_socket_count;
for (int i = 0; i < max_socket_count; i++) {
_socket[i] = 0;
}
}
int index = find_socket_index(0);
if (index == -1) {
tr_error("No free sockets!");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_SOCKET;
}
tr_info("Socket %d open", index);
// create local socket structure, socket on modem is created when app calls sendto/recvfrom
_socket[index] = new CellularSocket;
CellularSocket *psock;
psock = _socket[index];
memset(psock, 0, sizeof(CellularSocket));
SocketAddress addr(0, get_dynamic_ip_port());
psock->id = index;
psock->localAddress = addr;
psock->proto = proto;
*handle = psock;
_socket_mutex.unlock();
return NSAPI_ERROR_OK;
}
nsapi_error_t AT_CellularStack::socket_close(nsapi_socket_t handle)
{
int err = NSAPI_ERROR_DEVICE_ERROR;
struct CellularSocket *socket = (struct CellularSocket *)handle;
if (!socket) {
return err;
}
int sock_id = socket->id;
bool sock_created = socket->created;
int index = find_socket_index(handle);
if (index == -1) {
tr_error("No socket found to be closed");
return err;
}
err = NSAPI_ERROR_OK;
// Close the socket on the modem if it was created
_at.lock();
if (sock_created) {
err = socket_close_impl(sock_id);
}
if (!err) {
tr_info("Socket %d closed", index);
} else {
tr_info("Socket %d close (id %d, created %d, started %d, error %d)", index, sock_id, socket->created, socket->started, err);
}
_socket[index] = NULL;
delete socket;
_at.unlock();
return err;
}
nsapi_error_t AT_CellularStack::socket_bind(nsapi_socket_t handle, const SocketAddress &addr)
{
struct CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
if (addr) {
socket->localAddress.set_addr(addr.get_addr());
}
if (addr.get_port()) {
socket->localAddress.set_port(addr.get_port());
}
_at.lock();
if (!socket->created) {
create_socket_impl(socket);
}
return _at.unlock_return_error();
}
nsapi_error_t AT_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;;
}
nsapi_error_t AT_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &addr)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
socket->remoteAddress = addr;
socket->connected = true;
return NSAPI_ERROR_OK;
}
nsapi_error_t AT_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)
{
return NSAPI_ERROR_UNSUPPORTED;;
}
nsapi_size_or_error_t AT_CellularStack::socket_send(nsapi_socket_t handle, const void *data, unsigned size)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket || !socket->connected) {
return NSAPI_ERROR_DEVICE_ERROR;
}
return socket_sendto(handle, socket->remoteAddress, data, size);
}
nsapi_size_or_error_t AT_CellularStack::socket_sendto(nsapi_socket_t handle, const SocketAddress &addr, const void *data, unsigned size)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
nsapi_size_or_error_t ret_val = NSAPI_ERROR_OK;
if (!socket->created) {
_at.lock();
ret_val = create_socket_impl(socket);
_at.unlock();
if (ret_val != NSAPI_ERROR_OK) {
tr_error("Socket %d create %s error %d", find_socket_index(socket), addr.get_ip_address(), ret_val);
return ret_val;
}
}
/* Check parameters */
if (addr.get_ip_version() == NSAPI_UNSPEC) {
return NSAPI_ERROR_DEVICE_ERROR;
}
_at.lock();
ret_val = socket_sendto_impl(socket, addr, data, size);
_at.unlock();
if (ret_val >= 0) {
tr_info("Socket %d sent %d bytes to %s port %d", find_socket_index(socket), ret_val, addr.get_ip_address(), addr.get_port());
} else if (ret_val != NSAPI_ERROR_WOULD_BLOCK) {
tr_error("Socket %d sendto %s error %d", find_socket_index(socket), addr.get_ip_address(), ret_val);
}
return ret_val;
}
nsapi_size_or_error_t AT_CellularStack::socket_recv(nsapi_socket_t handle, void *data, unsigned size)
{
return socket_recvfrom(handle, NULL, data, size);
}
nsapi_size_or_error_t AT_CellularStack::socket_recvfrom(nsapi_socket_t handle, SocketAddress *addr, void *buffer, unsigned size)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return NSAPI_ERROR_DEVICE_ERROR;
}
nsapi_size_or_error_t ret_val = NSAPI_ERROR_OK;
if (!socket->created) {
_at.lock();
ret_val = create_socket_impl(socket);
_at.unlock();
if (ret_val != NSAPI_ERROR_OK) {
tr_error("Socket %d create error %d", find_socket_index(socket), ret_val);
return ret_val;
}
}
_at.lock();
ret_val = socket_recvfrom_impl(socket, addr, buffer, size);
_at.unlock();
if (ret_val >= 0) {
if (addr) {
tr_info("Socket %d recv %d bytes from %s port %d", find_socket_index(socket), ret_val, addr->get_ip_address(), addr->get_port());
} else {
tr_info("Socket %d recv %d bytes", find_socket_index(socket), ret_val);
}
} else if (ret_val != NSAPI_ERROR_WOULD_BLOCK) {
tr_error("Socket %d recv error %d", find_socket_index(socket), ret_val);
}
return ret_val;
}
void AT_CellularStack::socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data)
{
CellularSocket *socket = (CellularSocket *)handle;
if (!socket) {
return;
}
socket->_cb = callback;
socket->_data = data;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
#include "rendering/renderablezindexcomparer.hpp"
#include "__mocks__/rendering/renderablemock.hpp"
using ::testing::ElementsAre;
TEST(RenderableZIndexComparer_Compare, If_first_z_index_is_less_than_second_z_index_Then_true_is_returned)
{
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
ASSERT_TRUE(comparer(&a, &b));
ASSERT_FALSE(comparer(&b, &a));
}
TEST(RenderableZIndexComparer_Compare, Is_compatible_to_std_sort)
{
// Arrange
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
RenderableMock c(0);
c.setZIndex(14);
std::vector<qrw::Renderable*> renderables = {&b, &c, &a};
// Act
std::sort(renderables.begin(), renderables.end(), comparer);
// Assert
ASSERT_THAT(renderables, ElementsAre(&a, &b, &c));
}
<commit_msg>2nd try fixing ci<commit_after>#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "rendering/renderablezindexcomparer.hpp"
#include "__mocks__/rendering/renderablemock.hpp"
using ::testing::ElementsAre;
TEST(RenderableZIndexComparer_Compare, If_first_z_index_is_less_than_second_z_index_Then_true_is_returned)
{
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
ASSERT_TRUE(comparer(&a, &b));
ASSERT_FALSE(comparer(&b, &a));
}
TEST(RenderableZIndexComparer_Compare, Is_compatible_to_std_sort)
{
// Arrange
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
RenderableMock c(0);
c.setZIndex(14);
std::vector<qrw::Renderable*> renderables = {&b, &c, &a};
// Act
std::sort(renderables.begin(), renderables.end(), comparer);
// Assert
ASSERT_THAT(renderables, ElementsAre(&a, &b, &c));
}
<|endoftext|> |
<commit_before>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH
#define MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH
#include <config.h>
#include <type_traits>
#include <dune/common/fmatrix.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/operator/2order/lagrangematrixsetup.hh>
#include <dune/multiscale/common/dirichletconstraints.hh>
#include <dune/multiscale/msfem/localproblems/subgrid-list.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/msfem/msfem_grid_specifier.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/hmm/cell_problem_numbering.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/fem/functions/checks.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
/**
* \todo docme
*/
class DiscreteEllipticMsFEMOperator
: boost::noncopyable
{
private:
typedef CommonTraits::DiscreteFunctionType CoarseDiscreteFunction;
typedef CommonTraits::DiscreteFunctionType FineDiscreteFunction;
typedef MacroMicroGridSpecifier MacroMicroGridSpecifierType;
typedef CommonTraits::DiffusionType DiffusionModel;
typedef typename CoarseDiscreteFunction::DiscreteFunctionSpaceType CoarseDiscreteFunctionSpace;
typedef typename FineDiscreteFunction::DiscreteFunctionSpaceType FineDiscreteFunctionSpace;
typedef typename FineDiscreteFunctionSpace::FunctionSpaceType FunctionSpace;
typedef typename FineDiscreteFunctionSpace::GridPartType FineGridPart;
typedef typename FineDiscreteFunctionSpace::GridType FineGrid;
typedef typename FineDiscreteFunctionSpace::RangeFieldType RangeFieldType;
typedef typename FineDiscreteFunctionSpace::DomainType DomainType;
typedef typename FineDiscreteFunctionSpace::RangeType RangeType;
typedef typename FineDiscreteFunctionSpace::JacobianRangeType JacobianRangeType;
typedef MsFEMLocalProblemSolver MsFEMLocalProblemSolverType;
static const int dimension = FineGridPart::GridType::dimension;
static const int polynomialOrder = FineDiscreteFunctionSpace::polynomialOrder;
typedef typename FineDiscreteFunction::LocalFunctionType FineLocalFunction;
typedef typename FineDiscreteFunctionSpace::BasisFunctionSetType FineBaseFunctionSet;
typedef typename FineDiscreteFunctionSpace::LagrangePointSetType FineLagrangePointSet;
typedef typename FineLagrangePointSet::Codim< 1 >::SubEntityIteratorType FineFaceDofIterator;
typedef typename FineGrid::Traits::LeafIndexSet FineGridLeafIndexSet;
typedef typename FineDiscreteFunctionSpace::IteratorType FineIterator;
typedef typename FineIterator::Entity FineEntity;
typedef typename FineEntity::EntityPointer FineEntityPointer;
typedef typename FineEntity::Geometry FineGeometry;
typedef typename FineGridPart::IntersectionIteratorType FineIntersectionIterator;
typedef typename FineIntersectionIterator::Intersection FineIntersection;
typedef Fem::CachingQuadrature< FineGridPart, 0 > FineQuadratureType;
typedef typename CoarseDiscreteFunctionSpace::GridPartType CoarseGridPart;
typedef typename CoarseDiscreteFunctionSpace::GridType CoarseGrid;
typedef typename CoarseDiscreteFunction::LocalFunctionType CoarseLocalFunction;
typedef typename CoarseDiscreteFunctionSpace::BasisFunctionSetType CoarseBaseFunctionSet;
typedef typename CoarseDiscreteFunctionSpace::LagrangePointSetType CoarseLagrangePointSet;
typedef typename CoarseLagrangePointSet::Codim< 1 >::SubEntityIteratorType CoarseFaceDofIterator;
typedef typename CoarseDiscreteFunctionSpace::IteratorType CoarseIterator;
typedef typename CoarseGrid::Traits::LeafIndexSet CoarseGridLeafIndexSet;
typedef typename CoarseIterator::Entity CoarseEntity;
typedef typename CoarseEntity::Geometry CoarseGeometry;
typedef typename CoarseGridPart::IntersectionIteratorType CoarseIntersectionIterator;
typedef typename CoarseIntersectionIterator::Intersection CoarseIntersection;
typedef Fem::CachingQuadrature< CoarseGridPart, 0 > CoarseQuadrature;
typedef MsFEMTraits::SubGridListType SubGridListType;
typedef typename SubGridListType::SubGridQuadratureType SubGridQuadratureType;
public:
DiscreteEllipticMsFEMOperator(MacroMicroGridSpecifierType& specifier,
const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace,
// number of layers per coarse grid entity T: U(T) is created by enrichting T with
// n(T)-layers:
MsFEMTraits::SubGridListType& subgrid_list,
const DiffusionModel& diffusion_op);
template< class SPMatrixObject >
void assemble_matrix(SPMatrixObject& global_matrix) const;
private:
MacroMicroGridSpecifierType& specifier_;
const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace_;
MsFEMTraits::SubGridListType& subgrid_list_;
const DiffusionModel& diffusion_operator_;
const bool petrovGalerkin_;
};
template< class SPMatrixObject >
void DiscreteEllipticMsFEMOperator::assemble_matrix(SPMatrixObject& global_matrix) const
{
// the local problem:
// Let 'T' denote a coarse grid element and
// let 'U(T)' denote the environment of 'T' that corresponds with the subgrid.
// if Petrov-Galerkin-MsFEM
if (petrovGalerkin_)
DSC_LOG_INFO << "Assembling Petrov-Galerkin-MsFEM Matrix." << std::endl;
else // if classical (symmetric) MsFEM
DSC_LOG_INFO << "Assembling MsFEM Matrix." << std::endl;
global_matrix.reserve();
global_matrix.clear();
const auto& coarseGridLeafIndexSet = coarseDiscreteFunctionSpace_.gridPart().grid().leafIndexSet();
for (const CoarseEntity& coarse_grid_entity : coarseDiscreteFunctionSpace_) {
const CoarseGeometry& coarse_grid_geometry = coarse_grid_entity.geometry();
assert(coarse_grid_entity.partitionType() == InteriorEntity);
const int global_index_entity = coarseGridLeafIndexSet.index(coarse_grid_entity);
DSFe::LocalMatrixProxy< SPMatrixObject > local_matrix(global_matrix, coarse_grid_entity, coarse_grid_entity);
const CoarseBaseFunctionSet& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet();
const unsigned int numMacroBaseFunctions = coarse_grid_baseSet.size();
// Load local solutions
Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarse_grid_entity, subgrid_list_, specifier_);
localSolutionManager.loadLocalSolutions();
Multiscale::MsFEM::LocalSolutionManager::LocalSolutionVectorType& localSolutions
= localSolutionManager.getLocalSolutions();
assert(localSolutions.size() > 0);
std::vector< typename CoarseBaseFunctionSet::JacobianRangeType > gradientPhi(numMacroBaseFunctions);
const int localQuadratureOrder = 2 * localSolutionManager.getLocalDiscreteFunctionSpace().order() + 2;
// iterator for the micro grid ( grid for the reference element T_0 )
for (const auto& localGridEntity : localSolutionManager.getLocalDiscreteFunctionSpace()) {
// check if "localGridEntity" (which is an entity of U(T)) is in T:
// -------------------------------------------------------------------
const auto& hostEntity
= localSolutionManager.getSubGridPart().grid().template getHostEntity< 0 >(localGridEntity);
// ignore overlay elements
if (global_index_entity == subgrid_list_.getEnclosingMacroCellIndex(hostEntity)) {
assert(hostEntity->partitionType() == InteriorEntity);
const auto& local_grid_geometry = localGridEntity.geometry();
// higher order quadrature, since A^{\epsilon} is highly variable
SubGridQuadratureType localQuadrature(localGridEntity, localQuadratureOrder);
const size_t numQuadraturePoints = localQuadrature.nop();
// number of local solutions without the boundary correctors. Those are only needed for the right hand side
const int numLocalSolutions = localSolutions.size() - localSolutionManager.numBoundaryCorrectors();
// evaluate the jacobians of all local solutions in all quadrature points
std::vector< std::vector< JacobianRangeType > >
allLocalSolutionEvaluations(numLocalSolutions,
std::vector< JacobianRangeType >(localQuadrature.nop(), JacobianRangeType(0.0)));
for (int lsNum = 0; lsNum < numLocalSolutions; ++lsNum) {
auto localFunction = localSolutions[lsNum]->localFunction(localGridEntity);
localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]);
}
for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) {
// local (barycentric) coordinates (with respect to entity)
const typename FineQuadratureType::CoordinateType& local_subgrid_point = localQuadrature.point(
localQuadraturePoint);
DomainType global_point_in_U_T = local_grid_geometry.global(local_subgrid_point);
const double weight_local_quadrature
= localQuadrature.weight(localQuadraturePoint) * local_grid_geometry.integrationElement(
local_subgrid_point);
// evaluate the jacobian of the coarse grid base set
const DomainType& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T);
coarse_grid_baseSet.jacobianAll(local_coarse_point, gradientPhi);
for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) {
for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) {
RangeType local_integral(0.0);
// Compute the gradients of the i'th and j'th local problem solutions
JacobianRangeType gradLocProbSoli(0.0), gradLocProbSolj(0.0);
if (specifier_.simplexCoarseGrid()) {
assert(allLocalSolutionEvaluations.size()==dimension);
// ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 )
for (int k = 0; k < dimension; ++k) {
gradLocProbSoli.axpy(gradientPhi[i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
gradLocProbSolj.axpy(gradientPhi[j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
}
} else {
assert(allLocalSolutionEvaluations.size()==numMacroBaseFunctions);
gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint];
gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint];
}
JacobianRangeType reconstructionGradPhii(gradientPhi[i]);
reconstructionGradPhii += gradLocProbSoli;
JacobianRangeType reconstructionGradPhij(gradientPhi[j]);
reconstructionGradPhij += gradLocProbSolj;
JacobianRangeType diffusive_flux(0.0);
diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux);
if (petrovGalerkin_)
local_integral += weight_local_quadrature * (diffusive_flux[0] * gradientPhi[j][0]);
else
local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]);
// add entries
local_matrix.add(j, i, local_integral);
}
}
}
}
}
}
const auto boundary = Problem::getModelData()->boundaryInfo();
Dune::DirichletConstraints<CoarseDiscreteFunctionSpace> constraints(*boundary, coarseDiscreteFunctionSpace_);
constraints.applyToOperator(global_matrix);
} // assemble_matrix
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
#endif // #ifndef MSFEM_ELLIPTIC_DiscreteElliptic_HH
<commit_msg>docu update<commit_after>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH
#define MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH
#include <config.h>
#include <type_traits>
#include <dune/common/fmatrix.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/operator/2order/lagrangematrixsetup.hh>
#include <dune/multiscale/common/dirichletconstraints.hh>
#include <dune/multiscale/msfem/localproblems/subgrid-list.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/msfem/msfem_grid_specifier.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/hmm/cell_problem_numbering.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/fem/functions/checks.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
/**
* \todo docme
*/
class DiscreteEllipticMsFEMOperator
: boost::noncopyable
{
private:
typedef CommonTraits::DiscreteFunctionType CoarseDiscreteFunction;
typedef CommonTraits::DiscreteFunctionType FineDiscreteFunction;
typedef MacroMicroGridSpecifier MacroMicroGridSpecifierType;
typedef CommonTraits::DiffusionType DiffusionModel;
typedef typename CoarseDiscreteFunction::DiscreteFunctionSpaceType CoarseDiscreteFunctionSpace;
typedef typename FineDiscreteFunction::DiscreteFunctionSpaceType FineDiscreteFunctionSpace;
typedef typename FineDiscreteFunctionSpace::FunctionSpaceType FunctionSpace;
typedef typename FineDiscreteFunctionSpace::GridPartType FineGridPart;
typedef typename FineDiscreteFunctionSpace::GridType FineGrid;
typedef typename FineDiscreteFunctionSpace::RangeFieldType RangeFieldType;
typedef typename FineDiscreteFunctionSpace::DomainType DomainType;
typedef typename FineDiscreteFunctionSpace::RangeType RangeType;
typedef typename FineDiscreteFunctionSpace::JacobianRangeType JacobianRangeType;
typedef MsFEMLocalProblemSolver MsFEMLocalProblemSolverType;
static const int dimension = FineGridPart::GridType::dimension;
static const int polynomialOrder = FineDiscreteFunctionSpace::polynomialOrder;
typedef typename FineDiscreteFunction::LocalFunctionType FineLocalFunction;
typedef typename FineDiscreteFunctionSpace::BasisFunctionSetType FineBaseFunctionSet;
typedef typename FineDiscreteFunctionSpace::LagrangePointSetType FineLagrangePointSet;
typedef typename FineLagrangePointSet::Codim< 1 >::SubEntityIteratorType FineFaceDofIterator;
typedef typename FineGrid::Traits::LeafIndexSet FineGridLeafIndexSet;
typedef typename FineDiscreteFunctionSpace::IteratorType FineIterator;
typedef typename FineIterator::Entity FineEntity;
typedef typename FineEntity::EntityPointer FineEntityPointer;
typedef typename FineEntity::Geometry FineGeometry;
typedef typename FineGridPart::IntersectionIteratorType FineIntersectionIterator;
typedef typename FineIntersectionIterator::Intersection FineIntersection;
typedef Fem::CachingQuadrature< FineGridPart, 0 > FineQuadratureType;
typedef typename CoarseDiscreteFunctionSpace::GridPartType CoarseGridPart;
typedef typename CoarseDiscreteFunctionSpace::GridType CoarseGrid;
typedef typename CoarseDiscreteFunction::LocalFunctionType CoarseLocalFunction;
typedef typename CoarseDiscreteFunctionSpace::BasisFunctionSetType CoarseBaseFunctionSet;
typedef typename CoarseDiscreteFunctionSpace::LagrangePointSetType CoarseLagrangePointSet;
typedef typename CoarseLagrangePointSet::Codim< 1 >::SubEntityIteratorType CoarseFaceDofIterator;
typedef typename CoarseDiscreteFunctionSpace::IteratorType CoarseIterator;
typedef typename CoarseGrid::Traits::LeafIndexSet CoarseGridLeafIndexSet;
typedef typename CoarseIterator::Entity CoarseEntity;
typedef typename CoarseEntity::Geometry CoarseGeometry;
typedef typename CoarseGridPart::IntersectionIteratorType CoarseIntersectionIterator;
typedef typename CoarseIntersectionIterator::Intersection CoarseIntersection;
typedef Fem::CachingQuadrature< CoarseGridPart, 0 > CoarseQuadrature;
typedef MsFEMTraits::SubGridListType SubGridListType;
typedef typename SubGridListType::SubGridQuadratureType SubGridQuadratureType;
public:
DiscreteEllipticMsFEMOperator(MacroMicroGridSpecifierType& specifier,
const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace,
// number of layers per coarse grid entity T: U(T) is created by enrichting T with
// n(T)-layers:
MsFEMTraits::SubGridListType& subgrid_list,
const DiffusionModel& diffusion_op);
template< class SPMatrixObject >
void assemble_matrix(SPMatrixObject& global_matrix) const;
private:
MacroMicroGridSpecifierType& specifier_;
const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace_;
MsFEMTraits::SubGridListType& subgrid_list_;
const DiffusionModel& diffusion_operator_;
const bool petrovGalerkin_;
};
template< class SPMatrixObject >
void DiscreteEllipticMsFEMOperator::assemble_matrix(SPMatrixObject& global_matrix) const
{
// the local problem:
// Let 'T' denote a coarse grid element and
// let 'U(T)' denote the environment of 'T' that corresponds with the subgrid.
// if Petrov-Galerkin-MsFEM
if (petrovGalerkin_)
DSC_LOG_INFO << "Assembling Petrov-Galerkin-MsFEM Matrix." << std::endl;
else // if classical (symmetric) MsFEM
DSC_LOG_INFO << "Assembling MsFEM Matrix." << std::endl;
global_matrix.reserve();
global_matrix.clear();
const auto& coarseGridLeafIndexSet = coarseDiscreteFunctionSpace_.gridPart().grid().leafIndexSet();
for (const CoarseEntity& coarse_grid_entity : coarseDiscreteFunctionSpace_) {
const CoarseGeometry& coarse_grid_geometry = coarse_grid_entity.geometry();
assert(coarse_grid_entity.partitionType() == InteriorEntity);
const int global_index_entity = coarseGridLeafIndexSet.index(coarse_grid_entity);
DSFe::LocalMatrixProxy< SPMatrixObject > local_matrix(global_matrix, coarse_grid_entity, coarse_grid_entity);
const CoarseBaseFunctionSet& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet();
const unsigned int numMacroBaseFunctions = coarse_grid_baseSet.size();
// Load local solutions
Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarse_grid_entity, subgrid_list_, specifier_);
localSolutionManager.loadLocalSolutions();
Multiscale::MsFEM::LocalSolutionManager::LocalSolutionVectorType& localSolutions
= localSolutionManager.getLocalSolutions();
assert(localSolutions.size() > 0);
std::vector< typename CoarseBaseFunctionSet::JacobianRangeType > gradientPhi(numMacroBaseFunctions);
const int localQuadratureOrder = 2 * localSolutionManager.getLocalDiscreteFunctionSpace().order() + 2;
// iterator for the micro grid ( grid for the reference element T_0 )
for (const auto& localGridEntity : localSolutionManager.getLocalDiscreteFunctionSpace()) {
// check if "localGridEntity" (which is an entity of U(T)) is in T:
// -------------------------------------------------------------------
const auto& hostEntity
= localSolutionManager.getSubGridPart().grid().template getHostEntity< 0 >(localGridEntity);
// ignore overlay elements
if (global_index_entity == subgrid_list_.getEnclosingMacroCellIndex(hostEntity)) {
assert(hostEntity->partitionType() == InteriorEntity);
const auto& local_grid_geometry = localGridEntity.geometry();
// higher order quadrature, since A^{\epsilon} is highly variable
SubGridQuadratureType localQuadrature(localGridEntity, localQuadratureOrder);
const size_t numQuadraturePoints = localQuadrature.nop();
// number of local solutions without the boundary correctors. Those are only needed for the right hand side
const int numLocalSolutions = localSolutions.size() - localSolutionManager.numBoundaryCorrectors();
// evaluate the jacobians of all local solutions in all quadrature points
std::vector< std::vector< JacobianRangeType > >
allLocalSolutionEvaluations(numLocalSolutions,
std::vector< JacobianRangeType >(localQuadrature.nop(), JacobianRangeType(0.0)));
for (int lsNum = 0; lsNum < numLocalSolutions; ++lsNum) {
auto localFunction = localSolutions[lsNum]->localFunction(localGridEntity);
localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]);
}
for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) {
// local (barycentric) coordinates (with respect to entity)
const typename FineQuadratureType::CoordinateType& local_subgrid_point = localQuadrature.point(
localQuadraturePoint);
DomainType global_point_in_U_T = local_grid_geometry.global(local_subgrid_point);
const double weight_local_quadrature
= localQuadrature.weight(localQuadraturePoint) * local_grid_geometry.integrationElement(
local_subgrid_point);
// evaluate the jacobian of the coarse grid base set
const DomainType& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T);
coarse_grid_baseSet.jacobianAll(local_coarse_point, gradientPhi);
for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) {
for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) {
RangeType local_integral(0.0);
// Compute the gradients of the i'th and j'th local problem solutions
JacobianRangeType gradLocProbSoli(0.0), gradLocProbSolj(0.0);
if (specifier_.simplexCoarseGrid()) {
assert(allLocalSolutionEvaluations.size()==dimension);
// ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 )
for (int k = 0; k < dimension; ++k) {
gradLocProbSoli.axpy(gradientPhi[i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
gradLocProbSolj.axpy(gradientPhi[j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
}
} else {
assert(allLocalSolutionEvaluations.size()==numMacroBaseFunctions);
gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint];
gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint];
}
JacobianRangeType reconstructionGradPhii(gradientPhi[i]);
reconstructionGradPhii += gradLocProbSoli;
JacobianRangeType reconstructionGradPhij(gradientPhi[j]);
reconstructionGradPhij += gradLocProbSolj;
JacobianRangeType diffusive_flux(0.0);
diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux);
if (petrovGalerkin_)
local_integral += weight_local_quadrature * (diffusive_flux[0] * gradientPhi[j][0]);
else
local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]);
// add entries
local_matrix.add(j, i, local_integral);
}
}
}
}
}
}
// set dirichlet-dofs to zero
const auto boundary = Problem::getModelData()->boundaryInfo();
Dune::DirichletConstraints<CoarseDiscreteFunctionSpace> constraints(*boundary, coarseDiscreteFunctionSpace_);
constraints.applyToOperator(global_matrix);
} // assemble_matrix
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
#endif // #ifndef MSFEM_ELLIPTIC_DiscreteElliptic_HH
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: filepickerstate.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-10-06 15:56:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FILEPICKERSTATE_HXX_
#define _FILEPICKERSTATE_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _CONTROLCOMMAND_HXX_
#include "controlcommand.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
//---------------------------------------------
//
//---------------------------------------------
class CControlCommand;
class CFileOpenDialog;
//---------------------------------------------
// declaration
//---------------------------------------------
class CFilePickerState
{
public:
virtual ~CFilePickerState( );
virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue ) = 0;
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction ) = 0;
virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable ) = 0;
virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel ) = 0;
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId ) = 0;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( CFileOpenDialog* aFileOpenDialog ) = 0;
virtual rtl::OUString SAL_CALL getDisplayDirectory( CFileOpenDialog* aFileOpenDialog ) = 0;
};
//---------------------------------------------
// this class is not thread-safe
//---------------------------------------------
class CNonExecuteFilePickerState : public CFilePickerState
{
public:
CNonExecuteFilePickerState( );
virtual ~CNonExecuteFilePickerState( );
virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue );
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction );
virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable );
virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel );
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( CFileOpenDialog* aFileOpenDialog );
virtual rtl::OUString SAL_CALL getDisplayDirectory( CFileOpenDialog* aFileOpenDialog );
void SAL_CALL reset( );
CControlCommand* SAL_CALL getControlCommand( ) const;
protected:
void SAL_CALL addControlCommand( CControlCommand* aControlCommand );
private:
CControlCommand* m_FirstControlCommand;
};
//---------------------------------------------
// this class is not thread-safe
//---------------------------------------------
class CExecuteFilePickerState : public CFilePickerState
{
public:
CExecuteFilePickerState( HWND hwndDlg = NULL );
virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue );
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction );
virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable );
virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel );
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( CFileOpenDialog* aFileOpenDialog );
virtual rtl::OUString SAL_CALL getDisplayDirectory( CFileOpenDialog* aFileOpenDialog );
void SAL_CALL initFilePickerControls( CControlCommand* firstControlCommand );
void SAL_CALL cacheControlState( HWND hwndControl, CFilePickerState* aFilePickerState );
void SAL_CALL setHwnd( HWND hwndDlg );
private:
inline sal_Bool SAL_CALL IsListboxControl( HWND hwndControl ) const;
inline sal_Int16 SAL_CALL ListboxIdToListboxLabelId( sal_Int16 aListboxId ) const;
inline HWND SAL_CALL GetListboxLabelItem( sal_Int16 aControlId ) const;
// returns a hwnd for a control if successful
// if bIncludeStdCtrls is false, the standard file dialog
// controls like OK button, etc. will not be considered
// the function return 0 on failure
HWND SAL_CALL GetHwndDlgItem( sal_Int16 aControlId, sal_Bool bIncludeStdCtrls = sal_True ) const;
HWND m_hwndDlg;
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.84); FILE MERGED 2005/09/05 17:13:36 rt 1.3.84.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filepickerstate.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:45:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FILEPICKERSTATE_HXX_
#define _FILEPICKERSTATE_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _CONTROLCOMMAND_HXX_
#include "controlcommand.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
//---------------------------------------------
//
//---------------------------------------------
class CControlCommand;
class CFileOpenDialog;
//---------------------------------------------
// declaration
//---------------------------------------------
class CFilePickerState
{
public:
virtual ~CFilePickerState( );
virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue ) = 0;
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction ) = 0;
virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable ) = 0;
virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel ) = 0;
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId ) = 0;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( CFileOpenDialog* aFileOpenDialog ) = 0;
virtual rtl::OUString SAL_CALL getDisplayDirectory( CFileOpenDialog* aFileOpenDialog ) = 0;
};
//---------------------------------------------
// this class is not thread-safe
//---------------------------------------------
class CNonExecuteFilePickerState : public CFilePickerState
{
public:
CNonExecuteFilePickerState( );
virtual ~CNonExecuteFilePickerState( );
virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue );
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction );
virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable );
virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel );
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( CFileOpenDialog* aFileOpenDialog );
virtual rtl::OUString SAL_CALL getDisplayDirectory( CFileOpenDialog* aFileOpenDialog );
void SAL_CALL reset( );
CControlCommand* SAL_CALL getControlCommand( ) const;
protected:
void SAL_CALL addControlCommand( CControlCommand* aControlCommand );
private:
CControlCommand* m_FirstControlCommand;
};
//---------------------------------------------
// this class is not thread-safe
//---------------------------------------------
class CExecuteFilePickerState : public CFilePickerState
{
public:
CExecuteFilePickerState( HWND hwndDlg = NULL );
virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue );
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction );
virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable );
virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel );
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( CFileOpenDialog* aFileOpenDialog );
virtual rtl::OUString SAL_CALL getDisplayDirectory( CFileOpenDialog* aFileOpenDialog );
void SAL_CALL initFilePickerControls( CControlCommand* firstControlCommand );
void SAL_CALL cacheControlState( HWND hwndControl, CFilePickerState* aFilePickerState );
void SAL_CALL setHwnd( HWND hwndDlg );
private:
inline sal_Bool SAL_CALL IsListboxControl( HWND hwndControl ) const;
inline sal_Int16 SAL_CALL ListboxIdToListboxLabelId( sal_Int16 aListboxId ) const;
inline HWND SAL_CALL GetListboxLabelItem( sal_Int16 aControlId ) const;
// returns a hwnd for a control if successful
// if bIncludeStdCtrls is false, the standard file dialog
// controls like OK button, etc. will not be considered
// the function return 0 on failure
HWND SAL_CALL GetHwndDlgItem( sal_Int16 aControlId, sal_Bool bIncludeStdCtrls = sal_True ) const;
HWND m_hwndDlg;
};
#endif
<|endoftext|> |
<commit_before><commit_msg>When doing the scheme check for applying V8 extensions, check against the activeDocumentLoader's url, not the document's current URL.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/vie_base_impl.h"
#include <sstream>
#include <string>
#include <utility>
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/modules/video_processing/main/interface/video_processing.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/video_engine/include/vie_errors.h"
#include "webrtc/video_engine/vie_capturer.h"
#include "webrtc/video_engine/vie_channel.h"
#include "webrtc/video_engine/vie_channel_manager.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/video_engine/vie_encoder.h"
#include "webrtc/video_engine/vie_impl.h"
#include "webrtc/video_engine/vie_input_manager.h"
#include "webrtc/video_engine/vie_shared_data.h"
namespace webrtc {
ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {
if (!video_engine) {
return NULL;
}
VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine);
ViEBaseImpl* vie_base_impl = vie_impl;
(*vie_base_impl)++; // Increase ref count.
return vie_base_impl;
}
int ViEBaseImpl::Release() {
(*this)--; // Decrease ref count.
int32_t ref_count = GetCount();
if (ref_count < 0) {
LOG(LS_WARNING) << "ViEBase released too many times.";
return -1;
}
return ref_count;
}
ViEBaseImpl::ViEBaseImpl(const Config& config)
: shared_data_(config) {}
ViEBaseImpl::~ViEBaseImpl() {}
int ViEBaseImpl::Init() {
return 0;
}
int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {
LOG_F(LS_INFO) << "SetVoiceEngine";
if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel,
CpuOveruseObserver* observer) {
LOG_F(LS_INFO) << "RegisterCpuOveruseObserver on channel " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder);
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
ViECapturer* capturer = is.Capture(provider->Id());
assert(capturer);
capturer->RegisterCpuOveruseObserver(observer);
}
shared_data_.overuse_observers()->insert(
std::pair<int, CpuOveruseObserver*>(video_channel, observer));
return 0;
}
int ViEBaseImpl::SetCpuOveruseOptions(int video_channel,
const CpuOveruseOptions& options) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder);
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
ViECapturer* capturer = is.Capture(provider->Id());
if (capturer) {
capturer->SetCpuOveruseOptions(options);
return 0;
}
}
return -1;
}
int ViEBaseImpl::CpuOveruseMeasures(int video_channel,
int* capture_jitter_ms,
int* avg_encode_time_ms,
int* encode_usage_percent,
int* capture_queue_delay_ms_per_s) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder);
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
ViECapturer* capturer = is.Capture(provider->Id());
if (capturer) {
capturer->CpuOveruseMeasures(capture_jitter_ms,
avg_encode_time_ms,
encode_usage_percent,
capture_queue_delay_ms_per_s);
return 0;
}
}
return -1;
}
int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT
return CreateChannel(video_channel, static_cast<const Config*>(NULL));
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
const Config* config) {
if (shared_data_.channel_manager()->CreateChannel(&video_channel,
config) == -1) {
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
LOG(LS_INFO) << "Video channel created: " << video_channel;
return 0;
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, true);
}
int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, false);
}
int ViEBaseImpl::DeleteChannel(const int video_channel) {
{
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
// Deregister the ViEEncoder if no other channel is using it.
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
if (cs.ChannelUsingViEEncoder(video_channel) == false) {
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
provider->DeregisterFrameCallback(vie_encoder);
}
}
}
if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
LOG(LS_INFO) << "Channel deleted " << video_channel;
return 0;
}
int ViEBaseImpl::ConnectAudioChannel(const int video_channel,
const int audio_channel) {
LOG_F(LS_INFO) << "ConnectAudioChannel, video channel " << video_channel
<< ", audio channel " << audio_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,
audio_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {
LOG_F(LS_INFO) << "DisconnectAudioChannel " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->DisconnectVoiceChannel(
video_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::StartSend(const int video_channel) {
LOG_F(LS_INFO) << "StartSend: " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder != NULL);
if (vie_encoder->Owner() != video_channel) {
LOG_F(LS_ERROR) << "Can't start send on a receive only channel.";
shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);
return -1;
}
// Pause and trigger a key frame.
vie_encoder->Pause();
int32_t error = vie_channel->StartSend();
if (error != 0) {
vie_encoder->Restart();
if (error == kViEBaseAlreadySending) {
shared_data_.SetLastError(kViEBaseAlreadySending);
}
LOG_F(LS_ERROR) << "Could not start sending " << video_channel;
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
vie_encoder->SendKeyFrame();
vie_encoder->Restart();
return 0;
}
int ViEBaseImpl::StopSend(const int video_channel) {
LOG_F(LS_INFO) << "StopSend " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
int32_t error = vie_channel->StopSend();
if (error != 0) {
if (error == kViEBaseNotSending) {
shared_data_.SetLastError(kViEBaseNotSending);
} else {
LOG_F(LS_ERROR) << "Could not stop sending " << video_channel;
shared_data_.SetLastError(kViEBaseUnknownError);
}
return -1;
}
return 0;
}
int ViEBaseImpl::StartReceive(const int video_channel) {
LOG_F(LS_INFO) << "StartReceive " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StartReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::StopReceive(const int video_channel) {
LOG_F(LS_INFO) << "StopReceive " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StopReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::GetVersion(char version[1024]) {
assert(kViEVersionMaxMessageSize == 1024);
if (!version) {
shared_data_.SetLastError(kViEBaseInvalidArgument);
return -1;
}
// Add WebRTC Version.
std::stringstream version_stream;
version_stream << "VideoEngine 3.52.0" << std::endl;
// Add build info.
version_stream << "Build: " << BUILDINFO << std::endl;
int version_length = version_stream.tellp();
assert(version_length < 1024);
memcpy(version, version_stream.str().c_str(), version_length);
version[version_length] = '\0';
return 0;
}
int ViEBaseImpl::LastError() {
return shared_data_.LastErrorInternal();
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel, bool sender) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(original_channel)) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->CreateChannel(&video_channel,
original_channel,
sender) == -1) {
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
LOG_F(LS_INFO) << "VideoChannel created: " << video_channel
<< ", base channel " << original_channel
<< ", is send channel : " << sender;
return 0;
}
} // namespace webrtc
<commit_msg>Updated WebRTC version to 3.53 [email protected]<commit_after>/*
* Copyright (c) 2012 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/vie_base_impl.h"
#include <sstream>
#include <string>
#include <utility>
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/modules/video_processing/main/interface/video_processing.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/video_engine/include/vie_errors.h"
#include "webrtc/video_engine/vie_capturer.h"
#include "webrtc/video_engine/vie_channel.h"
#include "webrtc/video_engine/vie_channel_manager.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/video_engine/vie_encoder.h"
#include "webrtc/video_engine/vie_impl.h"
#include "webrtc/video_engine/vie_input_manager.h"
#include "webrtc/video_engine/vie_shared_data.h"
namespace webrtc {
ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {
if (!video_engine) {
return NULL;
}
VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine);
ViEBaseImpl* vie_base_impl = vie_impl;
(*vie_base_impl)++; // Increase ref count.
return vie_base_impl;
}
int ViEBaseImpl::Release() {
(*this)--; // Decrease ref count.
int32_t ref_count = GetCount();
if (ref_count < 0) {
LOG(LS_WARNING) << "ViEBase released too many times.";
return -1;
}
return ref_count;
}
ViEBaseImpl::ViEBaseImpl(const Config& config)
: shared_data_(config) {}
ViEBaseImpl::~ViEBaseImpl() {}
int ViEBaseImpl::Init() {
return 0;
}
int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {
LOG_F(LS_INFO) << "SetVoiceEngine";
if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel,
CpuOveruseObserver* observer) {
LOG_F(LS_INFO) << "RegisterCpuOveruseObserver on channel " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder);
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
ViECapturer* capturer = is.Capture(provider->Id());
assert(capturer);
capturer->RegisterCpuOveruseObserver(observer);
}
shared_data_.overuse_observers()->insert(
std::pair<int, CpuOveruseObserver*>(video_channel, observer));
return 0;
}
int ViEBaseImpl::SetCpuOveruseOptions(int video_channel,
const CpuOveruseOptions& options) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder);
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
ViECapturer* capturer = is.Capture(provider->Id());
if (capturer) {
capturer->SetCpuOveruseOptions(options);
return 0;
}
}
return -1;
}
int ViEBaseImpl::CpuOveruseMeasures(int video_channel,
int* capture_jitter_ms,
int* avg_encode_time_ms,
int* encode_usage_percent,
int* capture_queue_delay_ms_per_s) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder);
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
ViECapturer* capturer = is.Capture(provider->Id());
if (capturer) {
capturer->CpuOveruseMeasures(capture_jitter_ms,
avg_encode_time_ms,
encode_usage_percent,
capture_queue_delay_ms_per_s);
return 0;
}
}
return -1;
}
int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT
return CreateChannel(video_channel, static_cast<const Config*>(NULL));
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
const Config* config) {
if (shared_data_.channel_manager()->CreateChannel(&video_channel,
config) == -1) {
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
LOG(LS_INFO) << "Video channel created: " << video_channel;
return 0;
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, true);
}
int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, false);
}
int ViEBaseImpl::DeleteChannel(const int video_channel) {
{
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
// Deregister the ViEEncoder if no other channel is using it.
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
if (cs.ChannelUsingViEEncoder(video_channel) == false) {
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
provider->DeregisterFrameCallback(vie_encoder);
}
}
}
if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
LOG(LS_INFO) << "Channel deleted " << video_channel;
return 0;
}
int ViEBaseImpl::ConnectAudioChannel(const int video_channel,
const int audio_channel) {
LOG_F(LS_INFO) << "ConnectAudioChannel, video channel " << video_channel
<< ", audio channel " << audio_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,
audio_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {
LOG_F(LS_INFO) << "DisconnectAudioChannel " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->DisconnectVoiceChannel(
video_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::StartSend(const int video_channel) {
LOG_F(LS_INFO) << "StartSend: " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder != NULL);
if (vie_encoder->Owner() != video_channel) {
LOG_F(LS_ERROR) << "Can't start send on a receive only channel.";
shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);
return -1;
}
// Pause and trigger a key frame.
vie_encoder->Pause();
int32_t error = vie_channel->StartSend();
if (error != 0) {
vie_encoder->Restart();
if (error == kViEBaseAlreadySending) {
shared_data_.SetLastError(kViEBaseAlreadySending);
}
LOG_F(LS_ERROR) << "Could not start sending " << video_channel;
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
vie_encoder->SendKeyFrame();
vie_encoder->Restart();
return 0;
}
int ViEBaseImpl::StopSend(const int video_channel) {
LOG_F(LS_INFO) << "StopSend " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
int32_t error = vie_channel->StopSend();
if (error != 0) {
if (error == kViEBaseNotSending) {
shared_data_.SetLastError(kViEBaseNotSending);
} else {
LOG_F(LS_ERROR) << "Could not stop sending " << video_channel;
shared_data_.SetLastError(kViEBaseUnknownError);
}
return -1;
}
return 0;
}
int ViEBaseImpl::StartReceive(const int video_channel) {
LOG_F(LS_INFO) << "StartReceive " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StartReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::StopReceive(const int video_channel) {
LOG_F(LS_INFO) << "StopReceive " << video_channel;
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StopReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::GetVersion(char version[1024]) {
assert(kViEVersionMaxMessageSize == 1024);
if (!version) {
shared_data_.SetLastError(kViEBaseInvalidArgument);
return -1;
}
// Add WebRTC Version.
std::stringstream version_stream;
version_stream << "VideoEngine 3.53.0" << std::endl;
// Add build info.
version_stream << "Build: " << BUILDINFO << std::endl;
int version_length = version_stream.tellp();
assert(version_length < 1024);
memcpy(version, version_stream.str().c_str(), version_length);
version[version_length] = '\0';
return 0;
}
int ViEBaseImpl::LastError() {
return shared_data_.LastErrorInternal();
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel, bool sender) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(original_channel)) {
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->CreateChannel(&video_channel,
original_channel,
sender) == -1) {
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
LOG_F(LS_INFO) << "VideoChannel created: " << video_channel
<< ", base channel " << original_channel
<< ", is send channel : " << sender;
return 0;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#pragma once
#include <sstream> // osstringstream
#include <iostream> // ostream
#include <cstdlib> // atoi
#include <stdexcept> // std::invalid_argument
#include "ip.hpp"
namespace cpl
{
namespace net
{
struct SockAddr
{
IP ip;
int port;
SockAddr()
{
}
SockAddr(IP ip, int port)
: ip(ip), port(port)
{
}
SockAddr(struct sockaddr_storage& addr)
{
set(reinterpret_cast<struct sockaddr&>(addr));
}
SockAddr(struct sockaddr& addr)
{
set(addr);
}
inline int
parse(std::string str)
{
std::size_t pos = str.rfind(":");
if (pos == std::string::npos) {
return -1;
}
auto addr_str = str.substr(0, pos);
auto port_str = str.substr(pos+1);
if (addr_str[0] == '[' && addr_str[addr_str.size() - 1] == ']') {
addr_str = addr_str.substr(1, addr_str.size() - 2);
}
if (ip.set(addr_str) < 0) {
return -1;
}
port = atoi(port_str.c_str());
return 0;
}
inline void
set(struct sockaddr& addr)
{
auto address_family = addr.sa_family;
if (address_family == AF_INET) {
auto addr_in = reinterpret_cast<struct sockaddr_in*>(&addr);
port = ntohs(addr_in->sin_port);
ip = IP(addr_in->sin_addr);
} else {
auto addr_in6 = reinterpret_cast<struct sockaddr_in6*>(&addr);
port = ntohs(addr_in6->sin6_port);
ip = IP(addr_in6->sin6_addr);
}
}
inline void
set(struct sockaddr_storage& addr)
{
set(reinterpret_cast<struct sockaddr&>(addr));
}
inline void
get_sockaddr(struct sockaddr* sockaddr)
{
if (ip.family == AF_INET) {
auto addr_in = reinterpret_cast<struct sockaddr_in*>(sockaddr);
addr_in->sin_port = htons(port);
addr_in->sin_addr = ip.addr.v4;
} else {
auto addr_in6 = reinterpret_cast<struct sockaddr_in6*>(sockaddr);
addr_in6->sin6_port = htons(port);
addr_in6->sin6_addr = ip.addr.v6;
}
}
friend std::ostream& operator << (std::ostream& os, const SockAddr& address)
{
os << address.ip << ":" << address.port;
return os;
}
std::string
str() const
{
std::string s;
std::ostringstream os;
os << ip << ":" << port;
s = os.str();
return s;
}
}; // SockAddr
} // net
} // cpl
<commit_msg>forgot to set sa_family<commit_after>#pragma once
#include <sstream> // osstringstream
#include <iostream> // ostream
#include <cstdlib> // atoi
#include <stdexcept> // std::invalid_argument
#include "ip.hpp"
namespace cpl
{
namespace net
{
struct SockAddr
{
IP ip;
int port;
SockAddr()
{
}
SockAddr(IP ip, int port)
: ip(ip), port(port)
{
}
SockAddr(struct sockaddr_storage& addr)
{
set(reinterpret_cast<struct sockaddr&>(addr));
}
SockAddr(struct sockaddr& addr)
{
set(addr);
}
inline int
parse(std::string str)
{
std::size_t pos = str.rfind(":");
if (pos == std::string::npos) {
return -1;
}
auto addr_str = str.substr(0, pos);
auto port_str = str.substr(pos+1);
if (addr_str[0] == '[' && addr_str[addr_str.size() - 1] == ']') {
addr_str = addr_str.substr(1, addr_str.size() - 2);
}
if (ip.set(addr_str) < 0) {
return -1;
}
port = atoi(port_str.c_str());
return 0;
}
inline void
set(struct sockaddr& addr)
{
auto address_family = addr.sa_family;
if (address_family == AF_INET) {
auto addr_in = reinterpret_cast<struct sockaddr_in*>(&addr);
port = ntohs(addr_in->sin_port);
ip = IP(addr_in->sin_addr);
} else {
auto addr_in6 = reinterpret_cast<struct sockaddr_in6*>(&addr);
port = ntohs(addr_in6->sin6_port);
ip = IP(addr_in6->sin6_addr);
}
}
inline void
set(struct sockaddr_storage& addr)
{
set(reinterpret_cast<struct sockaddr&>(addr));
}
inline void
get_sockaddr(struct sockaddr* sockaddr)
{
sockaddr->sa_family = ip.family;
if (ip.family == AF_INET) {
auto addr_in = reinterpret_cast<struct sockaddr_in*>(sockaddr);
addr_in->sin_port = htons(port);
addr_in->sin_addr = ip.addr.v4;
} else {
auto addr_in6 = reinterpret_cast<struct sockaddr_in6*>(sockaddr);
addr_in6->sin6_port = htons(port);
addr_in6->sin6_addr = ip.addr.v6;
}
}
friend std::ostream& operator << (std::ostream& os, const SockAddr& address)
{
os << address.ip << ":" << address.port;
return os;
}
std::string
str() const
{
std::string s;
std::ostringstream os;
os << ip << ":" << port;
s = os.str();
return s;
}
}; // SockAddr
} // net
} // cpl
<|endoftext|> |
<commit_before>#include "ExtrusionEntity.hpp"
#include "ExtrusionEntityCollection.hpp"
#include "ExPolygonCollection.hpp"
#include "ClipperUtils.hpp"
#include "Extruder.hpp"
#include "Flow.hpp"
#include <cmath>
#include <limits>
#include <sstream>
namespace Slic3r {
void
ExtrusionPath::intersect_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const
{
// perform clipping
Polylines clipped;
intersection<Polylines,Polylines>(this->polyline, collection, &clipped);
return this->_inflate_collection(clipped, retval);
}
void
ExtrusionPath::subtract_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const
{
// perform clipping
Polylines clipped;
diff<Polylines,Polylines>(this->polyline, collection, &clipped);
return this->_inflate_collection(clipped, retval);
}
void
ExtrusionPath::clip_end(double distance)
{
this->polyline.clip_end(distance);
}
void
ExtrusionPath::simplify(double tolerance)
{
this->polyline.simplify(tolerance);
}
double
ExtrusionPath::length() const
{
return this->polyline.length();
}
void
ExtrusionPath::_inflate_collection(const Polylines &polylines, ExtrusionEntityCollection* collection) const
{
for (Polylines::const_iterator it = polylines.begin(); it != polylines.end(); ++it) {
ExtrusionPath* path = this->clone();
path->polyline = *it;
collection->entities.push_back(path);
}
}
void ExtrusionPath::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const
{
offset(this->polyline, &out, scale_(this->width/2) + scaled_epsilon);
}
void ExtrusionPath::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const
{
// Instantiating the Flow class to get the line spacing.
// Don't know the nozzle diameter, setting to zero. It shall not matter it shall be optimized out by the compiler.
Flow flow(this->width, this->height, 0.f, this->is_bridge());
offset(this->polyline, &out, 0.5f * flow.scaled_spacing() + scaled_epsilon);
}
bool
ExtrusionLoop::make_clockwise()
{
bool was_ccw = this->polygon().is_counter_clockwise();
if (was_ccw) this->reverse();
return was_ccw;
}
bool
ExtrusionLoop::make_counter_clockwise()
{
bool was_cw = this->polygon().is_clockwise();
if (was_cw) this->reverse();
return was_cw;
}
void
ExtrusionLoop::reverse()
{
for (ExtrusionPaths::iterator path = this->paths.begin(); path != this->paths.end(); ++path)
path->reverse();
std::reverse(this->paths.begin(), this->paths.end());
}
Polygon
ExtrusionLoop::polygon() const
{
Polygon polygon;
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
// for each polyline, append all points except the last one (because it coincides with the first one of the next polyline)
polygon.points.insert(polygon.points.end(), path->polyline.points.begin(), path->polyline.points.end()-1);
}
return polygon;
}
double
ExtrusionLoop::length() const
{
double len = 0;
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
len += path->polyline.length();
return len;
}
bool
ExtrusionLoop::split_at_vertex(const Point &point)
{
for (ExtrusionPaths::iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
int idx = path->polyline.find_point(point);
if (idx != -1) {
if (this->paths.size() == 1) {
// just change the order of points
path->polyline.points.insert(path->polyline.points.end(), path->polyline.points.begin() + 1, path->polyline.points.begin() + idx + 1);
path->polyline.points.erase(path->polyline.points.begin(), path->polyline.points.begin() + idx);
} else {
// new paths list starts with the second half of current path
ExtrusionPaths new_paths;
new_paths.reserve(this->paths.size() + 1);
{
ExtrusionPath p = *path;
p.polyline.points.erase(p.polyline.points.begin(), p.polyline.points.begin() + idx);
if (p.polyline.is_valid()) new_paths.push_back(p);
}
// then we add all paths until the end of current path list
new_paths.insert(new_paths.end(), path+1, this->paths.end()); // not including this path
// then we add all paths since the beginning of current list up to the previous one
new_paths.insert(new_paths.end(), this->paths.begin(), path); // not including this path
// finally we add the first half of current path
{
ExtrusionPath p = *path;
p.polyline.points.erase(p.polyline.points.begin() + idx + 1, p.polyline.points.end());
if (p.polyline.is_valid()) new_paths.push_back(p);
}
// we can now override the old path list with the new one and stop looping
std::swap(this->paths, new_paths);
}
return true;
}
}
return false;
}
void
ExtrusionLoop::split_at(const Point &point)
{
if (this->paths.empty()) return;
// find the closest path and closest point belonging to that path
size_t path_idx = 0;
Point p = this->paths.front().first_point();
double min = point.distance_to(p);
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
Point p_tmp = point.projection_onto(path->polyline);
double dist = point.distance_to(p_tmp);
if (dist < min) {
p = p_tmp;
min = dist;
path_idx = path - this->paths.begin();
}
}
// now split path_idx in two parts
const ExtrusionPath &path = this->paths[path_idx];
ExtrusionPath p1(path.role, path.mm3_per_mm, path.width, path.height);
ExtrusionPath p2(path.role, path.mm3_per_mm, path.width, path.height);
path.polyline.split_at(p, &p1.polyline, &p2.polyline);
if (this->paths.size() == 1) {
if (! p1.polyline.is_valid())
std::swap(this->paths.front().polyline.points, p2.polyline.points);
else if (! p2.polyline.is_valid())
std::swap(this->paths.front().polyline.points, p1.polyline.points);
else {
p2.polyline.points.insert(p2.polyline.points.end(), p1.polyline.points.begin() + 1, p1.polyline.points.end());
std::swap(this->paths.front().polyline.points, p2.polyline.points);
}
} else {
// install the two paths
this->paths.erase(this->paths.begin() + path_idx);
if (p2.polyline.is_valid()) this->paths.insert(this->paths.begin() + path_idx, p2);
if (p1.polyline.is_valid()) this->paths.insert(this->paths.begin() + path_idx, p1);
}
// split at the new vertex
this->split_at_vertex(p);
}
void
ExtrusionLoop::clip_end(double distance, ExtrusionPaths* paths) const
{
*paths = this->paths;
while (distance > 0 && !paths->empty()) {
ExtrusionPath &last = paths->back();
double len = last.length();
if (len <= distance) {
paths->pop_back();
distance -= len;
} else {
last.polyline.clip_end(distance);
break;
}
}
}
bool
ExtrusionLoop::has_overhang_point(const Point &point) const
{
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
int pos = path->polyline.find_point(point);
if (pos != -1) {
// point belongs to this path
// we consider it overhang only if it's not an endpoint
return (path->is_bridge() && pos > 0 && pos != (int)(path->polyline.points.size())-1);
}
}
return false;
}
void ExtrusionLoop::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const
{
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
path->polygons_covered_by_width(out, scaled_epsilon);
}
void ExtrusionLoop::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const
{
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
path->polygons_covered_by_spacing(out, scaled_epsilon);
}
double
ExtrusionLoop::min_mm3_per_mm() const
{
double min_mm3_per_mm = std::numeric_limits<double>::max();
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
min_mm3_per_mm = std::min(min_mm3_per_mm, path->mm3_per_mm);
return min_mm3_per_mm;
}
}
<commit_msg>Fixed https://github.com/prusa3d/Slic3r/issues/32<commit_after>#include "ExtrusionEntity.hpp"
#include "ExtrusionEntityCollection.hpp"
#include "ExPolygonCollection.hpp"
#include "ClipperUtils.hpp"
#include "Extruder.hpp"
#include "Flow.hpp"
#include <cmath>
#include <limits>
#include <sstream>
namespace Slic3r {
void
ExtrusionPath::intersect_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const
{
// perform clipping
Polylines clipped;
intersection<Polylines,Polylines>(this->polyline, collection, &clipped);
return this->_inflate_collection(clipped, retval);
}
void
ExtrusionPath::subtract_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const
{
// perform clipping
Polylines clipped;
diff<Polylines,Polylines>(this->polyline, collection, &clipped);
return this->_inflate_collection(clipped, retval);
}
void
ExtrusionPath::clip_end(double distance)
{
this->polyline.clip_end(distance);
}
void
ExtrusionPath::simplify(double tolerance)
{
this->polyline.simplify(tolerance);
}
double
ExtrusionPath::length() const
{
return this->polyline.length();
}
void
ExtrusionPath::_inflate_collection(const Polylines &polylines, ExtrusionEntityCollection* collection) const
{
for (Polylines::const_iterator it = polylines.begin(); it != polylines.end(); ++it) {
ExtrusionPath* path = this->clone();
path->polyline = *it;
collection->entities.push_back(path);
}
}
void ExtrusionPath::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const
{
Polygons tmp;
offset(this->polyline, &tmp, scale_(this->width/2) + scaled_epsilon);
polygons_append(out, STDMOVE(tmp));
}
void ExtrusionPath::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const
{
// Instantiating the Flow class to get the line spacing.
// Don't know the nozzle diameter, setting to zero. It shall not matter it shall be optimized out by the compiler.
Flow flow(this->width, this->height, 0.f, this->is_bridge());
Polygons tmp;
offset(this->polyline, &tmp, 0.5f * flow.scaled_spacing() + scaled_epsilon);
polygons_append(out, STDMOVE(tmp));
}
bool
ExtrusionLoop::make_clockwise()
{
bool was_ccw = this->polygon().is_counter_clockwise();
if (was_ccw) this->reverse();
return was_ccw;
}
bool
ExtrusionLoop::make_counter_clockwise()
{
bool was_cw = this->polygon().is_clockwise();
if (was_cw) this->reverse();
return was_cw;
}
void
ExtrusionLoop::reverse()
{
for (ExtrusionPaths::iterator path = this->paths.begin(); path != this->paths.end(); ++path)
path->reverse();
std::reverse(this->paths.begin(), this->paths.end());
}
Polygon
ExtrusionLoop::polygon() const
{
Polygon polygon;
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
// for each polyline, append all points except the last one (because it coincides with the first one of the next polyline)
polygon.points.insert(polygon.points.end(), path->polyline.points.begin(), path->polyline.points.end()-1);
}
return polygon;
}
double
ExtrusionLoop::length() const
{
double len = 0;
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
len += path->polyline.length();
return len;
}
bool
ExtrusionLoop::split_at_vertex(const Point &point)
{
for (ExtrusionPaths::iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
int idx = path->polyline.find_point(point);
if (idx != -1) {
if (this->paths.size() == 1) {
// just change the order of points
path->polyline.points.insert(path->polyline.points.end(), path->polyline.points.begin() + 1, path->polyline.points.begin() + idx + 1);
path->polyline.points.erase(path->polyline.points.begin(), path->polyline.points.begin() + idx);
} else {
// new paths list starts with the second half of current path
ExtrusionPaths new_paths;
new_paths.reserve(this->paths.size() + 1);
{
ExtrusionPath p = *path;
p.polyline.points.erase(p.polyline.points.begin(), p.polyline.points.begin() + idx);
if (p.polyline.is_valid()) new_paths.push_back(p);
}
// then we add all paths until the end of current path list
new_paths.insert(new_paths.end(), path+1, this->paths.end()); // not including this path
// then we add all paths since the beginning of current list up to the previous one
new_paths.insert(new_paths.end(), this->paths.begin(), path); // not including this path
// finally we add the first half of current path
{
ExtrusionPath p = *path;
p.polyline.points.erase(p.polyline.points.begin() + idx + 1, p.polyline.points.end());
if (p.polyline.is_valid()) new_paths.push_back(p);
}
// we can now override the old path list with the new one and stop looping
std::swap(this->paths, new_paths);
}
return true;
}
}
return false;
}
void
ExtrusionLoop::split_at(const Point &point)
{
if (this->paths.empty()) return;
// find the closest path and closest point belonging to that path
size_t path_idx = 0;
Point p = this->paths.front().first_point();
double min = point.distance_to(p);
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
Point p_tmp = point.projection_onto(path->polyline);
double dist = point.distance_to(p_tmp);
if (dist < min) {
p = p_tmp;
min = dist;
path_idx = path - this->paths.begin();
}
}
// now split path_idx in two parts
const ExtrusionPath &path = this->paths[path_idx];
ExtrusionPath p1(path.role, path.mm3_per_mm, path.width, path.height);
ExtrusionPath p2(path.role, path.mm3_per_mm, path.width, path.height);
path.polyline.split_at(p, &p1.polyline, &p2.polyline);
if (this->paths.size() == 1) {
if (! p1.polyline.is_valid())
std::swap(this->paths.front().polyline.points, p2.polyline.points);
else if (! p2.polyline.is_valid())
std::swap(this->paths.front().polyline.points, p1.polyline.points);
else {
p2.polyline.points.insert(p2.polyline.points.end(), p1.polyline.points.begin() + 1, p1.polyline.points.end());
std::swap(this->paths.front().polyline.points, p2.polyline.points);
}
} else {
// install the two paths
this->paths.erase(this->paths.begin() + path_idx);
if (p2.polyline.is_valid()) this->paths.insert(this->paths.begin() + path_idx, p2);
if (p1.polyline.is_valid()) this->paths.insert(this->paths.begin() + path_idx, p1);
}
// split at the new vertex
this->split_at_vertex(p);
}
void
ExtrusionLoop::clip_end(double distance, ExtrusionPaths* paths) const
{
*paths = this->paths;
while (distance > 0 && !paths->empty()) {
ExtrusionPath &last = paths->back();
double len = last.length();
if (len <= distance) {
paths->pop_back();
distance -= len;
} else {
last.polyline.clip_end(distance);
break;
}
}
}
bool
ExtrusionLoop::has_overhang_point(const Point &point) const
{
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path) {
int pos = path->polyline.find_point(point);
if (pos != -1) {
// point belongs to this path
// we consider it overhang only if it's not an endpoint
return (path->is_bridge() && pos > 0 && pos != (int)(path->polyline.points.size())-1);
}
}
return false;
}
void ExtrusionLoop::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const
{
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
path->polygons_covered_by_width(out, scaled_epsilon);
}
void ExtrusionLoop::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const
{
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
path->polygons_covered_by_spacing(out, scaled_epsilon);
}
double
ExtrusionLoop::min_mm3_per_mm() const
{
double min_mm3_per_mm = std::numeric_limits<double>::max();
for (ExtrusionPaths::const_iterator path = this->paths.begin(); path != this->paths.end(); ++path)
min_mm3_per_mm = std::min(min_mm3_per_mm, path->mm3_per_mm);
return min_mm3_per_mm;
}
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <minizinc/optimize.hh>
#include <minizinc/hash.hh>
#include <minizinc/astiterator.hh>
#include <minizinc/prettyprinter.hh>
#include <unordered_set>
namespace MiniZinc {
class VarOccurrences {
public:
typedef std::unordered_set<Item*> Items;
ExpressionMap<Items> _m;
static Items empty;
void add(VarDecl* v, Item* i) {
ExpressionMap<Items>::iterator vi = _m.find(v);
if (vi==_m.end()) {
Items items; items.insert(i);
_m.insert(v, items);
} else {
vi->second.insert(i);
}
}
Items::iterator v_begin(VarDecl* v) {
ExpressionMap<Items>::iterator vi = _m.find(v);
if (vi==_m.end()) return empty.end();
return vi->second.begin();
}
Items::iterator v_end(VarDecl* v) {
ExpressionMap<Items>::iterator vi = _m.find(v);
if (vi==_m.end()) return empty.end();
return vi->second.end();
}
int occurrences(VarDecl* v) {
ExpressionMap<Items>::iterator vi = _m.find(v);
return (vi==_m.end() ? 0 : vi->second.size());
}
};
VarOccurrences::Items VarOccurrences::empty;
class CollectOccurrencesE : public EVisitor {
public:
VarOccurrences& vo;
Item* ci;
CollectOccurrencesE(VarOccurrences& vo0, Item* ci0)
: vo(vo0), ci(ci0) {}
void vId(const Id& id) {
if(id._decl)
vo.add(id._decl,ci);
}
};
class CollectOccurrencesI : public ItemVisitor {
public:
VarOccurrences& vo;
CollectOccurrencesI(VarOccurrences& vo0) : vo(vo0) {}
void vVarDeclI(VarDeclI* v) {
CollectOccurrencesE ce(vo,v);
BottomUpIterator<CollectOccurrencesE>(ce).run(v->_e);
}
void vConstraintI(ConstraintI* ci) {
CollectOccurrencesE ce(vo,ci);
BottomUpIterator<CollectOccurrencesE>(ce).run(ci->_e);
}
void vSolveI(SolveI* si) {
CollectOccurrencesE ce(vo,si);
BottomUpIterator<CollectOccurrencesE>(ce).run(si->_e);
}
};
class AnnotateVardecl : public ItemVisitor {
public:
VarOccurrences& vo;
AnnotateVardecl(VarOccurrences& vo0) : vo(vo0) {}
void vVarDeclI(VarDeclI* v) {
GCLock _gcl;
std::vector<Expression*> args(1);
args[0] = IntLit::a(Location(),vo.occurrences(v->_e));
Call* c = Call::a(Location(),"occ",args);
v->_e->annotate(Annotation::a(Location(),c));
}
};
void removeUnused(Model* m, VarOccurrences& vo) {
std::vector<Model*> models;
models.push_back(m);
while (!models.empty()) {
Model* cm = models.back();
models.pop_back();
unsigned int ci = 0;
for (unsigned int i=0; i<cm->_items.size(); i++) {
VarDeclI* vdi = cm->_items[i]->dyn_cast<VarDeclI>();
if ( vdi==NULL
// || ( !vdi->_e->introduced() )
|| (vo.occurrences(vdi->_e)!=0)
|| (vdi->_e->_e && vdi->_e->_ti->_domain != NULL))
cm->_items[ci++] = cm->_items[i];
}
cm->_items.resize(ci);
}
}
void optimize(Model* m) {
VarOccurrences vo;
CollectOccurrencesI co(vo);
iterItems<CollectOccurrencesI>(co,m);
// AnnotateVardecl avd(vo);
// iterItems<AnnotateVardecl>(avd,m);
removeUnused(m,vo);
}
}
<commit_msg>Recursively remove unused variables<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <minizinc/optimize.hh>
#include <minizinc/hash.hh>
#include <minizinc/astiterator.hh>
#include <minizinc/prettyprinter.hh>
#include <unordered_set>
namespace MiniZinc {
class VarOccurrences {
public:
typedef std::unordered_set<Item*> Items;
ExpressionMap<Items> _m;
static Items empty;
void add(VarDecl* v, Item* i) {
ExpressionMap<Items>::iterator vi = _m.find(v);
if (vi==_m.end()) {
Items items; items.insert(i);
_m.insert(v, items);
} else {
vi->second.insert(i);
}
}
/// Remove \a i from map and return new number of occurrences
int remove(VarDecl* v, Item* i) {
ExpressionMap<Items>::iterator vi = _m.find(v);
assert(vi!=_m.end());
vi->second.erase(i);
return vi->second.size();
}
Items::iterator v_begin(VarDecl* v) {
ExpressionMap<Items>::iterator vi = _m.find(v);
if (vi==_m.end()) return empty.end();
return vi->second.begin();
}
Items::iterator v_end(VarDecl* v) {
ExpressionMap<Items>::iterator vi = _m.find(v);
if (vi==_m.end()) return empty.end();
return vi->second.end();
}
int occurrences(VarDecl* v) {
ExpressionMap<Items>::iterator vi = _m.find(v);
return (vi==_m.end() ? 0 : vi->second.size());
}
};
VarOccurrences::Items VarOccurrences::empty;
class CollectOccurrencesE : public EVisitor {
public:
VarOccurrences& vo;
Item* ci;
CollectOccurrencesE(VarOccurrences& vo0, Item* ci0)
: vo(vo0), ci(ci0) {}
void vId(const Id& id) {
if(id._decl)
vo.add(id._decl,ci);
}
};
class CollectOccurrencesI : public ItemVisitor {
public:
VarOccurrences& vo;
CollectOccurrencesI(VarOccurrences& vo0) : vo(vo0) {}
void vVarDeclI(VarDeclI* v) {
CollectOccurrencesE ce(vo,v);
BottomUpIterator<CollectOccurrencesE>(ce).run(v->_e);
}
void vConstraintI(ConstraintI* ci) {
CollectOccurrencesE ce(vo,ci);
BottomUpIterator<CollectOccurrencesE>(ce).run(ci->_e);
}
void vSolveI(SolveI* si) {
CollectOccurrencesE ce(vo,si);
BottomUpIterator<CollectOccurrencesE>(ce).run(si->_e);
BottomUpIterator<CollectOccurrencesE>(ce).run(si->_ann);
}
};
class AnnotateVardecl : public ItemVisitor {
public:
VarOccurrences& vo;
AnnotateVardecl(VarOccurrences& vo0) : vo(vo0) {}
void vVarDeclI(VarDeclI* v) {
GCLock _gcl;
std::vector<Expression*> args(1);
args[0] = IntLit::a(Location(),vo.occurrences(v->_e));
Call* c = Call::a(Location(),"occ",args);
v->_e->annotate(Annotation::a(Location(),c));
}
};
class CollectDecls : public EVisitor {
public:
VarOccurrences& vo;
std::vector<VarDecl*>& vd;
VarDeclI* vdi;
CollectDecls(VarOccurrences& vo0,
std::vector<VarDecl*>& vd0,
VarDeclI* vdi0)
: vo(vo0), vd(vd0), vdi(vdi0) {}
void vId(Id& id) {
if(id._decl) {
if (vo.remove(id._decl,vdi) == 0) {
vd.push_back(id._decl);
}
}
}
};
void removeUnused(Model* m, VarOccurrences& vo) {
std::vector<bool> unused(m->_items.size(), true);
ExpressionMap<int> idx;
for (unsigned int i=0; i<m->_items.size(); i++) {
if (VarDeclI* vdi = m->_items[i]->dyn_cast<VarDeclI>()) {
idx.insert(vdi->_e,i);
}
}
std::vector<VarDecl*> vd;
for (unsigned int i=0; i<m->_items.size(); i++) {
VarDeclI* vdi = m->_items[i]->dyn_cast<VarDeclI>();
if ( vdi==NULL
// || ( !vdi->_e->introduced() )
|| (vo.occurrences(vdi->_e)!=0)
|| (vdi->_e->_e && vdi->_e->_ti->_domain != NULL)) {
unused[i] = false;
} else {
CollectDecls cd(vo,vd,vdi);
BottomUpIterator<CollectDecls>(cd).run(vdi->_e->_e);
}
}
while (!vd.empty()) {
VarDecl* cur = vd.back(); vd.pop_back();
int i = idx.find(cur)->second;
if (!unused[i]) {
unused[i] = true;
CollectDecls cd(vo,vd,m->_items[i]->cast<VarDeclI>());
BottomUpIterator<CollectDecls>(cd).run(cur->_e);
}
}
unsigned int ci = 0;
for (unsigned int i=0; i<m->_items.size(); i++) {
if (!unused[i]) {
m->_items[ci++] = m->_items[i];
} else {
}
}
m->_items.resize(ci);
}
void optimize(Model* m) {
VarOccurrences vo;
CollectOccurrencesI co(vo);
iterItems<CollectOccurrencesI>(co,m);
// AnnotateVardecl avd(vo);
// iterItems<AnnotateVardecl>(avd,m);
removeUnused(m,vo);
}
}
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/external.hpp"
#include "libbirch/memory.hpp"
#include "libbirch/Atomic.hpp"
namespace libbirch {
class Label;
class Finisher;
class Freezer;
class Copier;
class Recycler;
class Discarder;
class Restorer;
/**
* Base class for reference counted objects.
*
* @ingroup libbirch
*
* @attention In order to work correctly with multiple inheritance, Any must
* be the *first* base class.
*
* Reference-counted objects in LibBirch require four counts, rather than
* the usual two (shared and weak), in order to support lazy deep copy
* operations. These are:
*
* - a *shared* count,
* - a *memo shared* count,
* - a *weak* count, and
* - a *memo weak* count.
*
* The shared and weak counts behave as normal. The memo shared and memo weak
* counts serve to determine when an object is only reachable via a memo used
* to bookkeep lazy deep copy operations. Objects that are only reachable via
* a memo may be eligible for collection.
*
* The movement of the four counts triggers the following operations:
*
* -# When the shared count reaches zero, the object is *discarded*.
* -# If the shared count subsequently becomes nonzero again (this is
* allowed as long as the memo shared count is nonzero), the object is
* *restored*.
* -# If the shared and memo shared counts reach 0, the object is
* *destroyed*.
* -# If the weak and memo weak counts reach 0, the object is *deallocated*.
*
* These operations behave as follows:
*
* - **Discard** downgrades all shared pointers in the object to memo
* shared pointers.
* - **Restore** upgrades those memo shared pointers to shared pointers
* again.
* - **Destroy** calls the destructor of the object.
* - **Deallocate** collects the memory allocated to the object.
*
* The discard operation may be skipped when the destroy operation would
* immediately follow anyway; i.e. when the shared count reaches zero and the
* memo shared count is already at zero.
*
* At a high level, shared and weak pointers serve to determine which objects
* are reachable from the user program, while memo shared and memo weak
* pointers are used to determine which objects are reachable via a memo,
* and to break reference cycles that are induced by the memo, but which
* do not exist in the user program *per se*.
*
* A discarded object is in a state where reference cycles induced by a memo
* are broken, but it is otherwise still a valid object, and may still be
* accessible via a weak pointer in the user program.
*/
class Any {
public:
using class_type_ = Any;
using this_type_ = Any;
/**
* Constructor.
*/
Any() :
sharedCount(0u),
memoSharedCount(0u),
weakCount(1u),
memoWeakCount(1u),
label(rootLabel),
finished(false),
frozen(false),
frozenUnique(false),
discarded(false) {
// size and tid set by operator new
}
/**
* Special constructor for the root label.
*/
Any(int) :
sharedCount(0u),
memoSharedCount(0u),
weakCount(1u),
memoWeakCount(1u),
label(nullptr),
finished(false),
frozen(false),
frozenUnique(false),
discarded(false) {
// size and tid set by operator new
}
/**
* Copy constructor.
*/
Any(const Any& o) : Any() {
//
}
/**
* Destructor.
*/
virtual ~Any() {
assert(sharedCount.load() == 0u);
assert(memoSharedCount.load() == 0u);
}
/**
* New operator.
*/
void* operator new(std::size_t size) {
auto ptr = static_cast<Any*>(allocate(size));
ptr->size = static_cast<unsigned>(size);
ptr->tid = get_thread_num();
return ptr;
}
/**
* Delete operator.
*/
void operator delete(void* ptr) {
auto o = static_cast<Any*>(ptr);
o->destroy();
o->deallocate();
}
/**
* Assignment operator.
*/
Any& operator=(const Any&) {
return *this;
}
/**
* Get the size, in bytes, of the object.
*/
unsigned getSize() const {
return size;
}
/**
* Is this object reachable? An object is reachable if there exists a
* shared, memo shared, or weak pointer to it. If only a memo weak pointer
* to it exists, it is not considered reachable, and it may be cleaned up
* during memo maintenance.
*/
bool isReachable() const {
return numWeak() > 0u;
}
/**
* Is there definitely only one pointer to this object? This is
* conservative; it returns true if there is at most one shared or weak
* pointer to the object. Note, in particular, that the presence of a memo
* shared pointer means that an unknown number of pointers (including zero
* pointers) may update to the object in future.
*/
bool isUnique() const {
auto sharedCount = numShared();
auto memoSharedCount = numMemoShared();
auto weakCount = numWeak();
auto memoWeakCount = numMemoWeak();
return (sharedCount == 1u && memoSharedCount == 1u && weakCount == 1u && memoWeakCount == 1u) ||
(sharedCount == 0u && memoSharedCount == 0u && weakCount == 1u && memoWeakCount == 1u);
}
/**
* Get the class name.
*/
virtual const char* getClassName() const {
return "Any";
}
/**
* Finish the object.
*/
void finish(Label* label) {
if (!finished.exchange(true)) {
/* proceed with finish */
finish_(label);
}
}
/**
* Freeze the object.
*/
void freeze() {
assert(finished.load());
if (!frozen.exchange(true)) {
/* proceed with freeze */
frozenUnique.store(isUnique());
freeze_();
}
}
/**
* Copy the object.
*
* @param label The new label.
*/
Any* copy(Label* label) {
auto o = copy_(label);
o->sharedCount.set(0u);
o->memoSharedCount.set(0u);
o->weakCount.set(1u);
o->memoWeakCount.set(1u);
o->label = label;
o->tid = get_thread_num();
o->finished.set(false);
o->frozen.set(false);
o->frozenUnique.set(false);
o->discarded.set(false);
return o;
}
/**
* Recycle the object.
*
* @param label The new label.
*/
Any* recycle(Label* label) {
auto o = recycle_(label);
o->releaseLabel();
o->label = label;
o->holdLabel();
o->thaw();
return this;
}
/**
* Thaw the object.
*/
void thaw() {
finished.store(false);
frozen.store(false);
frozenUnique.store(false);
discarded.store(false);
}
/**
* Discard the object.
*/
void discard() {
if (!discarded.exchange(true)) {
discard_();
}
}
/**
* Restore the object.
*/
void restore() {
if (discarded.exchange(false)) {
restore_();
}
}
/**
* Shared count.
*/
unsigned numShared() const {
return sharedCount.load();
}
/**
* Increment the shared count.
*/
void incShared() {
if (++sharedCount == 1u) {
incMemoShared();
holdLabel();
if (discarded.load()) { // only false when initializing object
restore();
}
}
}
/**
* Decrement the shared count.
*/
void decShared() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
releaseLabel();
assert(numMemoShared() > 0u);
if (--memoSharedCount == 0u) {
/* skip the discard() in this case, just destroy() */
destroy();
decWeak();
} else {
discard();
}
}
}
/**
* Memo shared count.
*/
unsigned numMemoShared() const {
return memoSharedCount.load();
}
/**
* Increment the memo shared count.
*/
void incMemoShared() {
memoSharedCount.increment();
}
/**
* Decrement the memo shared count.
*/
void decMemoShared() {
assert(numMemoShared() > 0u);
if (--memoSharedCount == 0u) {
assert(numShared() == 0u);
destroy();
decWeak();
}
}
/**
* Simultaneously decrement the shared count and increment the shared memo
* count.
*/
void discardShared() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
assert(!discarded.load());
discard();
releaseLabel();
} else {
incMemoShared();
}
}
/**
* Simultaneously increment the shared count and decrement the shared memo
* count.
*/
void restoreShared() {
if (++sharedCount == 1u) {
assert(discarded.load());
holdLabel();
restore();
} else {
decMemoShared();
}
}
/**
* Weak count.
*/
unsigned numWeak() const {
return weakCount.load();
}
/**
* Increment the weak count.
*/
void incWeak() {
weakCount.increment();
}
/**
* Decrement the weak count.
*/
void decWeak() {
assert(weakCount.load() > 0u);
if (--weakCount == 0u) {
assert(numShared() == 0u);
assert(numMemoShared() == 0u);
decMemoWeak();
}
}
/**
* Memo weak count.
*/
unsigned numMemoWeak() const {
return memoWeakCount.load();
}
/**
* Increment the memo weak count.
*/
void incMemoWeak() {
memoWeakCount.increment();
}
/**
* Decrement the memo weak count.
*/
void decMemoWeak() {
assert(memoWeakCount.load() > 0u);
if (--memoWeakCount == 0u) {
assert(numShared() == 0u);
assert(numMemoShared() == 0u);
assert(numWeak() == 0u);
deallocate();
}
}
/**
* Get the label assigned to the object.
*/
Label* getLabel() const {
return label;
}
/**
* Is the object finished?
*/
bool isFinished() const {
return finished.load();
}
/**
* Is the object frozen?
*/
bool isFrozen() const {
return frozen.load();
}
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
bool isFrozenUnique() const {
return frozenUnique.load();
}
/**
* Is the object discarded?
*/
bool isDiscarded() const {
return discarded.load();
}
protected:
/**
* Increment the shared count of the label. This is used during
* initialization and restoration.
*/
void holdLabel();
/**
* Decrement the shared count of the label. This is used during discard.
*/
void releaseLabel();
/**
* Finish the member variables of the object.
*/
virtual void finish_(Label* label) = 0;
/**
* Freeze the member variables of the object.
*/
virtual void freeze_() = 0;
/**
* Copy the object.
*
* @param label The new label.
*/
virtual Any* copy_(Label* label) const = 0;
/**
* Recycle the object.
*
* @param label The new label.
*/
virtual Any* recycle_(Label* label) = 0;
/**
* Discard the object.
*/
virtual void discard_() = 0;
/**
* Restore the object.
*/
virtual void restore_() = 0;
/**
* Accept a visitor across member variables.
*/
template<class Visitor>
void accept_(const Visitor& v) {
//
}
private:
/**
* Destroy, but do not deallocate, the object.
*/
void destroy() {
assert(sharedCount.load() == 0u);
assert(memoSharedCount.load() == 0u);
this->~Any();
}
/**
* Deallocate the object. It should have previously been destroyed.
*/
void deallocate() {
assert(sharedCount.load() == 0u);
assert(memoSharedCount.load() == 0u);
assert(weakCount.load() == 0u);
assert(memoWeakCount.load() == 0u);
libbirch::deallocate(this, size, tid);
}
/**
* Shared count.
*/
Atomic<unsigned> sharedCount;
/**
* Memo shared count, or, if the shared count is nonzero, one plus the memo
* shared count.
*/
Atomic<unsigned> memoSharedCount;
/**
* Weak count, or, if the memo shared count is nonzero, one plus the weak
* count.
*/
Atomic<unsigned> weakCount;
/**
* Memo weak count, or, if the weak count is nonzero, one plus the memo
* weak count.
*/
Atomic<unsigned> memoWeakCount;
/**
* Label of the object.
*/
Label* label;
/**
* Size of the object. This is set immediately after construction. A value
* of zero is also indicative that the object is still being constructed.
* Consequently, if the shared count reaches zero while the size is zero,
* the object is not destroyed. This can happen when constructors create
* shared pointers to `this`.
*/
unsigned size;
/**
* Id of the thread associated with the object. This is used to return the
* allocation to the correct pool after use, even when returned by a
* different thread.
*/
int tid;
/**
* Finished flag.
*/
Atomic<bool> finished;
/**
* Frozen flag. A frozen object is read-only.
*/
Atomic<bool> frozen;
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
Atomic<bool> frozenUnique;
/**
* Discard flag.
*/
Atomic<bool> discarded;
};
}
<commit_msg>Bit-packed flags in Any for memory savings.<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/external.hpp"
#include "libbirch/memory.hpp"
#include "libbirch/Atomic.hpp"
namespace libbirch {
class Label;
class Finisher;
class Freezer;
class Copier;
class Recycler;
class Discarder;
class Restorer;
/**
* Base class for reference counted objects.
*
* @ingroup libbirch
*
* @attention In order to work correctly with multiple inheritance, Any must
* be the *first* base class.
*
* Reference-counted objects in LibBirch require four counts, rather than
* the usual two (shared and weak), in order to support lazy deep copy
* operations. These are:
*
* - a *shared* count,
* - a *memo shared* count,
* - a *weak* count, and
* - a *memo weak* count.
*
* The shared and weak counts behave as normal. The memo shared and memo weak
* counts serve to determine when an object is only reachable via a memo used
* to bookkeep lazy deep copy operations. Objects that are only reachable via
* a memo may be eligible for collection.
*
* The movement of the four counts triggers the following operations:
*
* -# When the shared count reaches zero, the object is *discarded*.
* -# If the shared count subsequently becomes nonzero again (this is
* allowed as long as the memo shared count is nonzero), the object is
* *restored*.
* -# If the shared and memo shared counts reach 0, the object is
* *destroyed*.
* -# If the weak and memo weak counts reach 0, the object is *deallocated*.
*
* These operations behave as follows:
*
* - **Discard** downgrades all shared pointers in the object to memo
* shared pointers.
* - **Restore** upgrades those memo shared pointers to shared pointers
* again.
* - **Destroy** calls the destructor of the object.
* - **Deallocate** collects the memory allocated to the object.
*
* The discard operation may be skipped when the destroy operation would
* immediately follow anyway; i.e. when the shared count reaches zero and the
* memo shared count is already at zero.
*
* At a high level, shared and weak pointers serve to determine which objects
* are reachable from the user program, while memo shared and memo weak
* pointers are used to determine which objects are reachable via a memo,
* and to break reference cycles that are induced by the memo, but which
* do not exist in the user program *per se*.
*
* A discarded object is in a state where reference cycles induced by a memo
* are broken, but it is otherwise still a valid object, and may still be
* accessible via a weak pointer in the user program.
*/
class Any {
public:
using class_type_ = Any;
using this_type_ = Any;
/**
* Constructor.
*/
Any() :
sharedCount(0u),
memoSharedCount(0u),
weakCount(1u),
memoWeakCount(1u),
label(rootLabel),
packed(0) {
// size and tid set by operator new
}
/**
* Special constructor for the root label.
*/
Any(int) :
sharedCount(0u),
memoSharedCount(0u),
weakCount(1u),
memoWeakCount(1u),
label(nullptr),
packed(0) {
// size and tid set by operator new
}
/**
* Copy constructor.
*/
Any(const Any& o) : Any() {
//
}
/**
* Destructor.
*/
virtual ~Any() {
assert(sharedCount.load() == 0u);
assert(memoSharedCount.load() == 0u);
}
/**
* New operator.
*/
void* operator new(std::size_t size) {
auto ptr = static_cast<Any*>(allocate(size));
ptr->size = static_cast<uint64_t>(size);
ptr->tid = get_thread_num();
return ptr;
}
/**
* Delete operator.
*/
void operator delete(void* ptr) {
auto o = static_cast<Any*>(ptr);
o->destroy();
o->deallocate();
}
/**
* Assignment operator.
*/
Any& operator=(const Any&) {
return *this;
}
/**
* Is this object reachable? An object is reachable if there exists a
* shared, memo shared, or weak pointer to it. If only a memo weak pointer
* to it exists, it is not considered reachable, and it may be cleaned up
* during memo maintenance.
*/
bool isReachable() const {
return numWeak() > 0u;
}
/**
* Is there definitely only one pointer to this object? This is
* conservative; it returns true if there is at most one shared or weak
* pointer to the object. Note, in particular, that the presence of a memo
* shared pointer means that an unknown number of pointers (including zero
* pointers) may update to the object in future.
*/
bool isUnique() const {
auto sharedCount = numShared();
auto memoSharedCount = numMemoShared();
auto weakCount = numWeak();
auto memoWeakCount = numMemoWeak();
return (sharedCount == 1u && memoSharedCount == 1u && weakCount == 1u && memoWeakCount == 1u) ||
(sharedCount == 0u && memoSharedCount == 0u && weakCount == 1u && memoWeakCount == 1u);
}
/**
* Get the class name.
*/
virtual const char* getClassName() const {
return "Any";
}
/**
* Finish the object.
*/
void finish(Label* label) {
auto old = packed.maskOr(1 << 0) & (1 << 0);
if (!old) {
/* proceed with finish */
finish_(label);
}
}
/**
* Freeze the object.
*/
void freeze() {
assert(isFinished());
auto old = packed.maskOr(1 << 1) & (1 << 1);
if (!old) {
/* proceed with freeze */
if (isUnique()) {
packed.maskOr(1 << 2);
}
freeze_();
}
}
/**
* Discard the object.
*/
void discard() {
auto old = packed.maskOr(1 << 3) & (1 << 3);
if (!old) {
discard_();
}
}
/**
* Restore the object.
*/
void restore() {
auto old = packed.maskAnd(~int16_t(1 << 3)) & (1 << 3);
if (old) {
restore_();
}
}
/**
* Copy the object.
*
* @param label The new label.
*/
Any* copy(Label* label) {
auto o = copy_(label);
o->sharedCount.set(0u);
o->memoSharedCount.set(0u);
o->weakCount.set(1u);
o->memoWeakCount.set(1u);
o->label = label;
o->tid = get_thread_num();
o->packed.set(0);
return o;
}
/**
* Recycle the object.
*
* @param label The new label.
*/
Any* recycle(Label* label) {
auto o = recycle_(label);
o->releaseLabel();
o->label = label;
o->holdLabel();
o->thaw();
return this;
}
/**
* Thaw the object.
*/
void thaw() {
packed.store(0);
}
/**
* Shared count.
*/
unsigned numShared() const {
return sharedCount.load();
}
/**
* Increment the shared count.
*/
void incShared() {
if (++sharedCount == 1u) {
incMemoShared();
holdLabel();
if (isDiscarded()) { // only false when initializing object
restore();
}
}
}
/**
* Decrement the shared count.
*/
void decShared() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
releaseLabel();
assert(numMemoShared() > 0u);
if (--memoSharedCount == 0u) {
/* skip the discard() in this case, just destroy() */
destroy();
decWeak();
} else {
discard();
}
}
}
/**
* Memo shared count.
*/
unsigned numMemoShared() const {
return memoSharedCount.load();
}
/**
* Increment the memo shared count.
*/
void incMemoShared() {
memoSharedCount.increment();
}
/**
* Decrement the memo shared count.
*/
void decMemoShared() {
assert(numMemoShared() > 0u);
if (--memoSharedCount == 0u) {
assert(numShared() == 0u);
destroy();
decWeak();
}
}
/**
* Simultaneously decrement the shared count and increment the shared memo
* count.
*/
void discardShared() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
assert(!isDiscarded());
discard();
releaseLabel();
} else {
incMemoShared();
}
}
/**
* Simultaneously increment the shared count and decrement the shared memo
* count.
*/
void restoreShared() {
if (++sharedCount == 1u) {
assert(isDiscarded());
holdLabel();
restore();
} else {
decMemoShared();
}
}
/**
* Weak count.
*/
unsigned numWeak() const {
return weakCount.load();
}
/**
* Increment the weak count.
*/
void incWeak() {
weakCount.increment();
}
/**
* Decrement the weak count.
*/
void decWeak() {
assert(weakCount.load() > 0u);
if (--weakCount == 0u) {
assert(numShared() == 0u);
assert(numMemoShared() == 0u);
decMemoWeak();
}
}
/**
* Memo weak count.
*/
unsigned numMemoWeak() const {
return memoWeakCount.load();
}
/**
* Increment the memo weak count.
*/
void incMemoWeak() {
memoWeakCount.increment();
}
/**
* Decrement the memo weak count.
*/
void decMemoWeak() {
assert(memoWeakCount.load() > 0u);
if (--memoWeakCount == 0u) {
assert(numShared() == 0u);
assert(numMemoShared() == 0u);
assert(numWeak() == 0u);
deallocate();
}
}
/**
* Get the label assigned to the object.
*/
Label* getLabel() const {
return label;
}
/**
* Is the object finished?
*/
bool isFinished() const {
return packed.load() & (1 << 0);
}
/**
* Is the object frozen?
*/
bool isFrozen() const {
return packed.load() & (1 << 1);
}
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
bool isFrozenUnique() const {
return packed.load() & (1 << 2);
}
/**
* Is the object discarded?
*/
bool isDiscarded() const {
return packed.load() & (1 << 3);
}
protected:
/**
* Increment the shared count of the label. This is used during
* initialization and restoration.
*/
void holdLabel();
/**
* Decrement the shared count of the label. This is used during discard.
*/
void releaseLabel();
/**
* Finish the member variables of the object.
*/
virtual void finish_(Label* label) = 0;
/**
* Freeze the member variables of the object.
*/
virtual void freeze_() = 0;
/**
* Copy the object.
*
* @param label The new label.
*/
virtual Any* copy_(Label* label) const = 0;
/**
* Recycle the object.
*
* @param label The new label.
*/
virtual Any* recycle_(Label* label) = 0;
/**
* Discard the object.
*/
virtual void discard_() = 0;
/**
* Restore the object.
*/
virtual void restore_() = 0;
/**
* Accept a visitor across member variables.
*/
template<class Visitor>
void accept_(const Visitor& v) {
//
}
private:
/**
* Destroy, but do not deallocate, the object.
*/
void destroy() {
assert(sharedCount.load() == 0u);
assert(memoSharedCount.load() == 0u);
this->~Any();
}
/**
* Deallocate the object. It should have previously been destroyed.
*/
void deallocate() {
assert(sharedCount.load() == 0u);
assert(memoSharedCount.load() == 0u);
assert(weakCount.load() == 0u);
assert(memoWeakCount.load() == 0u);
libbirch::deallocate(this, (unsigned)size, tid);
}
/**
* Shared count.
*/
Atomic<unsigned> sharedCount;
/**
* Memo shared count, or, if the shared count is nonzero, one plus the memo
* shared count.
*/
Atomic<unsigned> memoSharedCount;
/**
* Weak count, or, if the memo shared count is nonzero, one plus the weak
* count.
*/
Atomic<unsigned> weakCount;
/**
* Memo weak count, or, if the weak count is nonzero, one plus the memo
* weak count.
*/
Atomic<unsigned> memoWeakCount;
/**
* Label of the object.
*/
Label* label;
/**
* Id of the thread associated with the object. This is set immediately
* after allocation. It is used to return the allocation to the correct
* pool after use, even when returned by a different thread.
*/
int tid;
/**
* Size of the object. This is set immediately after allocation. It is used
* to return the allocation to the correct pool after use.
*/
uint16_t size;
/**
* Bitfield containing:
*
* * Finished flag.
* * Frozen flag.
* * Unique frozen flag: is the object frozen, and at the time of
* freezing, was there only one pointer to it?
* * Discard flag.
*
* The first field occupies 28 bits, the remainder 1 bit each.
*/
Atomic<uint16_t> packed;
};
}
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/external.hpp"
#include "libbirch/memory.hpp"
#include "libbirch/Atomic.hpp"
namespace libbirch {
class Label;
class Freezer;
class Copier;
using Recycler = Copier;
/**
* Base class for reference counted objects.
*
* @ingroup libbirch
*
* @attention In order to work correctly, Any must be the *first* base
* class in any inheritance hierarchy. This is particularly important when
* multiple inheritance is used.
*/
class Any {
public:
using class_type_ = Any;
using this_type_ = Any;
/**
* Constructor.
*/
Any() :
sharedCount(0u),
memoValueCount(0u),
weakCount(1u),
memoKeyCount(1u),
label(rootLabel),
frozen(false),
frozenUnique(false) {
// size and tid already set by operator new
}
/**
* Special constructor for the root label.
*/
Any(int) :
sharedCount(0u),
memoValueCount(0u),
weakCount(1u),
memoKeyCount(1u),
label(nullptr),
frozen(false),
frozenUnique(false) {
// size and tid already set by operator new
}
/**
* Copy constructor.
*/
Any(const Any& o) : Any() {
//
}
/**
* Destructor.
*/
virtual ~Any() {
assert(sharedCount.load() == 0u);
assert(memoValueCount.load() == 0u);
}
/**
* New operator.
*/
void* operator new(std::size_t size) {
auto ptr = static_cast<Any*>(allocate(size));
ptr->size = static_cast<unsigned>(size);
ptr->tid = get_thread_num();
return ptr;
}
/**
* Delete operator.
*/
void operator delete(void* ptr) {
auto counted = static_cast<Any*>(ptr);
counted->destroy();
counted->deallocate();
}
/**
* Assignment operator.
*/
Any& operator=(const Any&) {
return *this;
}
/**
* Get the size, in bytes, of the object.
*/
unsigned getSize() const {
return size;
}
/**
* Is this object reachable? An object is reachable if there exists a
* shared, memo value, or weak pointer to it. This is equivalent to a weak
* count or one or more. If only a memo key pointer to it exists, it is
* not considered reachable, and it may be cleaned up during memo
* maintenance.
*/
bool isReachable() const {
return numWeak() > 0u;
}
/**
* Is there definitely only one pointer to this object? This is
* conservative; it returns true if there is at most one shared or weak
* pointer to the object. Note, in particular, that the presence of a memo
* value pointer means that an unknown number of pointers (including zero
* pointers) may update to the object in future.
*/
bool isUnique() const {
return numShared() <= 1u && numMemoValue() <= 1u && numWeak() <= 1u;
// ^ recall first shared count increments memo value and weak counts
}
/**
* Finalize. This is called when the memo value count reaches zero,
* but before destruction and deallocation of the object. Object
* resurrection is supported: if the finalizer results in a nonzero memo
* value count, destruction and deallocation do not proceed.
*/
virtual void finalize() {
//
}
/**
* Freeze the object.
*
* @param v Freeze visitor.
*/
virtual void freeze_(const Freezer& v) = 0;
/**
* Copy the object.
*
* @param v Copy visitor.
*/
virtual Any* copy_(const Copier& v) const = 0;
/**
* Recycle the object.
*
* @param v Recycle visitor.
*/
virtual Any* recycle_(const Recycler& v) = 0;
/**
* Shared count.
*/
unsigned numShared() const {
return sharedCount.load();
}
/**
* Increment the shared count.
*/
void incShared() {
if (++sharedCount == 1u) {
/* to support object resurrection, when the shared count increases from
* zero, increment the memo value count also; this also occurs when an
* object is first created */
incMemoValue();
holdLabel();
}
}
/**
* Decrement the shared count.
*/
void decShared() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
releaseLabel();
decMemoValue();
}
}
/**
* Memo value count.
*/
unsigned numMemoValue() const {
return memoValueCount.load();
}
/**
* Increment the memo value count.
*/
void incMemoValue() {
memoValueCount.increment();
}
/**
* Decrement the memo value count.
*/
void decMemoValue() {
assert(numMemoValue() > 0u);
if (--memoValueCount == 0u) {
assert(numShared() == 0u);
finalize();
/* to support object resurrection, check the memo value count again
* before proceeding with destruction */
if (numMemoValue() == 0u) {
destroy();
decWeak();
}
}
}
/**
* Weak count.
*/
unsigned numWeak() const {
return weakCount.load();
}
/**
* Increment the weak count.
*/
void incWeak() {
weakCount.increment();
}
/**
* Decrement the weak count.
*/
void decWeak() {
assert(weakCount.load() > 0u);
if (--weakCount == 0u) {
assert(numShared() == 0u);
assert(numMemoValue() == 0u);
decMemoKey();
}
}
/**
* Memo key count.
*/
unsigned numMemoKey() const {
return memoKeyCount.load();
}
/**
* Increment the memo key count.
*/
void incMemoKey() {
memoKeyCount.increment();
}
/**
* Decrement the memo key count.
*/
void decMemoKey() {
assert(memoKeyCount.load() > 0u);
if (--memoKeyCount == 0u) {
assert(numShared() == 0u);
assert(numMemoValue() == 0u);
assert(numWeak() == 0u);
deallocate();
}
}
/**
* Get the label assigned to the object.
*/
Label* getLabel() const {
return label;
}
/**
* Set the label assigned to the object. The shared count must be zero, and
* the current label the root label. Typically this is applied to the new
* object immediately after a copy operation.
*/
void setLabel(Label* label) {
assert(getLabel() == rootLabel);
assert(numShared() == 0u);
this->label = label;
}
/**
* Replaced the label assigned to the object. The shared count must be
* greater than zero. Typically this is applied to an object immediately
* after a recycle operation.
*/
void replaceLabel(Label* label) {
assert(numShared() > 0u);
releaseLabel();
this->label = label;
holdLabel();
}
/**
* Freeze the object.
*
* @return Was the object *not* already frozen?
*/
bool freeze() {
bool frozenAlready = frozen;
frozen = true;
if (!frozenAlready) {
frozenUnique = isUnique();
}
return !frozenAlready;
}
/**
* Thaw the object.
*/
void thaw() {
frozen = false;
frozenUnique = false;
}
/**
* Is the object frozen? This returns true if either a freeze is in
* progress (i.e. another thread is in the process of freezing the object),
* or if the freeze is complete.
*/
bool isFrozen() const {
return frozen;
}
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
bool isFrozenUnique() const {
return frozenUnique;
}
protected:
/**
* Accept a visitor across member variables.
*/
template<class Visitor>
void accept_(const Visitor& v) {
//
}
private:
/**
* Increment the shared count of the label (if not null).
*/
void holdLabel();
/**
* Decrement the shared count of the label (if not null). This is used
* when the shared count for the object reduces to zero, while the memo
* value count may still be greater than zero, in order to break any
* reference cycles between objects and memos with the same label.
*/
void releaseLabel();
/**
* Destroy, but do not deallocate, the object.
*/
void destroy() {
assert(sharedCount.load() == 0u);
assert(memoValueCount.load() == 0u);
this->~Any();
}
/**
* Deallocate the object. It should have previously been destroyed.
*/
void deallocate() {
assert(sharedCount.load() == 0u);
assert(memoValueCount.load() == 0u);
assert(weakCount.load() == 0u);
assert(memoKeyCount.load() == 0u);
libbirch::deallocate(this, size, tid);
}
/**
* Shared count.
*/
Atomic<unsigned> sharedCount;
/**
* Memo value count. This is one plus the number of times that the object
* is held as a value in a memo. The plus one is a self-reference that is
* released when the shared count reaches zero.
*/
Atomic<unsigned> memoValueCount;
/**
* Weak count. This is one plus the number of times that the object is held
* by a weak pointer. The plus one is a self-reference that is released
* when the memo value count reaches zero.
*/
Atomic<unsigned> weakCount;
/**
* Memo key count. This is one plus the number of times that the object
* is held as a key in a memo. The plus one is a self-reference that is
* released when the weak count reaches zero.
*/
Atomic<unsigned> memoKeyCount;
/**
* Label of the object.
*/
Label* label;
/**
* Size of the object. This is set immediately after construction. A value
* of zero is also indicative that the object is still being constructed.
* Consequently, if the shared count reaches zero while the size is zero,
* the object is not destroyed. This can happen when constructors create
* shared pointers to `this`.
*/
unsigned size;
/**
* Id of the thread associated with the object. This is used to return the
* allocation to the correct pool after use, even when returned by a
* different thread.
*/
int tid:30;
/**
* Is this frozen (read-only)?
*/
bool frozen:1;
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
bool frozenUnique:1;
};
}
<commit_msg>Missing file from previous commit.<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/external.hpp"
#include "libbirch/memory.hpp"
#include "libbirch/Atomic.hpp"
namespace libbirch {
class Label;
class Freezer;
class Copier;
using Recycler = Copier;
/**
* Base class for reference counted objects.
*
* @ingroup libbirch
*
* @attention In order to work correctly, Any must be the *first* base
* class in any inheritance hierarchy. This is particularly important when
* multiple inheritance is used.
*/
class Any {
public:
using class_type_ = Any;
using this_type_ = Any;
/**
* Constructor.
*/
Any() :
sharedCount(0u),
memoValueCount(0u),
weakCount(1u),
memoKeyCount(1u),
label(rootLabel),
frozen(false),
frozenUnique(false) {
// size and tid already set by operator new
}
/**
* Special constructor for the root label.
*/
Any(int) :
sharedCount(0u),
memoValueCount(0u),
weakCount(1u),
memoKeyCount(1u),
label(nullptr),
frozen(false),
frozenUnique(false) {
// size and tid already set by operator new
}
/**
* Copy constructor.
*/
Any(const Any& o) : Any() {
//
}
/**
* Destructor.
*/
virtual ~Any() {
assert(sharedCount.load() == 0u);
assert(memoValueCount.load() == 0u);
}
/**
* New operator.
*/
void* operator new(std::size_t size) {
auto ptr = static_cast<Any*>(allocate(size));
ptr->size = static_cast<unsigned>(size);
ptr->tid = get_thread_num();
return ptr;
}
/**
* Delete operator.
*/
void operator delete(void* ptr) {
auto counted = static_cast<Any*>(ptr);
counted->destroy();
counted->deallocate();
}
/**
* Assignment operator.
*/
Any& operator=(const Any&) {
return *this;
}
/**
* Get the size, in bytes, of the object.
*/
unsigned getSize() const {
return size;
}
/**
* Is this object reachable? An object is reachable if there exists a
* shared, memo value, or weak pointer to it. This is equivalent to a weak
* count or one or more. If only a memo key pointer to it exists, it is
* not considered reachable, and it may be cleaned up during memo
* maintenance.
*/
bool isReachable() const {
return numWeak() > 0u;
}
/**
* Is there definitely only one pointer to this object? This is
* conservative; it returns true if there is at most one shared or weak
* pointer to the object. Note, in particular, that the presence of a memo
* value pointer means that an unknown number of pointers (including zero
* pointers) may update to the object in future.
*/
bool isUnique() const {
return numShared() <= 1u && numMemoValue() <= 1u && numWeak() <= 1u;
// ^ recall first shared count increments memo value and weak counts
}
/**
* Finalize. This is called when the memo value count reaches zero,
* but before destruction and deallocation of the object. Object
* resurrection is supported: if the finalizer results in a nonzero memo
* value count, destruction and deallocation do not proceed.
*/
virtual void finalize() {
//
}
/**
* Freeze the object.
*
* @param v Freeze visitor.
*/
virtual void freeze_(const Freezer& v) = 0;
/**
* Copy the object.
*
* @param v Copy visitor.
*/
virtual Any* copy_(const Copier& v) const = 0;
/**
* Recycle the object.
*
* @param v Recycle visitor.
*/
virtual Any* recycle_(const Recycler& v) = 0;
/**
* Shared count.
*/
unsigned numShared() const {
return sharedCount.load();
}
/**
* Increment the shared count.
*/
void incShared() {
if (++sharedCount == 1u) {
/* to support object resurrection, when the shared count increases from
* zero, increment the memo value count also; this also occurs when an
* object is first created */
incMemoValue();
holdLabel();
}
}
/**
* Decrement the shared count.
*/
void decShared() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
releaseLabel();
decMemoValue();
}
}
/**
* Memo value count.
*/
unsigned numMemoValue() const {
return memoValueCount.load();
}
/**
* Increment the memo value count.
*/
void incMemoValue() {
memoValueCount.increment();
}
/**
* Decrement the memo value count.
*/
void decMemoValue() {
assert(numMemoValue() > 0u);
if (--memoValueCount == 0u) {
assert(numShared() == 0u);
finalize();
/* to support object resurrection, check the memo value count again
* before proceeding with destruction */
if (numMemoValue() == 0u) {
destroy();
decWeak();
}
}
}
/**
* Weak count.
*/
unsigned numWeak() const {
return weakCount.load();
}
/**
* Increment the weak count.
*/
void incWeak() {
weakCount.increment();
}
/**
* Decrement the weak count.
*/
void decWeak() {
assert(weakCount.load() > 0u);
if (--weakCount == 0u) {
assert(numShared() == 0u);
assert(numMemoValue() == 0u);
decMemoKey();
}
}
/**
* Memo key count.
*/
unsigned numMemoKey() const {
return memoKeyCount.load();
}
/**
* Increment the memo key count.
*/
void incMemoKey() {
memoKeyCount.increment();
}
/**
* Decrement the memo key count.
*/
void decMemoKey() {
assert(memoKeyCount.load() > 0u);
if (--memoKeyCount == 0u) {
assert(numShared() == 0u);
assert(numMemoValue() == 0u);
assert(numWeak() == 0u);
deallocate();
}
}
/**
* Get the label assigned to the object.
*/
Label* getLabel() const {
return label;
}
/**
* Set the label assigned to the object. The shared count must be zero, and
* the current label the root label. Typically this is applied to the new
* object immediately after a copy operation.
*/
void setLabel(Label* label) {
assert(getLabel() == rootLabel);
assert(numShared() == 0u);
this->label = label;
}
/**
* Replaced the label assigned to the object. The shared count must be
* greater than zero. Typically this is applied to an object immediately
* after a recycle operation.
*/
void replaceLabel(Label* label) {
assert(numShared() > 0u);
auto old = this->label;
releaseLabel();
this->label = label;
holdLabel();
}
/**
* Freeze the object.
*
* @return Was the object *not* already frozen?
*/
bool freeze() {
bool frozenAlready = frozen;
frozen = true;
if (!frozenAlready) {
frozenUnique = isUnique();
}
return !frozenAlready;
}
/**
* Thaw the object.
*/
void thaw() {
frozen = false;
frozenUnique = false;
}
/**
* Is the object frozen? This returns true if either a freeze is in
* progress (i.e. another thread is in the process of freezing the object),
* or if the freeze is complete.
*/
bool isFrozen() const {
return frozen;
}
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
bool isFrozenUnique() const {
return frozenUnique;
}
protected:
/**
* Accept a visitor across member variables.
*/
template<class Visitor>
void accept_(const Visitor& v) {
//
}
private:
/**
* Increment the shared count of the label (if not null).
*/
void holdLabel();
/**
* Decrement the shared count of the label (if not null). This is used
* when the shared count for the object reduces to zero, while the memo
* value count may still be greater than zero, in order to break any
* reference cycles between objects and memos with the same label.
*/
void releaseLabel();
/**
* Destroy, but do not deallocate, the object.
*/
void destroy() {
assert(sharedCount.load() == 0u);
assert(memoValueCount.load() == 0u);
this->~Any();
}
/**
* Deallocate the object. It should have previously been destroyed.
*/
void deallocate() {
assert(sharedCount.load() == 0u);
assert(memoValueCount.load() == 0u);
assert(weakCount.load() == 0u);
assert(memoKeyCount.load() == 0u);
libbirch::deallocate(this, size, tid);
}
/**
* Shared count.
*/
Atomic<unsigned> sharedCount;
/**
* Memo value count. This is one plus the number of times that the object
* is held as a value in a memo. The plus one is a self-reference that is
* released when the shared count reaches zero.
*/
Atomic<unsigned> memoValueCount;
/**
* Weak count. This is one plus the number of times that the object is held
* by a weak pointer. The plus one is a self-reference that is released
* when the memo value count reaches zero.
*/
Atomic<unsigned> weakCount;
/**
* Memo key count. This is one plus the number of times that the object
* is held as a key in a memo. The plus one is a self-reference that is
* released when the weak count reaches zero.
*/
Atomic<unsigned> memoKeyCount;
/**
* Label of the object.
*/
Label* label;
/**
* Size of the object. This is set immediately after construction. A value
* of zero is also indicative that the object is still being constructed.
* Consequently, if the shared count reaches zero while the size is zero,
* the object is not destroyed. This can happen when constructors create
* shared pointers to `this`.
*/
unsigned size;
/**
* Id of the thread associated with the object. This is used to return the
* allocation to the correct pool after use, even when returned by a
* different thread.
*/
int tid:30;
/**
* Is this frozen (read-only)?
*/
bool frozen:1;
/**
* Is the object frozen, and at the time of freezing, was there only one
* pointer to it?
*/
bool frozenUnique:1;
};
}
<|endoftext|> |
<commit_before>#include <async.h>
#include <aios.h>
#include <chord.h>
#include <coord.h>
#include <id_utils.h>
#include <misc_utils.h>
#include "rpclib.h"
#define TIMEOUT 10
chordID wellknown_ID = -1;
bool verify = false;
vec<chord_node> sequential;
void getsucc_cb (u_int64_t start, chord_node curr, chord_nodelistextres *res, clnt_stat err);
void
verify_succlist (const vec<chord_node> &zs)
{
size_t sz = zs.size ();
chord_node x = sequential.pop_front ();
// ensure we talked to who we think we should be talking to.
assert (x.x == zs[0].x);
if (sequential.size () == 0) {
for (size_t i = 1; i < sz; i++) {
sequential.push_back (zs[i]);
}
} else {
bool bad = false;
vec<chord_node> newseq;
size_t i = 1, j = 0;
while (i < sz && j < sequential.size ()) {
if (sequential[j].x == zs[i].x) {
newseq.push_back (sequential[j]);
j++; i++;
} else {
bad = true;
strbuf s;
s << " sequential[" << j << "] = " << sequential[j] << "\n";
s << " nlist[" << i << "] = " << zs[i] << "\n";
if (sequential[j].x < zs[i].x) {
aout << "nlist missing a successor!\n";
newseq.push_back (sequential[j]);
j++;
} else {
aout << "sequential missing a successor!\n";
newseq.push_back (zs[i]);
i++;
}
aout << s;
}
}
while (i < sz) {
newseq.push_back (zs[i++]);
}
if (j < sequential.size ()) {
bad = true;
newseq.push_back (sequential[j++]);
}
if (bad) {
for (size_t k = 0; k < zs.size (); k++)
aout << "nlist[" << k << "]: " << zs[k] << "\n";
for (size_t k = 0; k < sequential.size (); k++)
aout << "sequential[" << k << "]: " << sequential[k] << "\n";
aout << "\n";
}
sequential.clear ();
sequential = newseq;
}
}
void
getsucc (const chord_node &n)
{
chord_nodelistextres *res = New chord_nodelistextres ();
doRPC (n, chord_program_1, CHORDPROC_GETSUCC_EXT, &n.x, res,
wrap (&getsucc_cb, getusec (), n, res));
}
void
getsucc_cb (u_int64_t start, chord_node curr, chord_nodelistextres *res, clnt_stat err)
{
chord_node next;
if (err != 0 || res->status != CHORD_OK) {
aout << "failed to get a reading from " << curr << "; skipping.\n";
sequential.pop_front ();
if (sequential.size () == 0) {
fatal << "too many consecutive failures.\n";
}
next = sequential[0];
delete res;
getsucc (next);
return;
}
assert (res->resok->nlist.size () >= 2);
size_t sz = res->resok->nlist.size ();
vec<chord_node> zs;
for (size_t i = 0; i < sz; i++) {
chord_node z = make_chord_node (res->resok->nlist[i].n);
zs.push_back (z);
}
delete res;
if (verify) {
curr = zs[0];
verify_succlist (zs);
next = sequential[0];
} else {
next = zs[1];
sequential = zs;
curr = sequential.pop_front ();
}
// Print full information for the node we just talked to
chordID n = curr.x;
str host = curr.r.hostname;
u_short port = curr.r.port;
int index = curr.vnode_num;
assert (index >= 0);
char s[128];
sprintf (s, "e=%f", curr.e / PRED_ERR_MULT);
aout << n << " " << host << " " << port << " " << index << " "
<< curr.coords[0] << " " << curr.coords[1] << " " << curr.coords[2] << " "
<< s << " "
<< (getusec () - start) << "\n";
// wrapped around ring. done.
if (next.x == wellknown_ID)
exit (0);
if (next.x != zs[1].x)
aout << "XXX succlist had wrong successor!!!\n";
getsucc (next);
}
void
usage ()
{
fatal << "walk [-v] -j <host>:<port>\n";
}
int
main (int argc, char** argv)
{
setprogname (argv[0]);
str host = "not set";
unsigned short port = 0;
int ch;
while ((ch = getopt (argc, argv, "j:v")) != -1) {
switch (ch) {
case 'j':
{
char *bs_port = strchr(optarg, ':');
if (!bs_port) usage ();
*bs_port = 0;
bs_port++;
if (inet_addr (optarg) == INADDR_NONE) {
//yep, this blocks
struct hostent *h = gethostbyname (optarg);
if (!h) {
warn << "Invalid address or hostname: " << optarg << "\n";
usage ();
}
struct in_addr *ptr = (struct in_addr *)h->h_addr;
host = inet_ntoa (*ptr);
} else
host = optarg;
port = atoi (bs_port);
break;
}
case 'v':
verify = true;
break;
default:
usage ();
break;
}
}
if (host == "not set")
usage ();
wellknown_ID = make_chordID (host, port, 0);
chord_node wellknown_node;
wellknown_node.x = wellknown_ID;
wellknown_node.r.hostname = host;
wellknown_node.r.port = port;
wellknown_node.vnode_num = 0;
sequential.push_back (wellknown_node);
getsucc (wellknown_node);
amain ();
}
<commit_msg>Add -t option: exit the process after so many seconds.<commit_after>#include <async.h>
#include <aios.h>
#include <chord.h>
#include <coord.h>
#include <id_utils.h>
#include <misc_utils.h>
#include "rpclib.h"
#define TIMEOUT 10
chordID wellknown_ID = -1;
bool verify = false;
vec<chord_node> sequential;
void getsucc_cb (u_int64_t start, chord_node curr, chord_nodelistextres *res, clnt_stat err);
void
verify_succlist (const vec<chord_node> &zs)
{
size_t sz = zs.size ();
chord_node x = sequential.pop_front ();
// ensure we talked to who we think we should be talking to.
assert (x.x == zs[0].x);
if (sequential.size () == 0) {
for (size_t i = 1; i < sz; i++) {
sequential.push_back (zs[i]);
}
} else {
bool bad = false;
vec<chord_node> newseq;
size_t i = 1, j = 0;
while (i < sz && j < sequential.size ()) {
if (sequential[j].x == zs[i].x) {
newseq.push_back (sequential[j]);
j++; i++;
} else {
bad = true;
strbuf s;
s << " sequential[" << j << "] = " << sequential[j] << "\n";
s << " nlist[" << i << "] = " << zs[i] << "\n";
if (sequential[j].x < zs[i].x) {
aout << "nlist missing a successor!\n";
newseq.push_back (sequential[j]);
j++;
} else {
aout << "sequential missing a successor!\n";
newseq.push_back (zs[i]);
i++;
}
aout << s;
}
}
while (i < sz) {
newseq.push_back (zs[i++]);
}
if (j < sequential.size ()) {
bad = true;
newseq.push_back (sequential[j++]);
}
if (bad) {
for (size_t k = 0; k < zs.size (); k++)
aout << "nlist[" << k << "]: " << zs[k] << "\n";
for (size_t k = 0; k < sequential.size (); k++)
aout << "sequential[" << k << "]: " << sequential[k] << "\n";
aout << "\n";
}
sequential.clear ();
sequential = newseq;
}
}
void
getsucc (const chord_node &n)
{
chord_nodelistextres *res = New chord_nodelistextres ();
doRPC (n, chord_program_1, CHORDPROC_GETSUCC_EXT, &n.x, res,
wrap (&getsucc_cb, getusec (), n, res));
}
void
getsucc_cb (u_int64_t start, chord_node curr, chord_nodelistextres *res, clnt_stat err)
{
chord_node next;
if (err != 0 || res->status != CHORD_OK) {
aout << "failed to get a reading from " << curr << "; skipping.\n";
sequential.pop_front ();
if (sequential.size () == 0) {
fatal << "too many consecutive failures.\n";
}
next = sequential[0];
delete res;
getsucc (next);
return;
}
assert (res->resok->nlist.size () >= 2);
size_t sz = res->resok->nlist.size ();
vec<chord_node> zs;
for (size_t i = 0; i < sz; i++) {
chord_node z = make_chord_node (res->resok->nlist[i].n);
zs.push_back (z);
}
delete res;
if (verify) {
curr = zs[0];
verify_succlist (zs);
next = sequential[0];
} else {
next = zs[1];
sequential = zs;
curr = sequential.pop_front ();
}
// Print full information for the node we just talked to
chordID n = curr.x;
str host = curr.r.hostname;
u_short port = curr.r.port;
int index = curr.vnode_num;
assert (index >= 0);
char s[128];
sprintf (s, "e=%f", curr.e / PRED_ERR_MULT);
aout << n << " " << host << " " << port << " " << index << " "
<< curr.coords[0] << " " << curr.coords[1] << " " << curr.coords[2] << " "
<< s << " "
<< (getusec () - start) << "\n";
// wrapped around ring. done.
if (next.x == wellknown_ID)
exit (0);
if (next.x != zs[1].x)
aout << "XXX succlist had wrong successor!!!\n";
getsucc (next);
}
void
usage ()
{
warnx << "Usage: " << progname << " [-v] [-t maxtotaltime] -j <host>:<port>\n";
exit (1);
}
void
timedout (int t)
{
fatal << "timed out after " << t << " seconds.\n";
exit (1);
}
int
main (int argc, char** argv)
{
setprogname (argv[0]);
str host = "not set";
unsigned short port (0);
unsigned int maxtime (0);
int ch;
while ((ch = getopt (argc, argv, "j:t:v")) != -1) {
switch (ch) {
case 'j':
{
char *bs_port = strchr(optarg, ':');
if (!bs_port) usage ();
*bs_port = 0;
bs_port++;
if (inet_addr (optarg) == INADDR_NONE) {
//yep, this blocks
struct hostent *h = gethostbyname (optarg);
if (!h) {
warn << "Invalid address or hostname: " << optarg << "\n";
usage ();
}
struct in_addr *ptr = (struct in_addr *)h->h_addr;
host = inet_ntoa (*ptr);
} else
host = optarg;
port = atoi (bs_port);
break;
}
case 't':
maxtime = atoi (optarg);
break;
case 'v':
verify = true;
break;
default:
usage ();
break;
}
}
if (host == "not set")
usage ();
wellknown_ID = make_chordID (host, port, 0);
chord_node wellknown_node;
wellknown_node.x = wellknown_ID;
wellknown_node.r.hostname = host;
wellknown_node.r.port = port;
wellknown_node.vnode_num = 0;
sequential.push_back (wellknown_node);
getsucc (wellknown_node);
if (maxtime > 0)
delaycb (maxtime, wrap (&timedout, maxtime));
amain ();
}
<|endoftext|> |
<commit_before>#define TEST_CASE
#include <boost/test/included/unit_test.hpp>
#include "module_base.h"
#include "logger_enum.h"
using namespace boost::unit_test_framework;
//--stub functions--
LOG_LEVEL_TAG getloglevel(){ return LOG_LV_NONE; }
void putLogFatal( const unsigned int, const std::string&, const char*, int ){}
void putLogError( const unsigned int, const std::string&, const char*, int ){}
void putLogWarn( const unsigned int, const std::string&, const char*, int ){}
void putLogInfo( const unsigned int, const std::string&, const char*, int ){}
void putLogDebug( const unsigned int, const std::string&, const char*, int ){}
void* replication_pay_memory( const std::string&, unsigned int* ){ return NULL; }
void lock_func(){}
void unlock_func(){}
//--test class--
class module_base_test : public l7vs::module_base {
public:
module_base_test( std::string in_modulename ) : module_base( in_modulename ){};
~module_base_test();
};
//--tests--
void constractor_test(){
BOOST_MESSAGE( "----- constractor test start -----" );
module_base_test mod_base_test_1( "cinsert" );
module_base_test mod_base_test_2( "" );
module_base_test mod_base_test_3( NULL );
// ## test [1] constractor parameter set test ("cinsert")
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_1.name, "cinsert" );
// ## test [2] constractor parameter set test ("")
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_2.name, "" );
// ## test [3] constractor parameter set test (null)
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_3.name, NULL );
BOOST_MESSAGE( "----- constractor test end -----" );
}
void get_name_test(){
BOOST_MESSAGE( "----- get_name test start -----" );
module_base_test mod_base_test_1( "cinsert" );
module_base_test mod_base_test_2( "" );
module_base_test mod_base_test_3( NULL );
// ## test [1] get_name get test ("cinsert")
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_1.get_name(), "cinsert" );
// ## test [2] get_name get test ("cinsert")
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_1.get_name(), mod_base_test_1.name );
// ## test [3] get_name get test ("")
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_2.get_name(), "" );
// ## test [4] get_name get test ("")
std::cout << "4----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_2.get_name(), mod_base_test_2.name );
// ## test [5] get_name get test (null)
std::cout << "5----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_3.get_name(), NULL );
// ## test [6] get_name get test (null)
std::cout << "6----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test_3.get_name(), mod_base_test_3.name );
BOOST_MESSAGE( "----- get_name test end -----" );
}
void init_logger_functions_test(){
BOOST_MESSAGE( "----- init_logger_functions test start -----" );
module_base_test mod_base_test( "cinsert" );
getloglevel_func_type getloglevel = &getloglevel;
logger_func_type putLogFatal = &putLogFatal;
logger_func_type putLogError = &putLogError;
logger_func_type putLogWarn = &putLogWarn;
logger_func_type putLogInfo = &putLogInfo;
logger_func_type putLogDebug = &putLogDebug;
mod_base_test.init_logger_functions(
getloglevel,
putLogFatal,
putLogError,
putLogWarn,
putLogInfo,
putLogDebug );
// ## test [1] init_logger_functions parameter set test (getloglevel)
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.getloglevel, getloglevel );
// ## test [2] init_logger_functions parameter set test (putLogFatal)
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.putLogFatal, putLogFatal );
// ## test [3] init_logger_functions parameter set test (putLogError)
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.putLogError, putLogError );
// ## test [4] init_logger_functions parameter set test (putLogWarn)
std::cout << "4----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.putLogWarn, putLogWarn );
// ## test [5] init_logger_functions parameter set test (putLogInfo)
std::cout << "5----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.putLogInfo, putLogInfo );
// ## test [6] init_logger_functions parameter set test (putLogDebug)
std::cout << "6----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.putLogDebug, putLogDebug );
BOOST_MESSAGE( "----- init_logger_functions test end -----" );
}
void init_replication_functions_test(){
BOOST_MESSAGE( "----- init_replication_functions test start -----" );
module_base_test mod_base_test( "cinsert" );
replicationpaymemory_func_type replication_pay_memory = &replication_pay_memory;
boost::function< void( void ) > lock_func = &lock_func;
boost::function< void( void ) > unlock_func = &unlock_func;
const boost::asio::ip::tcp::endpoint& virtual_service_endpoint_tcp( "10.10.10.10:6555" );
const boost::asio::ip::udp::endpoint& virtual_service_endpoint_udp( "20.20.20.20:4444" );
mod_base_test.init_replication_functions(
replication_pay_memory,
lock_func,
unlock_func,
virtual_service_endpoint_tcp,
virtual_service_endpoint_udp );
// ## test [1] init_replication_functions parameter set test (replication_pay_memory)
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.replication_pay_memory, replication_pay_memory );
// ## test [1] init_replication_functions parameter set test (lock_func)
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.lock_func, lock_func );
// ## test [1] init_replication_functions parameter set test (unlock_func)
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.unlock_func, unlock_func );
// ## test [1] init_replication_functions parameter set test (virtual_service_endpoint_tcp)
std::cout << "4----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.virtual_service_endpoint_tcp, virtual_service_endpoint_tcp );
// ## test [1] init_replication_functions parameter set test (virtual_service_endpoint_udp)
std::cout << "5----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( mod_base_test.virtual_service_endpoint_udp, virtual_service_endpoint_udp );
BOOST_MESSAGE( "----- init_replication_functions test end -----" );
}
test_suite* init_unit_test_suite( int argc, char* argv[] ){
test_suite* ts = BOOST_TEST_SUITE( "module_base class test" );
ts->add( BOOST_TEST_CASE( &constractor_test ) );
ts->add( BOOST_TEST_CASE( &get_name_test ) );
ts->add( BOOST_TEST_CASE( &init_logger_functions_test ) );
ts->add( BOOST_TEST_CASE( &init_replication_functions_test ) );
framework::master_test_suite().add( ts );
return 0;
}
<commit_msg>CD完了<commit_after>#define TEST_CASE
#include <boost/test/included/unit_test.hpp>
#include "module_base.h"
using namespace boost::unit_test_framework;
using namespace l7vs;
//--stub functions--
LOG_LEVEL_TAG stb_getloglevel(){
std::cout << "getloglevel called." << std::endl;
return LOG_LV_NONE;
}
void stb_putLogFatal( const unsigned int, const std::string&, const char*, int ){
std::cout << "putLogFatal called." << std::endl;
}
void stb_putLogError( const unsigned int, const std::string&, const char*, int ){
std::cout << "putLogError called." << std::endl;
}
void stb_putLogWarn( const unsigned int, const std::string&, const char*, int ){
std::cout << "putLogWarn called." << std::endl;
}
void stb_putLogInfo( const unsigned int, const std::string&, const char*, int ){
std::cout << "putLogInfo called." << std::endl;
}
void stb_putLogDebug( const unsigned int, const std::string&, const char*, int ){
std::cout << "putLogDebug called." << std::endl;
}
void* stb_replication_pay_memory( const std::string&, unsigned int* ){
std::cout << "replication_pay_memory called." << std::endl;
return NULL;
}
void stb_replication_area_lock(){
std::cout << "replication_area_lock called." << std::endl;
}
void stb_replication_area_unlock(){
std::cout << "replication_area_unlock called." << std::endl;
}
//--test class--
class module_base_test : public module_base {
public:
module_base_test( std::string in_modulename ) : module_base( in_modulename ){}
~module_base_test(){}
bool is_tcp(){ return true; }
bool is_udp(){ return true; }
void replication_interrupt(){}
void constractor_test(){
BOOST_MESSAGE( "----- constractor test start -----" );
std::string module_name_1 = "cinsert";
std::string module_name_2 = "";
module_base_test module_base_test_1( module_name_1 );
module_base_test module_base_test_2( module_name_2 );
// ## test [1] constractor parameter set test ("cinsert")
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_1.name, module_name_1 );
// ## test [2] constractor parameter set test ("")
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_2.name, module_name_2 );
BOOST_MESSAGE( "----- constractor test end -----" );
}
void get_name_test(){
BOOST_MESSAGE( "----- get_name test start -----" );
std::string module_name_1 = "cinsert";
std::string module_name_2 = "";
module_base_test module_base_test_1( module_name_1 );
module_base_test module_base_test_2( module_name_2 );
// ## test [1] get_name get test ("cinsert")
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_1.get_name(), module_name_1 );
// ## test [2] get_name get test ("cinsert")
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_1.get_name(), module_base_test_1.name );
// ## test [3] get_name get test ("")
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_2.get_name(), module_name_2 );
// ## test [4] get_name get test ("")
std::cout << "4----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_2.get_name(), module_base_test_2.name );
BOOST_MESSAGE( "----- get_name test end -----" );
}
void init_logger_functions_test(
getloglevel_func_type ingetloglevel,
logger_func_type inputLogFatal,
logger_func_type inputLogError,
logger_func_type inputLogWarn,
logger_func_type inputLogInfo,
logger_func_type inputLogDebug ){
BOOST_MESSAGE( "----- init_logger_functions test start -----" );
module_base_test module_base_test_1( "cinsert" );
std::cout << "0----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.getloglevel == NULL );
BOOST_CHECK( module_base_test_1.putLogFatal == NULL );
BOOST_CHECK( module_base_test_1.putLogError == NULL );
BOOST_CHECK( module_base_test_1.putLogWarn == NULL );
BOOST_CHECK( module_base_test_1.putLogInfo == NULL );
BOOST_CHECK( module_base_test_1.putLogDebug == NULL );
module_base_test_1.init_logger_functions(
ingetloglevel,
inputLogFatal,
inputLogError,
inputLogWarn,
inputLogInfo,
inputLogDebug );
// ## test [1] init_logger_functions call test (getloglevel)
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.getloglevel != NULL );
module_base_test_1.getloglevel();
// ## test [2] init_logger_functions call test (putLogFatal)
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.putLogFatal != NULL );
module_base_test_1.putLogFatal( 0, "", NULL, 0 );
// ## test [3] init_logger_functions call test (putLogError)
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.putLogError != NULL );
module_base_test_1.putLogError( 0, "", NULL, 0 );
// ## test [4] init_logger_functions call test (putLogWarn)
std::cout << "4----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.putLogWarn != NULL );
module_base_test_1.putLogWarn( 0, "", NULL, 0 );
// ## test [5] init_logger_functions call test (putLogInfo)
std::cout << "5----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.putLogInfo != NULL );
module_base_test_1.putLogInfo( 0, "", NULL, 0 );
// ## test [6] init_logger_functions call test (putLogDebug)
std::cout << "6----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.putLogDebug != NULL );
module_base_test_1.putLogDebug( 0, "", NULL, 0 );
BOOST_MESSAGE( "----- init_logger_functions test end -----" );
}
void init_replication_functions_test(
replicationpaymemory_func_type inreplication_pay_memory,
boost::function< void( void ) > inreplication_area_lock,
boost::function< void( void ) > inreplication_area_unlock,
const boost::asio::ip::tcp::endpoint& invirtual_service_endpoint_tcp,
const boost::asio::ip::udp::endpoint& invirtual_service_endpoint_udp ){
BOOST_MESSAGE( "----- init_replication_functions test start -----" );
module_base_test module_base_test_1( "cinsert" );
std::cout << "0----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.replication_pay_memory == NULL );
BOOST_CHECK( module_base_test_1.replication_area_lock == NULL );
BOOST_CHECK( module_base_test_1.replication_area_unlock == NULL );
module_base_test_1.init_replication_functions(
inreplication_pay_memory,
inreplication_area_lock,
inreplication_area_unlock,
invirtual_service_endpoint_tcp,
invirtual_service_endpoint_udp );
// ## test [1] init_replication_functions parameter set test (replication_pay_memory)
std::cout << "1----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.replication_pay_memory != NULL );
module_base_test_1.replication_pay_memory( "", NULL );
// ## test [1] init_replication_functions call test (replication_area_lock)
std::cout << "2----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.replication_area_lock != NULL );
module_base_test_1.replication_area_lock();
// ## test [1] init_replication_functions call test (replication_area_unlock)
std::cout << "3----------------------------------------" << std::endl;
BOOST_CHECK( module_base_test_1.replication_area_unlock != NULL );
module_base_test_1.replication_area_unlock();
// ## test [1] init_replication_functions parameter set test (virtual_service_endpoint_tcp)
std::cout << "4----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_1.virtual_service_endpoint_tcp, invirtual_service_endpoint_tcp );
// ## test [1] init_replication_functions parameter set test (virtual_service_endpoint_udp)
std::cout << "5----------------------------------------" << std::endl;
BOOST_CHECK_EQUAL( module_base_test_1.virtual_service_endpoint_udp, invirtual_service_endpoint_udp );
BOOST_MESSAGE( "----- init_replication_functions test end -----" );
}
};
//--test functions--
void constractor_test(){
module_base_test module_base_test_1( "cinsert" );
module_base_test_1.constractor_test();
}
void get_name_test(){
module_base_test module_base_test_1( "cinsert" );
module_base_test_1.get_name_test();
}
void init_logger_functions_test(){
boost::function< LOG_LEVEL_TAG(void) > getloglevel = &stb_getloglevel;
boost::function< void ( const unsigned int, const std::string&, const char*, int ) > putLogFatal = &stb_putLogFatal;
boost::function< void ( const unsigned int, const std::string&, const char*, int ) > putLogError = &stb_putLogError;
boost::function< void ( const unsigned int, const std::string&, const char*, int ) > putLogWarn = &stb_putLogWarn;
boost::function< void ( const unsigned int, const std::string&, const char*, int ) > putLogInfo = &stb_putLogInfo;
boost::function< void ( const unsigned int, const std::string&, const char*, int ) > putLogDebug = &stb_putLogDebug;
module_base_test module_base_test_1( "cinsert" );
module_base_test_1.init_logger_functions_test( getloglevel,
putLogFatal,
putLogError,
putLogWarn,
putLogInfo,
putLogDebug);
}
void init_replication_functions_test(){
boost::function< void* ( const std::string&, unsigned int* ) > replication_pay_memory = &stb_replication_pay_memory;
boost::function< void( void ) > replication_area_lock = &stb_replication_area_lock;
boost::function< void( void ) > replication_area_unlock = &stb_replication_area_unlock;
boost::asio::ip::address address_1;
unsigned short port_1 = 1111;
boost::asio::ip::address address_2;
unsigned short port_2 = 2222;
boost::asio::ip::tcp::endpoint virtual_service_endpoint_tcp( address_1, port_1 );
boost::asio::ip::udp::endpoint virtual_service_endpoint_udp( address_2, port_2 );
module_base_test module_base_test_1( "cinsert" );
module_base_test_1.init_replication_functions_test(
replication_pay_memory,
replication_area_lock,
replication_area_unlock,
virtual_service_endpoint_tcp,
virtual_service_endpoint_udp );
}
test_suite* init_unit_test_suite( int argc, char* argv[] ){
test_suite* ts = BOOST_TEST_SUITE( "module_base class test" );
ts->add( BOOST_TEST_CASE( &constractor_test ) );
ts->add( BOOST_TEST_CASE( &get_name_test ) );
ts->add( BOOST_TEST_CASE( &init_logger_functions_test ) );
ts->add( BOOST_TEST_CASE( &init_replication_functions_test ) );
framework::master_test_suite().add( ts );
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Removed prints from connection<commit_after><|endoftext|> |
<commit_before><commit_msg>Write Defaults Fix<commit_after><|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkCommonActivator.h"
#include <berryPlatformUI.h>
#include <mitkLogMacros.h>
QmitkCommonActivator* QmitkCommonActivator::m_Instance = 0;
ctkPluginContext* QmitkCommonActivator::m_Context = 0;
ctkPluginContext* QmitkCommonActivator::GetContext()
{
return m_Context;
}
QmitkCommonActivator* QmitkCommonActivator::GetInstance()
{
return m_Instance;
}
berry::IPreferencesService::Pointer QmitkCommonActivator::GetPreferencesService()
{
return berry::IPreferencesService::Pointer(m_PrefServiceTracker->getService());
}
void
QmitkCommonActivator::start(ctkPluginContext* context)
{
this->m_Instance = this;
this->m_Context = context;
if(berry::PlatformUI::IsWorkbenchRunning())
{
m_ViewCoordinator = QmitkViewCoordinator::Pointer(new QmitkViewCoordinator);
m_ViewCoordinator->Start();
}
else
{
MITK_ERROR << "BlueBerry Workbench not running!";
}
}
void
QmitkCommonActivator::stop(ctkPluginContext* context)
{
Q_UNUSED(context)
m_ViewCoordinator->Stop();
m_ViewCoordinator = 0;
this->m_Context = 0;
this->m_Instance = 0;
}
Q_EXPORT_PLUGIN2(org_mitk_gui_qt_common, QmitkCommonActivator)
<commit_msg>initialize preference service tracker on start og qmitkcommon activator<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkCommonActivator.h"
#include <berryPlatformUI.h>
#include <mitkLogMacros.h>
QmitkCommonActivator* QmitkCommonActivator::m_Instance = 0;
ctkPluginContext* QmitkCommonActivator::m_Context = 0;
ctkPluginContext* QmitkCommonActivator::GetContext()
{
return m_Context;
}
QmitkCommonActivator* QmitkCommonActivator::GetInstance()
{
return m_Instance;
}
berry::IPreferencesService::Pointer QmitkCommonActivator::GetPreferencesService()
{
return berry::IPreferencesService::Pointer(m_PrefServiceTracker->getService());
}
void
QmitkCommonActivator::start(ctkPluginContext* context)
{
this->m_Instance = this;
this->m_Context = context;
this->m_PrefServiceTracker.reset(new ctkServiceTracker<berry::IPreferencesService*>(context));
if(berry::PlatformUI::IsWorkbenchRunning())
{
m_ViewCoordinator = QmitkViewCoordinator::Pointer(new QmitkViewCoordinator);
m_ViewCoordinator->Start();
}
else
{
MITK_ERROR << "BlueBerry Workbench not running!";
}
}
void
QmitkCommonActivator::stop(ctkPluginContext* context)
{
Q_UNUSED(context)
m_ViewCoordinator->Stop();
m_ViewCoordinator = 0;
this->m_Context = 0;
this->m_Instance = 0;
}
Q_EXPORT_PLUGIN2(org_mitk_gui_qt_common, QmitkCommonActivator)
<|endoftext|> |
<commit_before>// @(#)root/eve7:$Id$
// Author: Matevz Tadel 2007
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/REveSelection.hxx>
#include <ROOT/REveProjectionBases.hxx>
#include <ROOT/REveCompound.hxx>
#include <ROOT/REveManager.hxx>
#include "TClass.h"
#include "json.hpp"
using namespace ROOT::Experimental;
namespace REX = ROOT::Experimental;
/** \class REveSelection
\ingroup REve
Make sure there is a SINGLE running REveSelection for each
selection type (select/highlight).
*/
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
REveSelection::REveSelection(const std::string& n, const std::string& t, Color_t col) :
REveElement(n, t),
fPickToSelect (kPS_Projectable),
fActive (kTRUE),
fIsMaster (kTRUE)
{
SetupDefaultColorAndTransparency(col, true, false);
// Managing complete selection state on element level.
//
// Method pointers for propagation of selected / implied selected state
// to elements. This has to be done differently now -- and kept within
// REveSelection.
//
// Also, see REveManager::PreDeleteElement. We might need some sort of
// implied-selected-count after all (global, for all selections,
// highlights) ... and traverse all selections if the element gets zapped.
// Yup, we have it ...
// XXXX but ... we can also go up to master and check there directly !!!!!
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
REveSelection::~REveSelection()
{
DeactivateSelection();
RemoveNieces();
}
////////////////////////////////////////////////////////////////////////////////
/// Set to 'highlight' mode.
void REveSelection::SetHighlightMode()
{
// Most importantly, this sets the pointers-to-function-members in
// REveElement that are used to mark elements as (un)selected and
// implied-(un)selected.
fPickToSelect = kPS_Projectable;
fIsMaster = kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Select element indicated by the entry and fill its
/// implied-selected set.
void REveSelection::DoElementSelect(SelMap_i &entry)
{
Set_t &imp_set = entry->second.f_implied;
entry->first->FillImpliedSelectedSet(imp_set);
for (auto &imp_el: imp_set) imp_el->IncImpliedSelected();
}
////////////////////////////////////////////////////////////////////////////////
/// Deselect element indicated by the entry and clear its
/// implied-selected set.
void REveSelection::DoElementUnselect(SelMap_i &entry)
{
Set_t &imp_set = entry->second.f_implied;
for (auto &imp_el: imp_set) imp_el->DecImpliedSelected();
imp_set.clear();
}
////////////////////////////////////////////////////////////////////////////////
/// Check if elemenet el is selected (not implied selected).
bool REveSelection::HasNiece(REveElement *el) const
{
return fMap.find(el) != fMap.end();
}
////////////////////////////////////////////////////////////////////////////////
/// Check if any elements are selected.
bool REveSelection::HasNieces() const
{
return ! fMap.empty();
}
////////////////////////////////////////////////////////////////////////////////
/// Pre-addition check. Deny addition if el is already selected.
/// Virtual from REveAunt.
bool REveSelection::AcceptNiece(REveElement* el)
{
return el != this && fMap.find(el) == fMap.end() &&
el->IsA()->InheritsFrom(TClass::GetClass<REveSelection>()) == kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Add an element into selection, virtual from REveAunt
void REveSelection::AddNieceInternal(REveElement* el)
{
auto res = fMap.emplace(el, Record(el));
if (fActive) {
DoElementSelect(res.first);
SelectionAdded(el);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Virtual from REveAunt.
void REveSelection::RemoveNieceInternal(REveElement* el)
{
auto i = fMap.find(el);
if (i != fMap.end())
{
el->RemoveAunt(this);
if (fActive)
{
DoElementUnselect(i);
SelectionRemoved(el);
}
fMap.erase(i);
}
else
{
Warning("REveSelection::RemoveNieceLocal", "element not found in map.");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add an element into selection, virtual from REveAunt.
/// Overriden here just so that a signal can be emitted.
void REveSelection::RemoveNieces()
{
for (auto i = fMap.begin(); i != fMap.end(); ++i)
{
i->first->RemoveAunt(this);
DoElementUnselect(i);
}
fMap.clear();
SelectionCleared();
}
////////////////////////////////////////////////////////////////////////////////
/// Remove element from all implied-selected sets.
///
/// This is called as part of the element destruction from
/// REveManager::PreDeleteElement() and should not be called
/// directly.
void REveSelection::RemoveImpliedSelected(REveElement *el)
{
for (auto &i : fMap) {
auto j = i.second.f_implied.find(el);
if (j != i.second.f_implied.end())
i.second.f_implied.erase(j);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Recalculate implied-selected state for given selection entry.
/// Add new elements to implied-selected set and increase their
/// implied-selected count.
void REveSelection::RecheckImpliedSet(SelMap_i &smi)
{
Set_t set;
smi->first->FillImpliedSelectedSet(set);
for (auto &i: set)
{
if (smi->second.f_implied.find(i) == smi->second.f_implied.end())
{
smi->second.f_implied.insert(i);
i->IncImpliedSelected();
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// If given element is selected or implied-selected within this
/// selection then recheck implied-set for given selection entry.
void REveSelection::RecheckImpliedSetForElement(REveElement *el)
{
// Top-level selected.
{
auto i = fMap.find(el);
if (i != fMap.end())
RecheckImpliedSet(i);
}
// Implied selected (we can not tell if by this selection or some other),
// then we need to loop over all.
if (el->GetImpliedSelected() > 0)
{
for (auto i = fMap.begin(); i != fMap.end(); ++i)
{
if (i->second.f_implied.find(el) != i->second.f_implied.end())
RecheckImpliedSet(i);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionAdded signal.
void REveSelection::SelectionAdded(REveElement* /*el*/)
{
// XXXX
// Emit("SelectionAdded(REveElement*)", (Long_t)el);
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionRemoved signal.
void REveSelection::SelectionRemoved(REveElement* /*el*/)
{
// XXXX
// Emit("SelectionRemoved(REveElement*)", (Long_t)el);
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionCleared signal.
void REveSelection::SelectionCleared()
{
// XXXX
// Emit("SelectionCleared()");
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionRepeated signal.
void REveSelection::SelectionRepeated(REveElement* /*el*/)
{
// XXXX
// Emit("SelectionRepeated(REveElement*)", (Long_t)el);
}
////////////////////////////////////////////////////////////////////////////////
/// Activate this selection.
void REveSelection::ActivateSelection()
{
if (fActive) return;
fActive = kTRUE;
for (auto i = fMap.begin(); i != fMap.end(); ++i) {
DoElementSelect(i);
SelectionAdded(i->first);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Deactivate this selection.
void REveSelection::DeactivateSelection()
{
if (!fActive) return;
for (auto i = fMap.begin(); i != fMap.end(); ++i) {
DoElementUnselect(i);
}
SelectionCleared();
fActive = kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Given element el that was picked or clicked by the user, find
/// the parent/ancestor element that should actually become the main
/// selected element according to current selection mode.
REveElement* REveSelection::MapPickedToSelected(REveElement* el)
{
if (el == nullptr)
return nullptr;
if (el->ForwardSelection())
{
return el->ForwardSelection();
}
switch (fPickToSelect)
{
case kPS_Ignore:
{
return nullptr;
}
case kPS_Element:
{
return el;
}
case kPS_Projectable:
{
REveProjected* pted = dynamic_cast<REveProjected*>(el);
if (pted)
return dynamic_cast<REveElement*>(pted->GetProjectable());
return el;
}
case kPS_Compound:
{
REveElement* cmpnd = el->GetCompound();
if (cmpnd)
return cmpnd;
return el;
}
case kPS_PableCompound:
{
REveProjected* pted = dynamic_cast<REveProjected*>(el);
if (pted)
el = dynamic_cast<REveElement*>(pted->GetProjectable());
REveElement* cmpnd = el->GetCompound();
if (cmpnd)
return cmpnd;
return el;
}
case kPS_Master:
{
REveElement* mstr = el->GetMaster();
if (mstr)
return mstr;
return el;
}
}
return el;
}
////////////////////////////////////////////////////////////////////////////////
/// Called when user picks/clicks on an element. If multi is true,
/// the user is requiring a multiple selection (usually this is
/// associated with control-key being pressed at the time of pick
/// event).
void REveSelection::UserPickedElement(REveElement* el, Bool_t multi)
{
el = MapPickedToSelected(el);
if (el || HasChildren())
{
if ( ! multi)
RemoveNieces();
if (el)
{
if (HasNiece(el))
RemoveNiece(el);
else
AddNiece(el);
}
if (fIsMaster)
REX::gEve->ElementSelect(el);
REX::gEve->Redraw3D();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Called when element selection is repeated.
void REveSelection::UserRePickedElement(REveElement* el)
{
el = MapPickedToSelected(el);
if (el && HasNiece(el))
{
SelectionRepeated(el);
REX::gEve->Redraw3D();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Called when an element is unselected.
void REveSelection::UserUnPickedElement(REveElement* el)
{
el = MapPickedToSelected(el);
if (el && HasNiece(el))
{
RemoveNiece(el);
REX::gEve->Redraw3D();
}
}
//==============================================================================
void REveSelection::NewElementPicked(ElementId_t id, bool multi, bool secondary, const std::set<int>& secondary_idcs)
{
static const REveException eh("REveSelection::NewElementPicked ");
REveElement *pel = REX::gEve->FindElementById(id);
if ( ! pel) throw eh + "picked element id=" + id + " not found.";
REveElement *el = MapPickedToSelected(pel);
printf("REveSelection::NewElementPicked %p -> %p, multi: %d, secondary: %d", pel, el, multi, secondary);
if (secondary)
{
printf(" { ");
for (auto si : secondary_idcs) printf("%d ", si);
printf("}");
}
printf("\n");
Record *rec = find_record(el);
if (multi)
{
if (el)
{
if (rec)
{
if (secondary || rec->is_secondary()) // ??? should actually be && ???
{
// XXXX union or difference:
// - if all secondary_idcs are already in the record, toggle
// - if final result is empty set, remove element from selection
// - otherwise union
}
else
{
// XXXX remove the existing record
}
}
else
{
// XXXX insert the new record
}
}
else
{
// Multiple selection with 0 element ... do nothing, I think.
}
}
else // single selection (not multi)
{
if (el)
{
if (rec)
{
if (secondary || rec->is_secondary()) // ??? should actually be && ???
{
// if sets are identical, issue SelectionRepeated()
// else modify record for the new one, issue Repeated
}
else
{
// clear selection
// ??? should keep the newly clicked?
}
}
else
{
if (HasNieces()) RemoveNieces();
AddNiece(el);
}
}
else // Single selection with zero element --> clear selection.
{
if (HasNieces()) RemoveNieces();
}
}
StampObjProps();
}
////////////////////////////////////////////////////////////////////////////////
/// Remove pointers to el from implied selected sets.
int REveSelection::RemoveImpliedSelectedReferencesTo(REveElement *el)
{
int count = 0;
for (auto &i : fMap) {
auto j = i.second.f_implied.find(el);
if (j != i.second.f_implied.end()) {
i.second.f_implied.erase(j);
++count;
}
}
return count;
}
////////////////////////////////////////////////////////////////////////////////
/// Write core json. If rnr_offset negative, render data will not be written
Int_t REveSelection::WriteCoreJson(nlohmann::json &j, Int_t /* rnr_offset */)
{
REveElement::WriteCoreJson(j, -1);
nlohmann::json sel_list = nlohmann::json::array();
for (auto &i : fMap)
{
nlohmann::json rec = {}, imp = nlohmann::json::array(), sec = nlohmann::json::array();
rec["primary"] = i.first->GetElementId();
// XXX if not empty ???
for (auto &imp_el : i.second.f_implied) imp.push_back(imp_el->GetElementId());
rec["implied"] = imp;
// XXX if not empty / f_is_sec is false ???
for (auto &sec_id : i.second.f_sec_idcs) sec.push_back(sec_id);
rec["sec_idcs"] = sec;
sel_list.push_back(rec);
}
j["sel_list"] = sel_list;
j["UT_PostStream"] = "UT_Selection_Refresh_State"; // XXXX to be canonized
return 0;
}
<commit_msg>Fix removal of objects from selection.<commit_after>// @(#)root/eve7:$Id$
// Author: Matevz Tadel 2007
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/REveSelection.hxx>
#include <ROOT/REveProjectionBases.hxx>
#include <ROOT/REveCompound.hxx>
#include <ROOT/REveManager.hxx>
#include "TClass.h"
#include "json.hpp"
using namespace ROOT::Experimental;
namespace REX = ROOT::Experimental;
/** \class REveSelection
\ingroup REve
Make sure there is a SINGLE running REveSelection for each
selection type (select/highlight).
*/
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
REveSelection::REveSelection(const std::string& n, const std::string& t, Color_t col) :
REveElement(n, t),
fPickToSelect (kPS_Projectable),
fActive (kTRUE),
fIsMaster (kTRUE)
{
SetupDefaultColorAndTransparency(col, true, false);
// Managing complete selection state on element level.
//
// Method pointers for propagation of selected / implied selected state
// to elements. This has to be done differently now -- and kept within
// REveSelection.
//
// Also, see REveManager::PreDeleteElement. We might need some sort of
// implied-selected-count after all (global, for all selections,
// highlights) ... and traverse all selections if the element gets zapped.
// Yup, we have it ...
// XXXX but ... we can also go up to master and check there directly !!!!!
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
REveSelection::~REveSelection()
{
DeactivateSelection();
RemoveNieces();
}
////////////////////////////////////////////////////////////////////////////////
/// Set to 'highlight' mode.
void REveSelection::SetHighlightMode()
{
// Most importantly, this sets the pointers-to-function-members in
// REveElement that are used to mark elements as (un)selected and
// implied-(un)selected.
fPickToSelect = kPS_Projectable;
fIsMaster = kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Select element indicated by the entry and fill its
/// implied-selected set.
void REveSelection::DoElementSelect(SelMap_i &entry)
{
Set_t &imp_set = entry->second.f_implied;
entry->first->FillImpliedSelectedSet(imp_set);
for (auto &imp_el: imp_set) imp_el->IncImpliedSelected();
}
////////////////////////////////////////////////////////////////////////////////
/// Deselect element indicated by the entry and clear its
/// implied-selected set.
void REveSelection::DoElementUnselect(SelMap_i &entry)
{
Set_t &imp_set = entry->second.f_implied;
for (auto &imp_el: imp_set) imp_el->DecImpliedSelected();
imp_set.clear();
}
////////////////////////////////////////////////////////////////////////////////
/// Check if elemenet el is selected (not implied selected).
bool REveSelection::HasNiece(REveElement *el) const
{
return fMap.find(el) != fMap.end();
}
////////////////////////////////////////////////////////////////////////////////
/// Check if any elements are selected.
bool REveSelection::HasNieces() const
{
return ! fMap.empty();
}
////////////////////////////////////////////////////////////////////////////////
/// Pre-addition check. Deny addition if el is already selected.
/// Virtual from REveAunt.
bool REveSelection::AcceptNiece(REveElement* el)
{
return el != this && fMap.find(el) == fMap.end() &&
el->IsA()->InheritsFrom(TClass::GetClass<REveSelection>()) == kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Add an element into selection, virtual from REveAunt
void REveSelection::AddNieceInternal(REveElement* el)
{
auto res = fMap.emplace(el, Record(el));
if (fActive) {
DoElementSelect(res.first);
SelectionAdded(el);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Virtual from REveAunt.
void REveSelection::RemoveNieceInternal(REveElement* el)
{
auto i = fMap.find(el);
if (i != fMap.end())
{
if (fActive)
{
DoElementUnselect(i);
SelectionRemoved(el);
}
fMap.erase(i);
}
else
{
Warning("REveSelection::RemoveNieceLocal", "element not found in map.");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add an element into selection, virtual from REveAunt.
/// Overriden here just so that a signal can be emitted.
void REveSelection::RemoveNieces()
{
for (auto i = fMap.begin(); i != fMap.end(); ++i)
{
i->first->RemoveAunt(this);
DoElementUnselect(i);
}
fMap.clear();
SelectionCleared();
}
////////////////////////////////////////////////////////////////////////////////
/// Remove element from all implied-selected sets.
///
/// This is called as part of the element destruction from
/// REveManager::PreDeleteElement() and should not be called
/// directly.
void REveSelection::RemoveImpliedSelected(REveElement *el)
{
for (auto &i : fMap) {
auto j = i.second.f_implied.find(el);
if (j != i.second.f_implied.end())
i.second.f_implied.erase(j);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Recalculate implied-selected state for given selection entry.
/// Add new elements to implied-selected set and increase their
/// implied-selected count.
void REveSelection::RecheckImpliedSet(SelMap_i &smi)
{
Set_t set;
smi->first->FillImpliedSelectedSet(set);
for (auto &i: set)
{
if (smi->second.f_implied.find(i) == smi->second.f_implied.end())
{
smi->second.f_implied.insert(i);
i->IncImpliedSelected();
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// If given element is selected or implied-selected within this
/// selection then recheck implied-set for given selection entry.
void REveSelection::RecheckImpliedSetForElement(REveElement *el)
{
// Top-level selected.
{
auto i = fMap.find(el);
if (i != fMap.end())
RecheckImpliedSet(i);
}
// Implied selected (we can not tell if by this selection or some other),
// then we need to loop over all.
if (el->GetImpliedSelected() > 0)
{
for (auto i = fMap.begin(); i != fMap.end(); ++i)
{
if (i->second.f_implied.find(el) != i->second.f_implied.end())
RecheckImpliedSet(i);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionAdded signal.
void REveSelection::SelectionAdded(REveElement* /*el*/)
{
// XXXX
// Emit("SelectionAdded(REveElement*)", (Long_t)el);
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionRemoved signal.
void REveSelection::SelectionRemoved(REveElement* /*el*/)
{
// XXXX
// Emit("SelectionRemoved(REveElement*)", (Long_t)el);
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionCleared signal.
void REveSelection::SelectionCleared()
{
// XXXX
// Emit("SelectionCleared()");
}
////////////////////////////////////////////////////////////////////////////////
/// Emit SelectionRepeated signal.
void REveSelection::SelectionRepeated(REveElement* /*el*/)
{
// XXXX
// Emit("SelectionRepeated(REveElement*)", (Long_t)el);
}
////////////////////////////////////////////////////////////////////////////////
/// Activate this selection.
void REveSelection::ActivateSelection()
{
if (fActive) return;
fActive = kTRUE;
for (auto i = fMap.begin(); i != fMap.end(); ++i) {
DoElementSelect(i);
SelectionAdded(i->first);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Deactivate this selection.
void REveSelection::DeactivateSelection()
{
if (!fActive) return;
for (auto i = fMap.begin(); i != fMap.end(); ++i) {
DoElementUnselect(i);
}
SelectionCleared();
fActive = kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Given element el that was picked or clicked by the user, find
/// the parent/ancestor element that should actually become the main
/// selected element according to current selection mode.
REveElement* REveSelection::MapPickedToSelected(REveElement* el)
{
if (el == nullptr)
return nullptr;
if (el->ForwardSelection())
{
return el->ForwardSelection();
}
switch (fPickToSelect)
{
case kPS_Ignore:
{
return nullptr;
}
case kPS_Element:
{
return el;
}
case kPS_Projectable:
{
REveProjected* pted = dynamic_cast<REveProjected*>(el);
if (pted)
return dynamic_cast<REveElement*>(pted->GetProjectable());
return el;
}
case kPS_Compound:
{
REveElement* cmpnd = el->GetCompound();
if (cmpnd)
return cmpnd;
return el;
}
case kPS_PableCompound:
{
REveProjected* pted = dynamic_cast<REveProjected*>(el);
if (pted)
el = dynamic_cast<REveElement*>(pted->GetProjectable());
REveElement* cmpnd = el->GetCompound();
if (cmpnd)
return cmpnd;
return el;
}
case kPS_Master:
{
REveElement* mstr = el->GetMaster();
if (mstr)
return mstr;
return el;
}
}
return el;
}
////////////////////////////////////////////////////////////////////////////////
/// Called when user picks/clicks on an element. If multi is true,
/// the user is requiring a multiple selection (usually this is
/// associated with control-key being pressed at the time of pick
/// event).
void REveSelection::UserPickedElement(REveElement* el, Bool_t multi)
{
el = MapPickedToSelected(el);
if (el || HasChildren())
{
if ( ! multi)
RemoveNieces();
if (el)
{
if (HasNiece(el))
RemoveNiece(el);
else
AddNiece(el);
}
if (fIsMaster)
REX::gEve->ElementSelect(el);
REX::gEve->Redraw3D();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Called when element selection is repeated.
void REveSelection::UserRePickedElement(REveElement* el)
{
el = MapPickedToSelected(el);
if (el && HasNiece(el))
{
SelectionRepeated(el);
REX::gEve->Redraw3D();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Called when an element is unselected.
void REveSelection::UserUnPickedElement(REveElement* el)
{
el = MapPickedToSelected(el);
if (el && HasNiece(el))
{
RemoveNiece(el);
REX::gEve->Redraw3D();
}
}
//==============================================================================
void REveSelection::NewElementPicked(ElementId_t id, bool multi, bool secondary, const std::set<int>& secondary_idcs)
{
static const REveException eh("REveSelection::NewElementPicked ");
REveElement *pel = REX::gEve->FindElementById(id);
if ( ! pel) throw eh + "picked element id=" + id + " not found.";
REveElement *el = MapPickedToSelected(pel);
printf("REveSelection::NewElementPicked %p -> %p, multi: %d, secondary: %d", pel, el, multi, secondary);
if (secondary)
{
printf(" { ");
for (auto si : secondary_idcs) printf("%d ", si);
printf("}");
}
printf("\n");
Record *rec = find_record(el);
if (multi)
{
if (el)
{
if (rec)
{
if (secondary || rec->is_secondary()) // ??? should actually be && ???
{
// XXXX union or difference:
// - if all secondary_idcs are already in the record, toggle
// - if final result is empty set, remove element from selection
// - otherwise union
}
else
{
// XXXX remove the existing record
}
}
else
{
// XXXX insert the new record
}
}
else
{
// Multiple selection with 0 element ... do nothing, I think.
}
}
else // single selection (not multi)
{
if (el)
{
if (rec)
{
if (secondary || rec->is_secondary()) // ??? should actually be && ???
{
// if sets are identical, issue SelectionRepeated()
// else modify record for the new one, issue Repeated
}
else
{
// clear selection
// ??? should keep the newly clicked?
}
}
else
{
if (HasNieces()) RemoveNieces();
AddNiece(el);
}
}
else // Single selection with zero element --> clear selection.
{
if (HasNieces()) RemoveNieces();
}
}
StampObjProps();
}
////////////////////////////////////////////////////////////////////////////////
/// Remove pointers to el from implied selected sets.
int REveSelection::RemoveImpliedSelectedReferencesTo(REveElement *el)
{
int count = 0;
for (auto &i : fMap)
{
auto j = i.second.f_implied.find(el);
if (j != i.second.f_implied.end())
{
i.second.f_implied.erase(j);
el->DecImpliedSelected();
++count;
}
}
return count;
}
////////////////////////////////////////////////////////////////////////////////
/// Write core json. If rnr_offset negative, render data will not be written
Int_t REveSelection::WriteCoreJson(nlohmann::json &j, Int_t /* rnr_offset */)
{
REveElement::WriteCoreJson(j, -1);
nlohmann::json sel_list = nlohmann::json::array();
for (auto &i : fMap)
{
nlohmann::json rec = {}, imp = nlohmann::json::array(), sec = nlohmann::json::array();
rec["primary"] = i.first->GetElementId();
// XXX if not empty ???
for (auto &imp_el : i.second.f_implied) imp.push_back(imp_el->GetElementId());
rec["implied"] = imp;
// XXX if not empty / f_is_sec is false ???
for (auto &sec_id : i.second.f_sec_idcs) sec.push_back(sec_id);
rec["sec_idcs"] = sec;
sel_list.push_back(rec);
}
j["sel_list"] = sel_list;
j["UT_PostStream"] = "UT_Selection_Refresh_State"; // XXXX to be canonized
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "threadstackexecutorbase.h"
namespace vespalib {
void
ThreadStackExecutorBase::BlockedThread::wait() const
{
MonitorGuard guard(monitor);
while (blocked) {
guard.wait();
}
}
void
ThreadStackExecutorBase::BlockedThread::unblock()
{
MonitorGuard guard(monitor);
blocked = false;
guard.signal();
}
//-----------------------------------------------------------------------------
void
ThreadStackExecutorBase::block_thread(const LockGuard &, BlockedThread &blocked_thread)
{
auto pos = _blocked.begin();
while ((pos != _blocked.end()) &&
((*pos)->wait_task_count < blocked_thread.wait_task_count))
{
++pos;
}
_blocked.insert(pos, &blocked_thread);
}
void
ThreadStackExecutorBase::unblock_threads(const MonitorGuard &)
{
while (!_blocked.empty() && (_taskCount <= _blocked.back()->wait_task_count)) {
BlockedThread &blocked_thread = *(_blocked.back());
_blocked.pop_back();
blocked_thread.unblock();
}
}
void
ThreadStackExecutorBase::assignTask(const TaggedTask &task, Worker &worker)
{
MonitorGuard monitor(worker.monitor);
assert(worker.idle);
assert(worker.task.task == 0);
worker.idle = false;
worker.task = task;
monitor.signal();
}
bool
ThreadStackExecutorBase::obtainTask(Worker &worker)
{
{
MonitorGuard monitor(_monitor);
if (worker.task.task != 0) {
--_taskCount;
_barrier.completeEvent(worker.task.token);
worker.task.task = 0;
}
unblock_threads(monitor);
if (!_tasks.empty()) {
worker.task = _tasks.front();
_tasks.pop();
wakeup(monitor);
return true;
}
if (_closed) {
return false;
}
worker.idle = true;
_workers.push(&worker);
}
{
MonitorGuard monitor(worker.monitor);
while (worker.idle) {
monitor.wait();
}
}
return (worker.task.task != 0);
}
void
ThreadStackExecutorBase::Run(FastOS_ThreadInterface *, void *)
{
Worker worker;
while (obtainTask(worker)) {
worker.task.task->run();
delete worker.task.task;
}
_executorCompletion.await(); // to allow unsafe signaling
}
//-----------------------------------------------------------------------------
ThreadStackExecutorBase::ThreadStackExecutorBase(uint32_t stackSize,
uint32_t taskLimit)
: _pool(stackSize),
_monitor(),
_stats(),
_executorCompletion(),
_tasks(),
_workers(),
_barrier(),
_taskCount(0),
_taskLimit(taskLimit),
_closed(false)
{
assert(taskLimit > 0);
}
void
ThreadStackExecutorBase::start(uint32_t threads)
{
assert(threads > 0);
for (uint32_t i = 0; i < threads; ++i) {
FastOS_ThreadInterface *thread = _pool.NewThread(this);
assert(thread != 0);
(void)thread;
}
}
void
ThreadStackExecutorBase::internalSetTaskLimit(uint32_t taskLimit)
{
MonitorGuard monitor(_monitor);
_taskLimit = taskLimit;
}
ThreadStackExecutorBase::Stats
ThreadStackExecutorBase::getStats()
{
LockGuard lock(_monitor);
Stats stats = _stats;
_stats = Stats();
_stats.maxPendingTasks = _taskCount;
return stats;
}
ThreadStackExecutorBase::Task::UP
ThreadStackExecutorBase::execute(Task::UP task)
{
MonitorGuard monitor(_monitor);
if (acceptNewTask(monitor)) {
TaggedTask taggedTask(task.release(), _barrier.startEvent());
++_taskCount;
++_stats.acceptedTasks;
_stats.maxPendingTasks = (_taskCount > _stats.maxPendingTasks)
?_taskCount : _stats.maxPendingTasks;
if (!_workers.empty()) {
Worker *worker = _workers.back();
_workers.popBack();
monitor.unlock(); // <- UNLOCK
assignTask(taggedTask, *worker);
} else {
_tasks.push(taggedTask);
}
} else {
++_stats.rejectedTasks;
}
return std::move(task);
}
ThreadStackExecutorBase &
ThreadStackExecutorBase::shutdown()
{
ArrayQueue<Worker*> idle;
{
MonitorGuard monitor(_monitor);
_closed = true;
_taskLimit = 0;
idle.swap(_workers);
assert(idle.empty() || _tasks.empty()); // idle -> empty queue
wakeup(monitor);
}
while (!idle.empty()) {
assignTask(TaggedTask(), *idle.back());
idle.popBack();
}
return *this;
}
ThreadStackExecutorBase &
ThreadStackExecutorBase::sync()
{
BarrierCompletion barrierCompletion;
{
LockGuard lock(_monitor);
if (!_barrier.startBarrier(barrierCompletion)) {
return *this;
}
}
barrierCompletion.gate.await();
return *this;
}
void
ThreadStackExecutorBase::wait_for_task_count(uint32_t task_count)
{
LockGuard lock(_monitor);
if (_taskCount <= task_count) {
return;
}
BlockedThread self(task_count);
block_thread(lock, self);
lock.unlock(); // <- UNLOCK
self.wait();
}
void
ThreadStackExecutorBase::cleanup()
{
shutdown().sync();
_executorCompletion.countDown();
_pool.Close();
}
ThreadStackExecutorBase::~ThreadStackExecutorBase()
{
assert(_pool.isClosed());
assert(_taskCount == 0);
assert(_blocked.empty());
}
} // namespace vespalib
<commit_msg>assert when counting down active tasks<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "threadstackexecutorbase.h"
namespace vespalib {
void
ThreadStackExecutorBase::BlockedThread::wait() const
{
MonitorGuard guard(monitor);
while (blocked) {
guard.wait();
}
}
void
ThreadStackExecutorBase::BlockedThread::unblock()
{
MonitorGuard guard(monitor);
blocked = false;
guard.signal();
}
//-----------------------------------------------------------------------------
void
ThreadStackExecutorBase::block_thread(const LockGuard &, BlockedThread &blocked_thread)
{
auto pos = _blocked.begin();
while ((pos != _blocked.end()) &&
((*pos)->wait_task_count < blocked_thread.wait_task_count))
{
++pos;
}
_blocked.insert(pos, &blocked_thread);
}
void
ThreadStackExecutorBase::unblock_threads(const MonitorGuard &)
{
while (!_blocked.empty() && (_taskCount <= _blocked.back()->wait_task_count)) {
BlockedThread &blocked_thread = *(_blocked.back());
_blocked.pop_back();
blocked_thread.unblock();
}
}
void
ThreadStackExecutorBase::assignTask(const TaggedTask &task, Worker &worker)
{
MonitorGuard monitor(worker.monitor);
assert(worker.idle);
assert(worker.task.task == 0);
worker.idle = false;
worker.task = task;
monitor.signal();
}
bool
ThreadStackExecutorBase::obtainTask(Worker &worker)
{
{
MonitorGuard monitor(_monitor);
if (worker.task.task != 0) {
assert(_taskCount != 0);
worker.task.task = 0;
--_taskCount;
_barrier.completeEvent(worker.task.token);
}
unblock_threads(monitor);
if (!_tasks.empty()) {
worker.task = _tasks.front();
_tasks.pop();
wakeup(monitor);
return true;
}
if (_closed) {
return false;
}
worker.idle = true;
_workers.push(&worker);
}
{
MonitorGuard monitor(worker.monitor);
while (worker.idle) {
monitor.wait();
}
}
return (worker.task.task != 0);
}
void
ThreadStackExecutorBase::Run(FastOS_ThreadInterface *, void *)
{
Worker worker;
while (obtainTask(worker)) {
worker.task.task->run();
delete worker.task.task;
}
_executorCompletion.await(); // to allow unsafe signaling
}
//-----------------------------------------------------------------------------
ThreadStackExecutorBase::ThreadStackExecutorBase(uint32_t stackSize,
uint32_t taskLimit)
: _pool(stackSize),
_monitor(),
_stats(),
_executorCompletion(),
_tasks(),
_workers(),
_barrier(),
_taskCount(0),
_taskLimit(taskLimit),
_closed(false)
{
assert(taskLimit > 0);
}
void
ThreadStackExecutorBase::start(uint32_t threads)
{
assert(threads > 0);
for (uint32_t i = 0; i < threads; ++i) {
FastOS_ThreadInterface *thread = _pool.NewThread(this);
assert(thread != 0);
(void)thread;
}
}
void
ThreadStackExecutorBase::internalSetTaskLimit(uint32_t taskLimit)
{
MonitorGuard monitor(_monitor);
_taskLimit = taskLimit;
}
ThreadStackExecutorBase::Stats
ThreadStackExecutorBase::getStats()
{
LockGuard lock(_monitor);
Stats stats = _stats;
_stats = Stats();
_stats.maxPendingTasks = _taskCount;
return stats;
}
ThreadStackExecutorBase::Task::UP
ThreadStackExecutorBase::execute(Task::UP task)
{
MonitorGuard monitor(_monitor);
if (acceptNewTask(monitor)) {
TaggedTask taggedTask(task.release(), _barrier.startEvent());
++_taskCount;
++_stats.acceptedTasks;
_stats.maxPendingTasks = (_taskCount > _stats.maxPendingTasks)
?_taskCount : _stats.maxPendingTasks;
if (!_workers.empty()) {
Worker *worker = _workers.back();
_workers.popBack();
monitor.unlock(); // <- UNLOCK
assignTask(taggedTask, *worker);
} else {
_tasks.push(taggedTask);
}
} else {
++_stats.rejectedTasks;
}
return std::move(task);
}
ThreadStackExecutorBase &
ThreadStackExecutorBase::shutdown()
{
ArrayQueue<Worker*> idle;
{
MonitorGuard monitor(_monitor);
_closed = true;
_taskLimit = 0;
idle.swap(_workers);
assert(idle.empty() || _tasks.empty()); // idle -> empty queue
wakeup(monitor);
}
while (!idle.empty()) {
assignTask(TaggedTask(), *idle.back());
idle.popBack();
}
return *this;
}
ThreadStackExecutorBase &
ThreadStackExecutorBase::sync()
{
BarrierCompletion barrierCompletion;
{
LockGuard lock(_monitor);
if (!_barrier.startBarrier(barrierCompletion)) {
return *this;
}
}
barrierCompletion.gate.await();
return *this;
}
void
ThreadStackExecutorBase::wait_for_task_count(uint32_t task_count)
{
LockGuard lock(_monitor);
if (_taskCount <= task_count) {
return;
}
BlockedThread self(task_count);
block_thread(lock, self);
lock.unlock(); // <- UNLOCK
self.wait();
}
void
ThreadStackExecutorBase::cleanup()
{
shutdown().sync();
_executorCompletion.countDown();
_pool.Close();
}
ThreadStackExecutorBase::~ThreadStackExecutorBase()
{
assert(_pool.isClosed());
assert(_taskCount == 0);
assert(_blocked.empty());
}
} // namespace vespalib
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 "thrift/lib/cpp2/async/ThreadBoundAdaptorChannel.h"
namespace apache {
namespace thrift {
namespace {
// This callback implementation makes sure that all the callbacks coming from
// the server are executed on this channel's EventBase. This EventBase will be
// passed during the constructor of the channel.
// This is similar to the implementation in PooledRequestChannel.
template <bool oneWay>
class EvbRequestCallback final : public RequestClientCallback {
public:
EvbRequestCallback(
RequestClientCallback::Ptr cb,
folly::Executor::KeepAlive<folly::EventBase> evb)
: evb_(std::move(evb)), cb_(std::move(cb)) {}
void onRequestSent() noexcept override {
if (oneWay) {
evb_->runInEventBaseThread(
[cb = std::move(cb_)]() mutable { cb.release()->onRequestSent(); });
delete this;
} else {
requestSent_ = true;
}
}
void onResponse(ClientReceiveState&& rs) noexcept override {
evb_->runInEventBaseThread([requestSent = requestSent_,
cb = std::move(cb_),
rs = std::move(rs)]() mutable {
if (requestSent) {
cb->onRequestSent();
}
cb.release()->onResponse(std::move(rs));
});
delete this;
}
void onResponseError(folly::exception_wrapper ex) noexcept override {
evb_->runInEventBaseThread([requestSent = requestSent_,
cb = std::move(cb_),
ex = std::move(ex)]() mutable {
if (requestSent) {
cb->onRequestSent();
}
cb.release()->onResponseError(std::move(ex));
});
delete this;
}
private:
bool requestSent_{false};
folly::Executor::KeepAlive<folly::EventBase> evb_;
RequestClientCallback::Ptr cb_;
};
// This implementation of streaming callbacks is making sure that the calls to
// the client and server sides are being made on the proper threads.
//
// When a callback is received from the server, it is scheduled on client's
// eventbase and when a callback is received from the client, it is scheduled on
// server's eventbase.
//
// There is also refCounting logic in here to know when to clean this callback.
class EvbStreamCallback final : public StreamClientCallback,
public StreamServerCallback {
public:
EvbStreamCallback(StreamClientCallback* clientCallback, folly::EventBase* evb)
: clientCallback_(clientCallback),
evb_(folly::Executor::getKeepAliveToken(evb)) {}
// StreamClientCallback
FOLLY_NODISCARD bool onFirstResponse(
FirstResponsePayload&& firstResponse,
folly::EventBase* serverEvb,
StreamServerCallback* serverCallback) noexcept override {
serverEvb_ = folly::Executor::getKeepAliveToken(serverEvb);
setServerCallback(serverCallback);
eventBaseRunHelper(evb_, [&, fr = std::move(firstResponse)]() mutable {
DCHECK(clientCallback_);
std::ignore =
clientCallback_->onFirstResponse(std::move(fr), evb_.get(), this);
});
return true;
}
// Terminating callback. Clean up the client callback stored.
void onFirstResponseError(folly::exception_wrapper ew) noexcept override {
eventBaseRunHelper(evb_, [&, ewr = std::move(ew)]() mutable {
DCHECK(clientCallback_);
clientCallback_->onFirstResponseError(std::move(ewr));
setClientCallback(nullptr);
});
}
bool onStreamNext(StreamPayload&& payload) noexcept override {
eventBaseRunHelper(evb_, [&, pl = std::move(payload)]() mutable {
if (clientCallback_) {
std::ignore = clientCallback_->onStreamNext(std::move(pl));
}
});
return true;
}
// Terminating callback. Clean up the client and server callbacks stored.
void onStreamError(folly::exception_wrapper ew) noexcept override {
eventBaseRunHelper(evb_, [&, ewr = std::move(ew)]() mutable {
if (clientCallback_) {
clientCallback_->onStreamError(std::move(ewr));
setClientCallback(nullptr);
}
});
setServerCallback(nullptr);
}
// Terminating callback. Clean up the client and server callbacks stored.
void onStreamComplete() noexcept override {
eventBaseRunHelper(evb_, [&]() mutable {
if (clientCallback_) {
clientCallback_->onStreamComplete();
setClientCallback(nullptr);
}
});
setServerCallback(nullptr);
}
void resetServerCallback(
StreamServerCallback& serverCallback) noexcept override {
DCHECK(serverCallback_);
DCHECK(&serverCallback);
serverCallback_ = &serverCallback;
}
// StreamServerCallback
// Terminating callback. Clean up the client and server callbacks stored.
void onStreamCancel() noexcept override {
eventBaseRunHelper(serverEvb_, [&]() mutable {
if (serverCallback_) {
serverCallback_->onStreamCancel();
setServerCallback(nullptr);
}
});
setClientCallback(nullptr);
}
bool onStreamRequestN(uint64_t num) noexcept override {
eventBaseRunHelper(serverEvb_, [&]() mutable {
if (serverCallback_) {
std::ignore = serverCallback_->onStreamRequestN(num);
}
});
return true;
}
void resetClientCallback(
StreamClientCallback& clientCallback) noexcept override {
DCHECK(clientCallback_);
DCHECK(&clientCallback);
clientCallback_ = &clientCallback;
}
private:
// Increment the refCount before scheduling on the eventbase and decrement it
// as soon as the eventbase scope is done.
template <typename F>
void eventBaseRunHelper(
folly::Executor::KeepAlive<folly::EventBase> runEvb,
F&& fn) {
incRef();
runEvb->runInEventBaseThread(
[f = std::forward<F>(fn),
g = folly::makeGuard([&] { decRef(); })]() mutable { f(); });
}
void setServerCallback(StreamServerCallback* serverCallback) {
DCHECK(!serverCallback_ != !serverCallback);
serverCallback_ = serverCallback;
if (serverCallback_) {
incRef();
} else {
decRef();
}
}
void setClientCallback(StreamClientCallback* clientCallback) {
DCHECK(clientCallback_);
clientCallback_ = clientCallback;
if (!clientCallback_) {
decRef();
}
}
void incRef() {
refCount_.fetch_add(1, std::memory_order_relaxed);
}
void decRef() {
if (refCount_.fetch_sub(1, std::memory_order_acq_rel) == 1) {
delete this;
}
}
private:
StreamClientCallback* clientCallback_{nullptr};
StreamServerCallback* serverCallback_{nullptr};
folly::Executor::KeepAlive<folly::EventBase> evb_;
folly::Executor::KeepAlive<folly::EventBase> serverEvb_;
// Starting at 1 since the server already has a reference to this when we
// called sendRequestStream().
std::atomic<int64_t> refCount_ = 1;
};
} // namespace
ThreadBoundAdaptorChannel::ThreadBoundAdaptorChannel(
folly::EventBase* evb,
std::shared_ptr<RequestChannel> threadSafeChannel)
: threadSafeChannel_(std::move(threadSafeChannel)), evb_(evb) {
DCHECK(threadSafeChannel_->getEventBase() == nullptr);
}
void ThreadBoundAdaptorChannel::sendRequestResponse(
const RpcOptions& options,
folly::StringPiece methodName,
SerializedRequest&& request,
std::shared_ptr<transport::THeader> header,
RequestClientCallback::Ptr cob) {
cob = RequestClientCallback::Ptr(new EvbRequestCallback<false>(
std::move(cob), folly::Executor::getKeepAliveToken(evb_)));
threadSafeChannel_->sendRequestResponse(
options,
methodName,
std::move(request),
std::move(header),
std::move(cob));
}
void ThreadBoundAdaptorChannel::sendRequestNoResponse(
const RpcOptions& options,
folly::StringPiece methodName,
SerializedRequest&& request,
std::shared_ptr<transport::THeader> header,
RequestClientCallback::Ptr cob) {
cob = RequestClientCallback::Ptr(new EvbRequestCallback<true>(
std::move(cob), folly::Executor::getKeepAliveToken(evb_)));
threadSafeChannel_->sendRequestNoResponse(
options,
methodName,
std::move(request),
std::move(header),
std::move(cob));
}
void ThreadBoundAdaptorChannel::sendRequestStream(
const RpcOptions& options,
folly::StringPiece methodName,
SerializedRequest&& request,
std::shared_ptr<transport::THeader> header,
StreamClientCallback* cob) {
cob = new EvbStreamCallback(std::move(cob), evb_);
threadSafeChannel_->sendRequestStream(
options,
methodName,
std::move(request),
std::move(header),
std::move(cob));
}
void ThreadBoundAdaptorChannel::sendRequestSink(
const RpcOptions& /* options */,
folly::StringPiece /* methodName */,
SerializedRequest&& /* request */,
std::shared_ptr<transport::THeader> /* header */,
SinkClientCallback* /* cob */) {
// Currently not implemented.
LOG(FATAL) << "Not implemented";
}
void ThreadBoundAdaptorChannel::setCloseCallback(CloseCallback* cb) {
threadSafeChannel_->setCloseCallback(cb);
}
folly::EventBase* ThreadBoundAdaptorChannel::getEventBase() const {
return evb_;
}
uint16_t ThreadBoundAdaptorChannel::getProtocolId() {
return threadSafeChannel_->getProtocolId();
}
InteractionId ThreadBoundAdaptorChannel::createInteraction(
folly::StringPiece name) {
return threadSafeChannel_->createInteraction(name);
}
void ThreadBoundAdaptorChannel::terminateInteraction(InteractionId idWrapper) {
threadSafeChannel_->terminateInteraction(std::move(idWrapper));
}
} // namespace thrift
} // namespace apache
<commit_msg>Fix ThreadBoundAdaptorChannel::onStreamRequestN<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 "thrift/lib/cpp2/async/ThreadBoundAdaptorChannel.h"
namespace apache {
namespace thrift {
namespace {
// This callback implementation makes sure that all the callbacks coming from
// the server are executed on this channel's EventBase. This EventBase will be
// passed during the constructor of the channel.
// This is similar to the implementation in PooledRequestChannel.
template <bool oneWay>
class EvbRequestCallback final : public RequestClientCallback {
public:
EvbRequestCallback(
RequestClientCallback::Ptr cb,
folly::Executor::KeepAlive<folly::EventBase> evb)
: evb_(std::move(evb)), cb_(std::move(cb)) {}
void onRequestSent() noexcept override {
if (oneWay) {
evb_->runInEventBaseThread(
[cb = std::move(cb_)]() mutable { cb.release()->onRequestSent(); });
delete this;
} else {
requestSent_ = true;
}
}
void onResponse(ClientReceiveState&& rs) noexcept override {
evb_->runInEventBaseThread([requestSent = requestSent_,
cb = std::move(cb_),
rs = std::move(rs)]() mutable {
if (requestSent) {
cb->onRequestSent();
}
cb.release()->onResponse(std::move(rs));
});
delete this;
}
void onResponseError(folly::exception_wrapper ex) noexcept override {
evb_->runInEventBaseThread([requestSent = requestSent_,
cb = std::move(cb_),
ex = std::move(ex)]() mutable {
if (requestSent) {
cb->onRequestSent();
}
cb.release()->onResponseError(std::move(ex));
});
delete this;
}
private:
bool requestSent_{false};
folly::Executor::KeepAlive<folly::EventBase> evb_;
RequestClientCallback::Ptr cb_;
};
// This implementation of streaming callbacks is making sure that the calls to
// the client and server sides are being made on the proper threads.
//
// When a callback is received from the server, it is scheduled on client's
// eventbase and when a callback is received from the client, it is scheduled on
// server's eventbase.
//
// There is also refCounting logic in here to know when to clean this callback.
class EvbStreamCallback final : public StreamClientCallback,
public StreamServerCallback {
public:
EvbStreamCallback(StreamClientCallback* clientCallback, folly::EventBase* evb)
: clientCallback_(clientCallback),
evb_(folly::Executor::getKeepAliveToken(evb)) {}
// StreamClientCallback
FOLLY_NODISCARD bool onFirstResponse(
FirstResponsePayload&& firstResponse,
folly::EventBase* serverEvb,
StreamServerCallback* serverCallback) noexcept override {
serverEvb_ = folly::Executor::getKeepAliveToken(serverEvb);
setServerCallback(serverCallback);
eventBaseRunHelper(evb_, [&, fr = std::move(firstResponse)]() mutable {
DCHECK(clientCallback_);
std::ignore =
clientCallback_->onFirstResponse(std::move(fr), evb_.get(), this);
});
return true;
}
// Terminating callback. Clean up the client callback stored.
void onFirstResponseError(folly::exception_wrapper ew) noexcept override {
eventBaseRunHelper(evb_, [&, ewr = std::move(ew)]() mutable {
DCHECK(clientCallback_);
clientCallback_->onFirstResponseError(std::move(ewr));
setClientCallback(nullptr);
});
}
bool onStreamNext(StreamPayload&& payload) noexcept override {
eventBaseRunHelper(evb_, [&, pl = std::move(payload)]() mutable {
if (clientCallback_) {
std::ignore = clientCallback_->onStreamNext(std::move(pl));
}
});
return true;
}
// Terminating callback. Clean up the client and server callbacks stored.
void onStreamError(folly::exception_wrapper ew) noexcept override {
eventBaseRunHelper(evb_, [&, ewr = std::move(ew)]() mutable {
if (clientCallback_) {
clientCallback_->onStreamError(std::move(ewr));
setClientCallback(nullptr);
}
});
setServerCallback(nullptr);
}
// Terminating callback. Clean up the client and server callbacks stored.
void onStreamComplete() noexcept override {
eventBaseRunHelper(evb_, [&]() mutable {
if (clientCallback_) {
clientCallback_->onStreamComplete();
setClientCallback(nullptr);
}
});
setServerCallback(nullptr);
}
void resetServerCallback(
StreamServerCallback& serverCallback) noexcept override {
DCHECK(serverCallback_);
DCHECK(&serverCallback);
serverCallback_ = &serverCallback;
}
// StreamServerCallback
// Terminating callback. Clean up the client and server callbacks stored.
void onStreamCancel() noexcept override {
eventBaseRunHelper(serverEvb_, [&]() mutable {
if (serverCallback_) {
serverCallback_->onStreamCancel();
setServerCallback(nullptr);
}
});
setClientCallback(nullptr);
}
bool onStreamRequestN(uint64_t num) noexcept override {
eventBaseRunHelper(serverEvb_, [&, num]() mutable {
if (serverCallback_) {
std::ignore = serverCallback_->onStreamRequestN(num);
}
});
return true;
}
void resetClientCallback(
StreamClientCallback& clientCallback) noexcept override {
DCHECK(clientCallback_);
DCHECK(&clientCallback);
clientCallback_ = &clientCallback;
}
private:
// Increment the refCount before scheduling on the eventbase and decrement it
// as soon as the eventbase scope is done.
template <typename F>
void eventBaseRunHelper(
folly::Executor::KeepAlive<folly::EventBase> runEvb,
F&& fn) {
incRef();
runEvb->runInEventBaseThread(
[f = std::forward<F>(fn),
g = folly::makeGuard([&] { decRef(); })]() mutable { f(); });
}
void setServerCallback(StreamServerCallback* serverCallback) {
DCHECK(!serverCallback_ != !serverCallback);
serverCallback_ = serverCallback;
if (serverCallback_) {
incRef();
} else {
decRef();
}
}
void setClientCallback(StreamClientCallback* clientCallback) {
DCHECK(clientCallback_);
clientCallback_ = clientCallback;
if (!clientCallback_) {
decRef();
}
}
void incRef() {
refCount_.fetch_add(1, std::memory_order_relaxed);
}
void decRef() {
if (refCount_.fetch_sub(1, std::memory_order_acq_rel) == 1) {
delete this;
}
}
private:
StreamClientCallback* clientCallback_{nullptr};
StreamServerCallback* serverCallback_{nullptr};
folly::Executor::KeepAlive<folly::EventBase> evb_;
folly::Executor::KeepAlive<folly::EventBase> serverEvb_;
// Starting at 1 since the server already has a reference to this when we
// called sendRequestStream().
std::atomic<int64_t> refCount_ = 1;
};
} // namespace
ThreadBoundAdaptorChannel::ThreadBoundAdaptorChannel(
folly::EventBase* evb,
std::shared_ptr<RequestChannel> threadSafeChannel)
: threadSafeChannel_(std::move(threadSafeChannel)), evb_(evb) {
DCHECK(threadSafeChannel_->getEventBase() == nullptr);
}
void ThreadBoundAdaptorChannel::sendRequestResponse(
const RpcOptions& options,
folly::StringPiece methodName,
SerializedRequest&& request,
std::shared_ptr<transport::THeader> header,
RequestClientCallback::Ptr cob) {
cob = RequestClientCallback::Ptr(new EvbRequestCallback<false>(
std::move(cob), folly::Executor::getKeepAliveToken(evb_)));
threadSafeChannel_->sendRequestResponse(
options,
methodName,
std::move(request),
std::move(header),
std::move(cob));
}
void ThreadBoundAdaptorChannel::sendRequestNoResponse(
const RpcOptions& options,
folly::StringPiece methodName,
SerializedRequest&& request,
std::shared_ptr<transport::THeader> header,
RequestClientCallback::Ptr cob) {
cob = RequestClientCallback::Ptr(new EvbRequestCallback<true>(
std::move(cob), folly::Executor::getKeepAliveToken(evb_)));
threadSafeChannel_->sendRequestNoResponse(
options,
methodName,
std::move(request),
std::move(header),
std::move(cob));
}
void ThreadBoundAdaptorChannel::sendRequestStream(
const RpcOptions& options,
folly::StringPiece methodName,
SerializedRequest&& request,
std::shared_ptr<transport::THeader> header,
StreamClientCallback* cob) {
cob = new EvbStreamCallback(std::move(cob), evb_);
threadSafeChannel_->sendRequestStream(
options,
methodName,
std::move(request),
std::move(header),
std::move(cob));
}
void ThreadBoundAdaptorChannel::sendRequestSink(
const RpcOptions& /* options */,
folly::StringPiece /* methodName */,
SerializedRequest&& /* request */,
std::shared_ptr<transport::THeader> /* header */,
SinkClientCallback* /* cob */) {
// Currently not implemented.
LOG(FATAL) << "Not implemented";
}
void ThreadBoundAdaptorChannel::setCloseCallback(CloseCallback* cb) {
threadSafeChannel_->setCloseCallback(cb);
}
folly::EventBase* ThreadBoundAdaptorChannel::getEventBase() const {
return evb_;
}
uint16_t ThreadBoundAdaptorChannel::getProtocolId() {
return threadSafeChannel_->getProtocolId();
}
InteractionId ThreadBoundAdaptorChannel::createInteraction(
folly::StringPiece name) {
return threadSafeChannel_->createInteraction(name);
}
void ThreadBoundAdaptorChannel::terminateInteraction(InteractionId idWrapper) {
threadSafeChannel_->terminateInteraction(std::move(idWrapper));
}
} // namespace thrift
} // namespace apache
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.