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 "filehandle.h"
#include "common/continuation/continuation.h"
#include "common/logging.h"
#include "connection/datanodeconnection.h"
#include "reader/block_reader.h"
#include "hdfspp/events.h"
#include <future>
#include <tuple>
#define FMT_THIS_ADDR "this=" << (void*)this
namespace hdfs {
using ::hadoop::hdfs::LocatedBlocksProto;
FileHandle::~FileHandle() {}
FileHandleImpl::FileHandleImpl(const std::string & cluster_name,
const std::string & path,
::asio::io_service *io_service, const std::string &client_name,
const std::shared_ptr<const struct FileInfo> file_info,
std::shared_ptr<BadDataNodeTracker> bad_data_nodes,
std::shared_ptr<LibhdfsEvents> event_handlers)
: cluster_name_(cluster_name), path_(path), io_service_(io_service), client_name_(client_name), file_info_(file_info),
bad_node_tracker_(bad_data_nodes), offset_(0), cancel_state_(CancelTracker::New()), event_handlers_(event_handlers) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::FileHandleImpl("
<< FMT_THIS_ADDR << ", ...) called");
}
void FileHandleImpl::PositionRead(
void *buf, size_t nbyte, uint64_t offset,
const std::function<void(const Status &, size_t)> &handler) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::PositionRead("
<< FMT_THIS_ADDR << ", buf=" << buf
<< ", nbyte=" << nbyte << ") called");
/* prevent usage after cancelation */
if(cancel_state_->is_canceled()) {
handler(Status::Canceled(), 0);
return;
}
auto callback = [this, handler](const Status &status,
const std::string &contacted_datanode,
size_t bytes_read) {
/* determine if DN gets marked bad */
if (ShouldExclude(status)) {
bad_node_tracker_->AddBadNode(contacted_datanode);
}
handler(status, bytes_read);
};
AsyncPreadSome(offset, asio::buffer(buf, nbyte), bad_node_tracker_, callback);
}
Status FileHandleImpl::PositionRead(void *buf, size_t *nbyte, off_t offset) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::[sync]PositionRead("
<< FMT_THIS_ADDR << ", buf=" << buf
<< ", nbyte=" << *nbyte << ") called");
auto callstate = std::make_shared<std::promise<std::tuple<Status, size_t>>>();
std::future<std::tuple<Status, size_t>> future(callstate->get_future());
/* wrap async call with promise/future to make it blocking */
auto callback = [callstate](const Status &s, size_t bytes) {
callstate->set_value(std::make_tuple(s,bytes));
};
PositionRead(buf, *nbyte, offset, callback);
/* wait for async to finish */
auto returnstate = future.get();
auto stat = std::get<0>(returnstate);
if (!stat.ok()) {
return stat;
}
*nbyte = std::get<1>(returnstate);
return stat;
}
Status FileHandleImpl::Read(void *buf, size_t *nbyte) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::Read("
<< FMT_THIS_ADDR << ", buf=" << buf
<< ", nbyte=" << *nbyte << ") called");
Status stat = PositionRead(buf, nbyte, offset_);
if(!stat.ok()) {
return stat;
}
offset_ += *nbyte;
return Status::OK();
}
Status FileHandleImpl::Seek(off_t *offset, std::ios_base::seekdir whence) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::Seek("
<< ", offset=" << *offset << ", ...) called");
if(cancel_state_->is_canceled()) {
return Status::Canceled();
}
off_t new_offset = -1;
switch (whence) {
case std::ios_base::beg:
new_offset = *offset;
break;
case std::ios_base::cur:
new_offset = offset_ + *offset;
break;
case std::ios_base::end:
new_offset = file_info_->file_length_ + *offset;
break;
default:
/* unsupported */
return Status::InvalidArgument("Invalid Seek whence argument");
}
if(!CheckSeekBounds(new_offset)) {
return Status::InvalidArgument("Seek offset out of bounds");
}
offset_ = new_offset;
*offset = offset_;
return Status::OK();
}
/* return false if seek will be out of bounds */
bool FileHandleImpl::CheckSeekBounds(ssize_t desired_position) {
ssize_t file_length = file_info_->file_length_;
if (desired_position < 0 || desired_position > file_length) {
return false;
}
return true;
}
/*
* Note that this method must be thread-safe w.r.t. the unsafe operations occurring
* on the FileHandle
*/
void FileHandleImpl::AsyncPreadSome(
size_t offset, const MutableBuffers &buffers,
std::shared_ptr<NodeExclusionRule> excluded_nodes,
const std::function<void(const Status &, const std::string &, size_t)> handler) {
using ::hadoop::hdfs::DatanodeInfoProto;
using ::hadoop::hdfs::LocatedBlockProto;
LOG_TRACE(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
<< FMT_THIS_ADDR << ", ...) called");
if(cancel_state_->is_canceled()) {
handler(Status::Canceled(), "", 0);
return;
}
/**
* Note: block and chosen_dn will end up pointing to things inside
* the blocks_ vector. They shouldn't be directly deleted.
**/
auto block = std::find_if(
file_info_->blocks_.begin(), file_info_->blocks_.end(), [offset](const LocatedBlockProto &p) {
return p.offset() <= offset && offset < p.offset() + p.b().numbytes();
});
if (block == file_info_->blocks_.end()) {
LOG_WARN(kFileHandle, << "FileHandleImpl::AsyncPreadSome(" << FMT_THIS_ADDR
<< ", ...) Cannot find corresponding blocks");
handler(Status::InvalidArgument("Cannot find corresponding blocks"), "", 0);
return;
}
/**
* If user supplies a rule use it, otherwise use the tracker.
* User is responsible for making sure one of them isn't null.
**/
std::shared_ptr<NodeExclusionRule> rule =
excluded_nodes != nullptr ? excluded_nodes : bad_node_tracker_;
auto datanodes = block->locs();
auto it = std::find_if(datanodes.begin(), datanodes.end(),
[rule](const DatanodeInfoProto &dn) {
return !rule->IsBadNode(dn.id().datanodeuuid());
});
if (it == datanodes.end()) {
LOG_WARN(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
<< FMT_THIS_ADDR << ", ...) No datanodes available");
handler(Status::ResourceUnavailable("No datanodes available"), "", 0);
return;
}
DatanodeInfoProto &chosen_dn = *it;
uint64_t offset_within_block = offset - block->offset();
uint64_t size_within_block = std::min<uint64_t>(
block->b().numbytes() - offset_within_block, asio::buffer_size(buffers));
// This is where we will put the logic for re-using a DN connection; we can
// steal the FileHandle's dn and put it back when we're done
std::shared_ptr<DataNodeConnection> dn = CreateDataNodeConnection(io_service_, chosen_dn, &block->blocktoken());
std::string dn_id = dn->uuid_;
std::string client_name = client_name_;
// Wrap the DN in a block reader to handle the state and logic of the
// block request protocol
std::shared_ptr<BlockReader> reader;
reader = CreateBlockReader(BlockReaderOptions(), dn);
// Lambdas cannot capture copies of member variables so we'll make explicit
// copies for it
auto event_handlers = event_handlers_;
auto path = path_;
auto cluster_name = cluster_name_;
auto read_handler = [reader, event_handlers, cluster_name, path, dn_id, handler](const Status & status, size_t transferred) {
auto event_resp = event_handlers->call(FILE_DN_READ_EVENT, cluster_name.c_str(), path.c_str(), transferred);
#ifndef NDEBUG
if (event_resp.response() == event_response::kTest_Error) {
handler(event_resp.status(), dn_id, transferred);
return;
}
#endif
handler(status, dn_id, transferred);
};
auto connect_handler = [handler,event_handlers,cluster_name,path,read_handler,block,offset_within_block,size_within_block, buffers, reader, dn_id, client_name]
(Status status, std::shared_ptr<DataNodeConnection> dn) {
(void)dn;
auto event_resp = event_handlers->call(FILE_DN_CONNECT_EVENT, cluster_name.c_str(), path.c_str(), 0);
#ifndef NDEBUG
if (event_resp.response() == event_response::kTest_Error) {
status = event_resp.status();
}
#endif
if (status.ok()) {
reader->AsyncReadBlock(
client_name, *block, offset_within_block,
asio::buffer(buffers, size_within_block), read_handler);
} else {
handler(status, dn_id, 0);
}
};
dn->Connect(connect_handler);
return;
}
std::shared_ptr<BlockReader> FileHandleImpl::CreateBlockReader(const BlockReaderOptions &options,
std::shared_ptr<DataNodeConnection> dn)
{
std::shared_ptr<BlockReader> reader = std::make_shared<BlockReaderImpl>(options, dn, cancel_state_);
LOG_TRACE(kFileHandle, << "FileHandleImpl::CreateBlockReader(" << FMT_THIS_ADDR
<< ", ..., dnconn=" << dn.get()
<< ") called. New BlockReader = " << reader.get());
readers_.AddReader(reader);
return reader;
}
std::shared_ptr<DataNodeConnection> FileHandleImpl::CreateDataNodeConnection(
::asio::io_service * io_service,
const ::hadoop::hdfs::DatanodeInfoProto & dn,
const hadoop::common::TokenProto * token) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::CreateDataNodeConnection("
<< FMT_THIS_ADDR << ", ...) called");
return std::make_shared<DataNodeConnectionImpl>(io_service, dn, token, event_handlers_.get());
}
std::shared_ptr<LibhdfsEvents> FileHandleImpl::get_event_handlers() {
return event_handlers_;
}
void FileHandleImpl::CancelOperations() {
LOG_INFO(kFileHandle, << "FileHandleImpl::CancelOperations("
<< FMT_THIS_ADDR << ") called");
cancel_state_->set_canceled();
/* Push update to BlockReaders that may be hung in an asio call */
std::vector<std::shared_ptr<BlockReader>> live_readers = readers_.GetLiveReaders();
for(auto reader : live_readers) {
reader->CancelOperation();
}
}
void FileHandleImpl::SetFileEventCallback(file_event_callback callback) {
std::shared_ptr<LibhdfsEvents> new_event_handlers;
if (event_handlers_) {
new_event_handlers = std::make_shared<LibhdfsEvents>(*event_handlers_);
} else {
new_event_handlers = std::make_shared<LibhdfsEvents>();
}
new_event_handlers->set_file_callback(callback);
event_handlers_ = new_event_handlers;
}
bool FileHandle::ShouldExclude(const Status &s) {
if (s.ok()) {
return false;
}
switch (s.code()) {
/* client side resource exhaustion */
case Status::kResourceUnavailable:
case Status::kOperationCanceled:
return false;
case Status::kInvalidArgument:
case Status::kUnimplemented:
case Status::kException:
default:
return true;
}
}
}
<commit_msg>HDFS-10543: libhdfs++: hdfsRead stops at block boundary. Contributed by Xiaowei Zhu.<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 "filehandle.h"
#include "common/continuation/continuation.h"
#include "common/logging.h"
#include "connection/datanodeconnection.h"
#include "reader/block_reader.h"
#include "hdfspp/events.h"
#include <future>
#include <tuple>
#define FMT_THIS_ADDR "this=" << (void*)this
namespace hdfs {
using ::hadoop::hdfs::LocatedBlocksProto;
FileHandle::~FileHandle() {}
FileHandleImpl::FileHandleImpl(const std::string & cluster_name,
const std::string & path,
::asio::io_service *io_service, const std::string &client_name,
const std::shared_ptr<const struct FileInfo> file_info,
std::shared_ptr<BadDataNodeTracker> bad_data_nodes,
std::shared_ptr<LibhdfsEvents> event_handlers)
: cluster_name_(cluster_name), path_(path), io_service_(io_service), client_name_(client_name), file_info_(file_info),
bad_node_tracker_(bad_data_nodes), offset_(0), cancel_state_(CancelTracker::New()), event_handlers_(event_handlers) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::FileHandleImpl("
<< FMT_THIS_ADDR << ", ...) called");
}
void FileHandleImpl::PositionRead(
void *buf, size_t nbyte, uint64_t offset,
const std::function<void(const Status &, size_t)> &handler) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::PositionRead("
<< FMT_THIS_ADDR << ", buf=" << buf
<< ", nbyte=" << nbyte << ") called");
/* prevent usage after cancelation */
if(cancel_state_->is_canceled()) {
handler(Status::Canceled(), 0);
return;
}
auto callback = [this, handler](const Status &status,
const std::string &contacted_datanode,
size_t bytes_read) {
/* determine if DN gets marked bad */
if (ShouldExclude(status)) {
bad_node_tracker_->AddBadNode(contacted_datanode);
}
handler(status, bytes_read);
};
AsyncPreadSome(offset, asio::buffer(buf, nbyte), bad_node_tracker_, callback);
}
Status FileHandleImpl::PositionRead(void *buf, size_t *nbyte, off_t offset) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::[sync]PositionRead("
<< FMT_THIS_ADDR << ", buf=" << buf
<< ", nbyte=" << *nbyte << ") called");
size_t totalBytesRead = 0;
Status stat = Status::OK();
while (*nbyte != 0 && offset < (off_t)(file_info_->file_length_)) {
auto callstate = std::make_shared<std::promise<std::tuple<Status, size_t>>>();
std::future<std::tuple<Status, size_t>> future(callstate->get_future());
/* wrap async call with promise/future to make it blocking */
auto callback = [callstate](const Status &s, size_t bytes) {
callstate->set_value(std::make_tuple(s,bytes));
};
PositionRead(buf, *nbyte, offset, callback);
/* wait for async to finish */
auto returnstate = future.get();
stat = std::get<0>(returnstate);
if (!stat.ok()) {
return stat;
}
size_t bytesRead = std::get<1>(returnstate);
*nbyte = *nbyte - bytesRead;
totalBytesRead += bytesRead;
offset += bytesRead;
}
/* Update the bytes read for return */
*nbyte = totalBytesRead;
return stat;
}
Status FileHandleImpl::Read(void *buf, size_t *nbyte) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::Read("
<< FMT_THIS_ADDR << ", buf=" << buf
<< ", nbyte=" << *nbyte << ") called");
Status stat = PositionRead(buf, nbyte, offset_);
if(!stat.ok()) {
return stat;
}
offset_ += *nbyte;
return Status::OK();
}
Status FileHandleImpl::Seek(off_t *offset, std::ios_base::seekdir whence) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::Seek("
<< ", offset=" << *offset << ", ...) called");
if(cancel_state_->is_canceled()) {
return Status::Canceled();
}
off_t new_offset = -1;
switch (whence) {
case std::ios_base::beg:
new_offset = *offset;
break;
case std::ios_base::cur:
new_offset = offset_ + *offset;
break;
case std::ios_base::end:
new_offset = file_info_->file_length_ + *offset;
break;
default:
/* unsupported */
return Status::InvalidArgument("Invalid Seek whence argument");
}
if(!CheckSeekBounds(new_offset)) {
return Status::InvalidArgument("Seek offset out of bounds");
}
offset_ = new_offset;
*offset = offset_;
return Status::OK();
}
/* return false if seek will be out of bounds */
bool FileHandleImpl::CheckSeekBounds(ssize_t desired_position) {
ssize_t file_length = file_info_->file_length_;
if (desired_position < 0 || desired_position > file_length) {
return false;
}
return true;
}
/*
* Note that this method must be thread-safe w.r.t. the unsafe operations occurring
* on the FileHandle
*/
void FileHandleImpl::AsyncPreadSome(
size_t offset, const MutableBuffers &buffers,
std::shared_ptr<NodeExclusionRule> excluded_nodes,
const std::function<void(const Status &, const std::string &, size_t)> handler) {
using ::hadoop::hdfs::DatanodeInfoProto;
using ::hadoop::hdfs::LocatedBlockProto;
LOG_TRACE(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
<< FMT_THIS_ADDR << ", ...) called");
if(cancel_state_->is_canceled()) {
handler(Status::Canceled(), "", 0);
return;
}
/**
* Note: block and chosen_dn will end up pointing to things inside
* the blocks_ vector. They shouldn't be directly deleted.
**/
auto block = std::find_if(
file_info_->blocks_.begin(), file_info_->blocks_.end(), [offset](const LocatedBlockProto &p) {
return p.offset() <= offset && offset < p.offset() + p.b().numbytes();
});
if (block == file_info_->blocks_.end()) {
LOG_WARN(kFileHandle, << "FileHandleImpl::AsyncPreadSome(" << FMT_THIS_ADDR
<< ", ...) Cannot find corresponding blocks");
handler(Status::InvalidArgument("Cannot find corresponding blocks"), "", 0);
return;
}
/**
* If user supplies a rule use it, otherwise use the tracker.
* User is responsible for making sure one of them isn't null.
**/
std::shared_ptr<NodeExclusionRule> rule =
excluded_nodes != nullptr ? excluded_nodes : bad_node_tracker_;
auto datanodes = block->locs();
auto it = std::find_if(datanodes.begin(), datanodes.end(),
[rule](const DatanodeInfoProto &dn) {
return !rule->IsBadNode(dn.id().datanodeuuid());
});
if (it == datanodes.end()) {
LOG_WARN(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
<< FMT_THIS_ADDR << ", ...) No datanodes available");
handler(Status::ResourceUnavailable("No datanodes available"), "", 0);
return;
}
DatanodeInfoProto &chosen_dn = *it;
uint64_t offset_within_block = offset - block->offset();
uint64_t size_within_block = std::min<uint64_t>(
block->b().numbytes() - offset_within_block, asio::buffer_size(buffers));
// This is where we will put the logic for re-using a DN connection; we can
// steal the FileHandle's dn and put it back when we're done
std::shared_ptr<DataNodeConnection> dn = CreateDataNodeConnection(io_service_, chosen_dn, &block->blocktoken());
std::string dn_id = dn->uuid_;
std::string client_name = client_name_;
// Wrap the DN in a block reader to handle the state and logic of the
// block request protocol
std::shared_ptr<BlockReader> reader;
reader = CreateBlockReader(BlockReaderOptions(), dn);
// Lambdas cannot capture copies of member variables so we'll make explicit
// copies for it
auto event_handlers = event_handlers_;
auto path = path_;
auto cluster_name = cluster_name_;
auto read_handler = [reader, event_handlers, cluster_name, path, dn_id, handler](const Status & status, size_t transferred) {
auto event_resp = event_handlers->call(FILE_DN_READ_EVENT, cluster_name.c_str(), path.c_str(), transferred);
#ifndef NDEBUG
if (event_resp.response() == event_response::kTest_Error) {
handler(event_resp.status(), dn_id, transferred);
return;
}
#endif
handler(status, dn_id, transferred);
};
auto connect_handler = [handler,event_handlers,cluster_name,path,read_handler,block,offset_within_block,size_within_block, buffers, reader, dn_id, client_name]
(Status status, std::shared_ptr<DataNodeConnection> dn) {
(void)dn;
auto event_resp = event_handlers->call(FILE_DN_CONNECT_EVENT, cluster_name.c_str(), path.c_str(), 0);
#ifndef NDEBUG
if (event_resp.response() == event_response::kTest_Error) {
status = event_resp.status();
}
#endif
if (status.ok()) {
reader->AsyncReadBlock(
client_name, *block, offset_within_block,
asio::buffer(buffers, size_within_block), read_handler);
} else {
handler(status, dn_id, 0);
}
};
dn->Connect(connect_handler);
return;
}
std::shared_ptr<BlockReader> FileHandleImpl::CreateBlockReader(const BlockReaderOptions &options,
std::shared_ptr<DataNodeConnection> dn)
{
std::shared_ptr<BlockReader> reader = std::make_shared<BlockReaderImpl>(options, dn, cancel_state_);
LOG_TRACE(kFileHandle, << "FileHandleImpl::CreateBlockReader(" << FMT_THIS_ADDR
<< ", ..., dnconn=" << dn.get()
<< ") called. New BlockReader = " << reader.get());
readers_.AddReader(reader);
return reader;
}
std::shared_ptr<DataNodeConnection> FileHandleImpl::CreateDataNodeConnection(
::asio::io_service * io_service,
const ::hadoop::hdfs::DatanodeInfoProto & dn,
const hadoop::common::TokenProto * token) {
LOG_TRACE(kFileHandle, << "FileHandleImpl::CreateDataNodeConnection("
<< FMT_THIS_ADDR << ", ...) called");
return std::make_shared<DataNodeConnectionImpl>(io_service, dn, token, event_handlers_.get());
}
std::shared_ptr<LibhdfsEvents> FileHandleImpl::get_event_handlers() {
return event_handlers_;
}
void FileHandleImpl::CancelOperations() {
LOG_INFO(kFileHandle, << "FileHandleImpl::CancelOperations("
<< FMT_THIS_ADDR << ") called");
cancel_state_->set_canceled();
/* Push update to BlockReaders that may be hung in an asio call */
std::vector<std::shared_ptr<BlockReader>> live_readers = readers_.GetLiveReaders();
for(auto reader : live_readers) {
reader->CancelOperation();
}
}
void FileHandleImpl::SetFileEventCallback(file_event_callback callback) {
std::shared_ptr<LibhdfsEvents> new_event_handlers;
if (event_handlers_) {
new_event_handlers = std::make_shared<LibhdfsEvents>(*event_handlers_);
} else {
new_event_handlers = std::make_shared<LibhdfsEvents>();
}
new_event_handlers->set_file_callback(callback);
event_handlers_ = new_event_handlers;
}
bool FileHandle::ShouldExclude(const Status &s) {
if (s.ok()) {
return false;
}
switch (s.code()) {
/* client side resource exhaustion */
case Status::kResourceUnavailable:
case Status::kOperationCanceled:
return false;
case Status::kInvalidArgument:
case Status::kUnimplemented:
case Status::kException:
default:
return true;
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>add a OpenGLContext to unix backend<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: virdev.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2003-12-01 13:24:54 $
*
* 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): _______________________________________
*
*
************************************************************************/
#define _SV_VIRDEV_CXX
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <wrkwin.hxx>
#endif
#ifndef _SV_OUTDEV_H
#include <outdev.h>
#endif
#ifndef _SV_VIRDEV_HXX
#include <virdev.hxx>
#endif
using namespace ::com::sun::star::uno;
// =======================================================================
void VirtualDevice::ImplInitVirDev( const OutputDevice* pOutDev,
long nDX, long nDY, USHORT nBitCount )
{
DBG_ASSERT( nBitCount <= 1,
"VirtualDevice::VirtualDevice(): Only 0 or 1 is for BitCount allowed" );
if ( nDX < 1 )
nDX = 1;
if ( nDY < 1 )
nDY = 1;
ImplSVData* pSVData = ImplGetSVData();
if ( !pOutDev )
pOutDev = ImplGetDefaultWindow();
SalGraphics* pGraphics;
if ( !pOutDev->mpGraphics )
((OutputDevice*)pOutDev)->ImplGetGraphics();
pGraphics = pOutDev->mpGraphics;
if ( pGraphics )
mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( pGraphics, nDX, nDY, nBitCount );
else
mpVirDev = NULL;
if ( !mpVirDev )
GetpApp()->Exception( EXC_SYSOBJNOTCREATED );
mnBitCount = ( nBitCount ? nBitCount : pOutDev->GetBitCount() );
mnOutWidth = nDX;
mnOutHeight = nDY;
mbScreenComp = TRUE;
mbScreenComp = FALSE;
mnAlphaDepth = -1;
if( mnBitCount < 8 )
SetAntialiasing( ANTIALIASING_DISABLE_TEXT );
if ( pOutDev->GetOutDevType() == OUTDEV_PRINTER )
mbScreenComp = FALSE;
else if ( pOutDev->GetOutDevType() == OUTDEV_VIRDEV )
mbScreenComp = ((VirtualDevice*)pOutDev)->mbScreenComp;
meOutDevType = OUTDEV_VIRDEV;
mbDevOutput = TRUE;
mpFontList = pSVData->maGDIData.mpScreenFontList;
mpFontCache = pSVData->maGDIData.mpScreenFontCache;
mnDPIX = pOutDev->mnDPIX;
mnDPIY = pOutDev->mnDPIY;
maFont = pOutDev->maFont;
// Virtuelle Devices haben defaultmaessig einen weissen Hintergrund
SetBackground( Wallpaper( Color( COL_WHITE ) ) );
Erase();
// VirDev in Liste eintragen
mpNext = pSVData->maGDIData.mpFirstVirDev;
mpPrev = NULL;
if ( mpNext )
mpNext->mpPrev = this;
else
pSVData->maGDIData.mpLastVirDev = this;
pSVData->maGDIData.mpFirstVirDev = this;
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount, USHORT nAlphaBitCount )
: mpVirDev( NULL )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
// #110958# Enable alpha channel
mnAlphaDepth = nAlphaBitCount;
}
// -----------------------------------------------------------------------
VirtualDevice::~VirtualDevice()
{
DBG_TRACE( "VirtualDevice::~VirtualDevice()" );
ImplSVData* pSVData = ImplGetSVData();
ImplReleaseGraphics();
if ( mpVirDev )
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
// VirDev aus der Liste eintragen
if( mpPrev )
mpPrev->mpNext = mpNext;
else
pSVData->maGDIData.mpFirstVirDev = mpNext;
if( mpNext )
mpNext->mpPrev = mpPrev;
else
pSVData->maGDIData.mpLastVirDev = mpPrev;
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::ImplSetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
DBG_TRACE3( "VirtualDevice::ImplSetOutputSizePixel( %ld, %ld, %d )", rNewSize.Width(), rNewSize.Height(), (int)bErase );
if ( !mpVirDev )
return FALSE;
else if ( rNewSize == GetOutputSizePixel() )
{
if ( bErase )
Erase();
return TRUE;
}
BOOL bRet;
long nNewWidth = rNewSize.Width(), nNewHeight = rNewSize.Height();
if ( nNewWidth < 1 )
nNewWidth = 1;
if ( nNewHeight < 1 )
nNewHeight = 1;
if ( bErase )
{
bRet = mpVirDev->SetSize( nNewWidth, nNewHeight );
if ( bRet )
{
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
Erase();
}
}
else
{
SalVirtualDevice* pNewVirDev;
ImplSVData* pSVData = ImplGetSVData();
// we need a graphics
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return FALSE;
}
pNewVirDev = pSVData->mpDefInst->CreateVirtualDevice( mpGraphics, nNewWidth, nNewHeight, mnBitCount );
if ( pNewVirDev )
{
SalGraphics* pGraphics = pNewVirDev->GetGraphics();
if ( pGraphics )
{
SalTwoRect aPosAry;
long nWidth;
long nHeight;
if ( mnOutWidth < nNewWidth )
nWidth = mnOutWidth;
else
nWidth = nNewWidth;
if ( mnOutHeight < nNewHeight )
nHeight = mnOutHeight;
else
nHeight = nNewHeight;
aPosAry.mnSrcX = 0;
aPosAry.mnSrcY = 0;
aPosAry.mnSrcWidth = nWidth;
aPosAry.mnSrcHeight = nHeight;
aPosAry.mnDestX = 0;
aPosAry.mnDestY = 0;
aPosAry.mnDestWidth = nWidth;
aPosAry.mnDestHeight = nHeight;
pGraphics->CopyBits( &aPosAry, mpGraphics, this, this );
pNewVirDev->ReleaseGraphics( pGraphics );
ImplReleaseGraphics();
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
mpVirDev = pNewVirDev;
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
bRet = TRUE;
}
else
{
bRet = FALSE;
pSVData->mpDefInst->DestroyVirtualDevice( pNewVirDev );
}
}
else
bRet = FALSE;
}
return bRet;
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
if( ImplSetOutputSizePixel(rNewSize, bErase) )
{
if( mnAlphaDepth != -1 )
{
// #110958# Setup alpha bitmap
if(mpAlphaVDev && mpAlphaVDev->GetOutputSizePixel() != rNewSize)
{
delete mpAlphaVDev;
mpAlphaVDev = 0L;
}
if( !mpAlphaVDev )
{
mpAlphaVDev = new VirtualDevice( *this, mnAlphaDepth );
mpAlphaVDev->ImplSetOutputSizePixel(rNewSize, bErase);
}
// TODO: copy full outdev state to new one, here. Also needed in outdev2.cxx:DrawOutDev
if( GetLineColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetLineColor( COL_BLACK );
if( GetFillColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetFillColor( COL_BLACK );
mpAlphaVDev->SetMapMode( GetMapMode() );
}
return TRUE;
}
return FALSE;
}
// -----------------------------------------------------------------------
void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode )
{
switch( eRefDevMode )
{
case REFDEV_NONE:
default:
DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" );
// fall through
case REFDEV_MODE06:
mnDPIX = mnDPIY = 600;
break;
case REFDEV_MODE48:
mnDPIX = mnDPIY = 4800;
break;
case REFDEV_MODE96:
mnDPIX = mnDPIY = 9600;
break;
}
EnableOutput( FALSE ); // prevent output on reference device
mbScreenComp = FALSE;
// invalidate currently selected fonts
mbInitFont = TRUE;
mbNewFont = TRUE;
// avoid adjusting font lists when already in refdev mode
BYTE nOldRefDevMode = meRefDevMode;
meRefDevMode = (BYTE)eRefDevMode;
if( nOldRefDevMode != REFDEV_NONE )
return;
// the reference device should have only scalable fonts
// => clean up the original font lists before getting new ones
if ( mpFontEntry )
{
mpFontCache->Release( mpFontEntry );
mpFontEntry = NULL;
}
if ( mpGetDevFontList )
{
delete mpGetDevFontList;
mpGetDevFontList = NULL;
}
if ( mpGetDevSizeList )
{
delete mpGetDevSizeList;
mpGetDevSizeList = NULL;
}
// preserve global font lists
ImplSVData* pSVData = ImplGetSVData();
if( mpFontList && (mpFontList != pSVData->maGDIData.mpScreenFontList) )
delete mpFontList;
if( mpFontCache && (mpFontCache != pSVData->maGDIData.mpScreenFontCache) )
delete mpFontCache;
// get font list with scalable fonts only
ImplGetGraphics();
ImplDevFontList* pScalableDevFonts = new ImplDevFontList();
ImplDevFontListData* pData = pSVData->maGDIData.mpScreenFontList->First();
for(; pData; pData = pSVData->maGDIData.mpScreenFontList->Next() )
{
ImplFontData* pEntry = pData->mpFirst;
for(; pEntry; pEntry = pEntry->mpNext )
{
if( (pEntry->meType != TYPE_VECTOR)
&& (pEntry->meType != TYPE_SCALABLE) )
continue;
ImplFontData* pNewData = new ImplFontData();
*pNewData = *pEntry;
pScalableDevFonts->Add( pNewData );
}
}
// prepare to use new font lists
mpFontList = pScalableDevFonts;
mpFontCache = new ImplFontCache( FALSE );
}
// -----------------------------------------------------------------------
// eof
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.13.4); FILE MERGED 2003/12/17 16:05:10 mt 1.13.4.1: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings<commit_after>/*************************************************************************
*
* $RCSfile: virdev.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: vg $ $Date: 2004-01-06 13:57:02 $
*
* 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 _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <wrkwin.hxx>
#endif
#ifndef _SV_OUTDEV_H
#include <outdev.h>
#endif
#ifndef _SV_VIRDEV_HXX
#include <virdev.hxx>
#endif
using namespace ::com::sun::star::uno;
// =======================================================================
void VirtualDevice::ImplInitVirDev( const OutputDevice* pOutDev,
long nDX, long nDY, USHORT nBitCount )
{
DBG_ASSERT( nBitCount <= 1,
"VirtualDevice::VirtualDevice(): Only 0 or 1 is for BitCount allowed" );
if ( nDX < 1 )
nDX = 1;
if ( nDY < 1 )
nDY = 1;
ImplSVData* pSVData = ImplGetSVData();
if ( !pOutDev )
pOutDev = ImplGetDefaultWindow();
SalGraphics* pGraphics;
if ( !pOutDev->mpGraphics )
((OutputDevice*)pOutDev)->ImplGetGraphics();
pGraphics = pOutDev->mpGraphics;
if ( pGraphics )
mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( pGraphics, nDX, nDY, nBitCount );
else
mpVirDev = NULL;
if ( !mpVirDev )
GetpApp()->Exception( EXC_SYSOBJNOTCREATED );
mnBitCount = ( nBitCount ? nBitCount : pOutDev->GetBitCount() );
mnOutWidth = nDX;
mnOutHeight = nDY;
mbScreenComp = TRUE;
mbScreenComp = FALSE;
mnAlphaDepth = -1;
if( mnBitCount < 8 )
SetAntialiasing( ANTIALIASING_DISABLE_TEXT );
if ( pOutDev->GetOutDevType() == OUTDEV_PRINTER )
mbScreenComp = FALSE;
else if ( pOutDev->GetOutDevType() == OUTDEV_VIRDEV )
mbScreenComp = ((VirtualDevice*)pOutDev)->mbScreenComp;
meOutDevType = OUTDEV_VIRDEV;
mbDevOutput = TRUE;
mpFontList = pSVData->maGDIData.mpScreenFontList;
mpFontCache = pSVData->maGDIData.mpScreenFontCache;
mnDPIX = pOutDev->mnDPIX;
mnDPIY = pOutDev->mnDPIY;
maFont = pOutDev->maFont;
// Virtuelle Devices haben defaultmaessig einen weissen Hintergrund
SetBackground( Wallpaper( Color( COL_WHITE ) ) );
Erase();
// VirDev in Liste eintragen
mpNext = pSVData->maGDIData.mpFirstVirDev;
mpPrev = NULL;
if ( mpNext )
mpNext->mpPrev = this;
else
pSVData->maGDIData.mpLastVirDev = this;
pSVData->maGDIData.mpFirstVirDev = this;
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount, USHORT nAlphaBitCount )
: mpVirDev( NULL )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
// #110958# Enable alpha channel
mnAlphaDepth = nAlphaBitCount;
}
// -----------------------------------------------------------------------
VirtualDevice::~VirtualDevice()
{
DBG_TRACE( "VirtualDevice::~VirtualDevice()" );
ImplSVData* pSVData = ImplGetSVData();
ImplReleaseGraphics();
if ( mpVirDev )
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
// VirDev aus der Liste eintragen
if( mpPrev )
mpPrev->mpNext = mpNext;
else
pSVData->maGDIData.mpFirstVirDev = mpNext;
if( mpNext )
mpNext->mpPrev = mpPrev;
else
pSVData->maGDIData.mpLastVirDev = mpPrev;
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::ImplSetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
DBG_TRACE3( "VirtualDevice::ImplSetOutputSizePixel( %ld, %ld, %d )", rNewSize.Width(), rNewSize.Height(), (int)bErase );
if ( !mpVirDev )
return FALSE;
else if ( rNewSize == GetOutputSizePixel() )
{
if ( bErase )
Erase();
return TRUE;
}
BOOL bRet;
long nNewWidth = rNewSize.Width(), nNewHeight = rNewSize.Height();
if ( nNewWidth < 1 )
nNewWidth = 1;
if ( nNewHeight < 1 )
nNewHeight = 1;
if ( bErase )
{
bRet = mpVirDev->SetSize( nNewWidth, nNewHeight );
if ( bRet )
{
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
Erase();
}
}
else
{
SalVirtualDevice* pNewVirDev;
ImplSVData* pSVData = ImplGetSVData();
// we need a graphics
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return FALSE;
}
pNewVirDev = pSVData->mpDefInst->CreateVirtualDevice( mpGraphics, nNewWidth, nNewHeight, mnBitCount );
if ( pNewVirDev )
{
SalGraphics* pGraphics = pNewVirDev->GetGraphics();
if ( pGraphics )
{
SalTwoRect aPosAry;
long nWidth;
long nHeight;
if ( mnOutWidth < nNewWidth )
nWidth = mnOutWidth;
else
nWidth = nNewWidth;
if ( mnOutHeight < nNewHeight )
nHeight = mnOutHeight;
else
nHeight = nNewHeight;
aPosAry.mnSrcX = 0;
aPosAry.mnSrcY = 0;
aPosAry.mnSrcWidth = nWidth;
aPosAry.mnSrcHeight = nHeight;
aPosAry.mnDestX = 0;
aPosAry.mnDestY = 0;
aPosAry.mnDestWidth = nWidth;
aPosAry.mnDestHeight = nHeight;
pGraphics->CopyBits( &aPosAry, mpGraphics, this, this );
pNewVirDev->ReleaseGraphics( pGraphics );
ImplReleaseGraphics();
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
mpVirDev = pNewVirDev;
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
bRet = TRUE;
}
else
{
bRet = FALSE;
pSVData->mpDefInst->DestroyVirtualDevice( pNewVirDev );
}
}
else
bRet = FALSE;
}
return bRet;
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
if( ImplSetOutputSizePixel(rNewSize, bErase) )
{
if( mnAlphaDepth != -1 )
{
// #110958# Setup alpha bitmap
if(mpAlphaVDev && mpAlphaVDev->GetOutputSizePixel() != rNewSize)
{
delete mpAlphaVDev;
mpAlphaVDev = 0L;
}
if( !mpAlphaVDev )
{
mpAlphaVDev = new VirtualDevice( *this, mnAlphaDepth );
mpAlphaVDev->ImplSetOutputSizePixel(rNewSize, bErase);
}
// TODO: copy full outdev state to new one, here. Also needed in outdev2.cxx:DrawOutDev
if( GetLineColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetLineColor( COL_BLACK );
if( GetFillColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetFillColor( COL_BLACK );
mpAlphaVDev->SetMapMode( GetMapMode() );
}
return TRUE;
}
return FALSE;
}
// -----------------------------------------------------------------------
void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode )
{
switch( eRefDevMode )
{
case REFDEV_NONE:
default:
DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" );
// fall through
case REFDEV_MODE06:
mnDPIX = mnDPIY = 600;
break;
case REFDEV_MODE48:
mnDPIX = mnDPIY = 4800;
break;
case REFDEV_MODE96:
mnDPIX = mnDPIY = 9600;
break;
}
EnableOutput( FALSE ); // prevent output on reference device
mbScreenComp = FALSE;
// invalidate currently selected fonts
mbInitFont = TRUE;
mbNewFont = TRUE;
// avoid adjusting font lists when already in refdev mode
BYTE nOldRefDevMode = meRefDevMode;
meRefDevMode = (BYTE)eRefDevMode;
if( nOldRefDevMode != REFDEV_NONE )
return;
// the reference device should have only scalable fonts
// => clean up the original font lists before getting new ones
if ( mpFontEntry )
{
mpFontCache->Release( mpFontEntry );
mpFontEntry = NULL;
}
if ( mpGetDevFontList )
{
delete mpGetDevFontList;
mpGetDevFontList = NULL;
}
if ( mpGetDevSizeList )
{
delete mpGetDevSizeList;
mpGetDevSizeList = NULL;
}
// preserve global font lists
ImplSVData* pSVData = ImplGetSVData();
if( mpFontList && (mpFontList != pSVData->maGDIData.mpScreenFontList) )
delete mpFontList;
if( mpFontCache && (mpFontCache != pSVData->maGDIData.mpScreenFontCache) )
delete mpFontCache;
// get font list with scalable fonts only
ImplGetGraphics();
ImplDevFontList* pScalableDevFonts = new ImplDevFontList();
ImplDevFontListData* pData = pSVData->maGDIData.mpScreenFontList->First();
for(; pData; pData = pSVData->maGDIData.mpScreenFontList->Next() )
{
ImplFontData* pEntry = pData->mpFirst;
for(; pEntry; pEntry = pEntry->mpNext )
{
if( (pEntry->meType != TYPE_VECTOR)
&& (pEntry->meType != TYPE_SCALABLE) )
continue;
ImplFontData* pNewData = new ImplFontData();
*pNewData = *pEntry;
pScalableDevFonts->Add( pNewData );
}
}
// prepare to use new font lists
mpFontList = pScalableDevFonts;
mpFontCache = new ImplFontCache( FALSE );
}
// -----------------------------------------------------------------------
// eof
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: strhelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2003-03-27 17:58:32 $
*
* 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 _SV_STRHELPER_HXX
#define _SV_STRHELPER_HXX
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
String GetCommandLineToken( int, const String& );
// gets one token of a unix command line style string
// doublequote, singlequote and singleleftquote protect their respective
// contents
int GetCommandLineTokenCount( const String& );
// returns number of tokens (zero if empty or whitespace only)
String WhitespaceToSpace( const String&, BOOL bProtect = TRUE );
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.836); FILE MERGED 2005/09/05 14:45:32 rt 1.3.836.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: strhelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:48:58 $
*
* 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 _SV_STRHELPER_HXX
#define _SV_STRHELPER_HXX
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
String GetCommandLineToken( int, const String& );
// gets one token of a unix command line style string
// doublequote, singlequote and singleleftquote protect their respective
// contents
int GetCommandLineTokenCount( const String& );
// returns number of tokens (zero if empty or whitespace only)
String WhitespaceToSpace( const String&, BOOL bProtect = TRUE );
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017, Tier IV, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Autoware 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 <iostream>
#include <thread>
#include <chrono>
#include <map>
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <geometry_msgs/TwistStamped.h>
#include "autoware_msgs/RemoteCmd.h"
#include "autoware_msgs/TwistGate.h"
#include "tablet_socket_msgs/mode_cmd.h"
#include "tablet_socket_msgs/gear_cmd.h"
#include "autoware_msgs/accel_cmd.h"
#include "autoware_msgs/brake_cmd.h"
#include "autoware_msgs/steer_cmd.h"
#include "autoware_msgs/ControlCommandStamped.h"
class TwistGate
{
using remote_msgs_t = autoware_msgs::RemoteCmd;
using twist_gate_msgs_t = autoware_msgs::TwistGate;
public:
TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh);
~TwistGate();
private:
void watchdog_timer();
void remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg);
void auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg);
void auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg);
void auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg);
void auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg);
void auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg);
void auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg);
void auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg);
void reset_select_cmd_msg();
ros::NodeHandle nh_;
ros::NodeHandle private_nh_;
ros::Publisher emergency_stop_pub_;
ros::Publisher select_cmd_pub_;
ros::Subscriber remote_cmd_sub_;
std::map<std::string , ros::Subscriber> auto_cmd_sub_stdmap_;
twist_gate_msgs_t twist_gate_msg_;
std_msgs::Bool emergency_stop_msg_;
ros::Time remote_cmd_time_;
ros::Duration timeout_period_;
std::thread watchdog_timer_thread_;
enum class CommandMode{AUTO=1, REMOTE=2} command_mode_;
};
TwistGate::TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh) :
nh_(nh)
,private_nh_(private_nh)
,timeout_period_(1.0)
,command_mode_(CommandMode::REMOTE)
{
emergency_stop_pub_ = nh_.advertise<std_msgs::Bool>("/emergency_stop", 1, true);
select_cmd_pub_ = nh_.advertise<twist_gate_msgs_t>("/select_cmd", 1, true);
remote_cmd_sub_ = nh_.subscribe("/remote_cmd", 1, &TwistGate::remote_cmd_callback, this);
auto_cmd_sub_stdmap_["twist_cmd"] = nh_.subscribe("/twist_cmd", 1, &TwistGate::auto_cmd_twist_cmd_callback, this);
auto_cmd_sub_stdmap_["mode_cmd"] = nh_.subscribe("/mode_cmd", 1, &TwistGate::auto_cmd_mode_cmd_callback, this);
auto_cmd_sub_stdmap_["gear_cmd"] = nh_.subscribe("/gear_cmd", 1, &TwistGate::auto_cmd_gear_cmd_callback, this);
auto_cmd_sub_stdmap_["accel_cmd"] = nh_.subscribe("/accel_cmd", 1, &TwistGate::auto_cmd_accel_cmd_callback, this);
auto_cmd_sub_stdmap_["steer_cmd"] = nh_.subscribe("/steer_cmd", 1, &TwistGate::auto_cmd_steer_cmd_callback, this);
auto_cmd_sub_stdmap_["brake_cmd"] = nh_.subscribe("/brake_cmd", 1, &TwistGate::auto_cmd_brake_cmd_callback, this);
auto_cmd_sub_stdmap_["ctrl_cmd"] = nh_.subscribe("/ctrl_cmd", 1, &TwistGate::auto_cmd_ctrl_cmd_callback, this);
twist_gate_msg_.header.seq = 0;
emergency_stop_msg_.data = false;
remote_cmd_time_ = ros::Time::now();
watchdog_timer_thread_ = std::thread(&TwistGate::watchdog_timer, this);
watchdog_timer_thread_.detach();
}
TwistGate::~TwistGate()
{
}
void TwistGate::reset_select_cmd_msg()
{
twist_gate_msg_.linear_x = 0;
twist_gate_msg_.angular_z = 0;
twist_gate_msg_.mode = 0;
twist_gate_msg_.gear = 0;
twist_gate_msg_.blinker = 0;
twist_gate_msg_.accel = 0;
twist_gate_msg_.brake = 0;
twist_gate_msg_.steer = 0;
twist_gate_msg_.linear_velocity = -1;
twist_gate_msg_.steering_angle = 0;
}
void TwistGate::watchdog_timer()
{
while(1)
{
ros::Time now_time = ros::Time::now();
bool emergency_flag = false;
// if lost Communication
if(command_mode_ == CommandMode::REMOTE && now_time - remote_cmd_time_ > timeout_period_) {
emergency_flag = true;
std::cout << "Lost Communication!" << std::endl;
}
if(emergency_stop_msg_.data == true)
{
emergency_flag = true;
std::cout << "Emergency Mode!" << std::endl;
}
if(emergency_flag) {
command_mode_ = CommandMode::AUTO;
emergency_stop_msg_.data = true;
emergency_stop_pub_.publish(emergency_stop_msg_);
std::cout << "Emergency Stop!" << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::cout << "c_mode:" << static_cast<int>(command_mode_)
<< " e_stop:" << static_cast<bool>(emergency_stop_msg_.data)
<< " diff_time:" << (now_time - remote_cmd_time_).toSec()
<< std::endl;
}
}
void TwistGate::remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg)
{
command_mode_ = static_cast<CommandMode>(input_msg->control_mode);
emergency_stop_msg_.data = static_cast<bool>(input_msg->emergency);
remote_cmd_time_ = ros::Time::now();
if(command_mode_ == CommandMode::REMOTE)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.linear_x = input_msg->accel;
twist_gate_msg_.angular_z = input_msg->steer;
twist_gate_msg_.steering_angle = input_msg->steer;
twist_gate_msg_.accel = input_msg->accel;
twist_gate_msg_.brake = input_msg->brake;
twist_gate_msg_.steer = input_msg->steer;
twist_gate_msg_.gear = input_msg->gear;
twist_gate_msg_.blinker = input_msg->blinker;
twist_gate_msg_.mode = input_msg->mode;
twist_gate_msg_.emergency = input_msg->emergency;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.linear_x = input_msg->twist.linear.x;
twist_gate_msg_.angular_z = input_msg->twist.angular.z;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
//TODO:check this if statement
if(input_msg->mode == -1 || input_msg->mode == 0){
reset_select_cmd_msg();
}
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.mode = input_msg->mode;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.gear = input_msg->gear;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.accel = input_msg->accel;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.steer = input_msg->steer;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.brake = input_msg->brake;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.linear_velocity = input_msg->cmd.linear_velocity;
twist_gate_msg_.steering_angle = input_msg->cmd.steering_angle;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "twist_gate");
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
TwistGate twist_gate(nh, private_nh);
ros::spin();
return 0;
}
<commit_msg>refactor code and add ctrl mode topic<commit_after>/*
* Copyright (c) 2017, Tier IV, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Autoware 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 <iostream>
#include <thread>
#include <chrono>
#include <map>
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <std_msgs/String.h>
#include <geometry_msgs/TwistStamped.h>
#include "autoware_msgs/RemoteCmd.h"
#include "autoware_msgs/TwistGate.h"
#include "tablet_socket_msgs/mode_cmd.h"
#include "tablet_socket_msgs/gear_cmd.h"
#include "autoware_msgs/accel_cmd.h"
#include "autoware_msgs/brake_cmd.h"
#include "autoware_msgs/steer_cmd.h"
#include "autoware_msgs/ControlCommandStamped.h"
class TwistGate
{
using remote_msgs_t = autoware_msgs::RemoteCmd;
using twist_gate_msgs_t = autoware_msgs::TwistGate;
public:
TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh);
~TwistGate();
private:
void watchdog_timer();
void remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg);
void auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg);
void auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg);
void auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg);
void auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg);
void auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg);
void auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg);
void auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg);
void reset_select_cmd_msg();
ros::NodeHandle nh_;
ros::NodeHandle private_nh_;
ros::Publisher emergency_stop_pub_;
ros::Publisher control_command_pub_;
ros::Publisher select_cmd_pub_;
ros::Subscriber remote_cmd_sub_;
std::map<std::string , ros::Subscriber> auto_cmd_sub_stdmap_;
twist_gate_msgs_t twist_gate_msg_;
std_msgs::Bool emergency_stop_msg_;
ros::Time remote_cmd_time_;
ros::Duration timeout_period_;
std::thread watchdog_timer_thread_;
enum class CommandMode{AUTO=1, REMOTE=2} command_mode_, previous_command_mode_;
std_msgs::String command_mode_topic_;
};
TwistGate::TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh) :
nh_(nh)
,private_nh_(private_nh)
,timeout_period_(1.0)
,command_mode_(CommandMode::AUTO)
,previous_command_mode_(CommandMode::AUTO)
{
emergency_stop_pub_ = nh_.advertise<std_msgs::Bool>("/emergency_stop", 1, true);
control_command_pub_ = nh_.advertise<std_msgs::String>("/ctrl_mode", 1);
select_cmd_pub_ = nh_.advertise<twist_gate_msgs_t>("/select_cmd", 1, true);
remote_cmd_sub_ = nh_.subscribe("/remote_cmd", 1, &TwistGate::remote_cmd_callback, this);
auto_cmd_sub_stdmap_["twist_cmd"] = nh_.subscribe("/twist_cmd", 1, &TwistGate::auto_cmd_twist_cmd_callback, this);
auto_cmd_sub_stdmap_["mode_cmd"] = nh_.subscribe("/mode_cmd", 1, &TwistGate::auto_cmd_mode_cmd_callback, this);
auto_cmd_sub_stdmap_["gear_cmd"] = nh_.subscribe("/gear_cmd", 1, &TwistGate::auto_cmd_gear_cmd_callback, this);
auto_cmd_sub_stdmap_["accel_cmd"] = nh_.subscribe("/accel_cmd", 1, &TwistGate::auto_cmd_accel_cmd_callback, this);
auto_cmd_sub_stdmap_["steer_cmd"] = nh_.subscribe("/steer_cmd", 1, &TwistGate::auto_cmd_steer_cmd_callback, this);
auto_cmd_sub_stdmap_["brake_cmd"] = nh_.subscribe("/brake_cmd", 1, &TwistGate::auto_cmd_brake_cmd_callback, this);
auto_cmd_sub_stdmap_["ctrl_cmd"] = nh_.subscribe("/ctrl_cmd", 1, &TwistGate::auto_cmd_ctrl_cmd_callback, this);
twist_gate_msg_.header.seq = 0;
emergency_stop_msg_.data = false;
remote_cmd_time_ = ros::Time::now();
watchdog_timer_thread_ = std::thread(&TwistGate::watchdog_timer, this);
watchdog_timer_thread_.detach();
}
TwistGate::~TwistGate()
{
}
void TwistGate::reset_select_cmd_msg()
{
twist_gate_msg_.linear_x = 0;
twist_gate_msg_.angular_z = 0;
twist_gate_msg_.mode = 0;
twist_gate_msg_.gear = 0;
twist_gate_msg_.blinker = 0;
twist_gate_msg_.accel = 0;
twist_gate_msg_.brake = 0;
twist_gate_msg_.steer = 0;
twist_gate_msg_.linear_velocity = -1;
twist_gate_msg_.steering_angle = 0;
}
void TwistGate::watchdog_timer()
{
while(1)
{
ros::Time now_time = ros::Time::now();
bool emergency_flag = false;
// check command mode
if(previous_command_mode_ != command_mode_) {
if(command_mode_ == CommandMode::AUTO) {
command_mode_topic_.data = "AUTO";
}
else if(command_mode_ == CommandMode::REMOTE) {
command_mode_topic_.data = "REMOTE";
}
else{
command_mode_topic_.data = "UNDEFINED";
}
control_command_pub_.publish(command_mode_topic_);
previous_command_mode_ = command_mode_;
}
// if lost Communication
if(command_mode_ == CommandMode::REMOTE && now_time - remote_cmd_time_ > timeout_period_) {
emergency_flag = true;
std::cout << "Lost Communication!" << std::endl;
}
// if push emergency stop button
if(emergency_stop_msg_.data == true)
{
emergency_flag = true;
std::cout << "Emergency Mode!" << std::endl;
}
// Emergency
if(emergency_flag) {
command_mode_ = CommandMode::AUTO;
emergency_stop_msg_.data = true;
emergency_stop_pub_.publish(emergency_stop_msg_);
std::cout << "Emergency Stop!" << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void TwistGate::remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg)
{
command_mode_ = static_cast<CommandMode>(input_msg->control_mode);
emergency_stop_msg_.data = static_cast<bool>(input_msg->emergency);
remote_cmd_time_ = ros::Time::now();
if(command_mode_ == CommandMode::REMOTE)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.linear_x = input_msg->accel;
twist_gate_msg_.angular_z = input_msg->steer;
twist_gate_msg_.steering_angle = input_msg->steer;
twist_gate_msg_.accel = input_msg->accel;
twist_gate_msg_.brake = input_msg->brake;
twist_gate_msg_.steer = input_msg->steer;
twist_gate_msg_.gear = input_msg->gear;
twist_gate_msg_.blinker = input_msg->blinker;
twist_gate_msg_.mode = input_msg->mode;
twist_gate_msg_.emergency = input_msg->emergency;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.linear_x = input_msg->twist.linear.x;
twist_gate_msg_.angular_z = input_msg->twist.angular.z;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
//TODO:check this if statement
if(input_msg->mode == -1 || input_msg->mode == 0){
reset_select_cmd_msg();
}
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.mode = input_msg->mode;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.gear = input_msg->gear;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.accel = input_msg->accel;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.steer = input_msg->steer;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.brake = input_msg->brake;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
void TwistGate::auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg)
{
if(command_mode_ == CommandMode::AUTO)
{
twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
twist_gate_msg_.header.stamp = input_msg->header.stamp;
twist_gate_msg_.header.seq++;
twist_gate_msg_.linear_velocity = input_msg->cmd.linear_velocity;
twist_gate_msg_.steering_angle = input_msg->cmd.steering_angle;
select_cmd_pub_.publish(twist_gate_msg_);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "twist_gate");
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
TwistGate twist_gate(nh, private_nh);
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>#include "../Flare.h"
#include "FlareSpacecraftInterface.h"
#include "FlareSpacecraftComponent.h"
#include "../Game/FlareGame.h"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareSpacecraftInterface::UFlareSpacecraftInterface(const class FObjectInitializer& PCIP)
: Super(PCIP)
{
}
/*----------------------------------------------------
Content
----------------------------------------------------*/
const FSlateBrush* IFlareSpacecraftInterface::GetIcon(FFlareSpacecraftDescription* Characteristic)
{
if (Characteristic)
{
if (IFlareSpacecraftInterface::IsStation(Characteristic))
{
return FFlareStyleSet::GetIcon("SS");
}
else if (IFlareSpacecraftInterface::IsMilitary(Characteristic))
{
if (Characteristic->Size == EFlarePartSize::S)
{
return FFlareStyleSet::GetIcon("MS");
}
else if (Characteristic->Size == EFlarePartSize::M)
{
return FFlareStyleSet::GetIcon("MM");
}
else if (Characteristic->Size == EFlarePartSize::L)
{
return FFlareStyleSet::GetIcon("ML");
}
}
else
{
if (Characteristic->Size == EFlarePartSize::S)
{
return FFlareStyleSet::GetIcon("CS");
}
else if (Characteristic->Size == EFlarePartSize::M)
{
return FFlareStyleSet::GetIcon("CM");
}
else if (Characteristic->Size == EFlarePartSize::L)
{
return FFlareStyleSet::GetIcon("CL");
}
}
}
return NULL;
}
bool IFlareSpacecraftInterface::IsStation(FFlareSpacecraftDescription* SpacecraftDesc)
{
return SpacecraftDesc->OrbitalEngineCount == 0;
}
bool IFlareSpacecraftInterface::IsMilitary(FFlareSpacecraftDescription* SpacecraftDesc)
{
return SpacecraftDesc->GunSlots.Num() > 0 || SpacecraftDesc->TurretSlots.Num() > 0;
}
EFlareResourcePriceContext::Type IFlareSpacecraftInterface::GetResourceUseType(FFlareResourceDescription* Resource)
{
// Check we're and station
if (!IsStation())
{
return EFlareResourcePriceContext::Default;
}
FFlareSpacecraftDescription* SpacecraftDescription = GetDescription();
// Parse factories
for (int FactoryIndex = 0; FactoryIndex < SpacecraftDescription->Factories.Num(); FactoryIndex++)
{
FFlareFactoryDescription* FactoryDescription = &SpacecraftDescription->Factories[FactoryIndex]->Data;
// Is input resource of a station ?
for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.InputResources.Num(); ResourceIndex++)
{
const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.InputResources[ResourceIndex];
if (&FactoryResource->Resource->Data == Resource)
{
return EFlareResourcePriceContext::FactoryInput;
}
}
// Is output resource of a station ?
for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.OutputResources.Num(); ResourceIndex++)
{
const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.OutputResources[ResourceIndex];
if (&FactoryResource->Resource->Data == Resource)
{
return EFlareResourcePriceContext::FactoryOutput;
}
}
}
// Customer resource ?
if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Consumer) && GetGame()->GetResourceCatalog()->IsCustomerResource(Resource))
{
return EFlareResourcePriceContext::ConsumerConsumption;
}
// Maintenance resource ?
if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Maintenance) && GetGame()->GetResourceCatalog()->IsMaintenanceResource(Resource))
{
return EFlareResourcePriceContext::MaintenanceConsumption;
}
return EFlareResourcePriceContext::Default;
}
void IFlareSpacecraftInterface::LockResources()
{
GetCargoBay()->UnlockAll();
if (GetDescription()->Factories.Num() > 0)
{
FFlareFactoryDescription* Factory = &GetDescription()->Factories[0]->Data;
for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.InputResources.Num() ; ResourceIndex++)
{
const FFlareFactoryResource* Resource = &Factory->CycleCost.InputResources[ResourceIndex];
if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
{
FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
}
}
for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.OutputResources.Num() ; ResourceIndex++)
{
const FFlareFactoryResource* Resource = &Factory->CycleCost.OutputResources[ResourceIndex];
if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
{
FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
}
}
}
if (HasCapability(EFlareSpacecraftCapability::Consumer))
{
for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->ConsumerResources.Num(); ResourceIndex++)
{
FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->ConsumerResources[ResourceIndex]->Data;
if (!GetCargoBay()->LockSlot(Resource))
{
FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
}
}
}
if (HasCapability(EFlareSpacecraftCapability::Maintenance))
{
for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->MaintenanceResources.Num(); ResourceIndex++)
{
FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->MaintenanceResources[ResourceIndex]->Data;
if (!GetCargoBay()->LockSlot(Resource))
{
FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
}
}
}
}
<commit_msg>Fixed build<commit_after>#include "../Flare.h"
#include "FlareSpacecraftInterface.h"
#include "FlareSpacecraftComponent.h"
#include "../Game/FlareGame.h"
#include "../Economy/FlareCargoBay.h"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareSpacecraftInterface::UFlareSpacecraftInterface(const class FObjectInitializer& PCIP)
: Super(PCIP)
{
}
/*----------------------------------------------------
Content
----------------------------------------------------*/
const FSlateBrush* IFlareSpacecraftInterface::GetIcon(FFlareSpacecraftDescription* Characteristic)
{
if (Characteristic)
{
if (IFlareSpacecraftInterface::IsStation(Characteristic))
{
return FFlareStyleSet::GetIcon("SS");
}
else if (IFlareSpacecraftInterface::IsMilitary(Characteristic))
{
if (Characteristic->Size == EFlarePartSize::S)
{
return FFlareStyleSet::GetIcon("MS");
}
else if (Characteristic->Size == EFlarePartSize::M)
{
return FFlareStyleSet::GetIcon("MM");
}
else if (Characteristic->Size == EFlarePartSize::L)
{
return FFlareStyleSet::GetIcon("ML");
}
}
else
{
if (Characteristic->Size == EFlarePartSize::S)
{
return FFlareStyleSet::GetIcon("CS");
}
else if (Characteristic->Size == EFlarePartSize::M)
{
return FFlareStyleSet::GetIcon("CM");
}
else if (Characteristic->Size == EFlarePartSize::L)
{
return FFlareStyleSet::GetIcon("CL");
}
}
}
return NULL;
}
bool IFlareSpacecraftInterface::IsStation(FFlareSpacecraftDescription* SpacecraftDesc)
{
return SpacecraftDesc->OrbitalEngineCount == 0;
}
bool IFlareSpacecraftInterface::IsMilitary(FFlareSpacecraftDescription* SpacecraftDesc)
{
return SpacecraftDesc->GunSlots.Num() > 0 || SpacecraftDesc->TurretSlots.Num() > 0;
}
EFlareResourcePriceContext::Type IFlareSpacecraftInterface::GetResourceUseType(FFlareResourceDescription* Resource)
{
// Check we're and station
if (!IsStation())
{
return EFlareResourcePriceContext::Default;
}
FFlareSpacecraftDescription* SpacecraftDescription = GetDescription();
// Parse factories
for (int FactoryIndex = 0; FactoryIndex < SpacecraftDescription->Factories.Num(); FactoryIndex++)
{
FFlareFactoryDescription* FactoryDescription = &SpacecraftDescription->Factories[FactoryIndex]->Data;
// Is input resource of a station ?
for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.InputResources.Num(); ResourceIndex++)
{
const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.InputResources[ResourceIndex];
if (&FactoryResource->Resource->Data == Resource)
{
return EFlareResourcePriceContext::FactoryInput;
}
}
// Is output resource of a station ?
for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.OutputResources.Num(); ResourceIndex++)
{
const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.OutputResources[ResourceIndex];
if (&FactoryResource->Resource->Data == Resource)
{
return EFlareResourcePriceContext::FactoryOutput;
}
}
}
// Customer resource ?
if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Consumer) && GetGame()->GetResourceCatalog()->IsCustomerResource(Resource))
{
return EFlareResourcePriceContext::ConsumerConsumption;
}
// Maintenance resource ?
if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Maintenance) && GetGame()->GetResourceCatalog()->IsMaintenanceResource(Resource))
{
return EFlareResourcePriceContext::MaintenanceConsumption;
}
return EFlareResourcePriceContext::Default;
}
void IFlareSpacecraftInterface::LockResources()
{
GetCargoBay()->UnlockAll();
if (GetDescription()->Factories.Num() > 0)
{
FFlareFactoryDescription* Factory = &GetDescription()->Factories[0]->Data;
for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.InputResources.Num() ; ResourceIndex++)
{
const FFlareFactoryResource* Resource = &Factory->CycleCost.InputResources[ResourceIndex];
if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
{
FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
}
}
for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.OutputResources.Num() ; ResourceIndex++)
{
const FFlareFactoryResource* Resource = &Factory->CycleCost.OutputResources[ResourceIndex];
if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
{
FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
}
}
}
if (HasCapability(EFlareSpacecraftCapability::Consumer))
{
for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->ConsumerResources.Num(); ResourceIndex++)
{
FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->ConsumerResources[ResourceIndex]->Data;
if (!GetCargoBay()->LockSlot(Resource))
{
FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
}
}
}
if (HasCapability(EFlareSpacecraftCapability::Maintenance))
{
for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->MaintenanceResources.Num(); ResourceIndex++)
{
FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->MaintenanceResources[ResourceIndex]->Data;
if (!GetCargoBay()->LockSlot(Resource))
{
FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
}
}
}
}
<|endoftext|>
|
<commit_before>/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2009 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/FileTransferChannelCreationProperties>
#include <TelepathyQt4/Global>
#include "TelepathyQt4/debug-internal.h"
#include <QSharedData>
#include <QFileInfo>
#include <QUrl>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT FileTransferChannelCreationProperties::Private : public QSharedData
{
Private(const QString &suggestedFileName, const QString &contentType,
qulonglong size)
: contentType(contentType),
size(size),
contentHashType(FileHashTypeNone)
{
QFileInfo fileInfo(suggestedFileName);
this->suggestedFileName = fileInfo.fileName();
}
Private(const QString &path, const QString &contentType)
: contentType(contentType),
contentHashType(FileHashTypeNone)
{
QFileInfo fileInfo(path);
if (fileInfo.exists()) {
// Set mandatory parameters
suggestedFileName = fileInfo.fileName();
size = fileInfo.size();
QUrl fileUri = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
uri = fileUri.toString();
// Set optional parameters
lastModificationTime = fileInfo.lastModified();
} else {
warning() << path << "is not a local file.";
}
}
/* mandatory parameters */
QString suggestedFileName;
QString contentType;
qulonglong size;
/* optional parameters */
FileHashType contentHashType;
QString contentHash;
QString description;
QDateTime lastModificationTime;
QString uri;
};
/**
* \class FileTransferChannelCreationProperties
* \ingroup clientchannel
* \headerfile TelepathyQt4/file-transfer-channel-creation-properties.h <TelepathyQt4/FileTransferChannelCreationProperties>
*
* \brief The FileTransferChannelCreationProperties class represents the
* properties of a file transfer channel request.
*/
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties()
{
}
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
const QString &suggestedFileName, const QString &contentType,
qulonglong size)
: mPriv(new Private(suggestedFileName, contentType, size))
{
}
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
const QString &path, const QString &contentType)
: mPriv(new Private(path, contentType))
{
if (mPriv->suggestedFileName.isEmpty()) {
mPriv = QSharedDataPointer<Private>(NULL);
}
}
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
const FileTransferChannelCreationProperties &other)
: mPriv(other.mPriv)
{
}
FileTransferChannelCreationProperties::~FileTransferChannelCreationProperties()
{
}
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::operator=(
const FileTransferChannelCreationProperties &other)
{
this->mPriv = other.mPriv;
return *this;
}
bool FileTransferChannelCreationProperties::operator==(
const FileTransferChannelCreationProperties &other) const
{
return mPriv == other.mPriv;
}
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setContentHash(
FileHashType contentHashType, const QString &contentHash)
{
if (!isValid()) {
// there is no point in updating content hash if not valid, as we miss filename, content
// type and size
return *this;
}
mPriv->contentHashType = contentHashType;
mPriv->contentHash = contentHash;
return *this;
}
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setDescription(
const QString &description)
{
if (!isValid()) {
// there is no point in updating description if not valid, as we miss filename, content
// type and size
return *this;
}
mPriv->description = description;
return *this;
}
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setLastModificationTime(
const QDateTime &lastModificationTime)
{
if (!isValid()) {
// there is no point in updating last modification time if not valid, as we miss filename,
// content type and size
return *this;
}
mPriv->lastModificationTime = lastModificationTime;
return *this;
}
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setUri(
const QString &uri)
{
if (!isValid()) {
// there is no point in updating uri if not valid, as we miss filename, content
// type and size
return *this;
}
mPriv->uri = uri;
return *this;
}
QString FileTransferChannelCreationProperties::suggestedFileName() const
{
if (!isValid()) {
return QString();
}
return mPriv->suggestedFileName;
}
QString FileTransferChannelCreationProperties::contentType() const
{
if (!isValid()) {
return QString();
}
return mPriv->contentType;
}
qulonglong FileTransferChannelCreationProperties::size() const
{
if (!isValid()) {
return 0;
}
return mPriv->size;
}
bool FileTransferChannelCreationProperties::hasContentHash() const
{
if (!isValid()) {
return false;
}
return (mPriv->contentHashType != FileHashTypeNone);
}
FileHashType FileTransferChannelCreationProperties::contentHashType() const
{
if (!isValid()) {
return FileHashTypeNone;
}
return mPriv->contentHashType;
}
QString FileTransferChannelCreationProperties::contentHash() const
{
if (!isValid()) {
return QString();
}
return mPriv->contentHash;
}
bool FileTransferChannelCreationProperties::hasDescription() const
{
if (!isValid()) {
return false;
}
return (!mPriv->description.isEmpty());
}
QString FileTransferChannelCreationProperties::description() const
{
if (!isValid()) {
return QString();
}
return mPriv->description;
}
bool FileTransferChannelCreationProperties::hasLastModificationTime() const
{
if (!isValid()) {
return false;
}
return (mPriv->lastModificationTime.isValid());
}
QDateTime FileTransferChannelCreationProperties::lastModificationTime() const
{
if (!isValid()) {
return QDateTime();
}
return mPriv->lastModificationTime;
}
bool FileTransferChannelCreationProperties::hasUri() const
{
if (!isValid()) {
return false;
}
return (!mPriv->uri.isEmpty());
}
QString FileTransferChannelCreationProperties::uri() const
{
if (!isValid()) {
return QString();
}
return mPriv->uri;
}
} // Tp
<commit_msg>Add documentation for class FileTransferChannelCreationProperties<commit_after>/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2009 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/FileTransferChannelCreationProperties>
#include <TelepathyQt4/Global>
#include "TelepathyQt4/debug-internal.h"
#include <QSharedData>
#include <QFileInfo>
#include <QUrl>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT FileTransferChannelCreationProperties::Private : public QSharedData
{
Private(const QString &suggestedFileName, const QString &contentType,
qulonglong size)
: contentType(contentType),
size(size),
contentHashType(FileHashTypeNone)
{
QFileInfo fileInfo(suggestedFileName);
this->suggestedFileName = fileInfo.fileName();
}
Private(const QString &path, const QString &contentType)
: contentType(contentType),
contentHashType(FileHashTypeNone)
{
QFileInfo fileInfo(path);
if (fileInfo.exists()) {
// Set mandatory parameters
suggestedFileName = fileInfo.fileName();
size = fileInfo.size();
QUrl fileUri = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
uri = fileUri.toString();
// Set optional parameters
lastModificationTime = fileInfo.lastModified();
} else {
warning() << path << "is not a local file.";
}
}
/* mandatory parameters */
QString suggestedFileName;
QString contentType;
qulonglong size;
/* optional parameters */
FileHashType contentHashType;
QString contentHash;
QString description;
QDateTime lastModificationTime;
QString uri;
};
/**
* \class FileTransferChannelCreationProperties
* \ingroup clientchannel
* \headerfile TelepathyQt4/file-transfer-channel-creation-properties.h <TelepathyQt4/FileTransferChannelCreationProperties>
*
* \brief The FileTransferChannelCreationProperties class represents the
* properties of a file transfer channel request.
*/
/**
* Create an invalid FileTransferChannelCreationProperties.
*/
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties()
{
}
/**
* Create a FileTransferChannelCreationProperties.
*
* If \a suggestedFileName or \a contentType are empty or if \a size is equal to
* zero, the channel request will fail.
* \a suggestedFileName will be cleaned of any path.
*
* \param suggestedFileName The name of the file on the sender's side. This is
* therefore given as a suggested filename for the
* receiver.
* \param contentType The content type (MIME) of the file.
* \param size The size of the content of the file.
* \sa setUri()
*/
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
const QString &suggestedFileName, const QString &contentType,
qulonglong size)
: mPriv(new Private(suggestedFileName, contentType, size))
{
}
/**
* Create a FileTransferChannelCreationProperties.
*
* This constructor accepts the path to a local file and sets the properties
* that can be deducted from the file.
* If \a path is not a local file the FileTransferChannelCreationProperties
* will be invalid.
*
* \param path The path to the local file to be sent.
*/
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
const QString &path, const QString &contentType)
: mPriv(new Private(path, contentType))
{
if (mPriv->suggestedFileName.isEmpty()) {
mPriv = QSharedDataPointer<Private>(NULL);
}
}
/**
* Copy constructor.
*/
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
const FileTransferChannelCreationProperties &other)
: mPriv(other.mPriv)
{
}
/**
* Class destructor.
*/
FileTransferChannelCreationProperties::~FileTransferChannelCreationProperties()
{
}
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::operator=(
const FileTransferChannelCreationProperties &other)
{
this->mPriv = other.mPriv;
return *this;
}
bool FileTransferChannelCreationProperties::operator==(
const FileTransferChannelCreationProperties &other) const
{
return mPriv == other.mPriv;
}
/**
* Set the content hash of the file and its type for the request.
*
* \param contentHashType The type of content hash.
* \param contentHash The hash of the file, of type \a contentHashType.
* \return This FileTransferChannelCreationProperties.
* \sa hasContentHash(), contentHash(), contentHashType()
*/
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setContentHash(
FileHashType contentHashType, const QString &contentHash)
{
if (!isValid()) {
// there is no point in updating content hash if not valid, as we miss filename, content
// type and size
return *this;
}
mPriv->contentHashType = contentHashType;
mPriv->contentHash = contentHash;
return *this;
}
/**
* Set a description of the file for the request.
*
* \param description The description of the file.
* \return This FileTransferChannelCreationProperties.
* \sa hasDescription(), description()
*/
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setDescription(
const QString &description)
{
if (!isValid()) {
// there is no point in updating description if not valid, as we miss filename, content
// type and size
return *this;
}
mPriv->description = description;
return *this;
}
/**
* Set the last modification time of the file for the request.
*
* \param lastModificationTime The last modification time of the file.
* \return This FileTransferChannelCreationProperties.
* \sa hasLastModificationTime(), lastModificationTime()
*/
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setLastModificationTime(
const QDateTime &lastModificationTime)
{
if (!isValid()) {
// there is no point in updating last modification time if not valid, as we miss filename,
// content type and size
return *this;
}
mPriv->lastModificationTime = lastModificationTime;
return *this;
}
/**
* Set the URI of the file for the request.
*
* \param uri The URI of the file.
* \return This FileTransferChannelCreationProperties.
* \sa uri()
*/
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setUri(
const QString &uri)
{
if (!isValid()) {
// there is no point in updating uri if not valid, as we miss filename, content
// type and size
return *this;
}
mPriv->uri = uri;
return *this;
}
/**
* Return the suggested file name for the request.
* If the suggested file name is empty, the channel request will fail.
*
* \return The suggested file name for the request.
*/
QString FileTransferChannelCreationProperties::suggestedFileName() const
{
if (!isValid()) {
return QString();
}
return mPriv->suggestedFileName;
}
/**
* Return the content type (MIME) of the file for the request.
* If the content type is empty, the channel request will fail.
*
* \return The content type of the file.
*/
QString FileTransferChannelCreationProperties::contentType() const
{
if (!isValid()) {
return QString();
}
return mPriv->contentType;
}
/**
* Return the size of the contents of the file for the request.
* If size is zero, the channel request will fail.
*
* \return The size of the contents of file.
*/
qulonglong FileTransferChannelCreationProperties::size() const
{
if (!isValid()) {
return 0;
}
return mPriv->size;
}
/**
* Return whether the request will have a content hash.
*
* \return \c true whether it will have a content hash, \c false otherwise.
* \sa contentHash(), contentHashType(), setContentHash()
*/
bool FileTransferChannelCreationProperties::hasContentHash() const
{
if (!isValid()) {
return false;
}
return (mPriv->contentHashType != FileHashTypeNone);
}
/**
* Return the type of the content hash for the request.
*
* \return The type of the content hash.
* \sa hasContentHash(), contentHash(), setContentHash()
*/
FileHashType FileTransferChannelCreationProperties::contentHashType() const
{
if (!isValid()) {
return FileHashTypeNone;
}
return mPriv->contentHashType;
}
/**
* Return the content hash of the file for the request.
*
* \return The hash of the contents of the file transfer, of type returned by
* contentHashType().
* \sa hasContentHash(), contentHashType(), setContentHash()
*/
QString FileTransferChannelCreationProperties::contentHash() const
{
if (!isValid()) {
return QString();
}
return mPriv->contentHash;
}
/**
* Return whether the request will have a descriprion.
*
* \return \c true whether it will have description, \c false otherwise.
* \sa description(), setDescription()
*/
bool FileTransferChannelCreationProperties::hasDescription() const
{
if (!isValid()) {
return false;
}
return (!mPriv->description.isEmpty());
}
/**
* Return the description of the file for the request.
*
* \return The description of the file.
* \sa hasDescription(), setDescription()
*/
QString FileTransferChannelCreationProperties::description() const
{
if (!isValid()) {
return QString();
}
return mPriv->description;
}
/**
* Return whether the request will have a last modification time.
*
* \return \c true whether it will have a last modification time, \c false
* otherwise.
* \sa lastModificationTime(), setLastModificationTime()
*/
bool FileTransferChannelCreationProperties::hasLastModificationTime() const
{
if (!isValid()) {
return false;
}
return (mPriv->lastModificationTime.isValid());
}
/**
* Return the last modification time of the file for the request.
*
* \return The last modification time of the file.
* \sa hasLastModificationTime(), setLastModificationTime()
*/
QDateTime FileTransferChannelCreationProperties::lastModificationTime() const
{
if (!isValid()) {
return QDateTime();
}
return mPriv->lastModificationTime;
}
/**
* Return whether the request will have an URI.
*
* \return \c true whether it will have URI, \c false otherwise.
* \sa uri(), setUri()
*/
bool FileTransferChannelCreationProperties::hasUri() const
{
if (!isValid()) {
return false;
}
return (!mPriv->uri.isEmpty());
}
/**
* Return the URI of the file for the request.
* If the URI property is empty and the file transfer is handled by an handler
* that is not this process, then it won't be able to initiate the file
* transfer.
*
* \return The URI of the file.
* \sa setUri()
*/
QString FileTransferChannelCreationProperties::uri() const
{
if (!isValid()) {
return QString();
}
return mPriv->uri;
}
} // Tp
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "Basics/init.h"
#include "Basics/logging.h"
#include "Basics/random.h"
#include "Basics/tri-strings.h"
#include "Basics/string-buffer.h"
#include "Basics/terminal-utils.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient("arangob");
////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////
static atomic<int> Started;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////
Mutex StartMutex;
////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////
static bool Async = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////
static int BatchSize = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////
static string Collection = "ArangoBenchmark";
////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////
static uint64_t Complexity = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////
static int Concurrency = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////
static bool Delay = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////
static bool KeepAlive = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////
static int Operations = 1000;
////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////
static string TestCase = "version";
////////////////////////////////////////////////////////////////////////////////
/// @brief print out replies on error
////////////////////////////////////////////////////////////////////////////////
static bool verbose = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////
#include "Benchmark/test-cases.h"
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////
static void UpdateStartCounter () {
++Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////
static int GetStartCounter () {
return Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////
static void Status (const string& value) {
if (! BaseClient.quiet()) {
cout << value << endl;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription description("STANDARD options");
description
("async", &Async, "send asychronous requests")
("concurrency", &Concurrency, "number of parallel connections")
("requests", &Operations, "total number of operations")
("batch-size", &BatchSize, "number of operations in one batch (0 disables batching)")
("keep-alive", &KeepAlive, "use HTTP keep-alive")
("collection", &Collection, "collection name to use in tests")
("test-case", &TestCase, "test case to use (possible values: version, document, collection, import-document, hash, skiplist, edge, shapes, shapes-append, random-shapes, crud, crud-append, crud-write-read, aqltrx, counttrx, multitrx, multi-collection, aqlinsert)")
("complexity", &Complexity, "complexity parameter for the test")
("delay", &Delay, "use a startup delay (necessary only when run in series)")
("progress", &Progress, "show progress")
("verbose", &verbose, "print out replies if the http-header indicates db-errors")
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, "--concurrency <concurrency> --requests <request> --test-case <case> ...", argc, argv, "arangob.conf");
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief startup and exit functions
////////////////////////////////////////////////////////////////////////////////
static void arangobEntryFunction ();
static void arangobExitFunction (int, void*);
#ifdef _WIN32
// .............................................................................
// Call this function to do various initialisations for windows only
// .............................................................................
void arangobEntryFunction () {
int maxOpenFiles = 1024;
int res = 0;
// ...........................................................................
// Uncomment this to call this for extended debug information.
// If you familiar with valgrind ... then this is not like that, however
// you do get some similar functionality.
// ...........................................................................
//res = initialiseWindows(TRI_WIN_INITIAL_SET_DEBUG_FLAG, 0);
res = initialiseWindows(TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER, 0);
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_SET_MAX_STD_IO,(const char*)(&maxOpenFiles));
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
_exit(1);
}
TRI_Application_Exit_SetExit(arangobExitFunction);
}
static void arangobExitFunction (int exitCode, void* data) {
int res = 0;
// ...........................................................................
// TODO: need a terminate function for windows to be called and cleanup
// any windows specific stuff.
// ...........................................................................
res = finaliseWindows(TRI_WIN_FINAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
exit(1);
}
exit(exitCode);
}
#else
static void arangobEntryFunction () {
}
static void arangobExitFunction (int exitCode, void* data) {
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int ret = EXIT_SUCCESS;
arangobEntryFunction();
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == nullptr) {
LOG_FATAL_AND_EXIT("invalid value for --server.endpoint ('%s')", BaseClient.endpointString().c_str());
}
BenchmarkOperation* testCase = GetTestCase(TestCase);
if (testCase == nullptr) {
LOG_FATAL_AND_EXIT("invalid test case name '%s'", TestCase.c_str());
return EXIT_FAILURE; // will not be reached
}
Status("starting threads...");
BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
ConditionVariable startCondition;
vector<Endpoint*> endpoints;
vector<BenchmarkThread*> threads;
const double stepSize = (double) Operations / (double) Concurrency;
int64_t realStep = (int64_t) stepSize;
if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
realStep++;
}
if (realStep % 1000 != 0) {
realStep += 1000 - (realStep % 1000);
}
// add some more offset so we don't get into trouble with threads of different speed
realStep += 10000;
// start client threads
for (int i = 0; i < Concurrency; ++i) {
Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
endpoints.push_back(endpoint);
BenchmarkThread* thread = new BenchmarkThread(testCase,
&startCondition,
&UpdateStartCounter,
i,
(unsigned long) BatchSize,
&operationsCounter,
endpoint,
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
BaseClient.sslProtocol(),
KeepAlive,
Async,
verbose);
threads.push_back(thread);
thread->setOffset((size_t) (i * realStep));
thread->start();
}
// give all threads a chance to start so they will not miss the broadcast
while (GetStartCounter() < Concurrency) {
usleep(5000);
}
if (Delay) {
Status("sleeping (startup delay)...");
sleep(10);
}
Status("executing tests...");
double start = TRI_microtime();
// broadcast the start signal to all threads
{
ConditionLocker guard(&startCondition);
guard.broadcast();
}
const size_t stepValue = (Operations / 20);
size_t nextReportValue = stepValue;
if (nextReportValue < 100) {
nextReportValue = 100;
}
while (1) {
const size_t numOperations = operationsCounter.getDone();
if (numOperations >= (size_t) Operations) {
break;
}
if (Progress && numOperations >= nextReportValue) {
LOG_INFO("number of operations: %d", (int) nextReportValue);
nextReportValue += stepValue;
}
usleep(20000);
}
double time = TRI_microtime() - start;
double requestTime = 0.0;
for (int i = 0; i < Concurrency; ++i) {
requestTime += threads[i]->getTime();
}
size_t failures = operationsCounter.failures();
size_t incomplete = operationsCounter.incompleteFailures();
cout << endl;
cout << "Total number of operations: " << Operations <<
", keep alive: " << (KeepAlive ? "yes" : "no") <<
", async: " << (Async ? "yes" : "no") <<
", batch size: " << BatchSize <<
", concurrency level (threads): " << Concurrency <<
endl;
cout << "Test case: " << TestCase <<
", complexity: " << Complexity <<
", database: '" << BaseClient.databaseName() <<
"', collection: '" << Collection << "'" <<
endl;
cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;
if (failures > 0) {
cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
}
if (incomplete > 0) {
cerr << "WARNING: " << incomplete << " arangob requests with incomplete results!!" << endl;
}
testCase->tearDown();
for (int i = 0; i < Concurrency; ++i) {
threads[i]->join();
delete threads[i];
delete endpoints[i];
}
delete testCase;
TRIAGENS_REST_SHUTDOWN;
if (failures > 0) {
ret = EXIT_FAILURE;
}
arangobExitFunction(ret, nullptr);
return ret;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>resolve conflict with namespace "Concurrency", introduced by MS on top-level...<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "Basics/init.h"
#include "Basics/logging.h"
#include "Basics/random.h"
#include "Basics/tri-strings.h"
#include "Basics/string-buffer.h"
#include "Basics/terminal-utils.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient("arangob");
////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////
static atomic<int> Started;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////
Mutex StartMutex;
////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////
static bool Async = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////
static int BatchSize = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////
static string Collection = "ArangoBenchmark";
////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////
static uint64_t Complexity = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////
static int ThreadConcurrency = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////
static bool Delay = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////
static bool KeepAlive = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////
static int Operations = 1000;
////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////
static string TestCase = "version";
////////////////////////////////////////////////////////////////////////////////
/// @brief print out replies on error
////////////////////////////////////////////////////////////////////////////////
static bool verbose = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////
#include "Benchmark/test-cases.h"
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////
static void UpdateStartCounter () {
++Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////
static int GetStartCounter () {
return Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////
static void Status (const string& value) {
if (! BaseClient.quiet()) {
cout << value << endl;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription description("STANDARD options");
description
("async", &Async, "send asychronous requests")
("concurrency", &ThreadConcurrency, "number of parallel connections")
("requests", &Operations, "total number of operations")
("batch-size", &BatchSize, "number of operations in one batch (0 disables batching)")
("keep-alive", &KeepAlive, "use HTTP keep-alive")
("collection", &Collection, "collection name to use in tests")
("test-case", &TestCase, "test case to use (possible values: version, document, collection, import-document, hash, skiplist, edge, shapes, shapes-append, random-shapes, crud, crud-append, crud-write-read, aqltrx, counttrx, multitrx, multi-collection, aqlinsert)")
("complexity", &Complexity, "complexity parameter for the test")
("delay", &Delay, "use a startup delay (necessary only when run in series)")
("progress", &Progress, "show progress")
("verbose", &verbose, "print out replies if the http-header indicates db-errors")
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, "--concurrency <concurrency> --requests <request> --test-case <case> ...", argc, argv, "arangob.conf");
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief startup and exit functions
////////////////////////////////////////////////////////////////////////////////
static void arangobEntryFunction ();
static void arangobExitFunction (int, void*);
#ifdef _WIN32
// .............................................................................
// Call this function to do various initialisations for windows only
// .............................................................................
void arangobEntryFunction () {
int maxOpenFiles = 1024;
int res = 0;
// ...........................................................................
// Uncomment this to call this for extended debug information.
// If you familiar with valgrind ... then this is not like that, however
// you do get some similar functionality.
// ...........................................................................
//res = initialiseWindows(TRI_WIN_INITIAL_SET_DEBUG_FLAG, 0);
res = initialiseWindows(TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER, 0);
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_SET_MAX_STD_IO,(const char*)(&maxOpenFiles));
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
_exit(1);
}
TRI_Application_Exit_SetExit(arangobExitFunction);
}
static void arangobExitFunction (int exitCode, void* data) {
int res = 0;
// ...........................................................................
// TODO: need a terminate function for windows to be called and cleanup
// any windows specific stuff.
// ...........................................................................
res = finaliseWindows(TRI_WIN_FINAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
exit(1);
}
exit(exitCode);
}
#else
static void arangobEntryFunction () {
}
static void arangobExitFunction (int exitCode, void* data) {
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int ret = EXIT_SUCCESS;
arangobEntryFunction();
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == nullptr) {
LOG_FATAL_AND_EXIT("invalid value for --server.endpoint ('%s')", BaseClient.endpointString().c_str());
}
BenchmarkOperation* testCase = GetTestCase(TestCase);
if (testCase == nullptr) {
LOG_FATAL_AND_EXIT("invalid test case name '%s'", TestCase.c_str());
return EXIT_FAILURE; // will not be reached
}
Status("starting threads...");
BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
ConditionVariable startCondition;
vector<Endpoint*> endpoints;
vector<BenchmarkThread*> threads;
const double stepSize = (double) Operations / (double) ThreadConcurrency;
int64_t realStep = (int64_t) stepSize;
if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
realStep++;
}
if (realStep % 1000 != 0) {
realStep += 1000 - (realStep % 1000);
}
// add some more offset so we don't get into trouble with threads of different speed
realStep += 10000;
// start client threads
for (int i = 0; i < ThreadConcurrency; ++i) {
Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
endpoints.push_back(endpoint);
BenchmarkThread* thread = new BenchmarkThread(testCase,
&startCondition,
&UpdateStartCounter,
i,
(unsigned long) BatchSize,
&operationsCounter,
endpoint,
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
BaseClient.sslProtocol(),
KeepAlive,
Async,
verbose);
threads.push_back(thread);
thread->setOffset((size_t) (i * realStep));
thread->start();
}
// give all threads a chance to start so they will not miss the broadcast
while (GetStartCounter() < ThreadConcurrency) {
usleep(5000);
}
if (Delay) {
Status("sleeping (startup delay)...");
sleep(10);
}
Status("executing tests...");
double start = TRI_microtime();
// broadcast the start signal to all threads
{
ConditionLocker guard(&startCondition);
guard.broadcast();
}
const size_t stepValue = (Operations / 20);
size_t nextReportValue = stepValue;
if (nextReportValue < 100) {
nextReportValue = 100;
}
while (1) {
const size_t numOperations = operationsCounter.getDone();
if (numOperations >= (size_t) Operations) {
break;
}
if (Progress && numOperations >= nextReportValue) {
LOG_INFO("number of operations: %d", (int) nextReportValue);
nextReportValue += stepValue;
}
usleep(20000);
}
double time = TRI_microtime() - start;
double requestTime = 0.0;
for (int i = 0; i < ThreadConcurrency; ++i) {
requestTime += threads[i]->getTime();
}
size_t failures = operationsCounter.failures();
size_t incomplete = operationsCounter.incompleteFailures();
cout << endl;
cout << "Total number of operations: " << Operations <<
", keep alive: " << (KeepAlive ? "yes" : "no") <<
", async: " << (Async ? "yes" : "no") <<
", batch size: " << BatchSize <<
", concurrency level (threads): " << ThreadConcurrency <<
endl;
cout << "Test case: " << TestCase <<
", complexity: " << Complexity <<
", database: '" << BaseClient.databaseName() <<
"', collection: '" << Collection << "'" <<
endl;
cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) ThreadConcurrency) << " s" << endl;
cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) ThreadConcurrency) << " s" << endl;
cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;
if (failures > 0) {
cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
}
if (incomplete > 0) {
cerr << "WARNING: " << incomplete << " arangob requests with incomplete results!!" << endl;
}
testCase->tearDown();
for (int i = 0; i < ThreadConcurrency; ++i) {
threads[i]->join();
delete threads[i];
delete endpoints[i];
}
delete testCase;
TRIAGENS_REST_SHUTDOWN;
if (failures > 0) {
ret = EXIT_FAILURE;
}
arangobExitFunction(ret, nullptr);
return ret;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>
|
<commit_before>/* Computes the gradient magnitude after convolving with a Gaussian kernel.
It uses IIR filter for approximating the convolution */
#include "vvITKFilterModule.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
const unsigned int Dimension = 3;
try
{
switch( info->InputVolumeScalarType )
{
case VTK_UNSIGNED_CHAR:
{
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, ImageType > FilterType;
VolView::PlugIn::FilterModule< FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Computing the gradient magnitude...");
// Set the parameters on it
module.GetFilter()->SetSigma( atof( info->GUIItems[ 0 ].CurrentValue) );
// Execute the filter
module.ProcessData( pds );
break;
}
case VTK_UNSIGNED_SHORT:
{
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, ImageType > FilterType;
VolView::PlugIn::FilterModule< FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Computing the gradient magnitude...");
// Set the parameters on it
module.GetFilter()->SetSigma( atof( info->GUIItems[ 0 ].CurrentValue) );
// Execute the filter
module.ProcessData( pds );
break;
}
}
}
catch( itk::ExceptionObject & except )
{
info->DisplayError( info, except.what() );
return -1;
}
return 0;
}
static int UpdateGUI(void *inf)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
info->GUIItems[0].Label = "Sigma";
info->GUIItems[0].GUIType = VV_GUI_SCALE;
info->GUIItems[0].Default = "1.0";
info->GUIItems[0].Help = "Standard deviation of the Gaussian kernel used to smooth the image before computing the gradient";
info->GUIItems[0].Hints = "0 20 0.1";
info->RequiredZOverlap = 0;
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents =
info->InputVolumeNumberOfComponents;
memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,
3*sizeof(int));
memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,
3*sizeof(float));
memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,
3*sizeof(float));
return 1;
}
extern "C" {
void VV_PLUGIN_EXPORT vvITKGradientMagnitudeRecursiveGaussianInit(vtkVVPluginInfo *info)
{
// setup information that never changes
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
info->Name = "Gradient Magnitude IIR (ITK)";
info->TerseDocumentation = "Gradient Magnitude Gaussian IIR";
info->FullDocumentation =
"This filter applies IIR filters to compute the equivalent of convolving the input image with the derivatives of a Gaussian kernel and then computing the magnitude of the resulting gradient.";
info->SupportsInPlaceProcessing = 0;
info->SupportsProcessingPieces = 0;
info->RequiredZOverlap = 0;
// Number of bytes required in intermediate memory per voxel
info->PerVoxelMemoryRequired = 16;
/* setup the GUI components */
info->NumberOfGUIItems = 1;
info->GUIItems = (vtkVVGUIItem *)malloc(info->NumberOfGUIItems*sizeof(vtkVVGUIItem));
}
}
<commit_msg>FIX: Normalization across scale added.<commit_after>/* Computes the gradient magnitude after convolving with a Gaussian kernel.
It uses IIR filter for approximating the convolution */
#include "vvITKFilterModule.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
const unsigned int Dimension = 3;
try
{
switch( info->InputVolumeScalarType )
{
case VTK_UNSIGNED_CHAR:
{
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, ImageType > FilterType;
VolView::PlugIn::FilterModule< FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Computing the gradient magnitude...");
// Set the parameters on it
module.GetFilter()->SetSigma( atof( info->GUIItems[ 0 ].CurrentValue) );
module.GetFilter()->SetNormalizeAcrossScale( true );
// Execute the filter
module.ProcessData( pds );
break;
}
case VTK_UNSIGNED_SHORT:
{
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, ImageType > FilterType;
VolView::PlugIn::FilterModule< FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Computing the gradient magnitude...");
// Set the parameters on it
module.GetFilter()->SetSigma( atof( info->GUIItems[ 0 ].CurrentValue) );
module.GetFilter()->SetNormalizeAcrossScale( true );
// Execute the filter
module.ProcessData( pds );
break;
}
}
}
catch( itk::ExceptionObject & except )
{
info->DisplayError( info, except.what() );
return -1;
}
return 0;
}
static int UpdateGUI(void *inf)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
info->GUIItems[0].Label = "Sigma";
info->GUIItems[0].GUIType = VV_GUI_SCALE;
info->GUIItems[0].Default = "1.0";
info->GUIItems[0].Help = "Standard deviation of the Gaussian kernel used to smooth the image before computing the gradient";
info->GUIItems[0].Hints = "0 20 0.1";
info->RequiredZOverlap = 0;
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents =
info->InputVolumeNumberOfComponents;
memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,
3*sizeof(int));
memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,
3*sizeof(float));
memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,
3*sizeof(float));
return 1;
}
extern "C" {
void VV_PLUGIN_EXPORT vvITKGradientMagnitudeRecursiveGaussianInit(vtkVVPluginInfo *info)
{
// setup information that never changes
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
info->Name = "Gradient Magnitude IIR (ITK)";
info->TerseDocumentation = "Gradient Magnitude Gaussian IIR";
info->FullDocumentation =
"This filter applies IIR filters to compute the equivalent of convolving the input image with the derivatives of a Gaussian kernel and then computing the magnitude of the resulting gradient.";
info->SupportsInPlaceProcessing = 0;
info->SupportsProcessingPieces = 0;
info->RequiredZOverlap = 0;
// Number of bytes required in intermediate memory per voxel
info->PerVoxelMemoryRequired = 16;
/* setup the GUI components */
info->NumberOfGUIItems = 1;
info->GUIItems = (vtkVVGUIItem *)malloc(info->NumberOfGUIItems*sizeof(vtkVVGUIItem));
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include "base/status_or.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/body.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/massive_body.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace astronomy {
namespace internal_orbital_elements {
using base::StatusOr;
using geometry::Instant;
using physics::Body;
using physics::DiscreteTrajectory;
using physics::MassiveBody;
using quantities::Angle;
using quantities::AngularFrequency;
using quantities::Difference;
using quantities::Infinity;
using quantities::Length;
using quantities::Time;
class OrbitalElements {
public:
template<typename PrimaryCentred>
static StatusOr<OrbitalElements> ForTrajectory(
DiscreteTrajectory<PrimaryCentred> const& trajectory,
MassiveBody const& primary,
Body const& secondary);
// The classical Keplerian elements (a, e, i, Ω, ω, M),
// together with an epoch.
struct ClassicalElements {
Instant time;
Length semimajor_axis;
double eccentricity;
Angle inclination;
Angle longitude_of_ascending_node;
Angle argument_of_periapsis;
Angle mean_anomaly;
};
// Mean element time series. These elements are free of short-period
// variations, i.e., variations whose period is the orbital period.
std::vector<ClassicalElements> const& mean_elements() const;
// The period of the (osculating) mean longitude λ = Ω + ω + M.
// Note that since our mean elements are filtered by integration over this
// period, it does not make much sense to recompute it based on our mean
// elements.
Time sidereal_period() const;
// The period of the (mean) mean argument of latitude u = ω + M.
Time nodal_period() const;
// The period of the (mean) mean anomaly M.
Time anomalistic_period() const;
// The rate of precession of Ω.
AngularFrequency nodal_precession() const;
// NOTE(egg): The argument of periapsis ω typically precesses as well.
// However, long-period variations tend to be comparatively large, so that a
// precession rate computed over a few orbits would be highly inaccurate.
// More importantly, whereas the actual value of Ω′ is relevant to, e.g.,
// orbit recurrence computation or sun-synchronicity, one typically cares
// about ω′ only when requiring that ω′ be 0 (in a frozen orbit), in which
// case the more relevant requirement is that ω stays close to some reference
// value.
// Of the mean classical elements (a, e, i, Ω, ω, M), under the influence of
// gravitational forces,
// — M always exhibits a fast secular variation (anomalistic mean motion);
// — Ω often exhibits a secular variation (nodal precession); there are
// however rare cases where it is kept constant (so-called inertial orbits
// that achieve Ω′ = 0 by being polar, e.g., CoRoT or Gravity Probe B); in
// that case, the frozen value may occasionally be relevant: for CoRoT, it
// determines the region of the sky that may be observed.
// — ω exhibits a secular variation, except for frozen orbits or orbits at the
// critical inclination; For frozen
// orbits (type II frozen orbits in the terminology of Ulrich Walter), its
// constant value must be eithre 90° or 270°; for orbits at the critical
// inclination (type I frozen orbits), ω is arbitrary; in highly eccentric
// cases, it is often chosen to be 270° so that the apogee is at high
// latitudes (Молния, みちびき, etc.).
// — a, e, i exhibit no secular variation.
// However, the elements that exhibit no secular variation still have
// long-period variations; instead of trying to characterize these complex
// effects, we provide the range of values taken by these elements over the
// trajectory being analysed.
// Represents the interval [min, max].
// TODO(egg): This makes sense for T = instant, but InfinitePast and
// InfiniteFuture work differently from Infinity.
template<typename T>
struct Interval {
T min = +Infinity<T>();
T max = -Infinity<T>();
Difference<T> measure() const;
T midpoint() const;
// Extends this interval so that it contains x.
void Include(T const& x);
};
// REMOVE BEFORE FLIGHT: rename these to mean_meow_range.
Interval<Length> mean_semimajor_axis_range() const;
Interval<double> mean_eccentricity_range() const;
Interval<Angle> mean_inclination_range() const;
Interval<Angle> mean_longitude_of_ascending_node_range() const;
Interval<Angle> mean_argument_of_periapsis_range() const;
// The equinoctial elements, and in particular the osculating equinoctial
// elements, are not directly interesting; anything that could be derived from
// them should be directly computed by this class instead. They are however
// useful for experimentation in Mathematica, to see whether the
// transformation from osculating to mean elements is well-behaved, whether
// the mean elements are stable, and what useful quantities can be derived
// from the mean elements.
// The equinoctial elements, together with an epoch.
// See Broucke and Cefola (1972), On the equinoctial orbit elements.
struct EquinoctialElements {
Instant t;
Length a;
double h;
double k;
Angle λ;
double p;
double q;
// pʹ and qʹ use the cotangent of the half-inclination instead of its
// tangent; they are better suited to retrograde orbits.
double pʹ;
double qʹ;
};
std::vector<EquinoctialElements> const& osculating_equinoctial_elements()
const;
std::vector<EquinoctialElements> const& mean_equinoctial_elements() const;
private:
OrbitalElements() = default;
template<typename PrimaryCentred>
static std::vector<EquinoctialElements> OsculatingEquinoctialElements(
DiscreteTrajectory<PrimaryCentred> const& trajectory,
MassiveBody const& primary,
Body const& secondary);
// |equinoctial_elements| must contain at least 2 elements.
static Time SiderealPeriod(
std::vector<EquinoctialElements> const& equinoctial_elements);
// |osculating| must contain at least 2 elements.
// The resulting elements are averaged over one period, centred on t.
static std::vector<EquinoctialElements> MeanEquinoctialElements(
std::vector<EquinoctialElements> const& osculating,
Time const& period);
static std::vector<ClassicalElements> ToClassicalElements(
std::vector<EquinoctialElements> const& equinoctial_elements);
// |mean_classical_elements_| must have been computed; sets
// |anomalistic_period_|, |nodal_period_|, and |nodal_precession_|
// accordingly. Note that this does not compute |sidereal_period_| (our mean
// element computation is based on it, so it gets computed earlier).
void ComputePeriodsAndPrecession();
void ComputeMeanElementRanges();
std::vector<EquinoctialElements> osculating_equinoctial_elements_;
Time sidereal_period_;
std::vector<EquinoctialElements> mean_equinoctial_elements_;
std::vector<ClassicalElements> mean_classical_elements_;
Time anomalistic_period_;
Time nodal_period_;
AngularFrequency nodal_precession_;
Interval<Length> mean_semimajor_axis_range_;
Interval<double> mean_eccentricity_range_;
Interval<Angle> mean_inclination_range_;
Interval<Angle> mean_longitude_of_ascending_node_range_;
Interval<Angle> mean_argument_of_periapsis_range_;
};
} // namespace internal_orbital_elements
using internal_orbital_elements::OrbitalElements;
} // namespace astronomy
} // namespace principia
#include "astronomy/orbital_elements_body.hpp"
<commit_msg>remove<commit_after>#pragma once
#include "base/status_or.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/body.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/massive_body.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace astronomy {
namespace internal_orbital_elements {
using base::StatusOr;
using geometry::Instant;
using physics::Body;
using physics::DiscreteTrajectory;
using physics::MassiveBody;
using quantities::Angle;
using quantities::AngularFrequency;
using quantities::Difference;
using quantities::Infinity;
using quantities::Length;
using quantities::Time;
class OrbitalElements {
public:
template<typename PrimaryCentred>
static StatusOr<OrbitalElements> ForTrajectory(
DiscreteTrajectory<PrimaryCentred> const& trajectory,
MassiveBody const& primary,
Body const& secondary);
// The classical Keplerian elements (a, e, i, Ω, ω, M),
// together with an epoch.
struct ClassicalElements {
Instant time;
Length semimajor_axis;
double eccentricity;
Angle inclination;
Angle longitude_of_ascending_node;
Angle argument_of_periapsis;
Angle mean_anomaly;
};
// Mean element time series. These elements are free of short-period
// variations, i.e., variations whose period is the orbital period.
std::vector<ClassicalElements> const& mean_elements() const;
// The period of the (osculating) mean longitude λ = Ω + ω + M.
// Note that since our mean elements are filtered by integration over this
// period, it does not make much sense to recompute it based on our mean
// elements.
Time sidereal_period() const;
// The period of the (mean) mean argument of latitude u = ω + M.
Time nodal_period() const;
// The period of the (mean) mean anomaly M.
Time anomalistic_period() const;
// The rate of precession of Ω.
AngularFrequency nodal_precession() const;
// NOTE(egg): The argument of periapsis ω typically precesses as well.
// However, long-period variations tend to be comparatively large, so that a
// precession rate computed over a few orbits would be highly inaccurate.
// More importantly, whereas the actual value of Ω′ is relevant to, e.g.,
// orbit recurrence computation or sun-synchronicity, one typically cares
// about ω′ only when requiring that ω′ be 0 (in a frozen orbit), in which
// case the more relevant requirement is that ω stays close to some reference
// value.
// Of the mean classical elements (a, e, i, Ω, ω, M), under the influence of
// gravitational forces,
// — M always exhibits a fast secular variation (anomalistic mean motion);
// — Ω often exhibits a secular variation (nodal precession); there are
// however rare cases where it is kept constant (so-called inertial orbits
// that achieve Ω′ = 0 by being polar, e.g., CoRoT or Gravity Probe B); in
// that case, the frozen value may occasionally be relevant: for CoRoT, it
// determines the region of the sky that may be observed.
// — ω exhibits a secular variation, except for frozen orbits or orbits at the
// critical inclination; For frozen
// orbits (type II frozen orbits in the terminology of Ulrich Walter), its
// constant value must be eithre 90° or 270°; for orbits at the critical
// inclination (type I frozen orbits), ω is arbitrary; in highly eccentric
// cases, it is often chosen to be 270° so that the apogee is at high
// latitudes (Молния, みちびき, etc.).
// — a, e, i exhibit no secular variation.
// However, the elements that exhibit no secular variation still have
// long-period variations; instead of trying to characterize these complex
// effects, we provide the range of values taken by these elements over the
// trajectory being analysed.
// Represents the interval [min, max].
// TODO(egg): This makes sense for T = instant, but InfinitePast and
// InfiniteFuture work differently from Infinity.
template<typename T>
struct Interval {
T min = +Infinity<T>();
T max = -Infinity<T>();
Difference<T> measure() const;
T midpoint() const;
// Extends this interval so that it contains x.
void Include(T const& x);
};
Interval<Length> mean_semimajor_axis_range() const;
Interval<double> mean_eccentricity_range() const;
Interval<Angle> mean_inclination_range() const;
Interval<Angle> mean_longitude_of_ascending_node_range() const;
Interval<Angle> mean_argument_of_periapsis_range() const;
// The equinoctial elements, and in particular the osculating equinoctial
// elements, are not directly interesting; anything that could be derived from
// them should be directly computed by this class instead. They are however
// useful for experimentation in Mathematica, to see whether the
// transformation from osculating to mean elements is well-behaved, whether
// the mean elements are stable, and what useful quantities can be derived
// from the mean elements.
// The equinoctial elements, together with an epoch.
// See Broucke and Cefola (1972), On the equinoctial orbit elements.
struct EquinoctialElements {
Instant t;
Length a;
double h;
double k;
Angle λ;
double p;
double q;
// pʹ and qʹ use the cotangent of the half-inclination instead of its
// tangent; they are better suited to retrograde orbits.
double pʹ;
double qʹ;
};
std::vector<EquinoctialElements> const& osculating_equinoctial_elements()
const;
std::vector<EquinoctialElements> const& mean_equinoctial_elements() const;
private:
OrbitalElements() = default;
template<typename PrimaryCentred>
static std::vector<EquinoctialElements> OsculatingEquinoctialElements(
DiscreteTrajectory<PrimaryCentred> const& trajectory,
MassiveBody const& primary,
Body const& secondary);
// |equinoctial_elements| must contain at least 2 elements.
static Time SiderealPeriod(
std::vector<EquinoctialElements> const& equinoctial_elements);
// |osculating| must contain at least 2 elements.
// The resulting elements are averaged over one period, centred on t.
static std::vector<EquinoctialElements> MeanEquinoctialElements(
std::vector<EquinoctialElements> const& osculating,
Time const& period);
static std::vector<ClassicalElements> ToClassicalElements(
std::vector<EquinoctialElements> const& equinoctial_elements);
// |mean_classical_elements_| must have been computed; sets
// |anomalistic_period_|, |nodal_period_|, and |nodal_precession_|
// accordingly. Note that this does not compute |sidereal_period_| (our mean
// element computation is based on it, so it gets computed earlier).
void ComputePeriodsAndPrecession();
void ComputeMeanElementRanges();
std::vector<EquinoctialElements> osculating_equinoctial_elements_;
Time sidereal_period_;
std::vector<EquinoctialElements> mean_equinoctial_elements_;
std::vector<ClassicalElements> mean_classical_elements_;
Time anomalistic_period_;
Time nodal_period_;
AngularFrequency nodal_precession_;
Interval<Length> mean_semimajor_axis_range_;
Interval<double> mean_eccentricity_range_;
Interval<Angle> mean_inclination_range_;
Interval<Angle> mean_longitude_of_ascending_node_range_;
Interval<Angle> mean_argument_of_periapsis_range_;
};
} // namespace internal_orbital_elements
using internal_orbital_elements::OrbitalElements;
} // namespace astronomy
} // namespace principia
#include "astronomy/orbital_elements_body.hpp"
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_main_delegate.h"
#include <string>
#include "atom/browser/atom_browser_client.h"
#include "atom/renderer/atom_renderer_client.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
namespace atom {
AtomMainDelegate::AtomMainDelegate() {
}
AtomMainDelegate::~AtomMainDelegate() {
}
void AtomMainDelegate::AddDataPackFromPath(
ui::ResourceBundle* bundle, const base::FilePath& pak_dir) {
#if defined(OS_WIN)
bundle->AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("ui_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
bundle->AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("webkit_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
#endif
}
bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
// Disable logging out to debug.log on Windows
#if defined(OS_WIN)
logging::LoggingSettings settings;
#if defined(DEBUG)
settings.logging_dest = logging::LOG_TO_ALL;
settings.log_file = L"debug.log";
settings.lock_log = logging::LOCK_LOG_FILE;
settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif
logging::InitLogging(settings);
#endif // defined(OS_WIN)
// Logging with pid and timestamp.
logging::SetLogItems(true, false, true, false);
// Enable convient stack printing.
#if defined(DEBUG) && defined(OS_LINUX)
base::debug::EnableInProcessStackDumping();
#endif
return brightray::MainDelegate::BasicStartupComplete(exit_code);
}
void AtomMainDelegate::PreSandboxStartup() {
brightray::MainDelegate::PreSandboxStartup();
CommandLine* command_line = CommandLine::ForCurrentProcess();
std::string process_type = command_line->GetSwitchValueASCII(
switches::kProcessType);
// Only append arguments for browser process.
if (!process_type.empty())
return;
// Add a flag to mark the start of switches added by atom-shell.
command_line->AppendSwitch("atom-shell-switches-start");
// Disable renderer sandbox for most of node's functions.
command_line->AppendSwitch(switches::kNoSandbox);
// Add a flag to mark the end of switches added by atom-shell.
command_line->AppendSwitch("atom-shell-switches-end");
}
content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() {
browser_client_.reset(new AtomBrowserClient);
return browser_client_.get();
}
content::ContentRendererClient*
AtomMainDelegate::CreateContentRendererClient() {
renderer_client_.reset(new AtomRendererClient);
return renderer_client_.get();
}
} // namespace atom
<commit_msg>win: Disable the LegacyRenderWidgetHostHWND, fixes #506.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_main_delegate.h"
#include <string>
#include "atom/browser/atom_browser_client.h"
#include "atom/renderer/atom_renderer_client.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
namespace atom {
AtomMainDelegate::AtomMainDelegate() {
}
AtomMainDelegate::~AtomMainDelegate() {
}
void AtomMainDelegate::AddDataPackFromPath(
ui::ResourceBundle* bundle, const base::FilePath& pak_dir) {
#if defined(OS_WIN)
bundle->AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("ui_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
bundle->AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("webkit_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
#endif
}
bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
// Disable logging out to debug.log on Windows
#if defined(OS_WIN)
logging::LoggingSettings settings;
#if defined(DEBUG)
settings.logging_dest = logging::LOG_TO_ALL;
settings.log_file = L"debug.log";
settings.lock_log = logging::LOCK_LOG_FILE;
settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif
logging::InitLogging(settings);
#endif // defined(OS_WIN)
// Logging with pid and timestamp.
logging::SetLogItems(true, false, true, false);
// Enable convient stack printing.
#if defined(DEBUG) && defined(OS_LINUX)
base::debug::EnableInProcessStackDumping();
#endif
return brightray::MainDelegate::BasicStartupComplete(exit_code);
}
void AtomMainDelegate::PreSandboxStartup() {
brightray::MainDelegate::PreSandboxStartup();
CommandLine* command_line = CommandLine::ForCurrentProcess();
std::string process_type = command_line->GetSwitchValueASCII(
switches::kProcessType);
// Only append arguments for browser process.
if (!process_type.empty())
return;
// Add a flag to mark the start of switches added by atom-shell.
command_line->AppendSwitch("atom-shell-switches-start");
#if defined(OS_WIN)
// Disable the LegacyRenderWidgetHostHWND, it made frameless windows unable
// to move and resize. We may consider enabling it again after upgraded to
// Chrome 38, which should have fixed the problem.
command_line->AppendSwitch(switches::kDisableLegacyIntermediateWindow);
#endif
// Disable renderer sandbox for most of node's functions.
command_line->AppendSwitch(switches::kNoSandbox);
// Add a flag to mark the end of switches added by atom-shell.
command_line->AppendSwitch("atom-shell-switches-end");
}
content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() {
browser_client_.reset(new AtomBrowserClient);
return browser_client_.get();
}
content::ContentRendererClient*
AtomMainDelegate::CreateContentRendererClient() {
renderer_client_.reset(new AtomRendererClient);
return renderer_client_.get();
}
} // namespace atom
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: i_type.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-11-15 13:26:32 $
*
* 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 ARY_IDL_I_TYPE_HXX
#define ARY_IDL_I_TYPE_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
#include <ary/re.hxx>
// PARAMETERS
#include <ary/idl/i_language.hxx>
namespace ary
{
namespace idl
{
class Gate;
/** Abstract base for all secondary productions of types
*/
class Type_2s
{
public:
virtual ~Type_2s() {}
static DYN Type_2s *
Create_(
RCid i_nCeId );
};
/** @resp Base of all IDL types.
@->Type represents the occurence of a type as base,
parameter, return type or element type in UNO IDL code.
Some of them relate to a @->CodeEntity, but
the @->Type "MyInterface" is something different than
the @->CodeEntity "MyInterface".
This is a storage base class, where more special
classes are derived from.
*/
class Type : public n22::RepositoryEntity
{
public:
typedef Type_2s secondary_productions;
// LIFECYCLE
virtual ~Type() {}
// INQUIRY
Type_id TypeId() const { return Type_id(Id()); }
/// @descr Does NOT clear the output-parameters.
void Get_Text(
StringVector & o_module,
String & o_name,
Ce_id & o_nRelatedCe,
int & o_nSequenceCount,
const Gate & i_rGate ) const;
Type_id TemplateParameterType() const;
private:
virtual void inq_Get_Text(
StringVector & o_module,
String & o_name,
Ce_id & o_nRelatedCe,
int & o_nSequemceCount,
const Gate & i_rGate ) const = 0;
virtual Type_id inq_TemplateParameterType() const;
};
inline void
Type::Get_Text( StringVector & o_module,
String & o_name,
Ce_id & o_nRelatedCe,
int & o_nSequenceCount,
const Gate & i_rGate ) const
{
inq_Get_Text(o_module,o_name,o_nRelatedCe,o_nSequenceCount,i_rGate);
}
inline Type_id
Type::TemplateParameterType() const
{
return inq_TemplateParameterType();
}
} // namespace idl
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.18); FILE MERGED 2005/09/05 13:09:22 rt 1.3.18.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: i_type.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:12:58 $
*
* 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 ARY_IDL_I_TYPE_HXX
#define ARY_IDL_I_TYPE_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
#include <ary/re.hxx>
// PARAMETERS
#include <ary/idl/i_language.hxx>
namespace ary
{
namespace idl
{
class Gate;
/** Abstract base for all secondary productions of types
*/
class Type_2s
{
public:
virtual ~Type_2s() {}
static DYN Type_2s *
Create_(
RCid i_nCeId );
};
/** @resp Base of all IDL types.
@->Type represents the occurence of a type as base,
parameter, return type or element type in UNO IDL code.
Some of them relate to a @->CodeEntity, but
the @->Type "MyInterface" is something different than
the @->CodeEntity "MyInterface".
This is a storage base class, where more special
classes are derived from.
*/
class Type : public n22::RepositoryEntity
{
public:
typedef Type_2s secondary_productions;
// LIFECYCLE
virtual ~Type() {}
// INQUIRY
Type_id TypeId() const { return Type_id(Id()); }
/// @descr Does NOT clear the output-parameters.
void Get_Text(
StringVector & o_module,
String & o_name,
Ce_id & o_nRelatedCe,
int & o_nSequenceCount,
const Gate & i_rGate ) const;
Type_id TemplateParameterType() const;
private:
virtual void inq_Get_Text(
StringVector & o_module,
String & o_name,
Ce_id & o_nRelatedCe,
int & o_nSequemceCount,
const Gate & i_rGate ) const = 0;
virtual Type_id inq_TemplateParameterType() const;
};
inline void
Type::Get_Text( StringVector & o_module,
String & o_name,
Ce_id & o_nRelatedCe,
int & o_nSequenceCount,
const Gate & i_rGate ) const
{
inq_Get_Text(o_module,o_name,o_nRelatedCe,o_nSequenceCount,i_rGate);
}
inline Type_id
Type::TemplateParameterType() const
{
return inq_TemplateParameterType();
}
} // namespace idl
} // namespace ary
#endif
<|endoftext|>
|
<commit_before>/*
* CompoundAgent.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Lesser General Public License for more details.
*
*/
#include "CompoundPart.h"
#include "openc2e.h"
#include "c16Image.h"
#include "SDLBackend.h"
void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y, is_transparent, transparency);
}
CompoundPart::CompoundPart(unsigned int _id, std::string spritefile, unsigned int fimg,
unsigned int _x, unsigned int _y, unsigned int _z) {
id = _id;
firstimg = fimg;
x = _x;
y = _y;
zorder = _z;
sprite = gallery.getImage(spritefile);
caos_assert(sprite);
pose = 0;
base = 0;
is_transparent = false;
framerate = 1;
framedelay = 0;
}
DullPart::DullPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}
ButtonPart::ButtonPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, const bytestring &animhover, int msgid, int option) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
messageid = msgid;
hitopaquepixelsonly = (option == 1);
hoveranimation = animhover;
}
FixedTextPart::FixedTextPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
// TODO: load fontsprite
}
TextEntryPart::TextEntryPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, unsigned int msgid, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
// TODO: load fontsprite, msgid
}
void CompoundPart::tick() {
if (!animation.empty()) {
if (framerate > 1) {
framedelay++;
if (framedelay == framerate + 1)
framedelay = 0;
}
if (framedelay == 0) {
unsigned int f = frameno + 1;
if (f == animation.size()) return;
if (animation[f] == 255) {
if (f == (animation.size() - 1)) f = 0;
else f = animation[f + 1];
}
setFrameNo(f);
}
}
}
/* vim: set noet: */
<commit_msg>Test * commitbot<commit_after>/*
* CompoundAgent.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Lesser General Public License for more details.
*
*/
#include "CompoundPart.h"
#include "openc2e.h"
#include "c16Image.h"
#include "SDLBackend.h"
void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y, is_transparent, transparency);
}
CompoundPart::CompoundPart(unsigned int _id, std::string spritefile, unsigned int fimg,
unsigned int _x, unsigned int _y, unsigned int _z) {
id = _id;
firstimg = fimg;
x = _x;
y = _y;
zorder = _z;
sprite = gallery.getImage(spritefile);
caos_assert(sprite);
pose = 0;
base = 0;
is_transparent = false;
framerate = 1;
framedelay = 0;
}
DullPart::DullPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}
ButtonPart::ButtonPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, const bytestring &animhover, int msgid, int option) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
messageid = msgid;
hitopaquepixelsonly = (option == 1);
hoveranimation = animhover;
}
FixedTextPart::FixedTextPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
// TODO: load fontsprite
}
TextEntryPart::TextEntryPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, unsigned int msgid, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
// TODO: load fontsprite, msgid
}
void CompoundPart::tick() {
if (!animation.empty()) {
if (framerate > 1) {
framedelay++;
if (framedelay == framerate + 1)
framedelay = 0;
}
if (framedelay == 0) {
unsigned int f = frameno + 1;
if (f == animation.size()) return;
if (animation[f] == 255) {
if (f == (animation.size() - 1)) f = 0;
else f = animation[f + 1];
}
setFrameNo(f);
}
}
}
/* vim: set noet: */
<|endoftext|>
|
<commit_before>#include "ComputeUtils.h"
#include "LuaUtils.h"
#include <pthread.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif
//
struct ComputeDevices {
#ifdef WANT_CUDA
// COMPUTE_LIB mCUDA; //
#endif
#ifdef WANT_METAL
// MTLDevice mMetalDevice;
#endif
};
//
static bool Exists (const char * name)
{
#ifdef _WIN32
HMODULE lib = LoadLibraryA(name);
#else
void * lib = dlopen(name, RTLD_NOW);
#endif
if (lib != NULL)
{
#ifdef _WIN32
FreeLibrary(lib);
#else
dlclose(lib);
#endif
}
return lib != NULL;
}
// Global device info
static ComputeDevices * sDevices;
// Avoid conflicts while launching device queries
static pthread_mutex_t s_DevicesInit = PTHREAD_MUTEX_INITIALIZER;
#ifdef WANT_CUDA
#include <cuda.h>
#include <cuda_runtime_api.h>
static bool CheckCUDA (ComputeCaps & caps)
{
if (!Exists(
#ifdef _WIN32
"nvcuda.dll"
#else
"libcuda.so"
#endif
)) return false;
int count;
if (CUDA_SUCCESS != cuInit(0)) return false;
if (CUDA_SUCCESS != cuDeviceGetCount(&count)) return false;
caps.mDevicesCUDA.resize(size_t(count));
for (int i = 0; i < count; i++)
{
ComputeCaps::DeviceInfoCUDA & dev = caps.mDevicesCUDA[i];
/*
struct cudaDeviceProp deviceProp;
if(cudaGetDeviceProperties(&deviceProp,i) == CUDA_SUCCESS)
{
int m,n;
cuDeviceComputeCapability(&m, &n, i);
unsigned long memory = (unsigned long)deviceProp.totalGlobalMem;
memory = memory / 1024;
memory = memory / 1024;
printf("Device Name: %s", deviceProp.name);
printf("Device Computer Capability: %d.%d", m, n);
printf("\nMem Size: %lu \n", memory);
printf("Max Threads: %d\n", deviceProp.maxThreadsPerBlock);
printf("Max Threads Dim[x?]: %d\n", deviceProp.maxThreadsDim[0]);
printf("Max Threads Dim[y?]: %d\n", deviceProp.maxThreadsDim[1]);
printf("Max Threads Dim[z?]: %d\n", deviceProp.maxThreadsDim[2]);
printf("Max Grid Size[x?]: %d\n", deviceProp.maxGridSize[0]);
printf("Max Grid Size[y?]: %d\n", deviceProp.maxGridSize[1]);
printf("Max Grid Size[z?]: %d\n", deviceProp.maxGridSize[2]);
}
*/
if (CUDA_SUCCESS != cuDeviceComputeCapability(&dev.mMajor, &dev.mMinor, i)) return false;
printf("%i, %i, %i!\n", i, dev.mMajor, dev.mMinor);
// ^^ TODO: Detect minimum acceptable version... (test on better device!)
}
return true;
}
#endif
//#include <iostream>
bool CheckComputeSupport (lua_State * L, ComputeCaps & caps)
{
if (!IsMainState(L)) return false;
caps.mFlags = 0;
ComputeDevices * cd = (ComputeDevices *)lua_newuserdata(L, sizeof(ComputeDevices)); // ..., devices
// TODO: Check C++ AMP support? (DirectX11 caps? otherwise have to include that .exe...)
// vs. https://github.com/debdattabasu/amp-radix-sort/blob/master/amp_sort/main.cpp#L14
#ifdef WANT_AMP
caps.mAccelerators = concurrency::accelerator::get_all();
/*
http://stackoverflow.com/a/7533864
TODO: investigate some more, suss out most useful fields
std::for_each(begin(caps.mAccelerators), end(caps.mAccelerators),[=](concurrency::accelerator acc){
std::wcout << "New accelerator: " << acc.description << std::endl;
std::wcout << "is_debug = " << acc.is_debug << std::endl;
std::wcout << "is_emulated = " << acc.is_emulated <<std::endl;
std::wcout << "dedicated_memory = " << acc.dedicated_memory << std::endl;
std::wcout << "device_path = " << acc.device_path << std::endl;
std::wcout << "has_display = " << acc.has_display << std::endl;
std::wcout << "version = " << (acc.version >> 16) << '.' << (acc.version & 0xFFFF) << std::endl;
});
*/
if (!caps.mAccelerators.empty()) caps.mFlags |= ComputeCaps::eAMP; // Probably too liberal (e.g. emulated stuff unlikely to be much good)
#endif
#ifdef WANT_CUDA
if (CheckCUDA(caps)) caps.mFlags |= ComputeCaps::eCUDA;
#endif
#ifdef WANT_METAL
/*
cd->mMetalDevice = MTLCreateSystemDefaultDevice();
if (cd->mMetalDevice) caps.mFlags |= ComputeCaps::eMetal;
*/
#endif
AttachGC(L, "compute_devices", [](lua_State * L)
{
ShutDownBackend(ComputeCaps::eCUDA);
ShutDownBackend(ComputeCaps::eMetal);
ShutDownBackend(ComputeCaps::eOpenCL);
ShutDownBackend(ComputeCaps::eRenderScript);
return 0;
});
pthread_mutex_lock(&s_DevicesInit);
sDevices = cd;
pthread_mutex_unlock(&s_DevicesInit);
return true;
}
void ShutDownBackend (ComputeCaps::Flag flag)
{
pthread_mutex_lock(&s_DevicesInit); // wait for any initialization
pthread_mutex_unlock(&s_DevicesInit);
if (!sDevices) return;
switch (flag)
{
case ComputeCaps::eAMP:
#ifdef WANT_AMP
// TODO!
#endif
break;
case ComputeCaps::eCUDA:
#ifdef WANT_CUDA
// TODO!
#endif
break;
case ComputeCaps::eMetal:
#ifdef WANT_METAL
/* if (mMetalDevice) ;
mMetalDevice = NULL;*/
#endif
break;
case ComputeCaps::eOpenCL:
#ifdef WANT_OPENCL
// TODO!
// http://arrayfire.com/getting-started-with-opencl-on-android/
// http://arrayfire.com/opencl-on-mobile-devices/
// https://stackoverflow.com/questions/26795921/does-android-support-opencl
// https://streamcomputing.eu/blog/2014-06-30/opencl-support-recent-android-smartphones/
#endif
break;
case ComputeCaps::eRenderScript:
#ifdef WANT_RENDERSCRIPT
// TODO!
// https://possiblemobile.com/2013/10/renderscript-for-all/
#endif
break;
}
}
#undef COMPUTE_LIB
#undef COMPUTE_PROC
#undef _CUDA_API_<commit_msg>Commented out header (no good on Mac yet)<commit_after>#include "ComputeUtils.h"
#include "LuaUtils.h"
#include <pthread.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif
//
struct ComputeDevices {
#ifdef WANT_CUDA
// COMPUTE_LIB mCUDA; //
#endif
#ifdef WANT_METAL
// MTLDevice mMetalDevice;
#endif
};
//
static bool Exists (const char * name)
{
#ifdef _WIN32
HMODULE lib = LoadLibraryA(name);
#else
void * lib = dlopen(name, RTLD_NOW);
#endif
if (lib != NULL)
{
#ifdef _WIN32
FreeLibrary(lib);
#else
dlclose(lib);
#endif
}
return lib != NULL;
}
// Global device info
static ComputeDevices * sDevices;
// Avoid conflicts while launching device queries
static pthread_mutex_t s_DevicesInit = PTHREAD_MUTEX_INITIALIZER;
#ifdef WANT_CUDA
#include <cuda.h>
//#include <cuda_runtime_api.h>
static bool CheckCUDA (ComputeCaps & caps)
{
if (!Exists(
#ifdef _WIN32
"nvcuda.dll"
#else
"libcuda.so"
#endif
)) return false;
int count;
if (CUDA_SUCCESS != cuInit(0)) return false;
if (CUDA_SUCCESS != cuDeviceGetCount(&count)) return false;
caps.mDevicesCUDA.resize(size_t(count));
for (int i = 0; i < count; i++)
{
ComputeCaps::DeviceInfoCUDA & dev = caps.mDevicesCUDA[i];
/*
struct cudaDeviceProp deviceProp;
if(cudaGetDeviceProperties(&deviceProp,i) == CUDA_SUCCESS)
{
int m,n;
cuDeviceComputeCapability(&m, &n, i);
unsigned long memory = (unsigned long)deviceProp.totalGlobalMem;
memory = memory / 1024;
memory = memory / 1024;
printf("Device Name: %s", deviceProp.name);
printf("Device Computer Capability: %d.%d", m, n);
printf("\nMem Size: %lu \n", memory);
printf("Max Threads: %d\n", deviceProp.maxThreadsPerBlock);
printf("Max Threads Dim[x?]: %d\n", deviceProp.maxThreadsDim[0]);
printf("Max Threads Dim[y?]: %d\n", deviceProp.maxThreadsDim[1]);
printf("Max Threads Dim[z?]: %d\n", deviceProp.maxThreadsDim[2]);
printf("Max Grid Size[x?]: %d\n", deviceProp.maxGridSize[0]);
printf("Max Grid Size[y?]: %d\n", deviceProp.maxGridSize[1]);
printf("Max Grid Size[z?]: %d\n", deviceProp.maxGridSize[2]);
}
*/
if (CUDA_SUCCESS != cuDeviceComputeCapability(&dev.mMajor, &dev.mMinor, i)) return false;
printf("%i, %i, %i!\n", i, dev.mMajor, dev.mMinor);
// ^^ TODO: Detect minimum acceptable version... (test on better device!)
}
return true;
}
#endif
//#include <iostream>
bool CheckComputeSupport (lua_State * L, ComputeCaps & caps)
{
if (!IsMainState(L)) return false;
caps.mFlags = 0;
ComputeDevices * cd = (ComputeDevices *)lua_newuserdata(L, sizeof(ComputeDevices)); // ..., devices
// TODO: Check C++ AMP support? (DirectX11 caps? otherwise have to include that .exe...)
// vs. https://github.com/debdattabasu/amp-radix-sort/blob/master/amp_sort/main.cpp#L14
#ifdef WANT_AMP
caps.mAccelerators = concurrency::accelerator::get_all();
/*
http://stackoverflow.com/a/7533864
TODO: investigate some more, suss out most useful fields
std::for_each(begin(caps.mAccelerators), end(caps.mAccelerators),[=](concurrency::accelerator acc){
std::wcout << "New accelerator: " << acc.description << std::endl;
std::wcout << "is_debug = " << acc.is_debug << std::endl;
std::wcout << "is_emulated = " << acc.is_emulated <<std::endl;
std::wcout << "dedicated_memory = " << acc.dedicated_memory << std::endl;
std::wcout << "device_path = " << acc.device_path << std::endl;
std::wcout << "has_display = " << acc.has_display << std::endl;
std::wcout << "version = " << (acc.version >> 16) << '.' << (acc.version & 0xFFFF) << std::endl;
});
*/
if (!caps.mAccelerators.empty()) caps.mFlags |= ComputeCaps::eAMP; // Probably too liberal (e.g. emulated stuff unlikely to be much good)
#endif
#ifdef WANT_CUDA
if (CheckCUDA(caps)) caps.mFlags |= ComputeCaps::eCUDA;
#endif
#ifdef WANT_METAL
/*
cd->mMetalDevice = MTLCreateSystemDefaultDevice();
if (cd->mMetalDevice) caps.mFlags |= ComputeCaps::eMetal;
*/
#endif
AttachGC(L, "compute_devices", [](lua_State * L)
{
ShutDownBackend(ComputeCaps::eCUDA);
ShutDownBackend(ComputeCaps::eMetal);
ShutDownBackend(ComputeCaps::eOpenCL);
ShutDownBackend(ComputeCaps::eRenderScript);
return 0;
});
pthread_mutex_lock(&s_DevicesInit);
sDevices = cd;
pthread_mutex_unlock(&s_DevicesInit);
return true;
}
void ShutDownBackend (ComputeCaps::Flag flag)
{
pthread_mutex_lock(&s_DevicesInit); // wait for any initialization
pthread_mutex_unlock(&s_DevicesInit);
if (!sDevices) return;
switch (flag)
{
case ComputeCaps::eAMP:
#ifdef WANT_AMP
// TODO!
#endif
break;
case ComputeCaps::eCUDA:
#ifdef WANT_CUDA
// TODO!
#endif
break;
case ComputeCaps::eMetal:
#ifdef WANT_METAL
/* if (mMetalDevice) ;
mMetalDevice = NULL;*/
#endif
break;
case ComputeCaps::eOpenCL:
#ifdef WANT_OPENCL
// TODO!
// http://arrayfire.com/getting-started-with-opencl-on-android/
// http://arrayfire.com/opencl-on-mobile-devices/
// https://stackoverflow.com/questions/26795921/does-android-support-opencl
// https://streamcomputing.eu/blog/2014-06-30/opencl-support-recent-android-smartphones/
#endif
break;
case ComputeCaps::eRenderScript:
#ifdef WANT_RENDERSCRIPT
// TODO!
// https://possiblemobile.com/2013/10/renderscript-for-all/
#endif
break;
}
}
#undef COMPUTE_LIB
#undef COMPUTE_PROC
#undef _CUDA_API_<|endoftext|>
|
<commit_before>#include "ofApp.h"
//------------------------------------------------------------------------------
void ofApp::setup()
{
ofSetFrameRate(30);
ofEnableAlphaBlending();
}
//------------------------------------------------------------------------------
void ofApp::draw()
{
ofBackground(0);
// get the current time
unsigned long long now = ofGetElapsedTimeMillis();
// cycle through the rectangles
for(int i = 0; i < numRectangles; i++)
{
// if now is past the next scheduled blink time
if(now > nextRectangleBlinkTime[i])
{
// schedule the next blink time
nextRectangleBlinkTime[i] = now + rectangleDelays[i];
// toggle the rectangle state
rectangleState[i] = !rectangleState[i];
}
// draw the rectangles
if(rectangleState[i])
{
// draw an unfilled rectangle if the state is "true"
ofNoFill();
}
else
{
// draw a filled rectangle if the state is "false"
ofFill();
}
ofSetColor(ofColor::yellow);
ofRect(rectangles[i]);
// Uncomment the following to draw based on the amount of time left
// before the next blink happens.
// unsigned long long timeUntilNextBlink = nextRectangleBlinkTime[i] - now;
//
// float percent = ofNormalize(timeUntilNextBlink,0,rectangleDelays[i]);
//
// ofFill();
// ofSetColor(255,0,0);
// ofRect(rectangles[i].x,
// rectangles[i].y + rectangles[i].height,
// 10,
// -rectangles[i].height * percent);
}
}
<commit_msg>Cleanup.<commit_after>#include "ofApp.h"
//------------------------------------------------------------------------------
void ofApp::setup()
{
ofSetFrameRate(30);
ofEnableAlphaBlending();
}
//------------------------------------------------------------------------------
void ofApp::draw()
{
ofBackground(0);
// get the current time
unsigned long long now = ofGetElapsedTimeMillis();
// cycle through the rectangles
for(int i = 0; i < numRectangles; i++)
{
// if now is past the next scheduled blink time
if(now > nextRectangleBlinkTime[i])
{
// schedule the next blink time
nextRectangleBlinkTime[i] = now + rectangleDelays[i];
// toggle the rectangle state
rectangleState[i] = !rectangleState[i];
}
// draw the rectangles
if(rectangleState[i])
{
// draw an unfilled rectangle if the state is "true"
ofNoFill();
}
else
{
// draw a filled rectangle if the state is "false"
ofFill();
}
ofSetColor(ofColor::yellow);
ofRect(rectangles[i]);
// Uncomment the following to draw based on the amount of time left
// before the next blink happens.
// unsigned long long timeUntilNextBlink = nextRectangleBlinkTime[i] - now;
//
// float percent = ofNormalize(timeUntilNextBlink,0,rectangleDelays[i]);
//
// ofFill();
// ofSetColor(255,0,0);
// ofRect(rectangles[i].x,
// rectangles[i].y + rectangles[i].height,
// 10,
// -rectangles[i].height * percent);
}
}
<|endoftext|>
|
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"
#include "../exceptions/context_index_out_of_range_exception.h"
#include "../result.h"
#include "query_executor_builder_visitor.h"
namespace You {
namespace Controller {
namespace Internal {
using You::NLP::QUERY;
using You::NLP::ADD_QUERY;
using You::NLP::EDIT_QUERY;
using You::NLP::DELETE_QUERY;
QueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor(
const Controller::Context& context)
: context(context) {
}
std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const ADD_QUERY& query) {
class AddTaskQueryExecutor : public QueryExecutor {
public:
explicit AddTaskQueryExecutor(
std::unique_ptr<QueryEngine::Query>&& query)
: QueryExecutor(std::move(query)) {
}
virtual ~AddTaskQueryExecutor() = default;
protected:
Result processResponse(
const You::QueryEngine::Response& response) override {
return ADD_RESULT {
boost::get<Task>(response)
};
}
};
return std::unique_ptr<QueryExecutor>(
new AddTaskQueryExecutor(
QueryEngine::AddTask(
query.description,
query.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,
query.priority == You::NLP::TaskPriority::HIGH ?
Task::Priority::IMPORTANT : Task::Priority::NORMAL,
Task::Dependencies()
)
)
);
}
std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const {
class EditTaskQueryExecutor : public QueryExecutor {
public:
explicit EditTaskQueryExecutor(
std::unique_ptr<QueryEngine::Query>&& query)
: QueryExecutor(std::move(query)) {
}
virtual ~EditTaskQueryExecutor() = default;
protected:
Result processResponse(
const You::QueryEngine::Response& response) override {
return EDIT_RESULT {
boost::get<Task>(response)
};
}
};
try {
const Task& task = context.at(query.taskID);
std::wstring description = query.description ?
query.description.get() :
Task::DEFAULT_DESCRIPTION;
boost::posix_time::ptime deadline = query.deadline ?
query.deadline.get() :
Task::DEFAULT_DEADLINE;
Task::Priority priority = query.priority ?
(query.priority == You::NLP::TaskPriority::HIGH ?
Task::Priority::IMPORTANT : Task::Priority::NORMAL) :
Task::DEFAULT_PRIORITY;
return std::unique_ptr<QueryExecutor>(
new EditTaskQueryExecutor(
QueryEngine::UpdateTask(
task.getID(),
description,
deadline,
Task::DEFAULT_PRIORITY,
Task::Dependencies()
)
)
);
} catch (std::out_of_range& e) {
throw ContextIndexOutOfRangeException(e);
}
}
std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const {
class DeleteTaskQueryExecutor : public QueryExecutor {
public:
explicit DeleteTaskQueryExecutor(
std::unique_ptr<QueryEngine::Query>&& query)
: QueryExecutor(std::move(query)) {
}
virtual ~DeleteTaskQueryExecutor() = default;
protected:
Result processResponse(
const You::QueryEngine::Response& response) override {
return DELETE_RESULT {
boost::get<Task::ID>(response)
};
}
};
try {
const Task& task = context.at(query.taskID);
return std::unique_ptr<QueryExecutor>(
new DeleteTaskQueryExecutor(
QueryEngine::DeleteTask(
task.getID()
)
)
);
} catch (std::out_of_range& e) {
throw ContextIndexOutOfRangeException(e);
}
}
} // namespace Internal
} // namespace Controller
} // namespace You
<commit_msg>Fix lints.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"
#include "../exceptions/context_index_out_of_range_exception.h"
#include "../result.h"
#include "query_executor_builder_visitor.h"
namespace You {
namespace Controller {
namespace Internal {
using You::NLP::QUERY;
using You::NLP::ADD_QUERY;
using You::NLP::EDIT_QUERY;
using You::NLP::DELETE_QUERY;
QueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor(
const Controller::Context& context)
: context(context) {
}
std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const ADD_QUERY& query) {
class AddTaskQueryExecutor : public QueryExecutor {
public:
explicit AddTaskQueryExecutor(
std::unique_ptr<QueryEngine::Query>&& query)
: QueryExecutor(std::move(query)) {
}
virtual ~AddTaskQueryExecutor() = default;
protected:
Result processResponse(
const You::QueryEngine::Response& response) override {
return ADD_RESULT {
boost::get<Task>(response)
};
}
};
return std::unique_ptr<QueryExecutor>(
new AddTaskQueryExecutor(
QueryEngine::AddTask(
query.description,
query.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,
query.priority == You::NLP::TaskPriority::HIGH ?
Task::Priority::IMPORTANT : Task::Priority::NORMAL,
Task::Dependencies()
)
)
);
}
std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const {
class EditTaskQueryExecutor : public QueryExecutor {
public:
explicit EditTaskQueryExecutor(
std::unique_ptr<QueryEngine::Query>&& query)
: QueryExecutor(std::move(query)) {
}
virtual ~EditTaskQueryExecutor() = default;
protected:
Result processResponse(
const You::QueryEngine::Response& response) override {
return EDIT_RESULT {
boost::get<Task>(response)
};
}
};
try {
const Task& task = context.at(query.taskID);
std::wstring description = query.description ?
query.description.get() :
Task::DEFAULT_DESCRIPTION;
boost::posix_time::ptime deadline = query.deadline ?
query.deadline.get() :
Task::DEFAULT_DEADLINE;
Task::Priority priority = query.priority ?
(query.priority == You::NLP::TaskPriority::HIGH ?
Task::Priority::IMPORTANT : Task::Priority::NORMAL) :
Task::DEFAULT_PRIORITY;
return std::unique_ptr<QueryExecutor>(
new EditTaskQueryExecutor(
QueryEngine::UpdateTask(
task.getID(),
description,
deadline,
Task::DEFAULT_PRIORITY,
Task::Dependencies())));
} catch (std::out_of_range& e) {
throw ContextIndexOutOfRangeException(e);
}
}
std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const {
class DeleteTaskQueryExecutor : public QueryExecutor {
public:
explicit DeleteTaskQueryExecutor(
std::unique_ptr<QueryEngine::Query>&& query)
: QueryExecutor(std::move(query)) {
}
virtual ~DeleteTaskQueryExecutor() = default;
protected:
Result processResponse(
const You::QueryEngine::Response& response) override {
return DELETE_RESULT {
boost::get<Task::ID>(response)
};
}
};
try {
const Task& task = context.at(query.taskID);
return std::unique_ptr<QueryExecutor>(
new DeleteTaskQueryExecutor(
QueryEngine::DeleteTask(
task.getID())));
} catch (std::out_of_range& e) {
throw ContextIndexOutOfRangeException(e);
}
}
} // namespace Internal
} // namespace Controller
} // namespace You
<|endoftext|>
|
<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <iostream>
#include <string>
// STDAIR
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/factory/FacBomContent.hpp>
// AIRSCHED
#include <airsched/command/ScheduleParserHelper.hpp>
#include <airsched/command/ScheduleParser.hpp>
#include <airsched/command/InventoryGenerator.hpp>
#include <airsched/service/Logger.hpp>
namespace AIRSCHED {
// //////////////////////////////////////////////////////////////////////
stdair::BomRoot& ScheduleParser::
generateInventories (const std::string& iFilename,
const stdair::AirlineFeatureSet& iAirlineFeatureSet,
const Date_T& iStartAnalysisDate) {
stdair::BomRoot& oBomRoot =
stdair::FacBomContent::instance().create<stdair::BomRoot> ();
// Set the AirlineFeatureSet for the BomRoot.
oBomRoot.setAirlineFeatureSet (&iAirlineFeatureSet);
// Initialise the Flight-Period file parser.
FlightPeriodFileParser lFlightPeriodParser (oBomRoot, iStartAnalysisDate,
iFilename);
// Parse the CSV-formatted schedule input file, and generate the
// corresponding Inventories for the airlines.
lFlightPeriodParser.generateInventories ();
// Complete the BomRoot BOM building
// Create the routings for all the inventories.
InventoryGenerator::createDirectAccesses (oBomRoot);
return oBomRoot;
}
}
<commit_msg>Small adaptation to stdair.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <iostream>
#include <string>
// STDAIR
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/Network.hpp>
#include <stdair/factory/FacBomContent.hpp>
// AIRSCHED
#include <airsched/command/ScheduleParserHelper.hpp>
#include <airsched/command/ScheduleParser.hpp>
#include <airsched/command/InventoryGenerator.hpp>
#include <airsched/service/Logger.hpp>
namespace AIRSCHED {
// //////////////////////////////////////////////////////////////////////
stdair::BomRoot& ScheduleParser::
generateInventories (const std::string& iFilename,
const stdair::AirlineFeatureSet& iAirlineFeatureSet,
const Date_T& iStartAnalysisDate) {
stdair::BomRoot& oBomRoot =
stdair::FacBomContent::instance().create<stdair::BomRoot> ();
// Set the AirlineFeatureSet for the BomRoot.
oBomRoot.setAirlineFeatureSet (&iAirlineFeatureSet);
// Initialise the Flight-Period file parser.
FlightPeriodFileParser lFlightPeriodParser (oBomRoot, iStartAnalysisDate,
iFilename);
// Parse the CSV-formatted schedule input file, and generate the
// corresponding Inventories for the airlines.
lFlightPeriodParser.generateInventories ();
// Complete the BomRoot BOM building
// Create the routings for all the inventories.
InventoryGenerator::createDirectAccesses (oBomRoot);
return oBomRoot;
}
}
<|endoftext|>
|
<commit_before>//
// BackCurl.cpp
// Created by Taymindis Woon on 23/5/17.
// Copyright © 2017 Taymindis Woon. All rights reserved.
//
#include "BackCurl.h"
namespace bcl {
/** If you activate mainLoopCallBack, please make sure bcl::LoopBackFire on the loop thread, for e.g. UI thread **/
void init() {
curl_global_init(CURL_GLOBAL_ALL);
}
void LoopBackFire() {
while (!internal::_mainLoopTasks.empty()) {
bcl::UniqueResponse response = std::move(internal::_mainLoopTasks.front());
internal::_mainLoopTasks.pop_front();
// lock during the task?
internal::_tasks_mutex.lock();
response->callBack(&(*response));
internal::_tasks_mutex.unlock();
}
}
bool isReady(FutureResponse const& f) {
return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
/*
You should call curl_global_cleanup once for each call you make to curl_global_init, after you are done using libcurl.
This function is not thread safe. You must not call it when any other thread in the program (i.e. a thread sharing the same memory) is running.
This doesn't just mean no other thread that is using libcurl. Because curl_global_cleanup calls functions of other libraries
that are similarly thread unsafe, it could conflict with any other thread that uses these other libraries.
*/
void cleanUp() {
curl_global_cleanup();
}
// For image purpose
size_t
writeByteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
MemoryByte *memBlock = (MemoryByte *)userp;
memBlock->append((unsigned char*)contents, realsize);
return realsize;
}
// For Content
size_t
writeContentCallback(void *contents, size_t size, size_t nmemb, void *contentWrapper) {
size_t realsize = size * nmemb;
std::string *memBlock = (std::string *)contentWrapper;
memBlock->append((char*)contents, realsize);
return realsize;
}
namespace internal {
std::deque<bcl::UniqueResponse> _mainLoopTasks;
std::mutex _tasks_mutex;
bool _hasMainLoopCallBack = false;
//void BackCurlLoopCallBackChecker(bcl::Response &s) {
// _hasMainLoopCallBack = true;
//}
void wrapResponse(bcl::Request &r, bcl::Response &resp) {
curl_easy_getinfo(r.curl, CURLINFO_RESPONSE_CODE, &resp.code);
curl_easy_getinfo(r.curl, CURLINFO_TOTAL_TIME, &resp.totalTime);
char *url = NULL;
curl_easy_getinfo(r.curl, CURLINFO_EFFECTIVE_URL, &url);
if (url)
resp.effectiveUrl = std::string(url);
char *ct = NULL;
curl_easy_getinfo(r.curl, CURLINFO_CONTENT_TYPE, &ct);
if (ct)
resp.contentType = std::string(ct);
resp.__body = r.dataPtr;
resp.curl = r.curl;
}
// template <typename DataType>
// auto __execute__(std::function<void(bcl::Request &req)> optsFilter, std::function<void(bcl::Response)> respFilter, CALL_TYPE,
// DataType &chunk) -> Response<decltype(chunk)>
void __execute__(bcl::Request &request, bcl::UniqueResponse response, bcl::internal::CALL_TYPE callType) {
CURLcode curlCode;
curl_slist *headersList = NULL;
// curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
request.curl = curl_easy_init();
try {
/***ROOT CAUSE MESSAGE***/
if ((curlCode = curl_easy_setopt(request.curl, CURLOPT_ERRORBUFFER, request.errorBuffer)) != CURLE_OK) {
fprintf(stderr, "Failed to set error buffer [%d]\n", curlCode);
throw request.errorBuffer;
}
request.callBack(&request);
bcl::Headers &headers = request.headers;
if (headers.size() > 0) {
for (size_t i = 0; i < headers.size(); ++i)
headersList = curl_slist_append(headersList, (headers.at(i).first + ": " + headers.at(i).second).c_str());
if (curl_easy_setopt(request.curl, CURLOPT_HTTPHEADER, headersList) != CURLE_OK) {
fprintf(stderr, "Failed to set headers params [%s]\n", request.errorBuffer);
throw request.errorBuffer;
}
}
/* get it! and check for errors*/
if (curl_easy_perform(request.curl) != CURLE_OK) {
throw request.errorBuffer;
}
} catch (char const* err) {
response->error = std::string(err);
} catch (std::exception& e) {
}
bcl::internal::wrapResponse(request, *response);
if (headersList) {
curl_slist_free_all(headersList);
}
// delete []request.cbPtr;
switch (callType) {
case internal::MAIN_LOOP_CALLBACK:
{
std::lock_guard<std::mutex> lock(_tasks_mutex);
_mainLoopTasks.push_back(std::move(response));
}
break;
case internal::ASYNC_CALL:
response->callBack(&(*response));
break;
default:
response->callBack(&(*response));
break;
}
}
void __execute__(bcl::Request &request, bcl::Response &response) {
CURLcode curlCode;
curl_slist *headersList = NULL;
// curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
request.curl = curl_easy_init();
try {
/***ROOT CAUSE MESSAGE***/
if ((curlCode = curl_easy_setopt(request.curl, CURLOPT_ERRORBUFFER, request.errorBuffer)) != CURLE_OK) {
fprintf(stderr, "Failed to set error buffer [%d]\n", curlCode);
throw request.errorBuffer;
}
request.callBack(&request);
bcl::Headers &headers = request.headers;
if (headers.size() > 0) {
for (size_t i = 0; i < headers.size(); ++i)
headersList = curl_slist_append(headersList, (headers.at(i).first + ": " + headers.at(i).second).c_str());
if (curl_easy_setopt(request.curl, CURLOPT_HTTPHEADER, headersList) != CURLE_OK) {
fprintf(stderr, "Failed to set headers params [%s]\n", request.errorBuffer);
throw request.errorBuffer;
}
}
/* get it! and check for errors*/
if (curl_easy_perform(request.curl) != CURLE_OK) {
throw request.errorBuffer;
}
} catch (char const* err) {
response.error = std::string(err);
} catch (std::exception& e) {
}
bcl::internal::wrapResponse(request, response);
if (headersList) {
curl_slist_free_all(headersList);
}
}
}
// ** Request Bundle **/
lmbdaptr& bcl::Request::attach_lmbdaptr() {
return callBack;
}
// ** Response Bundle ** /
bcl::Response::Response(bcl::Args &_args) {
args = _args;
curl = NULL;
__body = NULL;
cbPtr = NULL;
streamClose = NULL;
}
bcl::Response::~Response () {
// if (__streamRef != NULL && --(*__streamRef) == 0) {
close();
// }
}
void bcl::Response::close() {
// delete static_cast<std::remove_pointer<decltype(body)*>::type>(body); //best solution so far
if (__body && streamClose)
streamClose(this);
if(args)
delete []args;
// if (cbPtr)
// delete []cbPtr;
// printf("address of CURL is %p\n", curl);
if (curl)
curl_easy_cleanup(curl); // TODO please implement clean up curl later by using valgrind got error or not
// __body = NULL;
}
lmbdaptr& bcl::Response::attach_lmbdaptr() {
return callBack;
}
void bcl::Response::setStreamClose(lmbdaptr lmbdaClz) {
streamClose = lmbdaClz;
}
bcl::Arg::Arg(): type(0) {
__strRef = new int(1);
}
bcl::Arg::Arg(Arg* a) : type(a->type) {
mapVal(*a);
__strRef = new int(1);
}
bcl::Arg::Arg(const Arg& a) : type(a.type), __strRef(a.__strRef)
{
mapVal(a);
(*__strRef) ++;
}
Arg& bcl::Arg::operator = (const Arg& a)
{
// Assignment operator
if (this != &a) // Avoid self assignment
{
if (--(*__strRef) == 0) {
if (type == 5)
delete []getStr;
delete __strRef;
}
mapVal(a);
__strRef = a.__strRef;
(*__strRef)++;
}
return *this;
}
bcl::Arg::~Arg() {
if (--(*__strRef) == 0) {
if (type == 5)
delete []getStr;
delete __strRef;
}
}
void bcl::Arg::mapVal(const Arg &a) {
switch (a.type) {
case 1:
getInt = a.getInt;
break;
case 2:
getFloat = a.getFloat;
break;
case 3:
getLong = a.getLong;
break;
case 4:
getChar = a.getChar;
break;
case 5:
getStr = a.getStr;
break;
}
type = a.type;
}
// Request Args
void setArgs(bcl::Arg *args, int arg) {
Arg a;
a.getInt = arg;
a.type = 1;
*args = a;
}
void setArgs(bcl::Arg *args, float arg) {
Arg a;
a.getFloat = arg;
a.type = 2;
*args = a;
}
void setArgs(bcl::Arg *args, long arg) {
Arg a;
a.getLong = arg;
a.type = 3;
*args = a;
}
void setArgs(bcl::Arg *args, char arg) {
Arg a;
a.getChar = arg;
a.type = 4;
*args = a;
}
void setArgs(bcl::Arg *args, const char* arg) {
Arg a;
a.getStr = new char[strlen(arg) + 1];
strcpy(a.getStr, arg);
a.type = 5;
*args = a;
}
}
<commit_msg>remove redundant<commit_after>//
// BackCurl.cpp
// Created by Taymindis Woon on 23/5/17.
// Copyright © 2017 Taymindis Woon. All rights reserved.
//
#include "BackCurl.h"
namespace bcl {
/** If you activate mainLoopCallBack, please make sure bcl::LoopBackFire on the loop thread, for e.g. UI thread **/
void init() {
curl_global_init(CURL_GLOBAL_ALL);
}
void LoopBackFire() {
while (!internal::_mainLoopTasks.empty()) {
bcl::UniqueResponse response = std::move(internal::_mainLoopTasks.front());
internal::_mainLoopTasks.pop_front();
// lock during the task?
internal::_tasks_mutex.lock();
response->callBack(&(*response));
internal::_tasks_mutex.unlock();
}
}
bool isReady(FutureResponse const& f) {
return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
/*
You should call curl_global_cleanup once for each call you make to curl_global_init, after you are done using libcurl.
This function is not thread safe. You must not call it when any other thread in the program (i.e. a thread sharing the same memory) is running.
This doesn't just mean no other thread that is using libcurl. Because curl_global_cleanup calls functions of other libraries
that are similarly thread unsafe, it could conflict with any other thread that uses these other libraries.
*/
void cleanUp() {
curl_global_cleanup();
}
// For image purpose
size_t
writeByteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
MemoryByte *memBlock = (MemoryByte *)userp;
memBlock->append((unsigned char*)contents, realsize);
return realsize;
}
// For Content
size_t
writeContentCallback(void *contents, size_t size, size_t nmemb, void *contentWrapper) {
size_t realsize = size * nmemb;
std::string *memBlock = (std::string *)contentWrapper;
memBlock->append((char*)contents, realsize);
return realsize;
}
namespace internal {
std::deque<bcl::UniqueResponse> _mainLoopTasks;
std::mutex _tasks_mutex;
bool _hasMainLoopCallBack = false;
//void BackCurlLoopCallBackChecker(bcl::Response &s) {
// _hasMainLoopCallBack = true;
//}
void wrapResponse(bcl::Request &r, bcl::Response &resp) {
curl_easy_getinfo(r.curl, CURLINFO_RESPONSE_CODE, &resp.code);
curl_easy_getinfo(r.curl, CURLINFO_TOTAL_TIME, &resp.totalTime);
char *url = NULL;
curl_easy_getinfo(r.curl, CURLINFO_EFFECTIVE_URL, &url);
if (url)
resp.effectiveUrl = std::string(url);
char *ct = NULL;
curl_easy_getinfo(r.curl, CURLINFO_CONTENT_TYPE, &ct);
if (ct)
resp.contentType = std::string(ct);
resp.__body = r.dataPtr;
resp.curl = r.curl;
}
// template <typename DataType>
// auto __execute__(std::function<void(bcl::Request &req)> optsFilter, std::function<void(bcl::Response)> respFilter, CALL_TYPE,
// DataType &chunk) -> Response<decltype(chunk)>
void __execute__(bcl::Request &request, bcl::UniqueResponse response, bcl::internal::CALL_TYPE callType) {
CURLcode curlCode;
curl_slist *headersList = NULL;
// curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
request.curl = curl_easy_init();
try {
/***ROOT CAUSE MESSAGE***/
if ((curlCode = curl_easy_setopt(request.curl, CURLOPT_ERRORBUFFER, request.errorBuffer)) != CURLE_OK) {
fprintf(stderr, "Failed to set error buffer [%d]\n", curlCode);
throw request.errorBuffer;
}
request.callBack(&request);
bcl::Headers &headers = request.headers;
if (headers.size() > 0) {
for (size_t i = 0; i < headers.size(); ++i)
headersList = curl_slist_append(headersList, (headers.at(i).first + ": " + headers.at(i).second).c_str());
if (curl_easy_setopt(request.curl, CURLOPT_HTTPHEADER, headersList) != CURLE_OK) {
fprintf(stderr, "Failed to set headers params [%s]\n", request.errorBuffer);
throw request.errorBuffer;
}
}
/* get it! and check for errors*/
if (curl_easy_perform(request.curl) != CURLE_OK) {
throw request.errorBuffer;
}
} catch (char const* err) {
response->error = std::string(err);
} catch (std::exception& e) {
}
bcl::internal::wrapResponse(request, *response);
if (headersList) {
curl_slist_free_all(headersList);
}
// delete []request.cbPtr;
if(callType == internal::MAIN_LOOP_CALLBACK) {
std::lock_guard<std::mutex> lock(_tasks_mutex);
_mainLoopTasks.push_back(std::move(response));
} else {
response->callBack(&(*response));
}
}
void __execute__(bcl::Request &request, bcl::Response &response) {
CURLcode curlCode;
curl_slist *headersList = NULL;
// curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
request.curl = curl_easy_init();
try {
/***ROOT CAUSE MESSAGE***/
if ((curlCode = curl_easy_setopt(request.curl, CURLOPT_ERRORBUFFER, request.errorBuffer)) != CURLE_OK) {
fprintf(stderr, "Failed to set error buffer [%d]\n", curlCode);
throw request.errorBuffer;
}
request.callBack(&request);
bcl::Headers &headers = request.headers;
if (headers.size() > 0) {
for (size_t i = 0; i < headers.size(); ++i)
headersList = curl_slist_append(headersList, (headers.at(i).first + ": " + headers.at(i).second).c_str());
if (curl_easy_setopt(request.curl, CURLOPT_HTTPHEADER, headersList) != CURLE_OK) {
fprintf(stderr, "Failed to set headers params [%s]\n", request.errorBuffer);
throw request.errorBuffer;
}
}
/* get it! and check for errors*/
if (curl_easy_perform(request.curl) != CURLE_OK) {
throw request.errorBuffer;
}
} catch (char const* err) {
response.error = std::string(err);
} catch (std::exception& e) {
}
bcl::internal::wrapResponse(request, response);
if (headersList) {
curl_slist_free_all(headersList);
}
}
}
// ** Request Bundle **/
lmbdaptr& bcl::Request::attach_lmbdaptr() {
return callBack;
}
// ** Response Bundle ** /
bcl::Response::Response(bcl::Args &_args) {
args = _args;
curl = NULL;
__body = NULL;
cbPtr = NULL;
streamClose = NULL;
}
bcl::Response::~Response () {
// if (__streamRef != NULL && --(*__streamRef) == 0) {
close();
// }
}
void bcl::Response::close() {
// delete static_cast<std::remove_pointer<decltype(body)*>::type>(body); //best solution so far
if (__body && streamClose)
streamClose(this);
if(args)
delete []args;
// if (cbPtr)
// delete []cbPtr;
// printf("address of CURL is %p\n", curl);
if (curl)
curl_easy_cleanup(curl); // TODO please implement clean up curl later by using valgrind got error or not
// __body = NULL;
}
lmbdaptr& bcl::Response::attach_lmbdaptr() {
return callBack;
}
void bcl::Response::setStreamClose(lmbdaptr lmbdaClz) {
streamClose = lmbdaClz;
}
bcl::Arg::Arg(): type(0) {
__strRef = new int(1);
}
bcl::Arg::Arg(Arg* a) : type(a->type) {
mapVal(*a);
__strRef = new int(1);
}
bcl::Arg::Arg(const Arg& a) : type(a.type), __strRef(a.__strRef)
{
mapVal(a);
(*__strRef) ++;
}
Arg& bcl::Arg::operator = (const Arg& a)
{
// Assignment operator
if (this != &a) // Avoid self assignment
{
if (--(*__strRef) == 0) {
if (type == 5)
delete []getStr;
delete __strRef;
}
mapVal(a);
__strRef = a.__strRef;
(*__strRef)++;
}
return *this;
}
bcl::Arg::~Arg() {
if (--(*__strRef) == 0) {
if (type == 5)
delete []getStr;
delete __strRef;
}
}
void bcl::Arg::mapVal(const Arg &a) {
switch (a.type) {
case 1:
getInt = a.getInt;
break;
case 2:
getFloat = a.getFloat;
break;
case 3:
getLong = a.getLong;
break;
case 4:
getChar = a.getChar;
break;
case 5:
getStr = a.getStr;
break;
}
type = a.type;
}
// Request Args
void setArgs(bcl::Arg *args, int arg) {
Arg a;
a.getInt = arg;
a.type = 1;
*args = a;
}
void setArgs(bcl::Arg *args, float arg) {
Arg a;
a.getFloat = arg;
a.type = 2;
*args = a;
}
void setArgs(bcl::Arg *args, long arg) {
Arg a;
a.getLong = arg;
a.type = 3;
*args = a;
}
void setArgs(bcl::Arg *args, char arg) {
Arg a;
a.getChar = arg;
a.type = 4;
*args = a;
}
void setArgs(bcl::Arg *args, const char* arg) {
Arg a;
a.getStr = new char[strlen(arg) + 1];
strcpy(a.getStr, arg);
a.type = 5;
*args = a;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basidesh.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:25:06 $
*
* 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 _BASIDESH_HXX
#define _BASIDESH_HXX
#ifndef _SBXITEM_HXX
#include "sbxitem.hxx"
#endif
#include "scriptdocument.hxx"
#include "doceventnotifier.hxx"
#ifndef _VIEWFAC_HXX //autogen
#include <sfx2/viewfac.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SCRBAR_HXX //autogen
#include <vcl/scrbar.hxx>
#endif
#ifndef _TABLE_HXX //autogen
#include <tools/table.hxx>
#endif
#ifndef _SFXVIEWSH_HXX //autogen
#include <sfx2/viewsh.hxx>
#endif
#include <svx/ifaceids.hxx>
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAMPROVIDER_HXX_
#include <com/sun/star/io/XInputStreamProvider.hpp>
#endif
//----------------------------------------------------------------------------
const ULONG BASICIDE_UI_FEATURE_SHOW_BROWSER = 0x00000001;
//----------------------------------------------------------------------------
class ModulWindow;
class ModulWindowLayout;
class DialogWindow;
class SdrView;
class ObjectCatalog;
class BasicIDETabBar;
class TabBar;
class IDEBaseWindow;
class SbxObject;
class SbModule;
class StarBASIC;
class LocalizationMgr;
struct BasicIDEShell_Impl;
#if _SOLAR__PRIVATE
DECLARE_TABLE( IDEWindowTable, IDEBaseWindow* )
#else
typedef Table IDEWindowTable;
#endif
class BasicIDEShell :public SfxViewShell
,public ::basctl::DocumentEventListener
{
friend class JavaDebuggingListenerImpl;
friend class LocalizationMgr;
friend class BasicIDE;
ObjectCatalog* pObjectCatalog;
IDEWindowTable aIDEWindowTable;
USHORT nCurKey;
IDEBaseWindow* pCurWin;
ScriptDocument m_aCurDocument;
String m_aCurLibName;
LocalizationMgr* m_pCurLocalizationMgr;
ScrollBar aHScrollBar;
ScrollBar aVScrollBar;
ScrollBarBox aScrollBarBox;
BasicIDETabBar* pTabBar;
BOOL bTabBarSplitted;
BOOL bCreatingWindow;
ModulWindowLayout* pModulLayout;
BOOL m_bAppBasicModified;
::basctl::DocumentEventNotifier
m_aNotifier;
#if _SOLAR__PRIVATE
void Init();
void InitTabBar();
void InitScrollBars();
void CheckWindows();
void RemoveWindows( const ScriptDocument& rDocument, const String& rLibName, BOOL bDestroy );
void UpdateWindows();
void ShowObjectDialog( BOOL bShow, BOOL bCreateOrDestroy );
void InvalidateBasicIDESlots();
void StoreAllWindowData( BOOL bPersistent = TRUE );
void SetMDITitle();
void EnableScrollbars( BOOL bEnable );
void SetCurLib( const ScriptDocument& rDocument, String aLibName, bool bUpdateWindows = true , bool bCheck = true );
void SetCurLibForLocalization( const ScriptDocument& rDocument, String aLibName );
void ImplStartListening( StarBASIC* pBasic );
DECL_LINK( TabBarHdl, TabBar* );
DECL_LINK( AccelSelectHdl, Accelerator* );
DECL_LINK( ObjectDialogCancelHdl, ObjectCatalog * );
DECL_LINK( TabBarSplitHdl, TabBar * );
#endif
protected:
virtual void AdjustPosSizePixel( const Point &rPos, const Size &rSize );
virtual void OuterResizePixel( const Point &rPos, const Size &rSize );
virtual Size GetOptimalSizePixel() const;
USHORT InsertWindowInTable( IDEBaseWindow* pNewWin );
virtual USHORT PrepareClose( BOOL bUI, BOOL bForBrowsing );
void SetCurWindow( IDEBaseWindow* pNewWin, BOOL bUpdateTabBar = FALSE, BOOL bRememberAsCurrent = TRUE );
void ManageToolbars();
void RemoveWindow( IDEBaseWindow* pWindow, BOOL bDestroy, BOOL bAllowChangeCurWindow = TRUE );
void ArrangeTabBar();
ModulWindow* CreateBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName );
DialogWindow* CreateDlgWin( const ScriptDocument& rDocument, const String& rLibName, const String& rDlgName );
ModulWindow* FindBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName, BOOL bCreateIfNotExist, BOOL bFindSuspended = FALSE );
DialogWindow* FindDlgWin( const ScriptDocument& rDocument, const String& rLibName, const String& rDlgName, BOOL bCreateIfNotExist, BOOL bFindSuspended = FALSE );
ModulWindow* ShowActiveModuleWindow( StarBASIC* pBasic );
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
virtual void Activate(BOOL bMDI);
virtual void Deactivate(BOOL bMDI);
virtual void Move();
virtual void ShowCursor( FASTBOOL bOn = TRUE );
void CreateModulWindowLayout();
void DestroyModulWindowLayout();
void UpdateModulWindowLayout( bool bBasicStopped );
sal_Bool HasBasic() const;
// DocumentEventListener
virtual void onDocumentCreated( const ScriptDocument& _rDocument );
virtual void onDocumentOpened( const ScriptDocument& _rDocument );
virtual void onDocumentSave( const ScriptDocument& _rDocument );
virtual void onDocumentSaveDone( const ScriptDocument& _rDocument );
virtual void onDocumentSaveAs( const ScriptDocument& _rDocument );
virtual void onDocumentSaveAsDone( const ScriptDocument& _rDocument );
virtual void onDocumentClosed( const ScriptDocument& _rDocument );
virtual void onDocumentTitleChanged( const ScriptDocument& _rDocument );
virtual void onDocumentModeChanged( const ScriptDocument& _rDocument );
public:
TYPEINFO();
SFX_DECL_INTERFACE( SVX_INTERFACE_BASIDE_VIEWSH )
SFX_DECL_VIEWFACTORY(BasicIDEShell);
BasicIDEShell( SfxViewFrame *pFrame, Window *);
BasicIDEShell( SfxViewFrame *pFrame, SfxViewShell *pOldSh );
BasicIDEShell( SfxViewFrame *pFrame, const BasicIDEShell &rOrig );
~BasicIDEShell();
IDEBaseWindow* GetCurWindow() const { return pCurWin; }
const ScriptDocument&
GetCurDocument() const { return m_aCurDocument; }
const String& GetCurLibName() const { return m_aCurLibName; }
ObjectCatalog* GetObjectCatalog() const { return pObjectCatalog; }
LocalizationMgr* GetCurLocalizationMgr() const { return m_pCurLocalizationMgr; }
ScrollBar& GetHScrollBar() { return aHScrollBar; }
ScrollBar& GetVScrollBar() { return aVScrollBar; }
ScrollBarBox& GetScrollBarBox() { return aScrollBarBox; }
TabBar* GetTabBar() { return (TabBar*)pTabBar; }
IDEWindowTable& GetIDEWindowTable() { return aIDEWindowTable; }
SdrView* GetCurDlgView();
SfxUndoManager* GetUndoManager();
virtual USHORT Print( SfxProgress &rProgress, BOOL bIsAPI, PrintDialog *pPrintDialog = 0 );
virtual SfxPrinter* GetPrinter( BOOL bCreate );
virtual USHORT SetPrinter( SfxPrinter *pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL, bool bIsAPI=false );
virtual String GetSelectionText( BOOL bCompleteWords );
virtual BOOL HasSelection( BOOL bText ) const;
void GetState( SfxItemSet& );
void ExecuteGlobal( SfxRequest& rReq );
void ExecuteCurrent( SfxRequest& rReq );
void ExecuteBasic( SfxRequest& rReq );
void ExecuteDialog( SfxRequest& rReq );
virtual sal_Bool HasUIFeature( sal_uInt32 nFeature );
long CallBasicErrorHdl( StarBASIC* pBasic );
long CallBasicBreakHdl( StarBASIC* pBasic );
ModulWindowLayout* GetLayoutWindow() const { return pModulLayout; }
IDEBaseWindow* FindWindow( const ScriptDocument& rDocument, const String& rLibName = String(), const String& rName = String(), USHORT nType = BASICIDE_TYPE_UNKNOWN, BOOL bFindSuspended = FALSE );
IDEBaseWindow* FindApplicationWindow();
BOOL NextPage( BOOL bPrev = FALSE );
BOOL IsAppBasicModified() const { return m_bAppBasicModified; }
void SetAppBasicModified( BOOL bModified = TRUE ) { m_bAppBasicModified = bModified; }
// For Dialog Drag&Drop in Dialog Organizer
static void CopyDialogResources(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStreamProvider >& io_xISP,
const ScriptDocument& rSourceDoc, const String& rSourceLibName, const ScriptDocument& rDestDoc,
const String& rDestLibName, const String& rDlgName );
};
#endif // _BASIDESH_HXX
<commit_msg>INTEGRATION: CWS odbmacros2 (1.7.16); FILE MERGED 2008/02/25 13:26:53 fs 1.7.16.2: #i86427# GetCurrentDocument made public 2007/12/22 13:32:23 fs 1.7.16.1: #i49133# overload GetCurrentComponent<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basidesh.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:14:54 $
*
* 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 _BASIDESH_HXX
#define _BASIDESH_HXX
#ifndef _SBXITEM_HXX
#include "sbxitem.hxx"
#endif
#include "scriptdocument.hxx"
#include "doceventnotifier.hxx"
#ifndef _VIEWFAC_HXX //autogen
#include <sfx2/viewfac.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SCRBAR_HXX //autogen
#include <vcl/scrbar.hxx>
#endif
#ifndef _TABLE_HXX //autogen
#include <tools/table.hxx>
#endif
#ifndef _SFXVIEWSH_HXX //autogen
#include <sfx2/viewsh.hxx>
#endif
#include <svx/ifaceids.hxx>
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAMPROVIDER_HXX_
#include <com/sun/star/io/XInputStreamProvider.hpp>
#endif
//----------------------------------------------------------------------------
const ULONG BASICIDE_UI_FEATURE_SHOW_BROWSER = 0x00000001;
//----------------------------------------------------------------------------
class ModulWindow;
class ModulWindowLayout;
class DialogWindow;
class SdrView;
class ObjectCatalog;
class BasicIDETabBar;
class TabBar;
class IDEBaseWindow;
class SbxObject;
class SbModule;
class StarBASIC;
class LocalizationMgr;
struct BasicIDEShell_Impl;
#if _SOLAR__PRIVATE
DECLARE_TABLE( IDEWindowTable, IDEBaseWindow* )
#else
typedef Table IDEWindowTable;
#endif
class BasicIDEShell :public SfxViewShell
,public ::basctl::DocumentEventListener
{
friend class JavaDebuggingListenerImpl;
friend class LocalizationMgr;
friend class BasicIDE;
ObjectCatalog* pObjectCatalog;
IDEWindowTable aIDEWindowTable;
USHORT nCurKey;
IDEBaseWindow* pCurWin;
ScriptDocument m_aCurDocument;
String m_aCurLibName;
LocalizationMgr* m_pCurLocalizationMgr;
ScrollBar aHScrollBar;
ScrollBar aVScrollBar;
ScrollBarBox aScrollBarBox;
BasicIDETabBar* pTabBar;
BOOL bTabBarSplitted;
BOOL bCreatingWindow;
ModulWindowLayout* pModulLayout;
BOOL m_bAppBasicModified;
::basctl::DocumentEventNotifier
m_aNotifier;
#if _SOLAR__PRIVATE
void Init();
void InitTabBar();
void InitScrollBars();
void CheckWindows();
void RemoveWindows( const ScriptDocument& rDocument, const String& rLibName, BOOL bDestroy );
void UpdateWindows();
void ShowObjectDialog( BOOL bShow, BOOL bCreateOrDestroy );
void InvalidateBasicIDESlots();
void StoreAllWindowData( BOOL bPersistent = TRUE );
void SetMDITitle();
void EnableScrollbars( BOOL bEnable );
void SetCurLib( const ScriptDocument& rDocument, String aLibName, bool bUpdateWindows = true , bool bCheck = true );
void SetCurLibForLocalization( const ScriptDocument& rDocument, String aLibName );
void ImplStartListening( StarBASIC* pBasic );
DECL_LINK( TabBarHdl, TabBar* );
DECL_LINK( AccelSelectHdl, Accelerator* );
DECL_LINK( ObjectDialogCancelHdl, ObjectCatalog * );
DECL_LINK( TabBarSplitHdl, TabBar * );
#endif
protected:
virtual void AdjustPosSizePixel( const Point &rPos, const Size &rSize );
virtual void OuterResizePixel( const Point &rPos, const Size &rSize );
virtual Size GetOptimalSizePixel() const;
USHORT InsertWindowInTable( IDEBaseWindow* pNewWin );
virtual USHORT PrepareClose( BOOL bUI, BOOL bForBrowsing );
void SetCurWindow( IDEBaseWindow* pNewWin, BOOL bUpdateTabBar = FALSE, BOOL bRememberAsCurrent = TRUE );
void ManageToolbars();
void RemoveWindow( IDEBaseWindow* pWindow, BOOL bDestroy, BOOL bAllowChangeCurWindow = TRUE );
void ArrangeTabBar();
ModulWindow* CreateBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName );
DialogWindow* CreateDlgWin( const ScriptDocument& rDocument, const String& rLibName, const String& rDlgName );
ModulWindow* FindBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName, BOOL bCreateIfNotExist, BOOL bFindSuspended = FALSE );
DialogWindow* FindDlgWin( const ScriptDocument& rDocument, const String& rLibName, const String& rDlgName, BOOL bCreateIfNotExist, BOOL bFindSuspended = FALSE );
ModulWindow* ShowActiveModuleWindow( StarBASIC* pBasic );
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
virtual void Activate(BOOL bMDI);
virtual void Deactivate(BOOL bMDI);
virtual void Move();
virtual void ShowCursor( FASTBOOL bOn = TRUE );
void CreateModulWindowLayout();
void DestroyModulWindowLayout();
void UpdateModulWindowLayout( bool bBasicStopped );
sal_Bool HasBasic() const;
// DocumentEventListener
virtual void onDocumentCreated( const ScriptDocument& _rDocument );
virtual void onDocumentOpened( const ScriptDocument& _rDocument );
virtual void onDocumentSave( const ScriptDocument& _rDocument );
virtual void onDocumentSaveDone( const ScriptDocument& _rDocument );
virtual void onDocumentSaveAs( const ScriptDocument& _rDocument );
virtual void onDocumentSaveAsDone( const ScriptDocument& _rDocument );
virtual void onDocumentClosed( const ScriptDocument& _rDocument );
virtual void onDocumentTitleChanged( const ScriptDocument& _rDocument );
virtual void onDocumentModeChanged( const ScriptDocument& _rDocument );
public:
TYPEINFO();
SFX_DECL_INTERFACE( SVX_INTERFACE_BASIDE_VIEWSH )
SFX_DECL_VIEWFACTORY(BasicIDEShell);
BasicIDEShell( SfxViewFrame *pFrame, Window *);
BasicIDEShell( SfxViewFrame *pFrame, SfxViewShell *pOldSh );
BasicIDEShell( SfxViewFrame *pFrame, const BasicIDEShell &rOrig );
~BasicIDEShell();
IDEBaseWindow* GetCurWindow() const { return pCurWin; }
const ScriptDocument&
GetCurDocument() const { return m_aCurDocument; }
const String& GetCurLibName() const { return m_aCurLibName; }
ObjectCatalog* GetObjectCatalog() const { return pObjectCatalog; }
LocalizationMgr* GetCurLocalizationMgr() const { return m_pCurLocalizationMgr; }
ScrollBar& GetHScrollBar() { return aHScrollBar; }
ScrollBar& GetVScrollBar() { return aVScrollBar; }
ScrollBarBox& GetScrollBarBox() { return aScrollBarBox; }
TabBar* GetTabBar() { return (TabBar*)pTabBar; }
IDEWindowTable& GetIDEWindowTable() { return aIDEWindowTable; }
SdrView* GetCurDlgView() const;
SfxUndoManager* GetUndoManager();
virtual USHORT Print( SfxProgress &rProgress, BOOL bIsAPI, PrintDialog *pPrintDialog = 0 );
virtual SfxPrinter* GetPrinter( BOOL bCreate );
virtual USHORT SetPrinter( SfxPrinter *pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL, bool bIsAPI=false );
virtual String GetSelectionText( BOOL bCompleteWords );
virtual BOOL HasSelection( BOOL bText ) const;
void GetState( SfxItemSet& );
void ExecuteGlobal( SfxRequest& rReq );
void ExecuteCurrent( SfxRequest& rReq );
void ExecuteBasic( SfxRequest& rReq );
void ExecuteDialog( SfxRequest& rReq );
virtual sal_Bool HasUIFeature( sal_uInt32 nFeature );
long CallBasicErrorHdl( StarBASIC* pBasic );
long CallBasicBreakHdl( StarBASIC* pBasic );
ModulWindowLayout* GetLayoutWindow() const { return pModulLayout; }
IDEBaseWindow* FindWindow( const ScriptDocument& rDocument, const String& rLibName = String(), const String& rName = String(), USHORT nType = BASICIDE_TYPE_UNKNOWN, BOOL bFindSuspended = FALSE );
IDEBaseWindow* FindApplicationWindow();
BOOL NextPage( BOOL bPrev = FALSE );
BOOL IsAppBasicModified() const { return m_bAppBasicModified; }
void SetAppBasicModified( BOOL bModified = TRUE ) { m_bAppBasicModified = bModified; }
// For Dialog Drag&Drop in Dialog Organizer
static void CopyDialogResources(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStreamProvider >& io_xISP,
const ScriptDocument& rSourceDoc, const String& rSourceLibName, const ScriptDocument& rDestDoc,
const String& rDestLibName, const String& rDlgName );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >
GetCurrentDocument() const;
};
#endif // _BASIDESH_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dlgedobj.hxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: hr $ $Date: 2003-11-05 12:40:38 $
*
* 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 _BASCTL_DLGEDOBJ_HXX
#define _BASCTL_DLGEDOBJ_HXX
#ifndef _SVDOUNO_HXX
#include <svx/svdouno.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#include <vector>
#include <map>
typedef ::std::multimap< sal_Int16, ::rtl::OUString, ::std::less< sal_Int16 > > IndexToNameMap;
class DlgEdForm;
//============================================================================
// DlgEdObj
//============================================================================
class DlgEdObj: public SdrUnoObj
{
friend class DlgEditor;
friend class DlgEdFactory;
friend class DlgEdPropListenerImpl;
friend class DlgEdForm;
private:
sal_Bool bIsListening;
DlgEdForm* pDlgEdForm;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener> m_xPropertyChangeListener;
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener> m_xContainerListener;
protected:
DlgEdObj();
DlgEdObj(const ::rtl::OUString& rModelName);
DlgEdObj(const ::rtl::OUString& rModelName,
const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSFac);
virtual void WriteData(SvStream& rOut) const; // not working yet
virtual void ReadData(const SdrObjIOHeader& rHead, SvStream& rIn); // not working yet
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
DECL_LINK(OnCreate, void* );
void StartListening();
void EndListening(sal_Bool bRemoveListener = sal_True);
sal_Bool isListening() const { return bIsListening; }
public:
TYPEINFO();
virtual ~DlgEdObj();
virtual void SetPage(SdrPage* pNewPage);
virtual void SetDlgEdForm( DlgEdForm* pForm ) { pDlgEdForm = pForm; }
virtual DlgEdForm* GetDlgEdForm() const { return pDlgEdForm; }
virtual sal_uInt32 GetObjInventor() const;
virtual sal_uInt16 GetObjIdentifier() const;
virtual SdrObject* Clone() const; // not working yet
virtual SdrObject* Clone(SdrPage* pPage, SdrModel* pModel) const; // not working yet
virtual void operator= (const SdrObject& rObj); // not working yet
virtual void clonedFrom(const DlgEdObj* _pSource); // not working yet
virtual sal_Bool supportsService( const sal_Char* _pServiceName ) const;
virtual ::rtl::OUString GetDefaultName() const;
virtual ::rtl::OUString GetUniqueName() const;
virtual sal_Int32 GetStep() const;
virtual void UpdateStep();
virtual void SetDefaults();
virtual void SetRectFromProps();
virtual void SetPropsFromRect();
virtual void SAL_CALL NameChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL TabIndexChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException);
// PropertyChangeListener
virtual void SAL_CALL _propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);
// ContainerListener
virtual void SAL_CALL _elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL _elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL _elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
virtual void SetLayer(SdrLayerID nLayer);
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
};
//============================================================================
// DlgEdForm
//============================================================================
class DlgEdForm: public DlgEdObj
{
friend class DlgEditor;
friend class DlgEdFactory;
private:
DlgEditor* pDlgEditor;
::std::vector<DlgEdObj*> pChilds;
protected:
DlgEdForm(const ::rtl::OUString& rModelName);
DlgEdForm(const ::rtl::OUString& rModelName,
const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSFac);
DlgEdForm();
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
public:
TYPEINFO();
virtual ~DlgEdForm();
virtual void SetDlgEditor( DlgEditor* pEditor ) { pDlgEditor = pEditor; }
virtual DlgEditor* GetDlgEditor() const { return pDlgEditor; }
virtual void AddChild( DlgEdObj* pDlgEdObj );
virtual void RemoveChild( DlgEdObj* pDlgEdObj );
virtual ::std::vector<DlgEdObj*> GetChilds() const { return pChilds; }
virtual void UpdateStep();
virtual void SetRectFromProps();
virtual void SetPropsFromRect();
virtual void UpdateTabIndices();
virtual void UpdateTabOrder();
virtual void UpdateGroups();
virtual void UpdateTabOrderAndGroups();
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
};
#endif // _BASCTL_DLGEDOBJ_HXX
<commit_msg>INTEGRATION: CWS aw019 (1.17.116); FILE MERGED 2004/09/30 12:45:53 aw 1.17.116.1: #i11190#<commit_after>/*************************************************************************
*
* $RCSfile: dlgedobj.hxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 11:17:30 $
*
* 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 _BASCTL_DLGEDOBJ_HXX
#define _BASCTL_DLGEDOBJ_HXX
#ifndef _SVDOUNO_HXX
#include <svx/svdouno.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#include <vector>
#include <map>
typedef ::std::multimap< sal_Int16, ::rtl::OUString, ::std::less< sal_Int16 > > IndexToNameMap;
class DlgEdForm;
//============================================================================
// DlgEdObj
//============================================================================
class DlgEdObj: public SdrUnoObj
{
friend class DlgEditor;
friend class DlgEdFactory;
friend class DlgEdPropListenerImpl;
friend class DlgEdForm;
private:
sal_Bool bIsListening;
DlgEdForm* pDlgEdForm;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener> m_xPropertyChangeListener;
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener> m_xContainerListener;
protected:
DlgEdObj();
DlgEdObj(const ::rtl::OUString& rModelName);
DlgEdObj(const ::rtl::OUString& rModelName,
const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSFac);
//BFS01 virtual void WriteData(SvStream& rOut) const; // not working yet
//BFS01 virtual void ReadData(const SdrObjIOHeader& rHead, SvStream& rIn); // not working yet
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
DECL_LINK(OnCreate, void* );
void StartListening();
void EndListening(sal_Bool bRemoveListener = sal_True);
sal_Bool isListening() const { return bIsListening; }
public:
TYPEINFO();
virtual ~DlgEdObj();
virtual void SetPage(SdrPage* pNewPage);
virtual void SetDlgEdForm( DlgEdForm* pForm ) { pDlgEdForm = pForm; }
virtual DlgEdForm* GetDlgEdForm() const { return pDlgEdForm; }
virtual sal_uInt32 GetObjInventor() const;
virtual sal_uInt16 GetObjIdentifier() const;
virtual SdrObject* Clone() const; // not working yet
virtual SdrObject* Clone(SdrPage* pPage, SdrModel* pModel) const; // not working yet
virtual void operator= (const SdrObject& rObj); // not working yet
virtual void clonedFrom(const DlgEdObj* _pSource); // not working yet
virtual sal_Bool supportsService( const sal_Char* _pServiceName ) const;
virtual ::rtl::OUString GetDefaultName() const;
virtual ::rtl::OUString GetUniqueName() const;
virtual sal_Int32 GetStep() const;
virtual void UpdateStep();
virtual void SetDefaults();
virtual void SetRectFromProps();
virtual void SetPropsFromRect();
virtual void SAL_CALL NameChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL TabIndexChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException);
// PropertyChangeListener
virtual void SAL_CALL _propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);
// ContainerListener
virtual void SAL_CALL _elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL _elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL _elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
virtual void SetLayer(SdrLayerID nLayer);
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
};
//============================================================================
// DlgEdForm
//============================================================================
class DlgEdForm: public DlgEdObj
{
friend class DlgEditor;
friend class DlgEdFactory;
private:
DlgEditor* pDlgEditor;
::std::vector<DlgEdObj*> pChilds;
protected:
DlgEdForm(const ::rtl::OUString& rModelName);
DlgEdForm(const ::rtl::OUString& rModelName,
const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSFac);
DlgEdForm();
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
public:
TYPEINFO();
virtual ~DlgEdForm();
virtual void SetDlgEditor( DlgEditor* pEditor ) { pDlgEditor = pEditor; }
virtual DlgEditor* GetDlgEditor() const { return pDlgEditor; }
virtual void AddChild( DlgEdObj* pDlgEdObj );
virtual void RemoveChild( DlgEdObj* pDlgEdObj );
virtual ::std::vector<DlgEdObj*> GetChilds() const { return pChilds; }
virtual void UpdateStep();
virtual void SetRectFromProps();
virtual void SetPropsFromRect();
virtual void UpdateTabIndices();
virtual void UpdateTabOrder();
virtual void UpdateGroups();
virtual void UpdateTabOrderAndGroups();
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
};
#endif // _BASCTL_DLGEDOBJ_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: image.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2003-05-22 11:01:17 $
*
* 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 _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#include <tools/tenccvt.hxx>
#pragma hdrstop
#include <svtools/sbx.hxx>
#include "sb.hxx"
#include <string.h> // memset() etc
#include "image.hxx"
#include "filefmt.hxx"
SbiImage::SbiImage()
{
rTypes = new SbxArray;
pStringOff = NULL;
pStrings = NULL;
pCode = NULL;
nFlags =
nStrings =
nStringSize=
nCodeSize =
nDimBase = 0;
bInit =
bError = FALSE;
bFirstInit = TRUE;
eCharSet = gsl_getSystemTextEncoding();
}
SbiImage::~SbiImage()
{
Clear();
}
void SbiImage::Clear()
{
delete[] pStringOff;
delete[] pStrings;
delete[] pCode;
pStringOff = NULL;
pStrings = NULL;
pCode = NULL;
nFlags =
nStrings =
nStringSize=
nCodeSize = 0;
eCharSet = gsl_getSystemTextEncoding();
nDimBase = 0;
bError = FALSE;
}
/**************************************************************************
*
* Service-Routinen fuer das Laden und Speichern
*
**************************************************************************/
BOOL SbiGood( SvStream& r )
{
return BOOL( !r.IsEof() && r.GetError() == SVSTREAM_OK );
}
// Oeffnen eines Records
ULONG SbiOpenRecord( SvStream& r, UINT16 nSignature, UINT16 nElem )
{
ULONG nPos = r.Tell();
r << nSignature << (INT32) 0 << nElem;
return nPos;
}
// Schliessen eines Records
void SbiCloseRecord( SvStream& r, ULONG nOff )
{
ULONG nPos = r.Tell();
r.Seek( nOff + 2 );
r << (INT32) ( nPos - nOff - 8 );
r.Seek( nPos );
}
/**************************************************************************
*
* Laden und Speichern
*
**************************************************************************/
// Falls die Versionsnummer nicht passt, werden die binaeren Teile
// nicht geladen, wohl aber Source, Kommentar und Name.
BOOL SbiImage::Load( SvStream& r )
{
UINT16 nSign, nCount;
UINT32 nLen, nOff;
Clear();
ULONG nStart = r.Tell();
// Master-Record einlesen
r >> nSign >> nLen >> nCount;
ULONG nLast = r.Tell() + nLen;
UINT32 nVersion = 0; // Versionsnummer
UINT32 nCharSet; // System-Zeichensatz
UINT32 lDimBase;
UINT16 nReserved1;
UINT32 nReserved2;
UINT32 nReserved3;
BOOL bBadVer = FALSE;
if( nSign == B_MODULE )
{
r >> nVersion >> nCharSet >> lDimBase
>> nFlags >> nReserved1 >> nReserved2 >> nReserved3;
eCharSet = (CharSet) nCharSet;
eCharSet = GetSOLoadTextEncoding( eCharSet );
bBadVer = BOOL( nVersion != B_CURVERSION );
nDimBase = (USHORT) lDimBase;
}
ULONG nNext;
while( ( nNext = r.Tell() ) < nLast )
{
short i;
r >> nSign >> nLen >> nCount;
nNext += nLen + 8;
if( r.GetError() == SVSTREAM_OK )
switch( nSign )
{
case B_NAME:
r.ReadByteString( aName, eCharSet );
//r >> aName;
break;
case B_COMMENT:
r.ReadByteString( aComment, eCharSet );
//r >> aComment;
break;
case B_SOURCE:
{
String aTmp;
r.ReadByteString( aTmp, eCharSet );
aOUSource = aTmp;
//r >> aSource;
break;
}
case B_PCODE:
if( bBadVer ) break;
pCode = new char[ nLen ];
nCodeSize = (USHORT) nLen;
r.Read( pCode, nCodeSize );
break;
case B_PUBLICS:
case B_POOLDIR:
case B_SYMPOOL:
case B_LINERANGES:
break;
case B_STRINGPOOL:
if( bBadVer ) break;
MakeStrings( nCount );
for( i = 0; i < nStrings && SbiGood( r ); i++ )
{
r >> nOff;
pStringOff[ i ] = (USHORT) nOff;
}
r >> nLen;
if( SbiGood( r ) )
{
delete [] pStrings;
pStrings = new sal_Unicode[ nLen ];
nStringSize = (USHORT) nLen;
char* pByteStrings = new char[ nLen ];
r.Read( pByteStrings, nStringSize );
for( short i = 0; i < nStrings; i++ )
{
USHORT nOff = pStringOff[ i ];
String aStr( pByteStrings + nOff, eCharSet );
memcpy( pStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( sal_Unicode ) );
}
delete[] pByteStrings;
} break;
case B_MODEND:
goto done;
default:
break;
}
else
break;
r.Seek( nNext );
}
done:
r.Seek( nLast );
//if( eCharSet != ::GetSystemCharSet() )
//ConvertStrings();
if( !SbiGood( r ) )
bError = TRUE;
return BOOL( !bError );
}
BOOL SbiImage::Save( SvStream& r )
{
// Erst mal der Header:
ULONG nStart = SbiOpenRecord( r, B_MODULE, 1 );
ULONG nPos;
eCharSet = GetSOStoreTextEncoding( eCharSet );
r << (INT32) B_CURVERSION
<< (INT32) eCharSet
<< (INT32) nDimBase
<< (INT16) nFlags
<< (INT16) 0
<< (INT32) 0
<< (INT32) 0;
// Name?
if( aName.Len() && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_NAME, 1 );
r.WriteByteString( aName, eCharSet );
//r << aName;
SbiCloseRecord( r, nPos );
}
// Kommentar?
if( aComment.Len() && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_COMMENT, 1 );
r.WriteByteString( aComment, eCharSet );
//r << aComment;
SbiCloseRecord( r, nPos );
}
// Source?
if( aOUSource.getLength() && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_SOURCE, 1 );
String aTmp;
sal_Int32 nLen = aOUSource.getLength();
if( nLen > STRING_MAXLEN )
aTmp = aOUSource.copy( 0, STRING_MAXLEN - 1 );
else
aTmp = aOUSource;
r.WriteByteString( aTmp, eCharSet );
//r << aSource;
SbiCloseRecord( r, nPos );
}
// Binaere Daten?
if( pCode && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_PCODE, 1 );
r.Write( pCode, nCodeSize );
SbiCloseRecord( r, nPos );
}
// String-Pool?
if( nStrings )
{
nPos = SbiOpenRecord( r, B_STRINGPOOL, nStrings );
// Fuer jeden String:
// UINT32 Offset des Strings im Stringblock
for( short i = 0; i < nStrings && SbiGood( r ); i++ )
r << (UINT32) pStringOff[ i ];
// Danach der String-Block
char* pByteStrings = new char[ nStringSize ];
for( i = 0; i < nStrings; i++ )
{
USHORT nOff = pStringOff[ i ];
ByteString aStr( pStrings + nOff, eCharSet );
memcpy( pByteStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( char ) );
}
r << (UINT32) nStringSize;
r.Write( pByteStrings, nStringSize );
delete[] pByteStrings;
SbiCloseRecord( r, nPos );
}
// Und die Gesamtlaenge setzen
SbiCloseRecord( r, nStart );
if( !SbiGood( r ) )
bError = TRUE;
return BOOL( !bError );
}
/**************************************************************************
*
* Routinen, die auch vom Compiler gerufen werden
*
**************************************************************************/
void SbiImage::MakeStrings( short nSize )
{
nStrings = nStringIdx = nStringOff = 0;
nStringSize = 1024;
pStrings = new sal_Unicode[ nStringSize ];
pStringOff = new UINT16[ nSize ];
if( pStrings && pStringOff )
{
nStrings = nSize;
memset( pStringOff, 0, nSize * sizeof( UINT16 ) );
memset( pStrings, 0, nStringSize * sizeof( sal_Unicode ) );
}
else
bError = TRUE;
}
// Hinzufuegen eines Strings an den StringPool. Der String-Puffer
// waechst dynamisch in 1K-Schritten
void SbiImage::AddString( const String& r )
{
if( nStringIdx >= nStrings )
bError = TRUE;
if( !bError )
{
UINT16 len = r.Len() + 1;
long needed = (long) nStringOff + len;
if( needed > 0xFF00L )
bError = TRUE; // out of mem!
else if( (USHORT) needed > nStringSize )
{
UINT16 nNewLen = needed + 1024;
nNewLen &= 0xFC00; // trim to 1K border
sal_Unicode* p = new sal_Unicode[ nNewLen ];
if( p )
{
memcpy( p, pStrings, nStringSize * sizeof( sal_Unicode ) );
delete[] pStrings;
pStrings = p;
nStringSize = nNewLen;
}
else
bError = TRUE;
}
if( !bError )
{
pStringOff[ nStringIdx++ ] = nStringOff;
//ByteString aByteStr( r, eCharSet );
memcpy( pStrings + nStringOff, r.GetBuffer(), len * sizeof( sal_Unicode ) );
nStringOff += len;
// war das der letzte String? Dann die Groesse
// des Puffers aktualisieren
if( nStringIdx >= nStrings )
nStringSize = nStringOff;
}
}
}
// Codeblock hinzufuegen
// Der Block wurde vom Compiler aus der Klasse SbBuffer herausgeholt
// und ist bereits per new angelegt. Ausserdem enthaelt er alle Integers
// im Big Endian-Format, kann also direkt gelesen/geschrieben werden.
void SbiImage::AddCode( char* p, USHORT s )
{
pCode = p;
nCodeSize = s;
}
void SbiImage::AddType(SbxObject* pObject) // User-Type mit aufnehmen
{
SbxObject *pCopyObject = new SbxObject(*pObject);
rTypes->Insert (pCopyObject,rTypes->Count());
}
/**************************************************************************
*
* Zugriffe auf das Image
*
**************************************************************************/
// IDs zaehlen ab 1!!
String SbiImage::GetString( short nId ) const
{
if( nId && nId <= nStrings )
{
USHORT nOff = pStringOff[ --nId ];
String aStr( pStrings + nOff );
return aStr;
}
return String();
}
const SbxObject* SbiImage::FindType (String aTypeName) const
{
return (SbxObject *)rTypes->Find(aTypeName,SbxCLASS_OBJECT);
}
<commit_msg>INTEGRATION: CWS ooo20031110 (1.9.42); FILE MERGED 2003/11/11 11:06:28 waratah 1.9.42.1: #i22301# Correct for scoping rules<commit_after>/*************************************************************************
*
* $RCSfile: image.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2003-12-01 16:26:51 $
*
* 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 _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#include <tools/tenccvt.hxx>
#pragma hdrstop
#include <svtools/sbx.hxx>
#include "sb.hxx"
#include <string.h> // memset() etc
#include "image.hxx"
#include "filefmt.hxx"
SbiImage::SbiImage()
{
rTypes = new SbxArray;
pStringOff = NULL;
pStrings = NULL;
pCode = NULL;
nFlags =
nStrings =
nStringSize=
nCodeSize =
nDimBase = 0;
bInit =
bError = FALSE;
bFirstInit = TRUE;
eCharSet = gsl_getSystemTextEncoding();
}
SbiImage::~SbiImage()
{
Clear();
}
void SbiImage::Clear()
{
delete[] pStringOff;
delete[] pStrings;
delete[] pCode;
pStringOff = NULL;
pStrings = NULL;
pCode = NULL;
nFlags =
nStrings =
nStringSize=
nCodeSize = 0;
eCharSet = gsl_getSystemTextEncoding();
nDimBase = 0;
bError = FALSE;
}
/**************************************************************************
*
* Service-Routinen fuer das Laden und Speichern
*
**************************************************************************/
BOOL SbiGood( SvStream& r )
{
return BOOL( !r.IsEof() && r.GetError() == SVSTREAM_OK );
}
// Oeffnen eines Records
ULONG SbiOpenRecord( SvStream& r, UINT16 nSignature, UINT16 nElem )
{
ULONG nPos = r.Tell();
r << nSignature << (INT32) 0 << nElem;
return nPos;
}
// Schliessen eines Records
void SbiCloseRecord( SvStream& r, ULONG nOff )
{
ULONG nPos = r.Tell();
r.Seek( nOff + 2 );
r << (INT32) ( nPos - nOff - 8 );
r.Seek( nPos );
}
/**************************************************************************
*
* Laden und Speichern
*
**************************************************************************/
// Falls die Versionsnummer nicht passt, werden die binaeren Teile
// nicht geladen, wohl aber Source, Kommentar und Name.
BOOL SbiImage::Load( SvStream& r )
{
UINT16 nSign, nCount;
UINT32 nLen, nOff;
Clear();
ULONG nStart = r.Tell();
// Master-Record einlesen
r >> nSign >> nLen >> nCount;
ULONG nLast = r.Tell() + nLen;
UINT32 nVersion = 0; // Versionsnummer
UINT32 nCharSet; // System-Zeichensatz
UINT32 lDimBase;
UINT16 nReserved1;
UINT32 nReserved2;
UINT32 nReserved3;
BOOL bBadVer = FALSE;
if( nSign == B_MODULE )
{
r >> nVersion >> nCharSet >> lDimBase
>> nFlags >> nReserved1 >> nReserved2 >> nReserved3;
eCharSet = (CharSet) nCharSet;
eCharSet = GetSOLoadTextEncoding( eCharSet );
bBadVer = BOOL( nVersion != B_CURVERSION );
nDimBase = (USHORT) lDimBase;
}
ULONG nNext;
while( ( nNext = r.Tell() ) < nLast )
{
short i;
r >> nSign >> nLen >> nCount;
nNext += nLen + 8;
if( r.GetError() == SVSTREAM_OK )
switch( nSign )
{
case B_NAME:
r.ReadByteString( aName, eCharSet );
//r >> aName;
break;
case B_COMMENT:
r.ReadByteString( aComment, eCharSet );
//r >> aComment;
break;
case B_SOURCE:
{
String aTmp;
r.ReadByteString( aTmp, eCharSet );
aOUSource = aTmp;
//r >> aSource;
break;
}
case B_PCODE:
if( bBadVer ) break;
pCode = new char[ nLen ];
nCodeSize = (USHORT) nLen;
r.Read( pCode, nCodeSize );
break;
case B_PUBLICS:
case B_POOLDIR:
case B_SYMPOOL:
case B_LINERANGES:
break;
case B_STRINGPOOL:
if( bBadVer ) break;
MakeStrings( nCount );
for( i = 0; i < nStrings && SbiGood( r ); i++ )
{
r >> nOff;
pStringOff[ i ] = (USHORT) nOff;
}
r >> nLen;
if( SbiGood( r ) )
{
delete [] pStrings;
pStrings = new sal_Unicode[ nLen ];
nStringSize = (USHORT) nLen;
char* pByteStrings = new char[ nLen ];
r.Read( pByteStrings, nStringSize );
for( short i = 0; i < nStrings; i++ )
{
USHORT nOff = pStringOff[ i ];
String aStr( pByteStrings + nOff, eCharSet );
memcpy( pStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( sal_Unicode ) );
}
delete[] pByteStrings;
} break;
case B_MODEND:
goto done;
default:
break;
}
else
break;
r.Seek( nNext );
}
done:
r.Seek( nLast );
//if( eCharSet != ::GetSystemCharSet() )
//ConvertStrings();
if( !SbiGood( r ) )
bError = TRUE;
return BOOL( !bError );
}
BOOL SbiImage::Save( SvStream& r )
{
// Erst mal der Header:
ULONG nStart = SbiOpenRecord( r, B_MODULE, 1 );
ULONG nPos;
eCharSet = GetSOStoreTextEncoding( eCharSet );
r << (INT32) B_CURVERSION
<< (INT32) eCharSet
<< (INT32) nDimBase
<< (INT16) nFlags
<< (INT16) 0
<< (INT32) 0
<< (INT32) 0;
// Name?
if( aName.Len() && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_NAME, 1 );
r.WriteByteString( aName, eCharSet );
//r << aName;
SbiCloseRecord( r, nPos );
}
// Kommentar?
if( aComment.Len() && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_COMMENT, 1 );
r.WriteByteString( aComment, eCharSet );
//r << aComment;
SbiCloseRecord( r, nPos );
}
// Source?
if( aOUSource.getLength() && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_SOURCE, 1 );
String aTmp;
sal_Int32 nLen = aOUSource.getLength();
if( nLen > STRING_MAXLEN )
aTmp = aOUSource.copy( 0, STRING_MAXLEN - 1 );
else
aTmp = aOUSource;
r.WriteByteString( aTmp, eCharSet );
//r << aSource;
SbiCloseRecord( r, nPos );
}
// Binaere Daten?
if( pCode && SbiGood( r ) )
{
nPos = SbiOpenRecord( r, B_PCODE, 1 );
r.Write( pCode, nCodeSize );
SbiCloseRecord( r, nPos );
}
// String-Pool?
if( nStrings )
{
nPos = SbiOpenRecord( r, B_STRINGPOOL, nStrings );
// Fuer jeden String:
// UINT32 Offset des Strings im Stringblock
short i;
for( i = 0; i < nStrings && SbiGood( r ); i++ )
r << (UINT32) pStringOff[ i ];
// Danach der String-Block
char* pByteStrings = new char[ nStringSize ];
for( i = 0; i < nStrings; i++ )
{
USHORT nOff = pStringOff[ i ];
ByteString aStr( pStrings + nOff, eCharSet );
memcpy( pByteStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( char ) );
}
r << (UINT32) nStringSize;
r.Write( pByteStrings, nStringSize );
delete[] pByteStrings;
SbiCloseRecord( r, nPos );
}
// Und die Gesamtlaenge setzen
SbiCloseRecord( r, nStart );
if( !SbiGood( r ) )
bError = TRUE;
return BOOL( !bError );
}
/**************************************************************************
*
* Routinen, die auch vom Compiler gerufen werden
*
**************************************************************************/
void SbiImage::MakeStrings( short nSize )
{
nStrings = nStringIdx = nStringOff = 0;
nStringSize = 1024;
pStrings = new sal_Unicode[ nStringSize ];
pStringOff = new UINT16[ nSize ];
if( pStrings && pStringOff )
{
nStrings = nSize;
memset( pStringOff, 0, nSize * sizeof( UINT16 ) );
memset( pStrings, 0, nStringSize * sizeof( sal_Unicode ) );
}
else
bError = TRUE;
}
// Hinzufuegen eines Strings an den StringPool. Der String-Puffer
// waechst dynamisch in 1K-Schritten
void SbiImage::AddString( const String& r )
{
if( nStringIdx >= nStrings )
bError = TRUE;
if( !bError )
{
UINT16 len = r.Len() + 1;
long needed = (long) nStringOff + len;
if( needed > 0xFF00L )
bError = TRUE; // out of mem!
else if( (USHORT) needed > nStringSize )
{
UINT16 nNewLen = needed + 1024;
nNewLen &= 0xFC00; // trim to 1K border
sal_Unicode* p = new sal_Unicode[ nNewLen ];
if( p )
{
memcpy( p, pStrings, nStringSize * sizeof( sal_Unicode ) );
delete[] pStrings;
pStrings = p;
nStringSize = nNewLen;
}
else
bError = TRUE;
}
if( !bError )
{
pStringOff[ nStringIdx++ ] = nStringOff;
//ByteString aByteStr( r, eCharSet );
memcpy( pStrings + nStringOff, r.GetBuffer(), len * sizeof( sal_Unicode ) );
nStringOff += len;
// war das der letzte String? Dann die Groesse
// des Puffers aktualisieren
if( nStringIdx >= nStrings )
nStringSize = nStringOff;
}
}
}
// Codeblock hinzufuegen
// Der Block wurde vom Compiler aus der Klasse SbBuffer herausgeholt
// und ist bereits per new angelegt. Ausserdem enthaelt er alle Integers
// im Big Endian-Format, kann also direkt gelesen/geschrieben werden.
void SbiImage::AddCode( char* p, USHORT s )
{
pCode = p;
nCodeSize = s;
}
void SbiImage::AddType(SbxObject* pObject) // User-Type mit aufnehmen
{
SbxObject *pCopyObject = new SbxObject(*pObject);
rTypes->Insert (pCopyObject,rTypes->Count());
}
/**************************************************************************
*
* Zugriffe auf das Image
*
**************************************************************************/
// IDs zaehlen ab 1!!
String SbiImage::GetString( short nId ) const
{
if( nId && nId <= nStrings )
{
USHORT nOff = pStringOff[ --nId ];
String aStr( pStrings + nOff );
return aStr;
}
return String();
}
const SbxObject* SbiImage::FindType (String aTypeName) const
{
return (SbxObject *)rTypes->Find(aTypeName,SbxCLASS_OBJECT);
}
<|endoftext|>
|
<commit_before><commit_msg>Some correction as per new llvm<commit_after><|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/android/media_info_loader.h"
#include "base/bits.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebFrame.h"
using WebKit::WebFrame;
using WebKit::WebURLError;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
namespace content {
static const int kHttpOK = 200;
MediaInfoLoader::MediaInfoLoader(
const GURL& url,
WebKit::WebMediaPlayer::CORSMode cors_mode,
const ReadyCB& ready_cb)
: loader_failed_(false),
url_(url),
cors_mode_(cors_mode),
single_origin_(true),
ready_cb_(ready_cb) {}
MediaInfoLoader::~MediaInfoLoader() {}
void MediaInfoLoader::Start(WebKit::WebFrame* frame) {
// Make sure we have not started.
DCHECK(!ready_cb_.is_null());
CHECK(frame);
start_time_ = base::TimeTicks::Now();
// Prepare the request.
WebURLRequest request(url_);
request.setTargetType(WebURLRequest::TargetIsMedia);
frame->setReferrerForRequest(request, WebKit::WebURL());
scoped_ptr<WebURLLoader> loader;
if (test_loader_) {
loader = test_loader_.Pass();
} else {
WebURLLoaderOptions options;
if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUnspecified) {
options.allowCredentials = true;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
} else {
options.exposeAllResponseHeaders = true;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUseCredentials)
options.allowCredentials = true;
}
loader.reset(frame->createAssociatedURLLoader(options));
}
// Start the resource loading.
loader->loadAsynchronously(request, this);
active_loader_.reset(new ActiveLoader(loader.Pass()));
}
/////////////////////////////////////////////////////////////////////////////
// WebKit::WebURLLoaderClient implementation.
void MediaInfoLoader::willSendRequest(
WebURLLoader* loader,
WebURLRequest& newRequest,
const WebURLResponse& redirectResponse) {
// The load may have been stopped and |ready_cb| is destroyed.
// In this case we shouldn't do anything.
if (ready_cb_.is_null()) {
// Set the url in the request to an invalid value (empty url).
newRequest.setURL(WebKit::WebURL());
return;
}
// Only allow |single_origin_| if we haven't seen a different origin yet.
if (single_origin_)
single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin();
url_ = newRequest.url();
}
void MediaInfoLoader::didSendData(
WebURLLoader* loader,
unsigned long long bytes_sent,
unsigned long long total_bytes_to_be_sent) {
NOTIMPLEMENTED();
}
void MediaInfoLoader::didReceiveResponse(
WebURLLoader* loader,
const WebURLResponse& response) {
DVLOG(1) << "didReceiveResponse: HTTP/"
<< (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" :
response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" :
response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" :
"Unknown")
<< " " << response.httpStatusCode();
DCHECK(active_loader_.get());
if (response.httpStatusCode() == kHttpOK) {
DidBecomeReady(kOk);
return;
}
loader_failed_ = true;
DidBecomeReady(kFailed);
}
void MediaInfoLoader::didReceiveData(
WebURLLoader* loader,
const char* data,
int data_length,
int encoded_data_length) {
// Ignored.
}
void MediaInfoLoader::didDownloadData(
WebKit::WebURLLoader* loader,
int dataLength) {
NOTIMPLEMENTED();
}
void MediaInfoLoader::didReceiveCachedMetadata(
WebURLLoader* loader,
const char* data,
int data_length) {
NOTIMPLEMENTED();
}
void MediaInfoLoader::didFinishLoading(
WebURLLoader* loader,
double finishTime) {
DCHECK(active_loader_.get());
DidBecomeReady(kOk);
}
void MediaInfoLoader::didFail(
WebURLLoader* loader,
const WebURLError& error) {
DVLOG(1) << "didFail: reason=" << error.reason
<< ", isCancellation=" << error.isCancellation
<< ", domain=" << error.domain.utf8().data()
<< ", localizedDescription="
<< error.localizedDescription.utf8().data();
DCHECK(active_loader_.get());
loader_failed_ = true;
DidBecomeReady(kFailed);
}
bool MediaInfoLoader::HasSingleOrigin() const {
DCHECK(ready_cb_.is_null())
<< "Must become ready before calling HasSingleOrigin()";
return single_origin_;
}
bool MediaInfoLoader::DidPassCORSAccessCheck() const {
DCHECK(ready_cb_.is_null())
<< "Must become ready before calling DidPassCORSAccessCheck()";
return !loader_failed_ &&
cors_mode_ != WebKit::WebMediaPlayer::CORSModeUnspecified;
}
/////////////////////////////////////////////////////////////////////////////
// Helper methods.
void MediaInfoLoader::DidBecomeReady(Status status) {
UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay",
base::TimeTicks::Now() - start_time_);
active_loader_.reset();
if (!ready_cb_.is_null())
base::ResetAndReturn(&ready_cb_).Run(status);
}
} // namespace content
<commit_msg>[Android] Fix the issue of ContentShell can't play video with file scheme.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/android/media_info_loader.h"
#include "base/bits.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebFrame.h"
using WebKit::WebFrame;
using WebKit::WebURLError;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
namespace content {
static const int kHttpOK = 200;
MediaInfoLoader::MediaInfoLoader(
const GURL& url,
WebKit::WebMediaPlayer::CORSMode cors_mode,
const ReadyCB& ready_cb)
: loader_failed_(false),
url_(url),
cors_mode_(cors_mode),
single_origin_(true),
ready_cb_(ready_cb) {}
MediaInfoLoader::~MediaInfoLoader() {}
void MediaInfoLoader::Start(WebKit::WebFrame* frame) {
// Make sure we have not started.
DCHECK(!ready_cb_.is_null());
CHECK(frame);
start_time_ = base::TimeTicks::Now();
// Prepare the request.
WebURLRequest request(url_);
request.setTargetType(WebURLRequest::TargetIsMedia);
frame->setReferrerForRequest(request, WebKit::WebURL());
scoped_ptr<WebURLLoader> loader;
if (test_loader_) {
loader = test_loader_.Pass();
} else {
WebURLLoaderOptions options;
if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUnspecified) {
options.allowCredentials = true;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
} else {
options.exposeAllResponseHeaders = true;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUseCredentials)
options.allowCredentials = true;
}
loader.reset(frame->createAssociatedURLLoader(options));
}
// Start the resource loading.
loader->loadAsynchronously(request, this);
active_loader_.reset(new ActiveLoader(loader.Pass()));
}
/////////////////////////////////////////////////////////////////////////////
// WebKit::WebURLLoaderClient implementation.
void MediaInfoLoader::willSendRequest(
WebURLLoader* loader,
WebURLRequest& newRequest,
const WebURLResponse& redirectResponse) {
// The load may have been stopped and |ready_cb| is destroyed.
// In this case we shouldn't do anything.
if (ready_cb_.is_null()) {
// Set the url in the request to an invalid value (empty url).
newRequest.setURL(WebKit::WebURL());
return;
}
// Only allow |single_origin_| if we haven't seen a different origin yet.
if (single_origin_)
single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin();
url_ = newRequest.url();
}
void MediaInfoLoader::didSendData(
WebURLLoader* loader,
unsigned long long bytes_sent,
unsigned long long total_bytes_to_be_sent) {
NOTIMPLEMENTED();
}
void MediaInfoLoader::didReceiveResponse(
WebURLLoader* loader,
const WebURLResponse& response) {
DVLOG(1) << "didReceiveResponse: HTTP/"
<< (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" :
response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" :
response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" :
"Unknown")
<< " " << response.httpStatusCode();
DCHECK(active_loader_.get());
if (response.httpStatusCode() == kHttpOK || url_.SchemeIsFile()) {
DidBecomeReady(kOk);
return;
}
loader_failed_ = true;
DidBecomeReady(kFailed);
}
void MediaInfoLoader::didReceiveData(
WebURLLoader* loader,
const char* data,
int data_length,
int encoded_data_length) {
// Ignored.
}
void MediaInfoLoader::didDownloadData(
WebKit::WebURLLoader* loader,
int dataLength) {
NOTIMPLEMENTED();
}
void MediaInfoLoader::didReceiveCachedMetadata(
WebURLLoader* loader,
const char* data,
int data_length) {
NOTIMPLEMENTED();
}
void MediaInfoLoader::didFinishLoading(
WebURLLoader* loader,
double finishTime) {
DCHECK(active_loader_.get());
DidBecomeReady(kOk);
}
void MediaInfoLoader::didFail(
WebURLLoader* loader,
const WebURLError& error) {
DVLOG(1) << "didFail: reason=" << error.reason
<< ", isCancellation=" << error.isCancellation
<< ", domain=" << error.domain.utf8().data()
<< ", localizedDescription="
<< error.localizedDescription.utf8().data();
DCHECK(active_loader_.get());
loader_failed_ = true;
DidBecomeReady(kFailed);
}
bool MediaInfoLoader::HasSingleOrigin() const {
DCHECK(ready_cb_.is_null())
<< "Must become ready before calling HasSingleOrigin()";
return single_origin_;
}
bool MediaInfoLoader::DidPassCORSAccessCheck() const {
DCHECK(ready_cb_.is_null())
<< "Must become ready before calling DidPassCORSAccessCheck()";
return !loader_failed_ &&
cors_mode_ != WebKit::WebMediaPlayer::CORSModeUnspecified;
}
/////////////////////////////////////////////////////////////////////////////
// Helper methods.
void MediaInfoLoader::DidBecomeReady(Status status) {
UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay",
base::TimeTicks::Now() - start_time_);
active_loader_.reset();
if (!ready_cb_.is_null())
base::ResetAndReturn(&ready_cb_).Run(status);
}
} // namespace content
<|endoftext|>
|
<commit_before>#ifndef WIN32
//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/TerminalConfigUnix.h"
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
using namespace textinput;
using std::memcpy;
void
TerminalConfigUnix__handleAbortSignal(int signum) {
// Clean up before we are killed.
TerminalConfigUnix::Get().HandleAbortSignal(signum);
}
TerminalConfigUnix&
TerminalConfigUnix::Get() {
static TerminalConfigUnix s;
return s;
}
TerminalConfigUnix::TerminalConfigUnix():
fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
fOldTIOS = new termios;
fConfTIOS = new termios;
tcgetattr(fFD, fOldTIOS);
*fConfTIOS = *fOldTIOS;
#endif
fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);
}
TerminalConfigUnix::~TerminalConfigUnix() {
Detach();
delete fOldTIOS;
delete fConfTIOS;
}
void
TerminalConfigUnix::HandleAbortSignal(int signum) {
Detach();
if (fPrevAbortHandler) fPrevAbortHandler(signum);
}
void
TerminalConfigUnix::Attach() {
if (fIsAttached) return;
#ifdef TCSANOW
tcsetattr(fFD, TCSANOW, fConfTIOS);
#endif
fIsAttached = true;
}
void
TerminalConfigUnix::Detach() {
// Reset the terminal configuration.
if (!fIsAttached) return;
#ifdef TCSANOW
tcsetattr(fFD, TCSANOW, fOldTIOS);
#endif
fIsAttached = false;
}
#endif // ndef WIN32
<commit_msg>Solaris puts signal only into std::.<commit_after>#ifndef WIN32
//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/TerminalConfigUnix.h"
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
using namespace textinput;
using std::memcpy;
using std::signal;
void
TerminalConfigUnix__handleAbortSignal(int signum) {
// Clean up before we are killed.
TerminalConfigUnix::Get().HandleAbortSignal(signum);
}
TerminalConfigUnix&
TerminalConfigUnix::Get() {
static TerminalConfigUnix s;
return s;
}
TerminalConfigUnix::TerminalConfigUnix():
fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
fOldTIOS = new termios;
fConfTIOS = new termios;
tcgetattr(fFD, fOldTIOS);
*fConfTIOS = *fOldTIOS;
#endif
fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);
}
TerminalConfigUnix::~TerminalConfigUnix() {
Detach();
delete fOldTIOS;
delete fConfTIOS;
}
void
TerminalConfigUnix::HandleAbortSignal(int signum) {
Detach();
if (fPrevAbortHandler) fPrevAbortHandler(signum);
}
void
TerminalConfigUnix::Attach() {
if (fIsAttached) return;
#ifdef TCSANOW
tcsetattr(fFD, TCSANOW, fConfTIOS);
#endif
fIsAttached = true;
}
void
TerminalConfigUnix::Detach() {
// Reset the terminal configuration.
if (!fIsAttached) return;
#ifdef TCSANOW
tcsetattr(fFD, TCSANOW, fOldTIOS);
#endif
fIsAttached = false;
}
#endif // ndef WIN32
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/matrix.h"
template<class T>
class MatrixSubtractTest : public ::testing::Test {
public:
Nice::Matrix<T> m1;
Nice::Matrix<T> m2;
Nice::Matrix<T> result;
Nice::Matrix<T> testMatrix;
void MatrixSubtract() {
result = Nice::CpuOperations<T>::Subtract(m1, m2);
}
};
typedef ::testing::Types<int, double, float> MyTypes;
TYPED_TEST_CASE(MatrixSubtractTest, MyTypes);
TYPED_TEST(MatrixSubtractTest, MatrixSubtractFunctionality) {
this->m1.resize(2,2);
this->m2.resize(2,2);
// this->result.resize(2,2);
this->testMatrix.resize(2,2);
this->m1 << 2, 3,
4, 5;
this->m2 << 1, 2,
3, 2;
this->MatrixSubtract();
this->testMatrix << 1, 1,
1, 3;
ASSERT_TRUE(this->result.isApprox(this->testMatrix));
}
TYPED_TEST(MatrixSubtractTest, DifferentSizeMatrix) {
this->m1.resize(2,2);
this->m2.resize(3,2);
this->m1.setZero();
this->m2.setZero();
ASSERT_DEATH(this->MatrixSubtract(), ".*");
}
TYPED_TEST(MatrixSubtractTest, EmptyMatrix) {
ASSERT_DEATH(this->MatrixSubtract(), ".*");
}
<commit_msg>Code style update<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/matrix.h"
template<class T>
class MatrixSubtractTest : public ::testing::Test {
public:
Nice::Matrix<T> m1;
Nice::Matrix<T> m2;
Nice::Matrix<T> result;
Nice::Matrix<T> testMatrix;
void MatrixSubtract() {
result = Nice::CpuOperations<T>::Subtract(m1, m2);
}
};
typedef ::testing::Types<int, double, float> MyTypes;
TYPED_TEST_CASE(MatrixSubtractTest, MyTypes);
TYPED_TEST(MatrixSubtractTest, MatrixSubtractFunctionality) {
this->m1.resize(2, 2);
this->m2.resize(2, 2);
this->testMatrix.resize(2, 2);
this->m1 << 2, 3,
4, 5;
this->m2 << 1, 2,
3, 2;
this->MatrixSubtract();
this->testMatrix << 1, 1,
1, 3;
ASSERT_TRUE(this->result.isApprox(this->testMatrix));
}
TYPED_TEST(MatrixSubtractTest, DifferentSizeMatrix) {
this->m1.resize(2, 2);
this->m2.resize(3, 2);
this->m1.setZero();
this->m2.setZero();
ASSERT_DEATH(this->MatrixSubtract(), ".*");
}
TYPED_TEST(MatrixSubtractTest, EmptyMatrix) {
ASSERT_DEATH(this->MatrixSubtract(), ".*");
}
<|endoftext|>
|
<commit_before>#include "../../../include/stupid/internal/macros.hpp"
Q_LOGGING_CATEGORY(cutehmi_stupid_0_lib_loggingCategory, "cutehmi.stupid.0.lib")
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<commit_msg>Fix logging category name.<commit_after>#include "../../../include/stupid/internal/macros.hpp"
Q_LOGGING_CATEGORY(cutehmi_stupid_1_lib_loggingCategory, "cutehmi_stupid_1_lib")
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<|endoftext|>
|
<commit_before>//
// yas_audio_rendering_graph.cpp
//
#include "yas_audio_rendering_graph.h"
#include <audio/yas_audio_graph_connection.h>
#include <audio/yas_audio_graph_node.h>
#include <cpp_utils/yas_stl_utils.h>
using namespace yas;
namespace yas::audio {
std::vector<std::unique_ptr<rendering_node>> make_rendering_nodes(renderable_graph_node_ptr const &node) {
std::vector<std::unique_ptr<rendering_node>> sub_nodes;
rendering_connection_map connections;
for (auto const &pair : node->input_connections()) {
uint32_t const dst_bus_idx = pair.first;
graph_connection_ptr const connection = pair.second.lock();
renderable_graph_node_ptr const src_node = connection->source_node();
std::vector<std::unique_ptr<rendering_node>> src_rendering_nodes = make_rendering_nodes(src_node);
connections.emplace(dst_bus_idx, rendering_connection{connection->source_bus(), src_rendering_nodes.at(0).get(),
connection->format()});
yas::move_back_insert(sub_nodes, std::move(src_rendering_nodes));
}
std::vector<std::unique_ptr<rendering_node>> result;
result.emplace_back(std::make_unique<rendering_node>(node->render_handler(), std::move(connections)));
if (!sub_nodes.empty()) {
yas::move_back_insert(result, std::move(sub_nodes));
}
return result;
}
} // namespace yas::audio
audio::rendering_graph::rendering_graph(renderable_graph_node_ptr const &end_node)
: nodes(make_rendering_nodes(end_node)) {
}
<commit_msg>use renderable_graph_connection_ptr<commit_after>//
// yas_audio_rendering_graph.cpp
//
#include "yas_audio_rendering_graph.h"
#include <audio/yas_audio_graph_connection.h>
#include <audio/yas_audio_graph_node.h>
#include <cpp_utils/yas_stl_utils.h>
using namespace yas;
namespace yas::audio {
std::vector<std::unique_ptr<rendering_node>> make_rendering_nodes(renderable_graph_node_ptr const &node) {
std::vector<std::unique_ptr<rendering_node>> sub_nodes;
rendering_connection_map connections;
for (auto const &pair : node->input_connections()) {
uint32_t const dst_bus_idx = pair.first;
renderable_graph_connection_ptr const connection = pair.second.lock();
renderable_graph_node_ptr const src_node = connection->source_node();
std::vector<std::unique_ptr<rendering_node>> src_rendering_nodes = make_rendering_nodes(src_node);
connections.emplace(dst_bus_idx, rendering_connection{connection->source_bus(), src_rendering_nodes.at(0).get(),
connection->format()});
yas::move_back_insert(sub_nodes, std::move(src_rendering_nodes));
}
std::vector<std::unique_ptr<rendering_node>> result;
result.emplace_back(std::make_unique<rendering_node>(node->render_handler(), std::move(connections)));
if (!sub_nodes.empty()) {
yas::move_back_insert(result, std::move(sub_nodes));
}
return result;
}
} // namespace yas::audio
audio::rendering_graph::rendering_graph(renderable_graph_node_ptr const &end_node)
: nodes(make_rendering_nodes(end_node)) {
}
<|endoftext|>
|
<commit_before>//! [class-defn]
#include <memory>
#include <QApplication>
#include <QGuiApplication>
#include "QtWidgets/qwidget.h"
#include "Qt3D/qglview.h"
#include "Qt3D/qglscenenode.h"
#include "Qt3D/qglbuilder.h"
#include "Qt3D/qglteapot.h"
class TeapotView : public QGLView
{
Q_OBJECT
public:
TeapotView(QWindow *parent = 0)
: QGLView(parent),
teapot(nullptr)
{}
~TeapotView();
protected:
void initializeGL(QGLPainter *painter);
void paintGL(QGLPainter *painter);
private:
std::unique_ptr<QGLSceneNode> teapot;
};
//! [class-defn]
//! [initialize]
void TeapotView::initializeGL(QGLPainter *painter)
{
painter->setStandardEffect(QGL::LitMaterial);
//! [build-geometry]
QGLBuilder builder;
builder << QGLTeapot();
auto scene = builder.finalizedSceneNode();
teapot.reset(scene);
}
//! [initialize]
//! [destructor]
TeapotView::~TeapotView()
{
}
//! [destructor]
//! [paint]
void TeapotView::paintGL(QGLPainter *painter)
{
teapot->draw(painter);
}
//! [paint]
int mainQ3D(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
TeapotView view;
view.setTitle("Pure Q3D!");
view.resize(800, 600);
view.show();
return app.exec();
}
int mainQ3DWidget(int argc, char *argv[])
{
QApplication app(argc, argv);
TeapotView view;
// ownership is still at view! so don't delete the 'teapot' pointer!
QWidget* teapot(QWidget::createWindowContainer(&view));
teapot->setWindowTitle("Q3D as a QWidget!");
teapot->resize(800, 600);
teapot->show();
return app.exec();
}
//! [main]
int main(int argc, char *argv[]) {
//return mainQ3DWidget(argc, argv);
return mainQ3D(argc, argv);
}
//! [main]<commit_msg>included missing include of the corresponding moc file (i don't really understand the technique Qt uses)<commit_after>//! [class-defn]
#include <memory>
#include <QApplication>
#include <QGuiApplication>
#include "QtWidgets/qwidget.h"
#include "Qt3D/qglview.h"
#include "Qt3D/qglscenenode.h"
#include "Qt3D/qglbuilder.h"
#include "Qt3D/qglteapot.h"
class TeapotView : public QGLView
{
Q_OBJECT
public:
TeapotView(QWindow *parent = 0)
: QGLView(parent),
teapot(nullptr)
{}
~TeapotView();
protected:
void initializeGL(QGLPainter *painter);
void paintGL(QGLPainter *painter);
private:
std::unique_ptr<QGLSceneNode> teapot;
};
//! [class-defn]
//! [initialize]
void TeapotView::initializeGL(QGLPainter *painter)
{
painter->setStandardEffect(QGL::LitMaterial);
//! [build-geometry]
QGLBuilder builder;
builder << QGLTeapot();
auto scene = builder.finalizedSceneNode();
teapot.reset(scene);
}
//! [initialize]
//! [destructor]
TeapotView::~TeapotView()
{
}
//! [destructor]
//! [paint]
void TeapotView::paintGL(QGLPainter *painter)
{
teapot->draw(painter);
}
//! [paint]
int mainQ3D(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
TeapotView view;
view.setTitle("Pure Q3D!");
view.resize(800, 600);
view.show();
return app.exec();
}
int mainQ3DWidget(int argc, char *argv[])
{
QApplication app(argc, argv);
TeapotView view;
// ownership is still at view! so don't delete the 'teapot' pointer!
QWidget* teapot(QWidget::createWindowContainer(&view));
teapot->setWindowTitle("Q3D as a QWidget!");
teapot->resize(800, 600);
teapot->show();
return app.exec();
}
//! [main]
int main(int argc, char *argv[]) {
//return mainQ3DWidget(argc, argv);
return mainQ3D(argc, argv);
}
//! [main]
#include "dummy.moc"<|endoftext|>
|
<commit_before>#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "editorviewscene.h"
#include "realreporoles.h"
#include "../umllib/uml_element.h"
#include "../umllib/uml_guiobjectfactory.h"
EditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)
: QAbstractItemView(0)
{
this->view = view;
this->scene = scene;
// view->mv_iface = this;
scene->mv_iface = this;
scene->view = view;
}
QRect EditorViewMViface::visualRect(const QModelIndex &) const
{
return QRect();
}
void EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)
{
}
QModelIndex EditorViewMViface::indexAt(const QPoint &) const
{
return QModelIndex();
}
QModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,
Qt::KeyboardModifiers)
{
return QModelIndex();
}
int EditorViewMViface::horizontalOffset() const
{
return 0;
}
int EditorViewMViface::verticalOffset() const
{
return 0;
}
bool EditorViewMViface::isIndexHidden(const QModelIndex &) const
{
return false;
}
void EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )
{
}
QRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const
{
return QRegion();
}
/*
void EditorViewMViface::raiseClick ( const QGraphicsItem * item )
{
const UML::Element *e = qgraphicsitem_cast<const UML::Element *>(item);
if (e)
emit clicked(e->index());
}
*/
UML::Element* EditorViewMViface::getItem(int uuid)
{
return items[uuid];
}
void EditorViewMViface::reset()
{
items.clear();
scene->clearScene();
// so that our diagram be nicer
scene->removeItem(scene->addRect(QRect(-1000,-1000,2000,2000)));
if ( model() )
rowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1 );
}
void EditorViewMViface::setRootIndex(const QModelIndex &index)
{
QAbstractItemView::setRootIndex(index);
reset();
}
void EditorViewMViface::rowsInserted ( const QModelIndex & parent, int start, int end )
{
qDebug() << "========== rowsInserted";
// if ( parent != rootIndex() )
// return;
if ( parent == QModelIndex() )
return;
// qDebug() << "rowsInserted: adding items" << parent;
for (int row = start; row <= end; ++row) {
QPersistentModelIndex current = model()->index(row, 0, parent);
int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
int type = model()->index(row, 0, parent).data(Unreal::TypeRole).toInt();
int parent_uuid;
if ( parent != rootIndex() )
parent_uuid = parent.data(Unreal::IdRole).toInt();
else
parent_uuid = -1;
qDebug() << uuid << type;
if ( ! uuid )
continue;
if ( UML::Element *e = UML::GUIObjectFactory(type) ) {
scene->addItem(e);
e->setIndex(current);
e->setPos(current.data(Unreal::PositionRole).toPointF());
if ( parent_uuid != -1 )
e->setParentItem(items[parent_uuid]);
items[uuid] = e;
}
if ( model()->hasChildren(current) ) {
rowsInserted( current, 0, model()->rowCount( current ) );
}
}
// qDebug() << "rowsInserted: updating items";
for (int row = start; row <= end; ++row) {
int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
if (items.contains(uuid))
items[uuid]->updateData();
}
QAbstractItemView::rowsInserted(parent, start, end);
}
void EditorViewMViface::rowsAboutToBeRemoved ( const QModelIndex & parent, int start, int end )
{
for (int row = start; row <= end; ++row) {
int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
scene->removeItem(items[uuid]);
delete items[uuid];
items.remove(uuid);
}
QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
}
void EditorViewMViface::dataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight)
{
for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
int uuid = topLeft.sibling(row, 0).data(Unreal::IdRole).toInt();
if ( items.contains(uuid) )
items[uuid]->updateData();
else
rowsInserted(topLeft.parent(),row,row);
}
}
<commit_msg>Hujnja kakajato. (for english speakers: some weird shit)<commit_after>#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "editorviewscene.h"
#include "realreporoles.h"
#include "../umllib/uml_element.h"
#include "../umllib/uml_guiobjectfactory.h"
EditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)
: QAbstractItemView(0)
{
this->view = view;
this->scene = scene;
// view->mv_iface = this;
scene->mv_iface = this;
scene->view = view;
}
QRect EditorViewMViface::visualRect(const QModelIndex &) const
{
return QRect();
}
void EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)
{
}
QModelIndex EditorViewMViface::indexAt(const QPoint &) const
{
return QModelIndex();
}
QModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,
Qt::KeyboardModifiers)
{
return QModelIndex();
}
int EditorViewMViface::horizontalOffset() const
{
return 0;
}
int EditorViewMViface::verticalOffset() const
{
return 0;
}
bool EditorViewMViface::isIndexHidden(const QModelIndex &) const
{
return false;
}
void EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )
{
}
QRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const
{
return QRegion();
}
/*
void EditorViewMViface::raiseClick ( const QGraphicsItem * item )
{
const UML::Element *e = qgraphicsitem_cast<const UML::Element *>(item);
if (e)
emit clicked(e->index());
}
*/
UML::Element* EditorViewMViface::getItem(int uuid)
{
return items[uuid];
}
void EditorViewMViface::reset()
{
items.clear();
scene->clearScene();
// so that our diagram be nicer
scene->removeItem(scene->addRect(QRect(-1000,-1000,2000,2000)));
if ( model() )
rowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1 );
}
void EditorViewMViface::setRootIndex(const QModelIndex &index)
{
QAbstractItemView::setRootIndex(index);
reset();
}
void EditorViewMViface::rowsInserted ( const QModelIndex & parent, int start, int end )
{
qDebug() << "========== rowsInserted" << parent << start << end;
// if ( parent != rootIndex() )
// return;
if ( parent == QModelIndex() )
return;
// qDebug() << "rowsInserted: adding items" << parent;
for (int row = start; row <= end; ++row) {
QPersistentModelIndex current = model()->index(row, 0, parent);
int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
int type = model()->index(row, 0, parent).data(Unreal::TypeRole).toInt();
int parent_uuid;
if ( parent != rootIndex() )
parent_uuid = parent.data(Unreal::IdRole).toInt();
else
parent_uuid = -1;
qDebug() << uuid << type;
if ( ! uuid )
continue;
if ( UML::Element *e = UML::GUIObjectFactory(type) ) {
scene->addItem(e);
e->setIndex(current);
e->setPos(current.data(Unreal::PositionRole).toPointF());
if ( parent_uuid != -1 )
e->setParentItem(items[parent_uuid]);
items[uuid] = e;
}
if ( model()->hasChildren(current) ) {
rowsInserted( current, 0, model()->rowCount( current ) - 1 );
}
}
qDebug() << "rowsInserted: updating items";
for (int row = start; row <= end; ++row) {
int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
if (items.contains(uuid))
items[uuid]->updateData();
}
QAbstractItemView::rowsInserted(parent, start, end);
}
void EditorViewMViface::rowsAboutToBeRemoved ( const QModelIndex & parent, int start, int end )
{
for (int row = start; row <= end; ++row) {
int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
scene->removeItem(items[uuid]);
delete items[uuid];
items.remove(uuid);
}
QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
}
void EditorViewMViface::dataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight)
{
for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
int uuid = topLeft.sibling(row, 0).data(Unreal::IdRole).toInt();
if ( items.contains(uuid) )
items[uuid]->updateData();
else
rowsInserted(topLeft.parent(),row,row);
}
}
<|endoftext|>
|
<commit_before>#include <owlqn.h>
void OWLQN::optimize()
{
// compute dir
// compute grad
while (_cur_iter < _max_iter)
{
_cur_iter ++;
grad();
dir();
linearSearch();
shift();
}
}
void OWLQN::grad()
{
model->grad(_w, *_data, _grad);
}
void OWLQN::dir()
{
for (int i=0; i<_N; ++i)
{
_dir[i] = _grad[i];
}
// l1 so virtual grad
if (_l1>0)
{
for (int i=0; i<_N; ++i)
{
if (_w[i] > MinDoubleValue)
{
_dir[i] = -1.0*(_grad[i] + _l1)
}
else if (_w[i] < -1.0*MinDoubleValue)
{
_dir[i] = -1.0*(_grad[i] - _l1)
}
else
{
double l_grad = _grad[i]-_l1;
double r_grad = _grad[i]+_l1;
if (r_grad < 0.0)
{
_dir[i] = -1.0*r_grad;
}
else if (l_grad > 0.0)
{
_dir[i] = -1.0*l_grad;
}
else
{
_dir[i] = 0.0;
}
}
}
// check dir direction, same direction with -grad
for (int i=0; i<_N; ++i)
{
if (_dir[i]*_grad[i] > 0.0)
{
_dir[i] = 0.0;
}
}
}
else
{
for (int i=0; i<_N; ++i)
{
_dir[i] = -1.0*_grad[i];
}
}
// two loop lbfgs
// Hk+1 = G-1
// Hk+1 * yk = sk
// Hk+1 = (I-sy'/s'y)*Hk*(I-ys'/s'y) + ss'/s'y
// dir = -Hk+1*grad
// one loop, compute q[i] =
int i = _end;
while(i != _start)
{
i = (i-1)%_M;
_sy[i] = dot(_S[i], _Y[i]);
_alpha[i] = dot(_S[i], _dir) / _sy[i];
for (size_t k=0; k<_dir.size(); ++k)
{
_dir[k] -= _alpha[i]*_Y[i][k]
}
}
// H0 = I*(s'y/y'y)
i = (_end-1)%M;
double yy = _sy[i]/dot(_Y[i], _Y[i]);
for (size_t k=0; k<_dir.size(); ++k)
{
_dir[k] *= yy;
}
// second loop
i = _start;
while (i != _end)
{
_beta = dot(_Y[i], _dir) / _sy[i];
for (size_t k=0; k<_dir.size(); ++k)
{
_dir[k] -= _S[i][k]*(_beta + _alpha[i]);
}
i = (i+1)%M;
}
}
void OWLQN::linearSearch()
{
// check is _dir down dir
double res = 0.0;
}
void OWLQN::shift()
{
for (size_t k=0; k<_w.size(); ++i)
{
_S[_end][k] = _next_w[k] - _w[k];
_Y[_end][k] = _next_grad[k] - _grad[k];
}
_end = (_end+1) % M;
if (_cur_iter > M)
{
_start = (_start+1) % M;
}
}
double OWLQN::dot(vector<double> x, vector<double> y)
{
if (x.size() != y.size())
{
return 0.0;
}
double value = 0.0;
for (size_t i=0; i<x.size(); ++i)
{
value += x[i]*y[i];
}
return value;
}<commit_msg>modify some<commit_after>#include <owlqn.h>
void OWLQN::optimize()
{
// compute dir
// compute grad
while (_cur_iter < _max_iter)
{
_cur_iter ++;
grad();
dir();
linearSearch();
shift();
}
}
void OWLQN::grad()
{
model->grad(_w, *_data, _grad);
}
void OWLQN::dir()
{
for (int i=0; i<_N; ++i)
{
_dir[i] = _grad[i];
}
// l1 so virtual grad
if (_l1>0)
{
for (int i=0; i<_N; ++i)
{
if (_w[i] > MinDoubleValue)
{
_dir[i] = -1.0*(_grad[i] + _l1)
}
else if (_w[i] < -1.0*MinDoubleValue)
{
_dir[i] = -1.0*(_grad[i] - _l1)
}
else
{
double l_grad = _grad[i]-_l1;
double r_grad = _grad[i]+_l1;
if (r_grad < 0.0)
{
_dir[i] = -1.0*r_grad;
}
else if (l_grad > 0.0)
{
_dir[i] = -1.0*l_grad;
}
else
{
_dir[i] = 0.0;
}
}
}
}
else
{
for (int i=0; i<_N; ++i)
{
_dir[i] = -1.0*_grad[i];
}
}
// two loop lbfgs
// Hk+1 = G-1
// Hk+1 * yk = sk
// Hk+1 = (I-sy'/s'y)*Hk*(I-ys'/s'y) + ss'/s'y
// dir = -Hk+1*grad
// one loop, compute q[i] =
int i = _end;
while(i != _start)
{
i = (i-1)%_M;
_sy[i] = dot(_S[i], _Y[i]);
_alpha[i] = dot(_S[i], _dir) / _sy[i];
for (size_t k=0; k<_dir.size(); ++k)
{
_dir[k] -= _alpha[i]*_Y[i][k]
}
}
// H0 = I*(s'y/y'y)
i = (_end-1)%M;
double yy = _sy[i]/dot(_Y[i], _Y[i]);
for (size_t k=0; k<_dir.size(); ++k)
{
_dir[k] *= yy;
}
// second loop
i = _start;
while (i != _end)
{
_beta = dot(_Y[i], _dir) / _sy[i];
for (size_t k=0; k<_dir.size(); ++k)
{
_dir[k] -= _S[i][k]*(_beta + _alpha[i]);
}
i = (i+1)%M;
}
// fix dir sign
// check dir direction, same direction with l1 grad
for (int i=0; i<_N; ++i)
{
if (_dir[i]*_grad[i] > 0.0)
{
_dir[i] = 0.0;
}
}
}
void OWLQN::linearSearch()
{
// check is _dir down dir, so Hk+1 should be positive
// l1grad * _dir should be less than 0
double res = 0.0;
}
void OWLQN::shift()
{
for (size_t k=0; k<_w.size(); ++i)
{
_S[_end][k] = _next_w[k] - _w[k];
_Y[_end][k] = _next_grad[k] - _grad[k];
}
_end = (_end+1) % M;
if (_cur_iter > M)
{
_start = (_start+1) % M;
}
}
double OWLQN::dot(vector<double> x, vector<double> y)
{
if (x.size() != y.size())
{
return 0.0;
}
double value = 0.0;
for (size_t i=0; i<x.size(); ++i)
{
value += x[i]*y[i];
}
return value;
}<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"
#if !defined(OS_ANDROID)
namespace cc {
namespace {
class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green box is entirely behind a layer with background blur, so it
// should appear blurred on its edges.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
background->AddChild(green);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 436 pixels off by 1: crbug.com/259915
float percentage_pixels_large_error = 1.09f; // 436px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 1;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOutsets) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green border is outside the layer with background blur, but the
// background blur should use pixels from outside its layer borders, up to the
// radius of the blur effect. So the border should be blurred underneath the
// top layer causing the green to bleed under the transparent layer, but not
// in the 1px region between the transparent layer and the green border.
scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
background->AddChild(green_border);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(5.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 2596 pixels off by at most 2: crbug.com/259922
float percentage_pixels_large_error = 6.49f; // 2596px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_outsets.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// This verifies that the perspective of the clear layer (with black border)
// does not influence the blending of the green box behind it. Also verifies
// that the blur is correctly clipped inside the transformed clear layer.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
background->AddChild(green);
background->AddChild(blur);
background->SetPreserves3d(true);
gfx::Transform background_transform;
background_transform.ApplyPerspectiveDepth(200.0);
background->SetTransform(background_transform);
blur->SetPreserves3d(true);
gfx::Transform blur_transform;
blur_transform.Translate(55.0, 65.0);
blur_transform.RotateAboutXAxis(85.0);
blur_transform.RotateAboutYAxis(180.0);
blur_transform.RotateAboutZAxis(20.0);
blur_transform.Translate(-60.0, -60.0);
blur->SetTransform(blur_transform);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 151 pixels off by at most 2: crbug.com/225027
float percentage_pixels_large_error = 0.3775f; // 151px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_off_axis.png")));
}
} // namespace
} // namespace cc
#endif // OS_ANDROID
<commit_msg>Revert 220159 "cc: Re-enable LayerTreeHostFiltersPixelTest.Backg..."<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"
#if !defined(OS_ANDROID)
namespace cc {
namespace {
class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green box is entirely behind a layer with background blur, so it
// should appear blurred on its edges.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
background->AddChild(green);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 436 pixels off by 1: crbug.com/259915
float percentage_pixels_large_error = 1.09f; // 436px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 1;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, DISABLED_BackgroundFilterBlurOutsets) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green border is outside the layer with background blur, but the
// background blur should use pixels from outside its layer borders, up to the
// radius of the blur effect. So the border should be blurred underneath the
// top layer causing the green to bleed under the transparent layer, but not
// in the 1px region between the transparent layer and the green border.
scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
background->AddChild(green_border);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(5.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 2250 pixels off by at most 2: crbug.com/259922
float percentage_pixels_large_error = 5.625f; // 2250px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_outsets.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// This verifies that the perspective of the clear layer (with black border)
// does not influence the blending of the green box behind it. Also verifies
// that the blur is correctly clipped inside the transformed clear layer.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
background->AddChild(green);
background->AddChild(blur);
background->SetPreserves3d(true);
gfx::Transform background_transform;
background_transform.ApplyPerspectiveDepth(200.0);
background->SetTransform(background_transform);
blur->SetPreserves3d(true);
gfx::Transform blur_transform;
blur_transform.Translate(55.0, 65.0);
blur_transform.RotateAboutXAxis(85.0);
blur_transform.RotateAboutYAxis(180.0);
blur_transform.RotateAboutZAxis(20.0);
blur_transform.Translate(-60.0, -60.0);
blur->SetTransform(blur_transform);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 151 pixels off by at most 2: crbug.com/225027
float percentage_pixels_large_error = 0.3775f; // 151px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_off_axis.png")));
}
} // namespace
} // namespace cc
#endif // OS_ANDROID
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/accessibility_util.h"
#include "base/callback.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace accessibility {
// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
public:
// Initialize the ContentScriptLoader with the ID of the extension
// and the RenderViewHost where the scripts should be loaded.
ContentScriptLoader(const std::string& extension_id,
RenderViewHost* render_view_host)
: extension_id_(extension_id),
render_view_host_(render_view_host) {}
// Call this once with the ExtensionResource corresponding to each
// content script to be loaded.
void AppendScript(ExtensionResource resource) {
resources_.push(resource);
}
// Fianlly, call this method once to fetch all of the resources and
// load them. This method will delete this object when done.
void Run() {
if (resources_.empty()) {
delete this;
return;
}
ExtensionResource resource = resources_.front();
resources_.pop();
scoped_refptr<FileReader> reader(new FileReader(resource, NewCallback(
this, &ContentScriptLoader::OnFileLoaded)));
reader->Start();
}
private:
void OnFileLoaded(bool success, const std::string& data) {
if (success) {
ExtensionMsg_ExecuteCode_Params params;
params.request_id = 0;
params.extension_id = extension_id_;
params.is_javascript = true;
params.code = data;
params.all_frames = true;
params.in_main_world = false;
render_view_host_->Send(new ExtensionMsg_ExecuteCode(
render_view_host_->routing_id(), params));
}
Run();
}
std::string extension_id_;
RenderViewHost* render_view_host_;
std::queue<ExtensionResource> resources_;
};
void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
if (accessibility_enabled == enabled) {
LOG(INFO) << "Accessibility is already " <<
(enabled ? "enabled" : "diabled") << ". Going to do nothing.";
return;
}
g_browser_process->local_state()->SetBoolean(
prefs::kAccessibilityEnabled, enabled);
g_browser_process->local_state()->ScheduleSavePersistentPrefs();
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(enabled);
// Load/Unload ChromeVox
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* extension_service =
profile->GetExtensionService();
std::string manifest = ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
ExtensionService::ComponentExtensionInfo info(manifest, path);
if (enabled) { // Load ChromeVox
extension_service->register_component_extension(info);
const Extension* extension =
extension_service->LoadComponentExtension(info);
if (login_web_ui) {
RenderViewHost* render_view_host =
login_web_ui->tab_contents()->render_view_host();
ContentScriptLoader* loader = new ContentScriptLoader(
extension->id(), render_view_host);
for (size_t i = 0; i < extension->content_scripts().size(); i++) {
const UserScript& script = extension->content_scripts()[i];
for (size_t j = 0; j < script.js_scripts().size(); ++j) {
const UserScript::File &file = script.js_scripts()[j];
ExtensionResource resource = extension->GetResource(
file.relative_path());
loader->AppendScript(resource);
}
}
loader->Run(); // It cleans itself up when done.
}
LOG(INFO) << "ChromeVox was Loaded.";
} else { // Unload ChromeVox
extension_service->UnloadComponentExtension(info);
extension_service->UnregisterComponentExtension(info);
LOG(INFO) << "ChromeVox was Unloaded.";
}
}
void ToggleAccessibility(WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
accessibility_enabled = !accessibility_enabled;
EnableAccessibility(accessibility_enabled, login_web_ui);
};
} // namespace accessibility
} // namespace chromeos
<commit_msg>Write the accessibility pref immediately when it changes, rather than scheduling it to be written later. This prevents a bug where the user changes the setting and then immediately shuts down before it can be written. I filed http://crosbug.com/19491 to possibly fix the underlying bug instead (Local State not written before shutdown).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/accessibility_util.h"
#include "base/callback.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace accessibility {
// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
public:
// Initialize the ContentScriptLoader with the ID of the extension
// and the RenderViewHost where the scripts should be loaded.
ContentScriptLoader(const std::string& extension_id,
RenderViewHost* render_view_host)
: extension_id_(extension_id),
render_view_host_(render_view_host) {}
// Call this once with the ExtensionResource corresponding to each
// content script to be loaded.
void AppendScript(ExtensionResource resource) {
resources_.push(resource);
}
// Fianlly, call this method once to fetch all of the resources and
// load them. This method will delete this object when done.
void Run() {
if (resources_.empty()) {
delete this;
return;
}
ExtensionResource resource = resources_.front();
resources_.pop();
scoped_refptr<FileReader> reader(new FileReader(resource, NewCallback(
this, &ContentScriptLoader::OnFileLoaded)));
reader->Start();
}
private:
void OnFileLoaded(bool success, const std::string& data) {
if (success) {
ExtensionMsg_ExecuteCode_Params params;
params.request_id = 0;
params.extension_id = extension_id_;
params.is_javascript = true;
params.code = data;
params.all_frames = true;
params.in_main_world = false;
render_view_host_->Send(new ExtensionMsg_ExecuteCode(
render_view_host_->routing_id(), params));
}
Run();
}
std::string extension_id_;
RenderViewHost* render_view_host_;
std::queue<ExtensionResource> resources_;
};
void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
if (accessibility_enabled == enabled) {
LOG(INFO) << "Accessibility is already " <<
(enabled ? "enabled" : "diabled") << ". Going to do nothing.";
return;
}
g_browser_process->local_state()->SetBoolean(
prefs::kAccessibilityEnabled, enabled);
// Explicitly call SavePersistentPrefs instead of ScheduleSavePersistentPrefs
// so that this change gets written immediately, in case the user shuts
// down right now. TODO(dmazzoni) switch this back to
// ScheduleSavePersistentPrefs once http://crosbug.com/19491 is fixed.
g_browser_process->local_state()->SavePersistentPrefs();
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(enabled);
// Load/Unload ChromeVox
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* extension_service =
profile->GetExtensionService();
std::string manifest = ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
ExtensionService::ComponentExtensionInfo info(manifest, path);
if (enabled) { // Load ChromeVox
extension_service->register_component_extension(info);
const Extension* extension =
extension_service->LoadComponentExtension(info);
if (login_web_ui) {
RenderViewHost* render_view_host =
login_web_ui->tab_contents()->render_view_host();
ContentScriptLoader* loader = new ContentScriptLoader(
extension->id(), render_view_host);
for (size_t i = 0; i < extension->content_scripts().size(); i++) {
const UserScript& script = extension->content_scripts()[i];
for (size_t j = 0; j < script.js_scripts().size(); ++j) {
const UserScript::File &file = script.js_scripts()[j];
ExtensionResource resource = extension->GetResource(
file.relative_path());
loader->AppendScript(resource);
}
}
loader->Run(); // It cleans itself up when done.
}
LOG(INFO) << "ChromeVox was Loaded.";
} else { // Unload ChromeVox
extension_service->UnloadComponentExtension(info);
extension_service->UnregisterComponentExtension(info);
LOG(INFO) << "ChromeVox was Unloaded.";
}
}
void ToggleAccessibility(WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
accessibility_enabled = !accessibility_enabled;
EnableAccessibility(accessibility_enabled, login_web_ui);
};
} // namespace accessibility
} // namespace chromeos
<|endoftext|>
|
<commit_before>#ifndef __SCENECHANGER_HPP__
#define __SCENECHANGER_HPP__
#include "utils.hpp"
class SceneChanger {
public:
SceneChanger();/*
SceneChanger(sf::Vector2f pos, std::string nextScene, sf::Vector2f nextScenePos);
~SceneChanger();
std::string getNextSceneName();
directions getChangeDirection();
directions getOutsideDirection();
sf::FloatRect getRect(sf::Vector2f offset);
void setDirection(directions dir);
void setBounds(sf::FloatRect rect);
directions _dir;
sf::Vector2f _pos;
sf::FloatRect _bound;
std::string _nextScene;
sf::Vector2f _nextScenePos;
*/
};
#endif
<commit_msg>Delete SceneChanger.hpp<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2014, Dilyan Rusev
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 {organization} 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 "stdafx.h"
#include "Board.h"
#include <cassert>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include <algorithm>
#include "Log.h"
using std::begin;
using std::end;
Board::Board()
: WIDTH(10)
, HEIGHT(20)
, MAX_TETRIMONO_WIDTH(4)
, MAX_TETRIMONO_HEIGHT(4)
, m_currentX(0)
, m_currentY(0)
, m_currentStartX(0)
, m_currentEndX(0)
, m_currentStartY(0)
, m_currentEndY(0)
, m_currentType(Tetrimono_Empty)
, m_nextType(Tetrimono_Empty)
, m_elapsedSinceLastFall(0)
, m_timeBetweenFall(500)
, m_isGameOver(false)
, m_isFirstFallAfterSpawn(true)
, m_randomDistributor(Tetrimono_I, Tetrimono_Z) {
Empty(m_matrix);
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
SpawnNext();
}
Board::~Board() {
}
void Board::Update(float ms) {
if (m_isGameOver) {
return;
}
m_elapsedSinceLastFall += ms;
//Log("elaped = %f; ms = %f\n", m_elapsedSinceLastFall, ms);
if (m_elapsedSinceLastFall >= m_timeBetweenFall) {
m_elapsedSinceLastFall = 0;
MergeResult fallResult = MoveCurrent(0, 1);
if (fallResult == MergeResult_Conflict) {
if (!m_isFirstFallAfterSpawn) {
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
else {
m_isGameOver = true;
}
} else {
m_isFirstFallAfterSpawn = false;
}
}
}
void Board::FallDown() {
if (m_isGameOver) {
return;
}
MergeResult fallResult;
do {
fallResult = MoveCurrent(0, 1);
} while (fallResult != MergeResult_Conflict);
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
void Board::Empty(ArrayTetrimonos4x4& matrix) const {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::Empty(ArrayTetrimonos10x20& matrix) const {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::RemoveCurrentFromMatrix(ArrayTetrimonos10x20& matrix) const {
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX >= 0 && boardY >= 0 && boardX < WIDTH && boardY < HEIGHT && m_current[y][x] != Tetrimono_Empty) {
matrix[boardY][boardX] = Tetrimono_Empty;
}
}
}
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix) const {
int ignore1 = 0, ignore2 = 0, ignore3 = 0, ignore4 = 0;
GetMatrixFor(type, matrix, ignore1, ignore2, ignore3, ignore4);
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix, int& startX, int& endX, int& startY, int& endY) const {
Empty(matrix);
switch (type) {
case Tetrimono_I:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[3][1] = type;
startX = 1; endX = 1;
startY = 0; endY = 3;
break;
case Tetrimono_J:
matrix[0][2] = type;
matrix[1][2] = type;
matrix[2][2] = type;
matrix[2][1] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_L:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[2][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_O:
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_S:
matrix[0][2] = type;
matrix[1][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_T:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_Z:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
default:
assert(false);
break;
}
}
void Board::Spawn(Tetrimonos type) {
GetMatrixFor(type, m_current, m_currentStartX, m_currentEndX, m_currentStartY, m_currentEndY);
m_currentType = type;
m_currentX = (WIDTH - (m_currentEndX - m_currentStartX + 1)) / 2;
m_currentY = -(m_currentEndY - m_currentStartY + 1);
}
MergeResult Board::SpawnNext() {
Spawn(m_nextType);
ArrayTetrimonos10x20 merged;
std::copy(begin(m_matrix), end(m_matrix), begin(merged));
MergeResult mergeResult = MergeCurrent(merged);
std::copy(begin(merged), end(merged), begin(m_matrix));
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
return mergeResult;
}
MergeResult Board::MergeCurrent(ArrayTetrimonos10x20& result) const {
MergeResult mergeResult = MergeResult_OK;
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
mergeResult = MergeResult_Conflict;
continue;
} else if (boardY < 0) {
// going out from the top is not conflict by design
continue;
}
const Tetrimonos& source = m_current[y][x];
Tetrimonos& target = result[boardY][boardX];
if (target == Tetrimono_Empty) {
target = source;
} else if (source != Tetrimono_Empty ) {
mergeResult = MergeResult_Conflict;
}
}
}
return mergeResult;
}
MergeResult Board::MoveCurrent(int deltaX, int deltaY) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
m_currentX += deltaX;
m_currentY += deltaY;
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentX -= deltaX;
m_currentY -= deltaY;
}
return res;
}
MergeResult Board::Rotate(RotateDirection direction) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
int startX, endX, startY, endY;
startX = m_currentStartX;
endX = m_currentEndX;
startY = m_currentStartY;
endY = m_currentEndY;
ArrayTetrimonos4x4 original;
std::copy(begin(m_current), end(m_current), begin(original));
RotateCurrentMatrix(direction);
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentStartX = startX;
m_currentEndX = endX;
m_currentStartY = startY;
m_currentEndY = endY;
std::copy(begin(original), end(original), begin(m_current));
}
return res;
}
void Board::FindBoundsFor(const ArrayTetrimonos4x4& figure, int& startX, int& startY, int& endX, int& endY) const {
startX = MAX_TETRIMONO_WIDTH - 1;
endX = 0;
startY = MAX_TETRIMONO_HEIGHT - 1;
endY = 0;
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
if (figure[y][x] != Tetrimono_Empty) {
startX = std::min(startX, x);
endX = std::max(endX, x);
startY = std::min(startY, y);
endY = std::max(endY, y);
}
}
}
}
void Board::RotateCurrentMatrix(RotateDirection direction) {
ArrayTetrimonos4x4 source;
std::copy(begin(m_current), end(m_current), begin(source));
if (direction == RotateDirection_Clockwize) {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[x][MAX_TETRIMONO_HEIGHT - y - 1];
}
}
} else {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[MAX_TETRIMONO_WIDTH - x - 1][y];
}
}
}
FindBoundsFor(m_current, m_currentStartX, m_currentStartY, m_currentEndX, m_currentEndX);
}<commit_msg>fix rotation bug<commit_after>/*
Copyright (c) 2014, Dilyan Rusev
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 {organization} 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 "stdafx.h"
#include "Board.h"
#include <cassert>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include <algorithm>
#include "Log.h"
using std::begin;
using std::end;
Board::Board()
: WIDTH(10)
, HEIGHT(20)
, MAX_TETRIMONO_WIDTH(4)
, MAX_TETRIMONO_HEIGHT(4)
, m_currentX(0)
, m_currentY(0)
, m_currentStartX(0)
, m_currentEndX(0)
, m_currentStartY(0)
, m_currentEndY(0)
, m_currentType(Tetrimono_Empty)
, m_nextType(Tetrimono_Empty)
, m_elapsedSinceLastFall(0)
, m_timeBetweenFall(500)
, m_isGameOver(false)
, m_isFirstFallAfterSpawn(true)
, m_randomDistributor(Tetrimono_I, Tetrimono_Z) {
Empty(m_matrix);
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
SpawnNext();
}
Board::~Board() {
}
void Board::Update(float ms) {
if (m_isGameOver) {
return;
}
m_elapsedSinceLastFall += ms;
//Log("elaped = %f; ms = %f\n", m_elapsedSinceLastFall, ms);
if (m_elapsedSinceLastFall >= m_timeBetweenFall) {
m_elapsedSinceLastFall = 0;
MergeResult fallResult = MoveCurrent(0, 1);
if (fallResult == MergeResult_Conflict) {
if (!m_isFirstFallAfterSpawn) {
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
else {
m_isGameOver = true;
}
} else {
m_isFirstFallAfterSpawn = false;
}
}
}
void Board::FallDown() {
if (m_isGameOver) {
return;
}
MergeResult fallResult;
do {
fallResult = MoveCurrent(0, 1);
} while (fallResult != MergeResult_Conflict);
SpawnNext();
m_isFirstFallAfterSpawn = true;
}
void Board::Empty(ArrayTetrimonos4x4& matrix) const {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::Empty(ArrayTetrimonos10x20& matrix) const {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
matrix[y][x] = Tetrimono_Empty;
}
}
}
void Board::RemoveCurrentFromMatrix(ArrayTetrimonos10x20& matrix) const {
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX >= 0 && boardY >= 0 && boardX < WIDTH && boardY < HEIGHT && m_current[y][x] != Tetrimono_Empty) {
matrix[boardY][boardX] = Tetrimono_Empty;
}
}
}
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix) const {
int ignore1 = 0, ignore2 = 0, ignore3 = 0, ignore4 = 0;
GetMatrixFor(type, matrix, ignore1, ignore2, ignore3, ignore4);
}
void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix, int& startX, int& endX, int& startY, int& endY) const {
Empty(matrix);
switch (type) {
case Tetrimono_I:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[3][1] = type;
startX = 1; endX = 1;
startY = 0; endY = 3;
break;
case Tetrimono_J:
matrix[0][2] = type;
matrix[1][2] = type;
matrix[2][2] = type;
matrix[2][1] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_L:
matrix[0][1] = type;
matrix[1][1] = type;
matrix[2][1] = type;
matrix[2][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 2;
break;
case Tetrimono_O:
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 1; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_S:
matrix[0][2] = type;
matrix[1][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_T:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[0][2] = type;
matrix[1][1] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
case Tetrimono_Z:
matrix[0][0] = type;
matrix[0][1] = type;
matrix[1][1] = type;
matrix[1][2] = type;
startX = 0; endX = 2;
startY = 0; endY = 1;
break;
default:
assert(false);
break;
}
}
void Board::Spawn(Tetrimonos type) {
GetMatrixFor(type, m_current, m_currentStartX, m_currentEndX, m_currentStartY, m_currentEndY);
m_currentType = type;
m_currentX = (WIDTH - (m_currentEndX - m_currentStartX + 1)) / 2;
m_currentY = -(m_currentEndY - m_currentStartY + 1);
}
MergeResult Board::SpawnNext() {
Spawn(m_nextType);
ArrayTetrimonos10x20 merged;
std::copy(begin(m_matrix), end(m_matrix), begin(merged));
MergeResult mergeResult = MergeCurrent(merged);
std::copy(begin(merged), end(merged), begin(m_matrix));
m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
GetMatrixFor(m_nextType, m_next);
return mergeResult;
}
MergeResult Board::MergeCurrent(ArrayTetrimonos10x20& result) const {
MergeResult mergeResult = MergeResult_OK;
int boardX, boardY;
for (int y = m_currentStartY; y <= m_currentEndY; y++) {
for (int x = m_currentStartX; x <= m_currentEndX; x++) {
boardX = m_currentX + x;
boardY = m_currentY + y;
if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
mergeResult = MergeResult_Conflict;
continue;
} else if (boardY < 0) {
// going out from the top is not conflict by design
continue;
}
const Tetrimonos& source = m_current[y][x];
Tetrimonos& target = result[boardY][boardX];
if (target == Tetrimono_Empty) {
target = source;
} else if (source != Tetrimono_Empty ) {
mergeResult = MergeResult_Conflict;
}
}
}
return mergeResult;
}
MergeResult Board::MoveCurrent(int deltaX, int deltaY) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
m_currentX += deltaX;
m_currentY += deltaY;
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentX -= deltaX;
m_currentY -= deltaY;
}
return res;
}
MergeResult Board::Rotate(RotateDirection direction) {
ArrayTetrimonos10x20 mergedMatrix;
std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
RemoveCurrentFromMatrix(mergedMatrix);
int startX, endX, startY, endY;
startX = m_currentStartX;
endX = m_currentEndX;
startY = m_currentStartY;
endY = m_currentEndY;
ArrayTetrimonos4x4 original;
std::copy(begin(m_current), end(m_current), begin(original));
RotateCurrentMatrix(direction);
MergeResult res = MergeCurrent(mergedMatrix);
if (res == MergeResult_OK) {
std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
} else {
m_currentStartX = startX;
m_currentEndX = endX;
m_currentStartY = startY;
m_currentEndY = endY;
std::copy(begin(original), end(original), begin(m_current));
}
return res;
}
void Board::FindBoundsFor(const ArrayTetrimonos4x4& figure, int& startX, int& startY, int& endX, int& endY) const {
startX = MAX_TETRIMONO_WIDTH - 1;
endX = 0;
startY = MAX_TETRIMONO_HEIGHT - 1;
endY = 0;
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
if (figure[y][x] != Tetrimono_Empty) {
startX = std::min(startX, x);
endX = std::max(endX, x);
startY = std::min(startY, y);
endY = std::max(endY, y);
}
}
}
}
void Board::RotateCurrentMatrix(RotateDirection direction) {
ArrayTetrimonos4x4 source;
std::copy(begin(m_current), end(m_current), begin(source));
if (direction == RotateDirection_Clockwize) {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[x][MAX_TETRIMONO_HEIGHT - y - 1];
}
}
} else {
for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
m_current[y][x] = source[MAX_TETRIMONO_WIDTH - x - 1][y];
}
}
}
FindBoundsFor(m_current, m_currentStartX, m_currentStartY, m_currentEndX, m_currentEndY);
}<|endoftext|>
|
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
The elevation evaluator gets the surface elevation, slope, and updates pres + elev.
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "fractional_conductance_evaluator.hh"
namespace Amanzi {
namespace Flow {
namespace FlowRelations {
FractionalConductanceEvaluator::FractionalConductanceEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
Key domain = Keys::getDomain(my_key_);
vpd_key_ = Keys::readKey(plist_, domain, "volumetric ponded depth", "volumetric_ponded_depth");
dependencies_.insert(vpd_key_);
pdd_key_ = Keys::readKey(plist_, domain, "ponded depth minus depression depth", "ponded_depth_minus_depression_depth");
dependencies_.insert(pdd_key_);
delta_max_key_ = Keys::readKey(plist_, domain, "microtopographic relief", "microtopographic_relief");
dependencies_.insert(delta_max_key_);
delta_ex_key_ = plist_.get<std::string>("excluded volume key", Keys::getKey(domain,"excluded_volume"));
dependencies_.insert(delta_ex_key_);
depr_depth_key_ = plist_.get<std::string>("depression depth key", Keys::getKey(domain,"depression_depth"));
dependencies_.insert(depr_depth_key_);
}
FractionalConductanceEvaluator::FractionalConductanceEvaluator(const FractionalConductanceEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
pdd_key_(other.pdd_key_),
vpd_key_(other.vpd_key_),
delta_ex_key_(other.delta_ex_key_),
delta_max_key_(other.delta_max_key_),
depr_depth_key_(other.depr_depth_key_)
{};
Teuchos::RCP<FieldEvaluator>
FractionalConductanceEvaluator::Clone() const {
return Teuchos::rcp(new FractionalConductanceEvaluator(*this));
}
void FractionalConductanceEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Epetra_MultiVector& res = *result->ViewComponent("cell",false);
const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);
int ncells = res.MyLength();
assert(depr_depth_v[0][0] > 0.);
for (int c=0; c!=ncells; ++c) {
double depr_depth = depr_depth_v[0][c];
double delta_max = delta_max_v[0][c];
double delta_ex = delta_ex_v[0][c];
double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);
if (pdd_v[0][c] <= 0.0)
res[0][c] = 0;
else{
res[0][c] = (vpd[0][c] - fixed_depth) / (pdd_v[0][c]);
}
}
}
// This is hopefully never called?
void FractionalConductanceEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
// std::cout<<"Fractional Conductance Evaluator Partial Derivative -- NEVER CALLED??: \n"; abort();
std::cout<<"Fractional: "<<my_key_<<" "<<wrt_key<<"\n";
Epetra_MultiVector& res = *result->ViewComponent("cell",false);
const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);
int ncells = res.MyLength();
// assert(depr_depth_v[0][0] > 0.);
if (wrt_key == pdd_key_) {
for (int c=0; c!=ncells; ++c) {
double depr_depth = depr_depth_v[0][c];
double delta_max = delta_max_v[0][c];
double delta_ex = delta_ex_v[0][c];
double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);
if (pdd_v[0][c] <= 0.0)
res[0][c] = 0;
else{
res[0][c] = - (vpd[0][c] - fixed_depth) / std::pow(pdd_v[0][c],2.);
}
}
}
else if (wrt_key == vpd_key_) {
for (int c=0; c!=ncells; ++c) {
double depr_depth = depr_depth_v[0][c];
double delta_max = delta_max_v[0][c];
double delta_ex = delta_ex_v[0][c];
double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);
if (pdd_v[0][c] <= 0.0)
res[0][c] = 0;
else{
res[0][c] = 1.0 / pdd_v[0][c];
}
}
}
else {
Errors::Message msg("VolumetricHeightSubgridEvaluator: Not Implemented: no derivatives implemented other than ponded depth.");
Exceptions::amanzi_throw(msg);
}
}
} //namespace
} //namespace
} //namespace
<commit_msg>removed couts.<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
The elevation evaluator gets the surface elevation, slope, and updates pres + elev.
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "fractional_conductance_evaluator.hh"
namespace Amanzi {
namespace Flow {
namespace FlowRelations {
FractionalConductanceEvaluator::FractionalConductanceEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
Key domain = Keys::getDomain(my_key_);
vpd_key_ = Keys::readKey(plist_, domain, "volumetric ponded depth", "volumetric_ponded_depth");
dependencies_.insert(vpd_key_);
pdd_key_ = Keys::readKey(plist_, domain, "ponded depth minus depression depth", "ponded_depth_minus_depression_depth");
dependencies_.insert(pdd_key_);
delta_max_key_ = Keys::readKey(plist_, domain, "microtopographic relief", "microtopographic_relief");
dependencies_.insert(delta_max_key_);
delta_ex_key_ = plist_.get<std::string>("excluded volume key", Keys::getKey(domain,"excluded_volume"));
dependencies_.insert(delta_ex_key_);
depr_depth_key_ = plist_.get<std::string>("depression depth key", Keys::getKey(domain,"depression_depth"));
dependencies_.insert(depr_depth_key_);
}
FractionalConductanceEvaluator::FractionalConductanceEvaluator(const FractionalConductanceEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
pdd_key_(other.pdd_key_),
vpd_key_(other.vpd_key_),
delta_ex_key_(other.delta_ex_key_),
delta_max_key_(other.delta_max_key_),
depr_depth_key_(other.depr_depth_key_)
{};
Teuchos::RCP<FieldEvaluator>
FractionalConductanceEvaluator::Clone() const {
return Teuchos::rcp(new FractionalConductanceEvaluator(*this));
}
void FractionalConductanceEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Epetra_MultiVector& res = *result->ViewComponent("cell",false);
const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);
int ncells = res.MyLength();
assert(depr_depth_v[0][0] > 0.);
for (int c=0; c!=ncells; ++c) {
double depr_depth = depr_depth_v[0][c];
double delta_max = delta_max_v[0][c];
double delta_ex = delta_ex_v[0][c];
double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);
if (pdd_v[0][c] <= 0.0)
res[0][c] = 0;
else{
res[0][c] = (vpd[0][c] - fixed_depth) / (pdd_v[0][c]);
}
}
}
// This is hopefully never called?
void FractionalConductanceEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
Epetra_MultiVector& res = *result->ViewComponent("cell",false);
const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);
int ncells = res.MyLength();
// assert(depr_depth_v[0][0] > 0.);
if (wrt_key == pdd_key_) {
for (int c=0; c!=ncells; ++c) {
double depr_depth = depr_depth_v[0][c];
double delta_max = delta_max_v[0][c];
double delta_ex = delta_ex_v[0][c];
double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);
if (pdd_v[0][c] <= 0.0)
res[0][c] = 0;
else{
res[0][c] = - (vpd[0][c] - fixed_depth) / std::pow(pdd_v[0][c],2.);
}
}
}
else if (wrt_key == vpd_key_) {
for (int c=0; c!=ncells; ++c) {
double depr_depth = depr_depth_v[0][c];
double delta_max = delta_max_v[0][c];
double delta_ex = delta_ex_v[0][c];
double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);
if (pdd_v[0][c] <= 0.0)
res[0][c] = 0;
else{
res[0][c] = 1.0 / pdd_v[0][c];
}
}
}
else {
Errors::Message msg("VolumetricHeightSubgridEvaluator: Not Implemented: no derivatives implemented other than ponded depth.");
Exceptions::amanzi_throw(msg);
}
}
} //namespace
} //namespace
} //namespace
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 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) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.6 2000/01/18 21:32:21 aruna1
* XMLCh assigned to wchar_t
*
* Revision 1.5 1999/12/14 23:53:25 rahulj
* Removed the offending Ctrl-M's from the commit message
* logs which was giving packaging problems.
*
* PR:
* Obtained from:
* Submitted by:
* Reviewed by:
*
* Revision 1.4 1999/11/23 02:00:12 rahulj
* Code now works under HPUX 11. Tested inmemory message loader.
* Revamped makefiles. Builds with both DCE threads as well as pthread libraries.
*
* Revision 1.3 1999/11/12 20:36:57 rahulj
* Changed library name to xerces-c.lib.
*
* Revision 1.1.1.1 1999/11/09 01:07:34 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:23 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT
// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#if defined(XML_HPUX_CC)
#define NO_NATIVE_BOOL
#endif
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
#ifndef INCLUDE_THIS_FILE
#define INCLUDE_THIS_FILE
#include <wchar.h>
#endif
typedef wchar_t XMLCh;
typedef unsigned short UTF16Ch;
// ---------------------------------------------------------------------------
// Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int XMLUInt32;
// ---------------------------------------------------------------------------
// Provide prototypes for some string methods that are not always available
// on all platforms.
// ---------------------------------------------------------------------------
int stricmp(const char* const str1, const char* const str2);
int strnicmp(const char* const str1, const char* const str2, const unsigned int count);
// ---------------------------------------------------------------------------
// The name of the DLL that is built by the HP CC version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<commit_msg>Modified XMLCh to unsigned short<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 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) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.7 2000/01/18 22:37:20 aruna1
* Modified XMLCh to unsigned short
*
* Revision 1.6 2000/01/18 21:32:21 aruna1
* XMLCh assigned to wchar_t
*
* Revision 1.5 1999/12/14 23:53:25 rahulj
* Removed the offending Ctrl-M's from the commit message
* logs which was giving packaging problems.
*
* PR:
* Obtained from:
* Submitted by:
* Reviewed by:
*
* Revision 1.4 1999/11/23 02:00:12 rahulj
* Code now works under HPUX 11. Tested inmemory message loader.
* Revamped makefiles. Builds with both DCE threads as well as pthread libraries.
*
* Revision 1.3 1999/11/12 20:36:57 rahulj
* Changed library name to xerces-c.lib.
*
* Revision 1.1.1.1 1999/11/09 01:07:34 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:23 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT
// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#if defined(XML_HPUX_CC)
#define NO_NATIVE_BOOL
#endif
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
#ifndef INCLUDE_THIS_FILE
#define INCLUDE_THIS_FILE
#include <wchar.h>
#endif
typedef unsigned short XMLCh;
typedef unsigned short UTF16Ch;
// ---------------------------------------------------------------------------
// Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int XMLUInt32;
// ---------------------------------------------------------------------------
// Provide prototypes for some string methods that are not always available
// on all platforms.
// ---------------------------------------------------------------------------
int stricmp(const char* const str1, const char* const str2);
int strnicmp(const char* const str1, const char* const str2, const unsigned int count);
// ---------------------------------------------------------------------------
// The name of the DLL that is built by the HP CC version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<|endoftext|>
|
<commit_before>#ifndef _PROPHY_PROPHY_HPP
#define _PROPHY_PROPHY_HPP
#include <stdint.h>
namespace prophy
{
inline void swap(uint8_t&)
{ }
inline void swap(uint16_t& in)
{
in = (in << 8) | (in >> 8);
}
inline void swap(uint32_t& in)
{
in = ((in << 8) & 0xFF00FF00) | ((in >> 8) & 0x00FF00FF);
in = (in << 16) | (in >> 16);
}
inline void swap(uint64_t& in)
{
in = ((in << 8) & 0xFF00FF00FF00FF00ULL ) | ((in >> 8) & 0x00FF00FF00FF00FFULL );
in = ((in << 16) & 0xFFFF0000FFFF0000ULL ) | ((in >> 16) & 0x0000FFFF0000FFFFULL );
in = (in << 32) | (in >> 32);
}
inline void swap(int8_t&)
{ }
inline void swap(int16_t& in)
{
swap(*static_cast<uint16_t*>(static_cast<void*>(&in)));
}
inline void swap(int32_t& in)
{
swap(*static_cast<uint32_t*>(static_cast<void*>(&in)));
}
inline void swap(int64_t& in)
{
swap(*static_cast<uint64_t*>(static_cast<void*>(&in)));
}
inline void swap(float& in)
{
swap(*static_cast<uint32_t*>(static_cast<void*>(&in)));
}
inline void swap(double& in)
{
swap(*static_cast<uint64_t*>(static_cast<void*>(&in)));
}
template <typename Tp>
struct alignment
{
struct finder
{
char align;
Tp t;
};
enum { value = sizeof(finder) - sizeof(Tp) };
};
template <typename Tp>
inline Tp* align(Tp* ptr)
{
enum { mask = alignment<Tp>::value - 1 };
return reinterpret_cast<Tp*>((reinterpret_cast<uintptr_t>(ptr) + mask) & ~uintptr_t(mask));
}
template <typename To, typename From>
inline To cast(From from)
{
return align(static_cast<To>(static_cast<void*>(from)));
}
template <typename Tp>
inline Tp* swap_n_fixed(Tp* first, size_t n)
{
while (n--)
{
swap(*first);
++first;
}
return first;
}
template <typename Tp>
inline Tp* swap_n_dynamic(Tp* first, size_t n)
{
while (n--)
{
first = swap(*first);
}
return first;
}
} // namespace prophy
#endif /* _PROPHY_PROPHY_HPP */
<commit_msg>double static cast refactored out<commit_after>#ifndef _PROPHY_PROPHY_HPP
#define _PROPHY_PROPHY_HPP
#include <stdint.h>
namespace prophy
{
inline void swap(uint8_t&)
{ }
inline void swap(uint16_t& in)
{
in = (in << 8) | (in >> 8);
}
inline void swap(uint32_t& in)
{
in = ((in << 8) & 0xFF00FF00) | ((in >> 8) & 0x00FF00FF);
in = (in << 16) | (in >> 16);
}
inline void swap(uint64_t& in)
{
in = ((in << 8) & 0xFF00FF00FF00FF00ULL ) | ((in >> 8) & 0x00FF00FF00FF00FFULL );
in = ((in << 16) & 0xFFFF0000FFFF0000ULL ) | ((in >> 16) & 0x0000FFFF0000FFFFULL );
in = (in << 32) | (in >> 32);
}
inline void swap(int8_t&)
{ }
inline void swap(int16_t& in)
{
swap(reinterpret_cast<uint16_t&>(in));
}
inline void swap(int32_t& in)
{
swap(reinterpret_cast<uint32_t&>(in));
}
inline void swap(int64_t& in)
{
swap(reinterpret_cast<uint64_t&>(in));
}
inline void swap(float& in)
{
swap(reinterpret_cast<uint32_t&>(in));
}
inline void swap(double& in)
{
swap(reinterpret_cast<uint64_t&>(in));
}
template <typename Tp>
struct alignment
{
struct finder
{
char align;
Tp t;
};
enum { value = sizeof(finder) - sizeof(Tp) };
};
template <typename Tp>
inline Tp* align(Tp* ptr)
{
enum { mask = alignment<Tp>::value - 1 };
return reinterpret_cast<Tp*>((reinterpret_cast<uintptr_t>(ptr) + mask) & ~uintptr_t(mask));
}
template <typename To, typename From>
inline To cast(From from)
{
return align(static_cast<To>(static_cast<void*>(from)));
}
template <typename Tp>
inline Tp* swap_n_fixed(Tp* first, size_t n)
{
while (n--)
{
swap(*first);
++first;
}
return first;
}
template <typename Tp>
inline Tp* swap_n_dynamic(Tp* first, size_t n)
{
while (n--)
{
first = swap(*first);
}
return first;
}
} // namespace prophy
#endif /* _PROPHY_PROPHY_HPP */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#define ENTDIM 8
#define COORDIM (ENTDIM-2)
#define PARAMDIM 5
namespace
{
int numofline (const char * fname)
{
int number_of_lines = 0;
std::string line;
std::ifstream myfile(fname);
while (std::getline(myfile, line))
++number_of_lines;
myfile.close();
return number_of_lines;
}
}
int main (int argc, char ** argv)
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl;
return 1;
}
int num_of_line = numofline(argv[1]);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << " " << num_of_ent << " entries " << std::endl;
// non perfomante ma easy to go
double ** param_mtx = new double *[num_of_ent];
double ** coord_mtx = new double *[num_of_ent];
for (int i = 0; i < num_of_ent; ++i)
{
coord_mtx[i] = new double[3*COORDIM];
param_mtx[i] = new double[PARAMDIM];
}
// leggere file coordinate tracce simulate plus parametri
std::string line;
std::ifstream mytfp;
mytfp.open (argv[1], std::ios::in);
std::getline (mytfp, line);
//std::cout << line << std::endl;
for (int i = 0; i < num_of_ent; ++i)
{
int fake1, fake2;
mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
std::cout << fake1 << " " << fake2 << std::endl;
#endif
for (int j = 0; j < COORDIM; ++j)
{
int a, b, c;
mytfp >> coord_mtx[i][j*3] >>
coord_mtx[i][j*3+1] >>
coord_mtx[i][j*3+2] >>
a >> b >> c;
}
mytfp >> param_mtx[i][0] >>
param_mtx[i][1] >>
param_mtx[i][2] >>
param_mtx[i][3] >>
param_mtx[i][4];
}
mytfp.close();
#ifdef DEBUG
for (int i = 0; i < num_of_ent; ++i)
{
for (int j = 0; j < COORDIM; ++j)
{
std::cout << coord_mtx[i][j*3] << " " <<
coord_mtx[i][j*3+1] << " " <<
coord_mtx[i][j*3+2] << std::endl;
}
std::cout << param_mtx[i][0] << " " <<
param_mtx[i][1] << " " <<
param_mtx[i][2] << " " <<
param_mtx[i][3] << " " <<
param_mtx[i][4] << std::endl;
}
#endif
double sum = 1.0e0;
double coordm[3*COORDIM] = {0.0e0};
double hc[3*COORDIM][3*COORDIM] = {0.0e0};
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm[i] += (coord_mtx[l][i]-coordm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<(3*COORDIM); ++j)
{
hc[i][j] += ((coord_mtx[l][i] - coordm[i])*
(coord_mtx[l][j] - coordm[j])-
(sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0);
}
}
}
for (int i=0; i<(3*COORDIM); ++i)
for (int j=i+1; j<(3*COORDIM); ++j)
if (hc[i][j] != hc[j][i])
std::cout << i << " " << j << " " <<
hc[i][j] << " ERROR" << std::endl;;
arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
hca(i,j) = hc[i][j];
arma::vec eigval;
arma::mat eigvec;
arma::eig_sym(eigval, eigvec, hca);
double totval = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
totval += eigval(i);
int j = 1;
double totvar = 0.0e0;
for (int i=(3*COORDIM-1); i>=0; --i)
{
if (j <= PARAMDIM)
totvar += 100.0e0*(eigval(i)/totval);
++j;
std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << std::endl;
}
std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl;
arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
hcai = hca.i();
//std::cout << hca * hcai ;
// and so on ...
std::fill(coordm, &(coordm[3*COORDIM]), 0.0e0 );
double paramm[PARAMDIM] = {0.0e0};
double hcp[3*COORDIM][PARAMDIM] = {0.0e0};
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm[i] += (coord_mtx[l][i]-coordm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
paramm[i] += (param_mtx[l][i]-paramm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<PARAMDIM; ++j)
{
hcp[i][j] += ((coord_mtx[l][i] - coordm[i])*
(param_mtx[l][j] - paramm[j])-
(sum-1.0e0)*hcp[i][j]/sum)/(sum-1.0e0);
}
}
}
// documento Annovi
// calcolo matrice di correlazione traccie HC
// diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali)
// A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce
// simulate.
// documento ATLAS
// calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione
// data C determinare il vettore di traslazione q
// c plus q costanti PCA
// write constants in a file
for (int i = 0; i < num_of_ent; ++i)
{
delete(coord_mtx[i]);
delete(param_mtx[i]);
}
delete(coord_mtx);
delete(param_mtx);
return 0;
}
<commit_msg>fast code/pseudocode (as in atlas tdr) to give an impression of armadillo API<commit_after>#include <iostream>
#include <fstream>
#include <string>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#define ENTDIM 8
#define COORDIM (ENTDIM-2)
#define PARAMDIM 5
namespace
{
int numofline (const char * fname)
{
int number_of_lines = 0;
std::string line;
std::ifstream myfile(fname);
while (std::getline(myfile, line))
++number_of_lines;
myfile.close();
return number_of_lines;
}
}
int main (int argc, char ** argv)
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl;
return 1;
}
int num_of_line = numofline(argv[1]);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << " " << num_of_ent << " entries " << std::endl;
// non perfomante ma easy to go
double ** param_mtx = new double *[num_of_ent];
double ** coord_mtx = new double *[num_of_ent];
for (int i = 0; i < num_of_ent; ++i)
{
coord_mtx[i] = new double[3*COORDIM];
param_mtx[i] = new double[PARAMDIM];
}
// leggere file coordinate tracce simulate plus parametri
std::string line;
std::ifstream mytfp;
mytfp.open (argv[1], std::ios::in);
std::getline (mytfp, line);
//std::cout << line << std::endl;
for (int i = 0; i < num_of_ent; ++i)
{
int fake1, fake2;
mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
std::cout << fake1 << " " << fake2 << std::endl;
#endif
for (int j = 0; j < COORDIM; ++j)
{
int a, b, c;
mytfp >> coord_mtx[i][j*3] >>
coord_mtx[i][j*3+1] >>
coord_mtx[i][j*3+2] >>
a >> b >> c;
}
mytfp >> param_mtx[i][0] >>
param_mtx[i][1] >>
param_mtx[i][2] >>
param_mtx[i][3] >>
param_mtx[i][4];
}
mytfp.close();
#ifdef DEBUG
for (int i = 0; i < num_of_ent; ++i)
{
for (int j = 0; j < COORDIM; ++j)
{
std::cout << coord_mtx[i][j*3] << " " <<
coord_mtx[i][j*3+1] << " " <<
coord_mtx[i][j*3+2] << std::endl;
}
std::cout << param_mtx[i][0] << " " <<
param_mtx[i][1] << " " <<
param_mtx[i][2] << " " <<
param_mtx[i][3] << " " <<
param_mtx[i][4] << std::endl;
}
#endif
double sum = 1.0e0;
double coordm[3*COORDIM];
double hc[3*COORDIM][3*COORDIM];
std::fill_n (coordm, (3*COORDIM), 0.0e0);
std::fill_n (&(hc[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0);
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm[i] += (coord_mtx[l][i]-coordm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<(3*COORDIM); ++j)
{
hc[i][j] += ((coord_mtx[l][i] - coordm[i])*
(coord_mtx[l][j] - coordm[j])-
(sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0);
}
}
}
for (int i=0; i<(3*COORDIM); ++i)
for (int j=i+1; j<(3*COORDIM); ++j)
if (hc[i][j] != hc[j][i])
std::cout << i << " " << j << " " <<
hc[i][j] << " ERROR" << std::endl;;
arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
hca(i,j) = hc[i][j];
arma::vec eigval;
arma::mat eigvec;
arma::eig_sym(eigval, eigvec, hca);
double totval = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
totval += eigval(i);
int j = 1;
double totvar = 0.0e0;
for (int i=(3*COORDIM-1); i>=0; --i)
{
if (j <= PARAMDIM)
totvar += 100.0e0*(eigval(i)/totval);
++j;
std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << std::endl;
}
std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl;
arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
hcai = hca.i();
//std::cout << hca * hcai ;
// and so on ...
double paramm[PARAMDIM];
arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM);
std::fill_n(coordm, (3*COORDIM), 0.0e0 );
std::fill_n(paramm, PARAMDIM, 0.0e0 );
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm[i] += (coord_mtx[l][i]-coordm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
paramm[i] += (param_mtx[l][i]-paramm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<PARAMDIM; ++j)
{
hcap(i,j) += ((coord_mtx[l][i] - coordm[i])*
(param_mtx[l][j] - paramm[j])-
(sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0);
}
}
}
arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM);
for (int i=0; i<PARAMDIM; ++i)
for (int l=0; l<(3*COORDIM); ++l)
for (int m=0; m<(3*COORDIM); ++m)
cmtx(i,l) += hcai(l,m) * hcap (m,i);
std::cout << "C matrix: " << std::endl;
std::cout << cmtx;
double q[PARAMDIM];
std::fill_n(q, PARAMDIM, 0.0e0 );
//std::cout << cmtx;
for (int i=0; i<PARAMDIM; ++i)
{
q[i] = paramm[i];
for (int j=0; j<(3*COORDIM); ++j)
q[i] -= cmtx(i,j)*coordm[j];
}
std::cout << "Q vector: " << std::endl;
for (int i=0; i<PARAMDIM; ++i)
std::cout << q[i] << std::endl;
// documento Annovi
// calcolo matrice di correlazione traccie HC
// diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali)
// A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce
// simulate.
// documento ATLAS
// calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione
// data C determinare il vettore di traslazione q
// c plus q costanti PCA
// write constants in a file
for (int i = 0; i < num_of_ent; ++i)
{
delete(coord_mtx[i]);
delete(param_mtx[i]);
}
delete(coord_mtx);
delete(param_mtx);
return 0;
}
<|endoftext|>
|
<commit_before>/***********
AUTHORS: Michael Katelman, Vijay Ganesh, Trevor Hansen, Dan Liew
BEGIN DATE: Oct, 2008
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**********************/
#include <gtest/gtest.h>
#include <stdio.h>
#include "stp/c_interface.h"
// FIXME: Pick a sensible testname that actually means something!
TEST(array_cvcl02, one)
{
VC vc = vc_createValidityChecker();
vc_setFlag(vc, 'n');
vc_setFlag(vc, 'd');
vc_setFlag(vc, 'p');
Expr cvcl_array = vc_varExpr1(vc, "a", 32, 32);
Expr i = vc_varExpr1(vc, "i", 0, 8);
Expr i32 = vc_bvConcatExpr(
vc, vc_bvConstExprFromStr(vc, "000000000000000000000000"), i);
Expr no_underflow = vc_bvLeExpr(vc, vc_bvConstExprFromInt(vc, 32, 0), i32);
Expr no_overflow = vc_bvLeExpr(vc, i32, vc_bvConstExprFromInt(vc, 32, 9));
Expr in_bounds = vc_andExpr(vc, no_underflow, no_overflow);
Expr a_of_i = vc_bvSignExtend(vc, vc_readExpr(vc, cvcl_array, i32), 32);
Expr a_of_i_eq_11 = vc_eqExpr(vc, vc_bvConcatExpr(vc, i32, a_of_i),
vc_bvConstExprFromInt(vc, 64, 11));
vc_assertFormula(vc, in_bounds);
vc_assertFormula(vc, a_of_i_eq_11);
vc_query(vc, vc_falseExpr(vc));
long long v;
Expr pre = vc_bvConstExprFromInt(vc, 24, 0);
int j;
for (j = 0; j < 10; j++)
{
Expr exprj = vc_bvConstExprFromInt(vc, 8, j);
Expr index = vc_bvConcatExpr(vc, pre, exprj);
index = vc_simplify(vc, index);
Expr a_of_j = vc_readExpr(vc, cvcl_array, index);
Expr ce = vc_getCounterExample(vc, a_of_j);
}
vc_Destroy(vc);
// vc_printCounterExample(vc);
// FIXME: Actually test something
// ASSERT_TRUE(false && "FIXME: Actually test something");
}
<commit_msg>Removing unused variable<commit_after>/***********
AUTHORS: Michael Katelman, Vijay Ganesh, Trevor Hansen, Dan Liew
BEGIN DATE: Oct, 2008
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**********************/
#include <gtest/gtest.h>
#include <stdio.h>
#include "stp/c_interface.h"
// FIXME: Pick a sensible testname that actually means something!
TEST(array_cvcl02, one)
{
VC vc = vc_createValidityChecker();
vc_setFlag(vc, 'n');
vc_setFlag(vc, 'd');
vc_setFlag(vc, 'p');
Expr cvcl_array = vc_varExpr1(vc, "a", 32, 32);
Expr i = vc_varExpr1(vc, "i", 0, 8);
Expr i32 = vc_bvConcatExpr(
vc, vc_bvConstExprFromStr(vc, "000000000000000000000000"), i);
Expr no_underflow = vc_bvLeExpr(vc, vc_bvConstExprFromInt(vc, 32, 0), i32);
Expr no_overflow = vc_bvLeExpr(vc, i32, vc_bvConstExprFromInt(vc, 32, 9));
Expr in_bounds = vc_andExpr(vc, no_underflow, no_overflow);
Expr a_of_i = vc_bvSignExtend(vc, vc_readExpr(vc, cvcl_array, i32), 32);
Expr a_of_i_eq_11 = vc_eqExpr(vc, vc_bvConcatExpr(vc, i32, a_of_i),
vc_bvConstExprFromInt(vc, 64, 11));
vc_assertFormula(vc, in_bounds);
vc_assertFormula(vc, a_of_i_eq_11);
vc_query(vc, vc_falseExpr(vc));
Expr pre = vc_bvConstExprFromInt(vc, 24, 0);
int j;
for (j = 0; j < 10; j++)
{
Expr exprj = vc_bvConstExprFromInt(vc, 8, j);
Expr index = vc_bvConcatExpr(vc, pre, exprj);
index = vc_simplify(vc, index);
Expr a_of_j = vc_readExpr(vc, cvcl_array, index);
Expr ce = vc_getCounterExample(vc, a_of_j);
}
vc_Destroy(vc);
// vc_printCounterExample(vc);
// FIXME: Actually test something
// ASSERT_TRUE(false && "FIXME: Actually test something");
}
<|endoftext|>
|
<commit_before>//---------------------------- quadrature_test.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- quadrature_test.cc ---------------------------
#include <iostream>
#include <fstream>
#include <base/logstream.h>
#include <base/quadrature_lib.h>
#include <cmath>
int main(int,char)
{
ofstream logfile("quadrature_test.output");
deallog.attach(logfile);
deallog.depth_console(0);
vector<Quadrature<1> *> quadratures(14);
quadratures[2]=new QGauss2<1>();
quadratures[3]=new QGauss3<1>();
quadratures[4]=new QGauss4<1>();
quadratures[5]=new QGauss5<1>();
quadratures[6]=new QGauss6<1>();
quadratures[7]=new QGauss7<1>();
quadratures[8]=new QGauss8<1>();
quadratures[9] = new QMidpoint<1>();
quadratures[10] = new QTrapez<1>();
quadratures[11] = new QSimpson<1>();
quadratures[12] = new QMilne<1>();
quadratures[13] = new QWeddle<1>();
for (unsigned int n=2; n<14; ++n)
{
Quadrature<1> *quadrature=quadratures[n];
const vector<Point<1> > &points=quadrature->get_points();
const vector<double> &weights=quadrature->get_weights();
deallog << "Quadrature no." << n;
unsigned int i=0;
double quadrature_int=0;
double exact_int=0;
double err = 0;
do
{
++i;
quadrature_int=0;
for (unsigned int x=0; x<quadrature->n_quadrature_points; ++x)
quadrature_int+=pow(points[x](0), i)*weights[x];
// the exact integral is 1/(i+1)
exact_int=1./(i+1);
err = fabs(quadrature_int-exact_int);
}
while (err<1e-15);
// Uncomment here for testing
// deallog << " (Error " << err << ")";
deallog << " is exact for polynomials of degree " << i-1 << endl;
}
}
<commit_msg>Check 2d Quadrature instead of 1d<commit_after>//---------------------------- quadrature_test.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- quadrature_test.cc ---------------------------
#include <iostream>
#include <fstream>
#include <base/logstream.h>
#include <base/quadrature_lib.h>
#include <cmath>
int main(int,char)
{
ofstream logfile("quadrature_test.output");
deallog.attach(logfile);
deallog.depth_console(0);
vector<Quadrature<2> *> quadratures(14);
quadratures[2]=new QGauss2<2>();
quadratures[3]=new QGauss3<2>();
quadratures[4]=new QGauss4<2>();
quadratures[5]=new QGauss5<2>();
quadratures[6]=new QGauss6<2>();
quadratures[7]=new QGauss7<2>();
quadratures[8]=new QGauss8<2>();
quadratures[9] = new QMidpoint<2>();
quadratures[10] = new QTrapez<2>();
quadratures[11] = new QSimpson<2>();
quadratures[12] = new QMilne<2>();
quadratures[13] = new QWeddle<2>();
for (unsigned int n=2; n<14; ++n)
{
Quadrature<2> *quadrature=quadratures[n];
const vector<Point<2> > &points=quadrature->get_points();
const vector<double> &weights=quadrature->get_weights();
deallog << "Quadrature no." << n;
unsigned int i=0;
double quadrature_int=0;
double exact_int=0;
double err = 0;
do
{
++i;
quadrature_int=0;
// Check the polynomial x^i*y^i
for (unsigned int x=0; x<quadrature->n_quadrature_points; ++x)
quadrature_int+=pow(points[x](0), i)*pow(points[x](1), i)*weights[x];
// the exact integral is 1/(i+1)
exact_int=1./(i+1)/(i+1);
err = fabs(quadrature_int-exact_int);
}
while (err<1e-15);
// Uncomment here for testing
// deallog << " (Error " << err << ")";
deallog << " is exact for polynomials of degree " << i-1 << endl;
}
}
<|endoftext|>
|
<commit_before>#include "x86_64-Codegen.h"
#include "ASTNode.h"
#include "lib/Runtime.h"
#include "lib/SnowString.h"
#include "Internal.h"
#include <stdexcept>
#include <vector>
using namespace std;
#define __ m_Asm->
#define e__ entry_asm->
namespace snow {
namespace x86_64 {
// stack_frame->`member'
#define GET_STACK(member) (Address(rbp, (-(int)sizeof(StackFrame))+(int)offsetof(StackFrame, member)))
// temporaries[id]
#define GET_TEMPORARY(id) (Address(rbp, (-(int)sizeof(StackFrame))-(sizeof(VALUE)*(id+1))))
// reg[index] (reg must contain a pointer to an array of values)
#define GET_ARRAY_PTR(reg, index) (Address((reg), index * sizeof(VALUE)))
static const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 };
static const uint64_t num_arg_regs = 6;
Codegen::Codegen(ast::FunctionDefinition& def) :
snow::Codegen(def),
m_NumLocals(0),
m_NumStackArguments(0),
m_NumTemporaries(0) {
m_LocalMap = new LocalMap;
m_Asm = new x86_64::Assembler;
m_Return = new Label;
}
uint64_t Codegen::reserve_temporary() {
if (m_FreeTemporaries.size() > 0) {
uint64_t t = m_FreeTemporaries.back();
m_FreeTemporaries.pop_back();
return t;
}
return m_NumTemporaries++;
}
void Codegen::free_temporary(uint64_t id) {
m_FreeTemporaries.push_back(id);
}
void Codegen::get_local(uint64_t id, const Register& reg) {
ASSERT(!m_InGlobalScope);
__ mov(GET_STACK(locals), reg);
__ mov(GET_ARRAY_PTR(reg, id), reg);
}
void Codegen::set_local(const Register& reg, uint64_t id, const Register& tmp) {
ASSERT(reg != tmp && "Cannot use source register as temporary storage!");
ASSERT(!m_InGlobalScope);
__ mov(GET_STACK(locals), tmp);
__ mov(reg, GET_ARRAY_PTR(tmp, id));
}
Handle<CompiledCode> Codegen::compile(bool in_global_scope) {
m_InGlobalScope = in_global_scope;
RefPtr<x86_64::Assembler> entry_asm = new x86_64::Assembler;
__ subasm(entry_asm);
if (m_Def.arguments.size() > 0) {
__ comment("copy arguments to locals");
__ mov(GET_STACK(arguments), r8);
__ mov(GET_STACK(locals), r9);
size_t i = 0;
for each (iter, m_Def.arguments) {
auto local = m_LocalMap->define_local((*iter)->name);
__ mov(GET_ARRAY_PTR(r8, i), rax);
__ mov(rax, GET_ARRAY_PTR(r9, local));
++i;
}
}
__ comment("function body");
compile(*m_Def.sequence);
uint64_t return_temporary = reserve_temporary();
__ comment("function exit");
__ bind(m_Return);
__ mov(rax, GET_TEMPORARY(return_temporary));
__ call("snow_leave_scope");
__ mov(GET_TEMPORARY(return_temporary), rax);
__ leave();
__ ret();
// Compile the function entry, now that we know all the locals and
// temporaries.
{
e__ comment("function entry");
int stack_size = sizeof(StackFrame) + sizeof(VALUE)*(m_NumTemporaries + m_NumStackArguments);
// maintain 16-byte stack alignment
stack_size += stack_size % 16;
e__ enter(stack_size);
e__ mov(rbp, rsi);
e__ sub(sizeof(StackFrame), rsi);
e__ mov(rsi, rax);
e__ sub((m_NumTemporaries+m_NumStackArguments)*sizeof(VALUE), rax);
e__ mov(rax, GET_STACK(temporaries));
e__ mov(m_NumTemporaries+m_NumStackArguments, GET_STACK(num_temporaries));
e__ call("snow_enter_scope");
e__ mov(nil(), rax);
}
Handle<CompiledCode> code = __ compile();
code->set_local_map(m_LocalMap);
for each (iter, m_Related) {
code->add_related(*iter);
}
return code;
}
void Codegen::compile(ast::Literal& literal) {
__ comment(std::string("literal: `") + literal.string + std::string("'"));
using ast::Literal;
const char* str = literal.string.c_str();
VALUE val = nil();
switch (literal.type) {
case Literal::INTEGER_DEC_TYPE:
val = value(strtoll(str, NULL, 10));
break;
case Literal::INTEGER_HEX_TYPE:
val = value(strtoll(str, NULL, 16));
break;
case Literal::INTEGER_BIN_TYPE:
val = value(strtoll(str, NULL, 2));
break;
case Literal::FLOAT_TYPE:
// TODO: Doubles
val = value(strtof(str, NULL));
break;
case Literal::STRING_TYPE:
val = new(kMalloc) String(str);
break;
case Literal::TRUE_TYPE:
val = value(true);
break;
case Literal::FALSE_TYPE:
val = value(false);
break;
case Literal::NIL_TYPE:
val = nil();
break;
case Literal::SYMBOL_TYPE:
val = symbol(str);
break;
}
__ mov(val, rax);
}
void Codegen::compile(ast::Identifier& id) {
__ comment(std::string("identifier: `") + value_to_string(id.name) + std::string("'"));
if (!m_InGlobalScope && m_LocalMap->has_local(id.name)) {
// It's a local from current scope...
get_local(m_LocalMap->local(id.name), rax);
} else {
// THE PAIN! It's from a parent scope...
__ mov(rbp, rdi);
__ sub(sizeof(StackFrame), rdi);
__ mov(id.name, rsi);
__ mov(id.quiet, rdx);
__ call("snow_get_local");
}
}
void Codegen::compile(ast::Sequence& seq) {
for each (iter, seq.nodes) {
(*iter)->compile(*this);
}
}
void Codegen::compile(ast::FunctionDefinition& def) {
__ comment("function definition");
RefPtr<Codegen> codegen = new Codegen(def);
Handle<CompiledCode> code = codegen->compile();
m_Related.push_back(code);
VALUE func = new(kMalloc) Function(*code);
__ mov(func, rdi);
__ mov(GET_STACK(scope), rsi);
__ call("snow_set_parent_scope");
__ mov(func, rax);
}
void Codegen::compile(ast::Return& ret) {
__ comment("return");
if (ret.expression)
ret.expression->compile(*this);
else
__ clear(rax);
__ jmp(m_Return);
}
void Codegen::compile(ast::Assignment& assign) {
assign.expression->compile(*this);
__ comment(std::string("assignment: ") + value_to_string(assign.identifier->name));
if (!m_InGlobalScope) {
uint64_t l;
if (m_LocalMap->has_local(assign.identifier->name))
l = m_LocalMap->local(assign.identifier->name);
else
l = m_LocalMap->define_local(assign.identifier->name);
set_local(rax, l);
} else {
__ mov(rbp, rdi);
__ sub(sizeof(StackFrame), rdi);
__ mov(assign.identifier->name, rsi);
__ mov(rax, rdx);
__ call("snow_set_local");
}
}
void Codegen::compile(ast::IfCondition& cond) {
RefPtr<Label> test_cond = new Label;
RefPtr<Label> after = new Label;
__ bind(test_cond);
__ comment("if cond");
cond.expression->compile(*this);
__ mov(rax, rdi);
__ call("snow_eval_truth");
__ cmp(cond.unless, rax);
__ j(CC_EQUAL, after);
__ comment("if body");
cond.if_true->compile(*this);
__ bind(after);
}
void Codegen::compile(ast::IfElseCondition& cond) {
RefPtr<Label> test_cond = new Label;
RefPtr<Label> if_true = new Label;
RefPtr<Label> if_false = new Label;
RefPtr<Label> after = new Label;
__ bind(test_cond);
__ comment("if-else cond");
cond.expression->compile(*this);
__ mov(rax, rdi);
__ call("snow_eval_truth");
__ cmp(cond.unless, rax);
__ j(CC_EQUAL, if_false);
__ bind(if_true);
__ comment("if true");
cond.if_true->compile(*this);
__ jmp(after);
__ bind(if_false);
__ comment("if false");
cond.if_false->compile(*this);
__ bind(after);
}
void Codegen::compile(ast::Call& call) {
auto self_tmp = reserve_temporary();
__ comment("self for call");
call.self->compile(*this);
__ mov(rax, GET_TEMPORARY(self_tmp));
// evaluate arguments and store temporaries
auto num_args = call.arguments->length();
uint64_t args_tmp[num_args];
size_t i = 0;
for each (arg_iter, call.arguments->nodes) {
args_tmp[i] = reserve_temporary();
__ comment(string_printf("argument %d", i));
(*arg_iter)->compile(*this);
__ mov(rax, GET_TEMPORARY(args_tmp[i]));
++i;
}
auto function_tmp = self_tmp;
if (call.member) {
__ comment("method call");
function_tmp = reserve_temporary();
__ mov(GET_TEMPORARY(self_tmp), rdi);
__ mov(call.member->name, rsi);
__ call("snow_get");
__ mov(rax, GET_TEMPORARY(function_tmp));
__ mov(GET_TEMPORARY(self_tmp), rdi);
} else {
__ comment("closure call");
__ clear(rdi); // "self" is NULL for closures
}
__ mov(GET_TEMPORARY(function_tmp), rsi);
__ mov(num_args, rdx);
bool rsp_in_rbx = false;
for (size_t i = 0; i < num_args; ++i) {
const size_t arg_offset = i + 3;
if (arg_offset < num_arg_regs) {
__ mov(GET_TEMPORARY(args_tmp[i]), *arg_regs[arg_offset]);
} else {
const size_t stack_offset = arg_offset - num_arg_regs;
if (m_NumStackArguments < stack_offset)
m_NumStackArguments = stack_offset;
__ mov(GET_TEMPORARY(args_tmp[i]), rax);
if (!rsp_in_rbx) {
__ mov(rsp, rbx);
rsp_in_rbx = true;
}
__ mov(rax, Address(rbx, stack_offset*sizeof(VALUE)));
}
free_temporary(args_tmp[i]);
}
if (self_tmp == function_tmp)
free_temporary(self_tmp);
else {
free_temporary(self_tmp);
free_temporary(function_tmp);
}
// finally!
__ clear(rax);
__ call("snow_call");
}
void Codegen::compile(ast::Get& get) {
__ comment(std::string("get `") + value_to_string(get.member->name) + "'");
get.self->compile(*this);
__ mov(rax, rdi);
__ mov(get.member->name, rsi);
__ call("snow_get");
}
void Codegen::compile(ast::Set& set) {
__ comment(std::string("set `") + value_to_string(set.member->name) + "'");
set.expression->compile(*this);
auto tmp = reserve_temporary();
__ mov(rax, GET_TEMPORARY(tmp));
set.self->compile(*this);
__ mov(rax, rdi);
__ mov(set.member->name, rsi);
__ mov(GET_TEMPORARY(tmp), rdx);
__ call("snow_set");
free_temporary(tmp);
}
void Codegen::compile(ast::Loop& loop) {
RefPtr<Label> test_cond = new Label;
RefPtr<Label> body = new Label;
RefPtr<Label> after = new Label;
__ bind(test_cond);
__ comment("loop cond");
loop.expression->compile(*this);
__ mov(rax, rdi);
__ call("snow_eval_truth");
__ cmp(0, rax);
__ j(CC_EQUAL, after);
__ bind(body);
__ comment("loop body");
loop.while_true->compile(*this);
__ jmp(test_cond);
__ bind(after);
}
void Codegen::compile(ast::Self&) {
__ mov(GET_STACK(self), rax);
}
void Codegen::compile(ast::It&) {
__ mov(GET_STACK(it), rax);
}
}
}
<commit_msg>x86_64 codegen: Fixed stack frame initialization and exit<commit_after>#include "x86_64-Codegen.h"
#include "ASTNode.h"
#include "lib/Runtime.h"
#include "lib/SnowString.h"
#include "Internal.h"
#include <stdexcept>
#include <vector>
using namespace std;
#define __ m_Asm->
#define e__ entry_asm->
namespace snow {
namespace x86_64 {
// stack_frame->`member'
#define GET_STACK(member) (Address(rbp, (-(int)sizeof(StackFrame))+(int)offsetof(StackFrame, member)))
// temporaries[id]
#define GET_TEMPORARY(id) (Address(rbp, (-(int)sizeof(StackFrame))-(sizeof(VALUE)*(id+1))))
// reg[index] (reg must contain a pointer to an array of values)
#define GET_ARRAY_PTR(reg, index) (Address((reg), index * sizeof(VALUE)))
static const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 };
static const uint64_t num_arg_regs = 6;
Codegen::Codegen(ast::FunctionDefinition& def) :
snow::Codegen(def),
m_NumLocals(0),
m_NumStackArguments(0),
m_NumTemporaries(0) {
m_LocalMap = new LocalMap;
m_Asm = new x86_64::Assembler;
m_Return = new Label;
}
uint64_t Codegen::reserve_temporary() {
if (m_FreeTemporaries.size() > 0) {
uint64_t t = m_FreeTemporaries.back();
m_FreeTemporaries.pop_back();
return t;
}
return m_NumTemporaries++;
}
void Codegen::free_temporary(uint64_t id) {
m_FreeTemporaries.push_back(id);
}
void Codegen::get_local(uint64_t id, const Register& reg) {
ASSERT(!m_InGlobalScope);
__ mov(GET_STACK(locals), reg);
__ mov(GET_ARRAY_PTR(reg, id), reg);
}
void Codegen::set_local(const Register& reg, uint64_t id, const Register& tmp) {
ASSERT(reg != tmp && "Cannot use source register as temporary storage!");
ASSERT(!m_InGlobalScope);
__ mov(GET_STACK(locals), tmp);
__ mov(reg, GET_ARRAY_PTR(tmp, id));
}
Handle<CompiledCode> Codegen::compile(bool in_global_scope) {
m_InGlobalScope = in_global_scope;
RefPtr<x86_64::Assembler> entry_asm = new x86_64::Assembler;
__ subasm(entry_asm);
if (m_Def.arguments.size() > 0) {
__ comment("copy arguments to locals");
__ mov(GET_STACK(arguments), r8);
__ mov(GET_STACK(locals), r9);
size_t i = 0;
for each (iter, m_Def.arguments) {
auto local = m_LocalMap->define_local((*iter)->name);
__ mov(GET_ARRAY_PTR(r8, i), rax);
__ mov(rax, GET_ARRAY_PTR(r9, local));
++i;
}
}
__ comment("function body");
compile(*m_Def.sequence);
uint64_t return_temporary = reserve_temporary();
__ comment("function exit");
__ bind(m_Return);
__ mov(rax, GET_TEMPORARY(return_temporary));
if (m_InGlobalScope) {
// Preserve objects in global scope for GC
__ call("snow_leave_global_subscope");
} else {
__ call("snow_leave_scope");
}
__ mov(GET_TEMPORARY(return_temporary), rax);
__ leave();
__ ret();
// Compile the function entry, now that we know all the locals and
// temporaries.
{
e__ comment("function entry");
int stack_size = sizeof(StackFrame) + sizeof(VALUE)*(m_NumTemporaries + m_NumStackArguments);
// maintain 16-byte stack alignment
stack_size += stack_size % 16;
e__ enter(stack_size);
e__ mov(rbp, rsi);
e__ sub(sizeof(StackFrame), rsi);
e__ mov(rsi, rax);
e__ sub((m_NumTemporaries+m_NumStackArguments)*sizeof(VALUE), rax);
e__ mov(rax, GET_STACK(temporaries));
e__ mov(m_NumTemporaries+m_NumStackArguments, rax);
e__ mov(rax, GET_STACK(num_temporaries));
e__ call("snow_enter_scope");
e__ mov(nil(), rax);
}
Handle<CompiledCode> code = __ compile();
code->set_local_map(m_LocalMap);
for each (iter, m_Related) {
code->add_related(*iter);
}
return code;
}
void Codegen::compile(ast::Literal& literal) {
__ comment(std::string("literal: `") + literal.string + std::string("'"));
using ast::Literal;
const char* str = literal.string.c_str();
VALUE val = nil();
switch (literal.type) {
case Literal::INTEGER_DEC_TYPE:
val = value(strtoll(str, NULL, 10));
break;
case Literal::INTEGER_HEX_TYPE:
val = value(strtoll(str, NULL, 16));
break;
case Literal::INTEGER_BIN_TYPE:
val = value(strtoll(str, NULL, 2));
break;
case Literal::FLOAT_TYPE:
// TODO: Doubles
val = value(strtof(str, NULL));
break;
case Literal::STRING_TYPE:
val = new(kMalloc) String(str);
break;
case Literal::TRUE_TYPE:
val = value(true);
break;
case Literal::FALSE_TYPE:
val = value(false);
break;
case Literal::NIL_TYPE:
val = nil();
break;
case Literal::SYMBOL_TYPE:
val = symbol(str);
break;
}
__ mov(val, rax);
}
void Codegen::compile(ast::Identifier& id) {
__ comment(std::string("identifier: `") + value_to_string(id.name) + std::string("'"));
if (!m_InGlobalScope && m_LocalMap->has_local(id.name)) {
// It's a local from current scope...
get_local(m_LocalMap->local(id.name), rax);
} else {
// THE PAIN! It's from a parent scope...
__ mov(rbp, rdi);
__ sub(sizeof(StackFrame), rdi);
__ mov(id.name, rsi);
__ mov(id.quiet, rdx);
__ call("snow_get_local");
}
}
void Codegen::compile(ast::Sequence& seq) {
for each (iter, seq.nodes) {
(*iter)->compile(*this);
}
}
void Codegen::compile(ast::FunctionDefinition& def) {
__ comment("function definition");
RefPtr<Codegen> codegen = new Codegen(def);
Handle<CompiledCode> code = codegen->compile();
m_Related.push_back(code);
VALUE func = new(kMalloc) Function(*code);
__ mov(func, rdi);
__ mov(GET_STACK(scope), rsi);
__ call("snow_set_parent_scope");
__ mov(func, rax);
}
void Codegen::compile(ast::Return& ret) {
__ comment("return");
if (ret.expression)
ret.expression->compile(*this);
else
__ clear(rax);
__ jmp(m_Return);
}
void Codegen::compile(ast::Assignment& assign) {
assign.expression->compile(*this);
__ comment(std::string("assignment: ") + value_to_string(assign.identifier->name));
if (!m_InGlobalScope) {
uint64_t l;
if (m_LocalMap->has_local(assign.identifier->name))
l = m_LocalMap->local(assign.identifier->name);
else
l = m_LocalMap->define_local(assign.identifier->name);
set_local(rax, l);
} else {
__ mov(rbp, rdi);
__ sub(sizeof(StackFrame), rdi);
__ mov(assign.identifier->name, rsi);
__ mov(rax, rdx);
__ call("snow_set_local");
}
}
void Codegen::compile(ast::IfCondition& cond) {
RefPtr<Label> test_cond = new Label;
RefPtr<Label> after = new Label;
__ bind(test_cond);
__ comment("if cond");
cond.expression->compile(*this);
__ mov(rax, rdi);
__ call("snow_eval_truth");
__ cmp(cond.unless, rax);
__ j(CC_EQUAL, after);
__ comment("if body");
cond.if_true->compile(*this);
__ bind(after);
}
void Codegen::compile(ast::IfElseCondition& cond) {
RefPtr<Label> test_cond = new Label;
RefPtr<Label> if_true = new Label;
RefPtr<Label> if_false = new Label;
RefPtr<Label> after = new Label;
__ bind(test_cond);
__ comment("if-else cond");
cond.expression->compile(*this);
__ mov(rax, rdi);
__ call("snow_eval_truth");
__ cmp(cond.unless, rax);
__ j(CC_EQUAL, if_false);
__ bind(if_true);
__ comment("if true");
cond.if_true->compile(*this);
__ jmp(after);
__ bind(if_false);
__ comment("if false");
cond.if_false->compile(*this);
__ bind(after);
}
void Codegen::compile(ast::Call& call) {
auto self_tmp = reserve_temporary();
__ comment("self for call");
call.self->compile(*this);
__ mov(rax, GET_TEMPORARY(self_tmp));
// evaluate arguments and store temporaries
auto num_args = call.arguments->length();
uint64_t args_tmp[num_args];
size_t i = 0;
for each (arg_iter, call.arguments->nodes) {
args_tmp[i] = reserve_temporary();
__ comment(string_printf("argument %d", i));
(*arg_iter)->compile(*this);
__ mov(rax, GET_TEMPORARY(args_tmp[i]));
++i;
}
auto function_tmp = self_tmp;
if (call.member) {
__ comment("method call");
function_tmp = reserve_temporary();
__ mov(GET_TEMPORARY(self_tmp), rdi);
__ mov(call.member->name, rsi);
__ call("snow_get");
__ mov(rax, GET_TEMPORARY(function_tmp));
__ mov(GET_TEMPORARY(self_tmp), rdi);
} else {
__ comment("closure call");
__ clear(rdi); // "self" is NULL for closures
}
__ mov(GET_TEMPORARY(function_tmp), rsi);
__ mov(num_args, rdx);
bool rsp_in_rbx = false;
for (size_t i = 0; i < num_args; ++i) {
const size_t arg_offset = i + 3;
if (arg_offset < num_arg_regs) {
__ mov(GET_TEMPORARY(args_tmp[i]), *arg_regs[arg_offset]);
} else {
const size_t stack_offset = arg_offset - num_arg_regs;
if (m_NumStackArguments < stack_offset)
m_NumStackArguments = stack_offset;
__ mov(GET_TEMPORARY(args_tmp[i]), rax);
if (!rsp_in_rbx) {
__ mov(rsp, rbx);
rsp_in_rbx = true;
}
__ mov(rax, Address(rbx, stack_offset*sizeof(VALUE)));
}
free_temporary(args_tmp[i]);
}
if (self_tmp == function_tmp)
free_temporary(self_tmp);
else {
free_temporary(self_tmp);
free_temporary(function_tmp);
}
// finally!
__ clear(rax);
__ call("snow_call");
}
void Codegen::compile(ast::Get& get) {
__ comment(std::string("get `") + value_to_string(get.member->name) + "'");
get.self->compile(*this);
__ mov(rax, rdi);
__ mov(get.member->name, rsi);
__ call("snow_get");
}
void Codegen::compile(ast::Set& set) {
__ comment(std::string("set `") + value_to_string(set.member->name) + "'");
set.expression->compile(*this);
auto tmp = reserve_temporary();
__ mov(rax, GET_TEMPORARY(tmp));
set.self->compile(*this);
__ mov(rax, rdi);
__ mov(set.member->name, rsi);
__ mov(GET_TEMPORARY(tmp), rdx);
__ call("snow_set");
free_temporary(tmp);
}
void Codegen::compile(ast::Loop& loop) {
RefPtr<Label> test_cond = new Label;
RefPtr<Label> body = new Label;
RefPtr<Label> after = new Label;
__ bind(test_cond);
__ comment("loop cond");
loop.expression->compile(*this);
__ mov(rax, rdi);
__ call("snow_eval_truth");
__ cmp(0, rax);
__ j(CC_EQUAL, after);
__ bind(body);
__ comment("loop body");
loop.while_true->compile(*this);
__ jmp(test_cond);
__ bind(after);
}
void Codegen::compile(ast::Self&) {
__ mov(GET_STACK(self), rax);
}
void Codegen::compile(ast::It&) {
__ mov(GET_STACK(it), rax);
}
}
}
<|endoftext|>
|
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/gl/gl_context.h"
#include <gflags/gflags.h>
#include <mutex>
#include <string>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/profiling.h"
#include "xenia/ui/gl/gl_immediate_drawer.h"
#include "xenia/ui/window.h"
DEFINE_bool(thread_safe_gl, false,
"Only allow one GL context to be active at a time.");
DEFINE_bool(disable_gl_context_reset, false,
"Do not aggressively reset the GL context (helps with capture "
"programs such as OBS or FRAPS).");
DEFINE_bool(random_clear_color, false, "Randomizes GL clear color.");
DEFINE_bool(gl_debug, false, "Enable OpenGL debug validation layer.");
DEFINE_bool(gl_debug_output, false, "Dump ARB_debug_output to stderr.");
DEFINE_bool(gl_debug_output_synchronous, true,
"ARB_debug_output will synchronize to be thread safe.");
namespace xe {
namespace ui {
namespace gl {
std::recursive_mutex GLContext::global_gl_mutex_;
void GLContext::FatalGLError(std::string error) {
xe::FatalError(
error +
"\nEnsure you have the latest drivers for your GPU and that it supports "
"OpenGL 4.5. See http://xenia.jp/faq/ for more information and a list"
"of supported GPUs.");
}
GLContext::GLContext(GraphicsProvider* provider, Window* target_window)
: GraphicsContext(provider, target_window) {}
GLContext::~GLContext() {}
void GLContext::AssertExtensionsPresent() {
if (!MakeCurrent()) {
FatalGLError("Unable to make GL context current.");
return;
}
// Check shader version at least 4.5 (matching GL 4.5).
auto glsl_version_raw =
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
std::string glsl_version(glsl_version_raw);
if (glsl_version.find("4.50") != 0) {
FatalGLError("OpenGL GLSL version 4.50 is required.");
return;
}
if (!GLEW_ARB_bindless_texture || !glMakeTextureHandleResidentARB) {
FatalGLError("OpenGL extension ARB_bindless_texture is required.");
return;
}
if (!GLEW_ARB_fragment_coord_conventions) {
FatalGLError(
"OpenGL extension ARB_fragment_coord_conventions is required.");
return;
}
ClearCurrent();
}
void GLContext::DebugMessage(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message) {
const char* source_name = nullptr;
switch (source) {
case GL_DEBUG_SOURCE_API_ARB:
source_name = "OpenGL";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
source_name = "Windows";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
source_name = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
source_name = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
source_name = "Application";
break;
case GL_DEBUG_SOURCE_OTHER_ARB:
source_name = "Other";
break;
default:
source_name = "(unknown source)";
break;
}
const char* type_name = nullptr;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
type_name = "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
type_name = "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
type_name = "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
type_name = "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
type_name = "performance";
break;
case GL_DEBUG_TYPE_OTHER:
type_name = "message";
break;
case GL_DEBUG_TYPE_MARKER:
type_name = "marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
type_name = "push group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
type_name = "pop group";
break;
default:
type_name = "(unknown type)";
break;
}
const char* severity_name = nullptr;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
severity_name = "high";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
severity_name = "medium";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
severity_name = "low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
severity_name = "notification";
break;
default:
severity_name = "(unknown severity)";
break;
}
XELOGE("GL4 %s: %s(%s) %d: %s", source_name, type_name, severity_name, id,
message);
}
void GLAPIENTRY GLContext::DebugMessageThunk(GLenum source, GLenum type,
GLuint id, GLenum severity,
GLsizei length,
const GLchar* message,
GLvoid* user_param) {
reinterpret_cast<GLContext*>(user_param)
->DebugMessage(source, type, id, severity, length, message);
}
void GLContext::SetupDebugging() {
if (!FLAGS_gl_debug || !FLAGS_gl_debug_output) {
return;
}
glEnable(GL_DEBUG_OUTPUT);
// Synchronous output hurts, but is required if we want to line up the logs.
if (FLAGS_gl_debug_output_synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
// Enable everything by default.
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
GL_TRUE);
// Disable annoying messages.
GLuint disable_message_ids[] = {
0x00020004, // Usage warning: Generic vertex attribute array 0 uses a
// pointer with a small value (0x0000000000000000). Is this
// intended to be used as an offset into a buffer object?
};
glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE,
GLsizei(xe::countof(disable_message_ids)),
disable_message_ids, GL_FALSE);
// Callback will be made from driver threads.
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(&DebugMessageThunk),
this);
}
ImmediateDrawer* GLContext::immediate_drawer() {
return immediate_drawer_.get();
}
bool GLContext::WasLost() {
if (!robust_access_supported_) {
// Can't determine if we lost the context.
return false;
}
if (context_lost_) {
return true;
}
auto status = glGetGraphicsResetStatusARB();
if (status != GL_NO_ERROR) {
// Graphics card reset.
XELOGE("============= TDR detected on context %p! Context %s =============",
handle(), status == GL_GUILTY_CONTEXT_RESET ? "guilty" : "innocent");
context_lost_ = true;
return true;
}
return false;
}
std::unique_ptr<RawImage> GLContext::Capture() {
GraphicsContextLock lock(this);
std::unique_ptr<RawImage> raw_image(new RawImage());
raw_image->width = target_window_->width();
raw_image->stride = raw_image->width * 4;
raw_image->height = target_window_->height();
raw_image->data.resize(raw_image->stride * raw_image->height);
glReadPixels(0, 0, target_window_->width(), target_window_->height(), GL_RGBA,
GL_UNSIGNED_BYTE, raw_image->data.data());
// Flip vertically in-place.
size_t yt = 0;
size_t yb = (raw_image->height - 1) * raw_image->stride;
while (yt < yb) {
for (size_t i = 0; i < raw_image->stride; ++i) {
std::swap(raw_image->data[yt + i], raw_image->data[yb + i]);
}
yt += raw_image->stride;
yb -= raw_image->stride;
}
return raw_image;
}
} // namespace gl
} // namespace ui
} // namespace xe
<commit_msg>Detect OpenGL 4.60 (#816)<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/gl/gl_context.h"
#include <gflags/gflags.h>
#include <mutex>
#include <string>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/profiling.h"
#include "xenia/ui/gl/gl_immediate_drawer.h"
#include "xenia/ui/window.h"
DEFINE_bool(thread_safe_gl, false,
"Only allow one GL context to be active at a time.");
DEFINE_bool(disable_gl_context_reset, false,
"Do not aggressively reset the GL context (helps with capture "
"programs such as OBS or FRAPS).");
DEFINE_bool(random_clear_color, false, "Randomizes GL clear color.");
DEFINE_bool(gl_debug, false, "Enable OpenGL debug validation layer.");
DEFINE_bool(gl_debug_output, false, "Dump ARB_debug_output to stderr.");
DEFINE_bool(gl_debug_output_synchronous, true,
"ARB_debug_output will synchronize to be thread safe.");
namespace xe {
namespace ui {
namespace gl {
std::recursive_mutex GLContext::global_gl_mutex_;
void GLContext::FatalGLError(std::string error) {
xe::FatalError(
error +
"\nEnsure you have the latest drivers for your GPU and that it supports "
"OpenGL 4.5. See http://xenia.jp/faq/ for more information and a list"
"of supported GPUs.");
}
GLContext::GLContext(GraphicsProvider* provider, Window* target_window)
: GraphicsContext(provider, target_window) {}
GLContext::~GLContext() {}
void GLContext::AssertExtensionsPresent() {
if (!MakeCurrent()) {
FatalGLError("Unable to make GL context current.");
return;
}
// Check shader version at least 4.5 (matching GL 4.5).
auto glsl_version_raw =
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
std::string glsl_version(glsl_version_raw);
if (glsl_version.find("4.5") == std::string::npos && glsl_version.find("4.6") == std::string::npos) {
FatalGLError("OpenGL GLSL version 4.50 or higher is required.");
return;
}
if (!GLEW_ARB_bindless_texture || !glMakeTextureHandleResidentARB) {
FatalGLError("OpenGL extension ARB_bindless_texture is required.");
return;
}
if (!GLEW_ARB_fragment_coord_conventions) {
FatalGLError(
"OpenGL extension ARB_fragment_coord_conventions is required.");
return;
}
ClearCurrent();
}
void GLContext::DebugMessage(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message) {
const char* source_name = nullptr;
switch (source) {
case GL_DEBUG_SOURCE_API_ARB:
source_name = "OpenGL";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
source_name = "Windows";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
source_name = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
source_name = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
source_name = "Application";
break;
case GL_DEBUG_SOURCE_OTHER_ARB:
source_name = "Other";
break;
default:
source_name = "(unknown source)";
break;
}
const char* type_name = nullptr;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
type_name = "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
type_name = "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
type_name = "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
type_name = "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
type_name = "performance";
break;
case GL_DEBUG_TYPE_OTHER:
type_name = "message";
break;
case GL_DEBUG_TYPE_MARKER:
type_name = "marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
type_name = "push group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
type_name = "pop group";
break;
default:
type_name = "(unknown type)";
break;
}
const char* severity_name = nullptr;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
severity_name = "high";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
severity_name = "medium";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
severity_name = "low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
severity_name = "notification";
break;
default:
severity_name = "(unknown severity)";
break;
}
XELOGE("GL4 %s: %s(%s) %d: %s", source_name, type_name, severity_name, id,
message);
}
void GLAPIENTRY GLContext::DebugMessageThunk(GLenum source, GLenum type,
GLuint id, GLenum severity,
GLsizei length,
const GLchar* message,
GLvoid* user_param) {
reinterpret_cast<GLContext*>(user_param)
->DebugMessage(source, type, id, severity, length, message);
}
void GLContext::SetupDebugging() {
if (!FLAGS_gl_debug || !FLAGS_gl_debug_output) {
return;
}
glEnable(GL_DEBUG_OUTPUT);
// Synchronous output hurts, but is required if we want to line up the logs.
if (FLAGS_gl_debug_output_synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
// Enable everything by default.
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
GL_TRUE);
// Disable annoying messages.
GLuint disable_message_ids[] = {
0x00020004, // Usage warning: Generic vertex attribute array 0 uses a
// pointer with a small value (0x0000000000000000). Is this
// intended to be used as an offset into a buffer object?
};
glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE,
GLsizei(xe::countof(disable_message_ids)),
disable_message_ids, GL_FALSE);
// Callback will be made from driver threads.
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(&DebugMessageThunk),
this);
}
ImmediateDrawer* GLContext::immediate_drawer() {
return immediate_drawer_.get();
}
bool GLContext::WasLost() {
if (!robust_access_supported_) {
// Can't determine if we lost the context.
return false;
}
if (context_lost_) {
return true;
}
auto status = glGetGraphicsResetStatusARB();
if (status != GL_NO_ERROR) {
// Graphics card reset.
XELOGE("============= TDR detected on context %p! Context %s =============",
handle(), status == GL_GUILTY_CONTEXT_RESET ? "guilty" : "innocent");
context_lost_ = true;
return true;
}
return false;
}
std::unique_ptr<RawImage> GLContext::Capture() {
GraphicsContextLock lock(this);
std::unique_ptr<RawImage> raw_image(new RawImage());
raw_image->width = target_window_->width();
raw_image->stride = raw_image->width * 4;
raw_image->height = target_window_->height();
raw_image->data.resize(raw_image->stride * raw_image->height);
glReadPixels(0, 0, target_window_->width(), target_window_->height(), GL_RGBA,
GL_UNSIGNED_BYTE, raw_image->data.data());
// Flip vertically in-place.
size_t yt = 0;
size_t yb = (raw_image->height - 1) * raw_image->stride;
while (yt < yb) {
for (size_t i = 0; i < raw_image->stride; ++i) {
std::swap(raw_image->data[yt + i], raw_image->data[yb + i]);
}
yt += raw_image->stride;
yb -= raw_image->stride;
}
return raw_image;
}
} // namespace gl
} // namespace ui
} // namespace xe
<|endoftext|>
|
<commit_before>/*********************************************
* Author: Jun Jiang - jiangjun4@sina.com
* Created: 2017-06-01 11:22
* Last modified: 2017-06-01 11:22
* Filename: TestRNN.cpp
* Description:
**********************************************/
#include "utils/RNNHelper.h"
#include "rnn/RNN.h"
int main(int argc, char** argv){
std::map<std::string, size_t> map;
abcdl::utils::RNNHelper helper(8000);
helper.read_word2index("data/word_to_index", map);
std::vector<abcdl::algebra::Mat*> data_seq_data;
std::vector<abcdl::algebra::Mat*> data_seq_label;
helper.read_seqdata("data/train_seq_data", &data_seq_data, "data/train_seq_label", &data_seq_label, 1000);
printf("Start training....\n");
abcdl::rnn::RNN rnn(8000, 100);
rnn.train(data_seq_data, data_seq_label);
for(auto&& d : data_seq_data){
delete d;
}
data_seq_data.clear();
for(auto&& d : data_seq_label){
delete d;
}
data_seq_label.clear();
}
<commit_msg>initialize<commit_after>/*********************************************
* Author: Jun Jiang - jiangjun4@sina.com
* Created: 2017-06-01 11:22
* Last modified: 2017-06-01 11:22
* Filename: TestRNN.cpp
* Description:
**********************************************/
#include "utils/RNNHelper.h"
#include "rnn/RNN.h"
int main(int argc, char** argv){
std::map<std::string, size_t> map;
abcdl::utils::RNNHelper helper(8000);
helper.read_word2index("data/rnn/word_to_index", map);
std::vector<abcdl::algebra::Mat*> data_seq_data;
std::vector<abcdl::algebra::Mat*> data_seq_label;
helper.read_seqdata("data/rnn/train_seq_data", &data_seq_data, "data/rnn/train_seq_label", &data_seq_label, 1000);
printf("Start training....\n");
abcdl::rnn::RNN rnn(8000, 100);
rnn.train(data_seq_data, data_seq_label);
for(auto&& d : data_seq_data){
delete d;
}
data_seq_data.clear();
for(auto&& d : data_seq_label){
delete d;
}
data_seq_label.clear();
}
<|endoftext|>
|
<commit_before>#include <chrono>
#include <vector>
#include <initializer_list>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cassert>
class bitvector {
const size_t n;
uint64_t* array;
public:
bitvector(size_t n_) : n(n_) {
assert(n > 0);
array = new uint64_t[n];
}
~bitvector() {
delete[] array;
}
void fill(uint64_t word) {
for (size_t i=0; i < n; i++)
array[i] = word;
}
void fill_random(int threshold) {
assert(threshold >= 0);
assert(threshold <= 100);
srand(0);
for (size_t i=0; i < n; i++) {
if ((rand() % 100) > threshold) {
array[i] = -1;
} else {
array[i] = 0;
}
}
}
size_t size() const {
return n * 64;
}
size_t cardinality() const {
size_t k = 0;
for (size_t i=0; i < n; i++) {
k += __builtin_popcountll(array[i]);
}
return k;
}
public:
template <typename CALLBACK>
void iterate_naive(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
if (tmp & 0x1) {
callback(k);
}
tmp >>= 1;
k += 1;
}
}
}
template <typename CALLBACK>
void iterate_better(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
const uint64_t t = tmp & (~tmp + 1);
const uint64_t r = __builtin_ctzll(t);
callback(k + r);
tmp ^= t;
}
}
}
template <typename CALLBACK>
void iterate_block3(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
switch (tmp & 0x7) {
case 0:
break;
case 1:
callback(k);
break;
case 2:
callback(k + 1);
break;
case 3:
callback(k);
callback(k + 1);
break;
case 4:
callback(k + 2);
break;
case 5:
callback(k);
callback(k + 2);
break;
case 6:
callback(k + 1);
callback(k + 2);
break;
case 7:
callback(k);
callback(k + 1);
callback(k + 2);
break;
}
tmp >>= 3;
k += 3;
}
}
}
template <typename CALLBACK>
void iterate_block4(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
switch (tmp & 0xf) {
case 0:
break;
case 1:
callback(k);
break;
case 2:
callback(k + 1);
break;
case 3:
callback(k);
callback(k + 1);
break;
case 4:
callback(k + 2);
break;
case 5:
callback(k);
callback(k + 2);
break;
case 6:
callback(k + 1);
callback(k + 2);
break;
case 7:
callback(k);
callback(k + 1);
callback(k + 2);
break;
case 8:
callback(k + 3);
break;
case 9:
callback(k);
callback(k + 3);
break;
case 10:
callback(k + 1);
callback(k + 3);
break;
case 11:
callback(k);
callback(k + 1);
callback(k + 3);
break;
case 12:
callback(k + 2);
callback(k + 3);
break;
case 13:
callback(k);
callback(k + 2);
callback(k + 3);
break;
case 14:
callback(k + 1);
callback(k + 2);
callback(k + 3);
break;
case 15:
callback(k);
callback(k + 1);
callback(k + 2);
callback(k + 3);
break;
}
tmp >>= 4;
k += 4;
}
}
}
};
void testcase(const bitvector& bv, int iterations) {
using clock = std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::microseconds;
uint64_t ta;
uint64_t tb;
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
uint64_t n = 0;
auto callback = [&n](size_t i) {
n += i;
};
bv.iterate_naive(callback);
k += n;
}
const auto t2 = clock::now();
ta = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tnaive: %10ld us [%ld]\n", ta, k);
}
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
uint64_t n = 0;
auto callback = [&n](size_t i) {
n += i;
};
bv.iterate_better(callback);
k += n;
}
const auto t2 = clock::now();
tb = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tbetter: %10ld us [%ld]", tb, k);
printf(" (%0.2f)\n", ta/double(tb));
}
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
uint64_t n = 0;
auto callback = [&n](size_t i) {
n += i;
};
bv.iterate_block3(callback);
k += n;
}
const auto t2 = clock::now();
tb = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tblock3: %10ld us [%ld]", tb, k);
printf(" (%0.2f)\n", ta/double(tb));
}
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
uint64_t n = 0;
auto callback = [&n](size_t i) {
n += i;
};
bv.iterate_block4(callback);
k += n;
}
const auto t2 = clock::now();
tb = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tblock4: %10ld us [%ld]", tb, k);
printf(" (%0.2f)\n", ta/double(tb));
}
}
template <typename INITIALIZER>
void test(const char* info, const std::vector<size_t>& sizes, int iterations, INITIALIZER initalizer) {
bool print = true;
for (size_t i: sizes) {
bitvector bv(i);
initalizer(bv);
if (print) {
printf("%s\n", info);
print = false;
}
printf("\tsize=%lu, cardinality=%lu\n", bv.size(), bv.cardinality());
testcase(bv, iterations);
}
}
int main() {
const std::vector<size_t> sizes = {64, 256, 1024, 4096, 8192};
test("empty", sizes, 10000, [](bitvector& bv) {bv.fill(0);});
test("1/4", sizes, 1000, [](bitvector& bv) {bv.fill(0x000000000000ffff);});
test("1/2", sizes, 1000, [](bitvector& bv) {bv.fill(0x00000000ffffffff);});
test("3/4", sizes, 1000, [](bitvector& bv) {bv.fill(0x0000ffffffffffff);});
test("full", sizes, 1000, [](bitvector& bv) {bv.fill(0xffffffffffffffff);});
test("rand", sizes, 1000, [](bitvector& bv) {bv.fill_random(80);});
test("rand2", sizes, 1000, [](bitvector& bv) {bv.fill_random(5);});
return 0;
}
<commit_msg>Refacto, allow to call function inside callback<commit_after>#include <chrono>
#include <vector>
#include <initializer_list>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cassert>
class bitvector {
const size_t n;
uint64_t* array;
public:
bitvector(size_t n_) : n(n_) {
assert(n > 0);
array = new uint64_t[n];
}
~bitvector() {
delete[] array;
}
void fill(uint64_t word) {
for (size_t i=0; i < n; i++)
array[i] = word;
}
void fill_random(int threshold) {
assert(threshold >= 0);
assert(threshold <= 100);
srand(0);
for (size_t i=0; i < n; i++) {
if ((rand() % 100) > threshold) {
array[i] = -1;
} else {
array[i] = 0;
}
}
}
size_t size() const {
return n * 64;
}
size_t cardinality() const {
size_t k = 0;
for (size_t i=0; i < n; i++) {
k += __builtin_popcountll(array[i]);
}
return k;
}
public:
template <typename CALLBACK>
void iterate_naive(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
if (tmp & 0x1) {
callback(k);
}
tmp >>= 1;
k += 1;
}
}
}
template <typename CALLBACK>
void iterate_better(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
const uint64_t t = tmp & (~tmp + 1);
const uint64_t r = __builtin_ctzll(t);
callback(k + r);
tmp ^= t;
}
}
}
template <typename CALLBACK>
void iterate_block3(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
switch (tmp & 0x7) {
case 0:
break;
case 1:
callback(k);
break;
case 2:
callback(k + 1);
break;
case 3:
callback(k);
callback(k + 1);
break;
case 4:
callback(k + 2);
break;
case 5:
callback(k);
callback(k + 2);
break;
case 6:
callback(k + 1);
callback(k + 2);
break;
case 7:
callback(k);
callback(k + 1);
callback(k + 2);
break;
}
tmp >>= 3;
k += 3;
}
}
}
template <typename CALLBACK>
void iterate_block4(CALLBACK callback) const {
for (size_t i=0; i < n; i++) {
uint64_t tmp = array[i];
size_t k = i * 64;
while (tmp) {
switch (tmp & 0xf) {
case 0:
break;
case 1:
callback(k);
break;
case 2:
callback(k + 1);
break;
case 3:
callback(k);
callback(k + 1);
break;
case 4:
callback(k + 2);
break;
case 5:
callback(k);
callback(k + 2);
break;
case 6:
callback(k + 1);
callback(k + 2);
break;
case 7:
callback(k);
callback(k + 1);
callback(k + 2);
break;
case 8:
callback(k + 3);
break;
case 9:
callback(k);
callback(k + 3);
break;
case 10:
callback(k + 1);
callback(k + 3);
break;
case 11:
callback(k);
callback(k + 1);
callback(k + 3);
break;
case 12:
callback(k + 2);
callback(k + 3);
break;
case 13:
callback(k);
callback(k + 2);
callback(k + 3);
break;
case 14:
callback(k + 1);
callback(k + 2);
callback(k + 3);
break;
case 15:
callback(k);
callback(k + 1);
callback(k + 2);
callback(k + 3);
break;
}
tmp >>= 4;
k += 4;
}
}
}
};
#ifdef __GNUC__
# define NOINLINE __attribute__((noline))
#else
# define NOINLINE
#endif
size_t callback_function(size_t index) {
return index;
}
void testcase(const bitvector& bv, int iterations, size_t (*cb_fun)(size_t)) {
using clock = std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::microseconds;
uint64_t ta;
uint64_t tb;
uint64_t n;
auto callback = [&n, cb_fun](size_t i) {
#if 0
n += cb_fun(i);
#else
n += i;
#endif
};
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
n = 0;
bv.iterate_naive(callback);
k += n;
}
const auto t2 = clock::now();
ta = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tnaive: %10ld us [%ld]\n", ta, k);
}
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
n = 0;
bv.iterate_better(callback);
k += n;
}
const auto t2 = clock::now();
tb = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tbetter: %10ld us [%ld]", tb, k);
printf(" (%0.2f)\n", ta/double(tb));
}
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
n = 0;
bv.iterate_block3(callback);
k += n;
}
const auto t2 = clock::now();
tb = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tblock3: %10ld us [%ld]", tb, k);
printf(" (%0.2f)\n", ta/double(tb));
}
{
int tmp = iterations;
volatile uint64_t k = 0;
const auto t1 = clock::now();
while (tmp--) {
n = 0;
bv.iterate_block4(callback);
k += n;
}
const auto t2 = clock::now();
tb = duration_cast<microseconds>(t2 - t1).count();
printf("\t\tblock4: %10ld us [%ld]", tb, k);
printf(" (%0.2f)\n", ta/double(tb));
}
}
template <typename INITIALIZER>
void test(const char* info, const std::vector<size_t>& sizes, int iterations, INITIALIZER initalizer) {
bool print = true;
for (size_t i: sizes) {
bitvector bv(i);
initalizer(bv);
if (print) {
printf("%s\n", info);
print = false;
}
printf("\tsize=%lu, cardinality=%lu\n", bv.size(), bv.cardinality());
testcase(bv, iterations, callback_function);
}
}
int main() {
const std::vector<size_t> sizes = {64, 256, 1024, 4096, 8192};
test("empty", sizes, 10000, [](bitvector& bv) {bv.fill(0);});
test("1/4", sizes, 1000, [](bitvector& bv) {bv.fill(0x000000000000ffff);});
test("1/2", sizes, 1000, [](bitvector& bv) {bv.fill(0x00000000ffffffff);});
test("3/4", sizes, 1000, [](bitvector& bv) {bv.fill(0x0000ffffffffffff);});
test("full", sizes, 1000, [](bitvector& bv) {bv.fill(0xffffffffffffffff);});
test("rand", sizes, 1000, [](bitvector& bv) {bv.fill_random(80);});
test("rand2", sizes, 1000, [](bitvector& bv) {bv.fill_random(5);});
return 0;
}
<|endoftext|>
|
<commit_before>#include <random>
#include <chrono>
#include <vendor/gmock/gmock.h>
#include <core/rendering/vertex/StaticIndexData.h>
#include <core/rendering/vertex/DynamicIndexData.h>
#include "mock/MockGpuBuffer.h"
#include "mock/MockVertexData.h"
#include "mock/MockGpuBufferFactory.h"
using ::testing::Return;
using ::testing::_;
namespace glove {
TEST(StaticIndexDataTest, ConstructorStoresGpuBufferAndNumverOfIndices) {
std::default_random_engine generator(
static_cast<ulong>(std::chrono::system_clock::now().time_since_epoch().count()));
std::uniform_int_distribution<int> distribution(0, 1000);
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
std::size_t numIndices = static_cast<std::size_t>(distribution(generator));
StaticIndexData indexData(gpuBuffer, numIndices);
EXPECT_EQ(gpuBuffer, indexData.GetGpuBuffer());
EXPECT_EQ(numIndices, indexData.GetIndexCount());
}
TEST(StaticIndexDataTest, BindBufferBindsUnderlyingGpuBuffer) {
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), Bind()).Times(1);
StaticIndexData indexData(gpuBuffer, 10);
indexData.BindBuffer();
}
TEST(DynamicIndexDataTest, ConstructorCreatesGpuBufferAndEmptyIndexList) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
EXPECT_EQ(gpuBuffer, indexData.GetGpuBuffer());
EXPECT_TRUE(indexData.GetIndices().empty());
EXPECT_EQ(0, indexData.GetIndexCount());
}
TEST(DynamicIndexDataTest, BindBufferBindsUnderlyingGpuBuffer) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), Bind()).Times(1);
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
indexData.BindBuffer();
}
TEST(DynamicIndexDataTest, FlushWritesToUnderlyingGpuBuffer) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), WriteData(0, _)).Times(1);
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
indexData.FlushBuffer();
}
TEST(DynamicIndexDataTest, GetIndexCountReturnsSizeOfBackingIndexListr) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
EXPECT_EQ(0, indexData.GetIndexCount());
indexData.GetIndices().push_back(5);
EXPECT_EQ(1, indexData.GetIndexCount());
indexData.GetIndices().push_back(2);
EXPECT_EQ(2, indexData.GetIndexCount());
}
TEST(DynamicIndexDataTest, CanSetIndexList) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
DynamicIndexData<unsigned int>::IndexList indices;
indices.push_back(1);
indices.push_back(2);
indices.push_back(3);
indexData.SetIndices(indices);
EXPECT_EQ(3, indexData.GetIndexCount());
EXPECT_EQ(indices, indexData.GetIndices());
}
}<commit_msg>Updated render interface tests to also check if DynamicIndexData::Flush calls the buffer's WriteData with proper size argument<commit_after>#include <random>
#include <chrono>
#include <vendor/gmock/gmock.h>
#include <core/rendering/vertex/StaticIndexData.h>
#include <core/rendering/vertex/DynamicIndexData.h>
#include "mock/MockGpuBuffer.h"
#include "mock/MockVertexData.h"
#include "mock/MockGpuBufferFactory.h"
using ::testing::Return;
using ::testing::_;
namespace glove {
TEST(StaticIndexDataTest, ConstructorStoresGpuBufferAndNumverOfIndices) {
std::default_random_engine generator(
static_cast<ulong>(std::chrono::system_clock::now().time_since_epoch().count()));
std::uniform_int_distribution<int> distribution(0, 1000);
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
std::size_t numIndices = static_cast<std::size_t>(distribution(generator));
StaticIndexData indexData(gpuBuffer, numIndices);
EXPECT_EQ(gpuBuffer, indexData.GetGpuBuffer());
EXPECT_EQ(numIndices, indexData.GetIndexCount());
}
TEST(StaticIndexDataTest, BindBufferBindsUnderlyingGpuBuffer) {
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), Bind()).Times(1);
StaticIndexData indexData(gpuBuffer, 10);
indexData.BindBuffer();
}
TEST(DynamicIndexDataTest, ConstructorCreatesGpuBufferAndEmptyIndexList) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
EXPECT_EQ(gpuBuffer, indexData.GetGpuBuffer());
EXPECT_TRUE(indexData.GetIndices().empty());
EXPECT_EQ(0, indexData.GetIndexCount());
}
TEST(DynamicIndexDataTest, BindBufferBindsUnderlyingGpuBuffer) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), Bind()).Times(1);
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
indexData.BindBuffer();
}
TEST(DynamicIndexDataTest, FlushCallsWriteDataOfUnderlyingBuffer) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), WriteData(0, _)).Times(1);
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
indexData.FlushBuffer();
}
TEST(DynamicIndexDataTest, FlushWritesDataToUnderlyingBuffer) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int>::IndexList indices;
indices.push_back(1);
indices.push_back(2);
indices.push_back(3);
EXPECT_CALL(*(MockGpuBuffer*)gpuBuffer.get(), WriteData(indices.size() * sizeof(unsigned int), _)).Times(1);
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
indexData.SetIndices(indices);
indexData.FlushBuffer();
}
TEST(DynamicIndexDataTest, GetIndexCountReturnsSizeOfBackingIndexListr) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
EXPECT_EQ(0, indexData.GetIndexCount());
indexData.GetIndices().push_back(5);
EXPECT_EQ(1, indexData.GetIndexCount());
indexData.GetIndices().push_back(2);
EXPECT_EQ(2, indexData.GetIndexCount());
}
TEST(DynamicIndexDataTest, CanSetIndexList) {
IGpuBufferFactoryPtr gpuBufferFactory(new MockGpuBufferFactory());
IGpuBufferPtr gpuBuffer(new MockGpuBuffer());
EXPECT_CALL(*(MockGpuBufferFactory*)gpuBufferFactory.get(), CreateIndexBuffer()).Times(1).WillOnce(Return(gpuBuffer));
DynamicIndexData<unsigned int> indexData(gpuBufferFactory);
DynamicIndexData<unsigned int>::IndexList indices;
indices.push_back(1);
indices.push_back(2);
indices.push_back(3);
indexData.SetIndices(indices);
EXPECT_EQ(3, indexData.GetIndexCount());
EXPECT_EQ(indices, indexData.GetIndices());
}
}<|endoftext|>
|
<commit_before>#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
#include <assert.h>
#include "itkCenteredSimilarity2DTransform.h"
// my files
#include "Stack.hpp"
#include "NormalizeImages.hpp"
#include "StackInitializers.hpp"
#include "RegistrationBuilder.hpp"
#include "StackAligner.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "StackTransforms.hpp"
#include "OptimizerConfig.hpp"
#include "Profiling.hpp"
namespace po = boost::program_options;
using namespace boost::filesystem;
po::variables_map parse_arguments(int argc, char *argv[]);
int main(int argc, char *argv[]) {
// Parse command line arguments
po::variables_map vm = parse_arguments(argc, argv);
// Process command line arguments
Dirs::SetDataSet( vm["dataSet"].as<string>() );
Dirs::SetOutputDirName( vm["outputDir"].as<string>() );
string blockDir = vm.count("blockDir") ? vm["blockDir"].as<string>() + "/" : Dirs::BlockDir();
string sliceDir = vm.count("sliceDir") ? vm["sliceDir"].as<string>() + "/" : Dirs::SliceDir();
const bool writeImages = vm["writeImages"].as<bool>();
vector< string > LoResFileNames, HiResFileNames;
if( vm.count("slice") )
{
LoResFileNames.push_back(blockDir + vm["slice"].as<string>());
HiResFileNames.push_back(sliceDir + vm["slice"].as<string>());
}
else
{
LoResFileNames = getFilePaths(blockDir, Dirs::SliceFile());
HiResFileNames = getFilePaths(sliceDir, Dirs::SliceFile());
}
// initialise stack objects with correct spacings, sizes etc
typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFileNames);
StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFileNames);
normalizeImages< StackType >(LoResImages);
normalizeImages< StackType >(HiResImages);
boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages);
boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages);
// Assert stacks have the same number of slices
assert(LoResStack->GetSize() == HiResStack->GetSize());
// initialize stacks' transforms so that 2D images line up at their centres.
if( vm.count("blockDir") )
// if working with segmentations already in the right coordinate system,
// no need to apply transforms
StackTransforms::InitializeToIdentity(*LoResStack);
else
{
// if working from the original images, apply the necessary translation
StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") );
ApplyAdjustments( *LoResStack, LoResFileNames, Dirs::ConfigDir() + "LoRes_adjustments/");
}
StackTransforms::InitializeToCommonCentre( *HiResStack );
StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack );
// create output dir before write operations
create_directory( Dirs::ResultsDir() );
// Generate fixed images to register against
LoResStack->updateVolumes();
if( writeImages )
{
writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + "LoResStack.mha" );
}
// initialise registration framework
typedef RegistrationBuilder< StackType > RegistrationBuilderType;
RegistrationBuilderType registrationBuilder;
RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();
StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration);
// Scale parameter space
OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() );
// Add time and memory probes
itkProbesCreate();
// perform centered rigid 2D registration on each pair of slices
itkProbesStart( "Aligning stacks" );
stackAligner.Update();
itkProbesStop( "Aligning stacks" );
// Report the time and memory taken by the registration
itkProbesReport( std::cout );
// write rigid transforms
if( writeImages )
{
HiResStack->updateVolumes();
writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResRigidStack.mha" );
// writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResRigidMask.mha" );
}
StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack);
// Scale parameter space
OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() );
// perform similarity rigid 2D registration
stackAligner.Update();
// write similarity transforms
if( writeImages )
{
HiResStack->updateVolumes();
writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResSimilarityStack.mha" );
}
// repeat registration with affine transform
StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack);
OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );
stackAligner.Update();
if( writeImages )
{
HiResStack->updateVolumes();
writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResAffineStack.mha" );
// writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResAffineMask.mha" );
}
// Update LoRes as the masks might have shrunk
LoResStack->updateVolumes();
// persist mask numberOfTimesTooBig
vector< string > fileNames = getFileNames(Dirs::SliceFile());
saveVectorToFiles(HiResStack->GetNumberOfTimesTooBig(), "number_of_times_too_big", fileNames );
// persist final metric values
saveVectorToFiles(stackAligner.GetFinalMetricValues(), "metric_values", fileNames );
// write transforms to directories labeled by both ds ratios
create_directory(Dirs::LoResTransformsDir());
create_directory(Dirs::HiResTransformsDir());
Save(*LoResStack, LoResFileNames, Dirs::LoResTransformsDir());
Save(*HiResStack, HiResFileNames, Dirs::HiResTransformsDir());
return EXIT_SUCCESS;
}
po::variables_map parse_arguments(int argc, char *argv[])
{
// Declare the supported options.
po::options_description opts("Options");
opts.add_options()
("help,h", "produce help message")
("dataSet", po::value<string>(), "which rat to use")
("outputDir", po::value<string>(), "directory to place results")
("slice", po::value<string>(), "optional individual slice to register")
("blockDir", po::value<string>(), "directory containing LoRes originals")
("sliceDir", po::value<string>(), "directory containing HiRes originals")
("writeImages", po::bool_switch(), "output images and masks")
;
po::positional_options_description p;
p.add("dataSet", 1)
.add("outputDir", 1)
.add("slice", 1);
// parse command line
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv)
.options(opts)
.positional(p)
.run(),
vm);
}
catch (std::exception& e)
{
cerr << "caught command-line parsing error" << endl;
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
}
po::notify(vm);
// if help is specified, or positional args aren't present
if (vm.count("help") || !vm.count("dataSet") || !vm.count("outputDir")) {
cerr << "Usage: "
<< argv[0] << " [--dataSet=]RatX [--outputDir=]my_dir [Options]"
<< endl << endl;
cerr << opts << "\n";
exit(EXIT_FAILURE);
}
return vm;
}
<commit_msg>Fixed BuildVolumes single slice bug and refactored image file paths vector.<commit_after>#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
#include <assert.h>
#include "itkCenteredSimilarity2DTransform.h"
// my files
#include "Stack.hpp"
#include "NormalizeImages.hpp"
#include "StackInitializers.hpp"
#include "RegistrationBuilder.hpp"
#include "StackAligner.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "StackTransforms.hpp"
#include "OptimizerConfig.hpp"
#include "Profiling.hpp"
namespace po = boost::program_options;
using namespace boost::filesystem;
po::variables_map parse_arguments(int argc, char *argv[]);
int main(int argc, char *argv[]) {
// Parse command line arguments
po::variables_map vm = parse_arguments(argc, argv);
// Process command line arguments
Dirs::SetDataSet( vm["dataSet"].as<string>() );
Dirs::SetOutputDirName( vm["outputDir"].as<string>() );
string blockDir = vm.count("blockDir") ? vm["blockDir"].as<string>() + "/" : Dirs::BlockDir();
string sliceDir = vm.count("sliceDir") ? vm["sliceDir"].as<string>() + "/" : Dirs::SliceDir();
const bool writeImages = vm["writeImages"].as<bool>();
vector< string > LoResFilePaths, HiResFilePaths;
if( vm.count("slice") )
{
LoResFilePaths.push_back(blockDir + vm["slice"].as<string>());
HiResFilePaths.push_back(sliceDir + vm["slice"].as<string>());
}
else
{
LoResFilePaths = getFilePaths(blockDir, Dirs::SliceFile());
HiResFilePaths = getFilePaths(sliceDir, Dirs::SliceFile());
}
// initialise stack objects with correct spacings, sizes etc
typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFilePaths);
StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFilePaths);
normalizeImages< StackType >(LoResImages);
normalizeImages< StackType >(HiResImages);
boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages);
boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages);
// Assert stacks have the same number of slices
assert(LoResStack->GetSize() == HiResStack->GetSize());
// initialize stacks' transforms so that 2D images line up at their centres.
if( vm.count("blockDir") )
// if working with segmentations already in the right coordinate system,
// no need to apply transforms
StackTransforms::InitializeToIdentity(*LoResStack);
else
{
// if working from the original images, apply the necessary translation
StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") );
ApplyAdjustments( *LoResStack, LoResFilePaths, Dirs::ConfigDir() + "LoRes_adjustments/");
}
StackTransforms::InitializeToCommonCentre( *HiResStack );
StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack );
// create output dir before write operations
create_directory( Dirs::ResultsDir() );
// Generate fixed images to register against
LoResStack->updateVolumes();
if( writeImages )
{
writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + "LoResStack.mha" );
}
// initialise registration framework
typedef RegistrationBuilder< StackType > RegistrationBuilderType;
RegistrationBuilderType registrationBuilder;
RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();
StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration);
// Scale parameter space
OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() );
// Add time and memory probes
itkProbesCreate();
// perform centered rigid 2D registration on each pair of slices
itkProbesStart( "Aligning stacks" );
stackAligner.Update();
itkProbesStop( "Aligning stacks" );
// Report the time and memory taken by the registration
itkProbesReport( std::cout );
// write rigid transforms
if( writeImages )
{
HiResStack->updateVolumes();
writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResRigidStack.mha" );
// writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResRigidMask.mha" );
}
StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack);
// Scale parameter space
OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() );
// perform similarity rigid 2D registration
stackAligner.Update();
// write similarity transforms
if( writeImages )
{
HiResStack->updateVolumes();
writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResSimilarityStack.mha" );
}
// repeat registration with affine transform
StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack);
OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );
stackAligner.Update();
if( writeImages )
{
HiResStack->updateVolumes();
writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResAffineStack.mha" );
// writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResAffineMask.mha" );
}
// Update LoRes as the masks might have shrunk
LoResStack->updateVolumes();
// persist mask numberOfTimesTooBig and final metric values
saveVectorToFiles(HiResStack->GetNumberOfTimesTooBig(), "number_of_times_too_big", HiResFilePaths );
saveVectorToFiles(stackAligner.GetFinalMetricValues(), "metric_values", HiResFilePaths );
// write transforms to directories labeled by both ds ratios
create_directory(Dirs::LoResTransformsDir());
create_directory(Dirs::HiResTransformsDir());
Save(*LoResStack, LoResFilePaths, Dirs::LoResTransformsDir());
Save(*HiResStack, HiResFilePaths, Dirs::HiResTransformsDir());
return EXIT_SUCCESS;
}
po::variables_map parse_arguments(int argc, char *argv[])
{
// Declare the supported options.
po::options_description opts("Options");
opts.add_options()
("help,h", "produce help message")
("dataSet", po::value<string>(), "which rat to use")
("outputDir", po::value<string>(), "directory to place results")
("slice", po::value<string>(), "optional individual slice to register")
("blockDir", po::value<string>(), "directory containing LoRes originals")
("sliceDir", po::value<string>(), "directory containing HiRes originals")
("writeImages", po::bool_switch(), "output images and masks")
;
po::positional_options_description p;
p.add("dataSet", 1)
.add("outputDir", 1)
.add("slice", 1);
// parse command line
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv)
.options(opts)
.positional(p)
.run(),
vm);
}
catch (std::exception& e)
{
cerr << "caught command-line parsing error" << endl;
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
}
po::notify(vm);
// if help is specified, or positional args aren't present
if (vm.count("help") || !vm.count("dataSet") || !vm.count("outputDir")) {
cerr << "Usage: "
<< argv[0] << " [--dataSet=]RatX [--outputDir=]my_dir [Options]"
<< endl << endl;
cerr << opts << "\n";
exit(EXIT_FAILURE);
}
return vm;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE beadstructure_test
#include <boost/test/unit_test.hpp>
#include <stdexcept>
#include <votca/csg/basebead.h>
#include <votca/csg/beadstructure.h> // IWYU pragma: keep
using namespace std;
using namespace votca::csg;
class TestBead : public BaseBead {
public:
TestBead() : BaseBead(){};
};
BOOST_AUTO_TEST_SUITE(beadstructure_test)
BOOST_AUTO_TEST_CASE(test_beadstructure_constructor) {
BeadStructure<TestBead> beadstructure;
}
BOOST_AUTO_TEST_CASE(test_beadstructure_beadcount) {
BeadStructure<TestBead> beadstructure;
BOOST_CHECK_EQUAL(beadstructure.BeadCount(), 0);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_add_and_getbead) {
BeadStructure<TestBead> beadstructure;
TestBead testbead;
testbead.setId(2);
beadstructure.AddBead(&testbead);
BOOST_CHECK_EQUAL(beadstructure.BeadCount(), 1);
auto testbead2 = beadstructure.getBead(2);
BOOST_CHECK_EQUAL(testbead2->getId(), testbead.getId());
}
BOOST_AUTO_TEST_CASE(test_beadstructure_ConnectBeads) {
BeadStructure<TestBead> beadstructure;
TestBead testbead1;
testbead1.setId(1);
testbead1.setName("Carbon");
TestBead testbead2;
testbead2.setId(2);
testbead2.setName("Carbon");
beadstructure.AddBead(&testbead1);
beadstructure.AddBead(&testbead2);
beadstructure.ConnectBeads(1, 2);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_isSingleStructure) {
BeadStructure<TestBead> beadstructure;
TestBead testbead1;
testbead1.setName("Carbon");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Oxygen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
beadstructure.AddBead(&testbead1);
beadstructure.AddBead(&testbead2);
BOOST_CHECK(!beadstructure.isSingleStructure());
// C - C
beadstructure.ConnectBeads(1, 2);
BOOST_CHECK(beadstructure.isSingleStructure());
// C - C O
beadstructure.AddBead(&testbead3);
BOOST_CHECK(!beadstructure.isSingleStructure());
// C - C - O
beadstructure.ConnectBeads(2, 3);
BOOST_CHECK(beadstructure.isSingleStructure());
// C - C - O H - H
beadstructure.AddBead(&testbead4);
beadstructure.AddBead(&testbead5);
beadstructure.ConnectBeads(4, 5);
BOOST_CHECK(!beadstructure.isSingleStructure());
}
BOOST_AUTO_TEST_CASE(test_beadstructure_isStructureEquivalent) {
BeadStructure<TestBead> beadstructure1;
BeadStructure<TestBead> beadstructure2;
// Beads for bead structure 1
TestBead testbead1;
testbead1.setName("Carbon");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Oxygen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Beads for bead structure 2
TestBead testbead6;
testbead6.setName("Carbon");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Carbon");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Oxygen");
testbead8.setId(8);
TestBead testbead9;
testbead9.setName("Hydrogen");
testbead9.setId(9);
TestBead testbead10;
testbead10.setName("Hydrogen");
testbead10.setId(10);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(&testbead1);
BOOST_CHECK(!beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure2.AddBead(&testbead6);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(&testbead2);
beadstructure2.AddBead(&testbead7);
beadstructure1.ConnectBeads(1, 2);
BOOST_CHECK(!beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure2.ConnectBeads(6, 7);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(&testbead3);
beadstructure1.AddBead(&testbead4);
beadstructure1.AddBead(&testbead5);
beadstructure1.ConnectBeads(2, 3);
beadstructure1.ConnectBeads(4, 5);
beadstructure2.AddBead(&testbead10);
beadstructure2.AddBead(&testbead8);
beadstructure2.AddBead(&testbead9);
beadstructure2.ConnectBeads(7, 8);
beadstructure2.ConnectBeads(9, 10);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
}
BOOST_AUTO_TEST_CASE(test_beadstructure_getNeighBeads) {
BeadStructure<TestBead> beadstructure1;
// Beads for bead structure 1
// Make a methane molecule
//
// H
// |
// H - C - H
// |
// H
//
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Make a Water molecule
//
// H - O - H
//
TestBead testbead6;
testbead6.setName("Hydrogen");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Oxygen");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Hydrogen");
testbead8.setId(8);
beadstructure1.AddBead(&testbead1);
beadstructure1.AddBead(&testbead2);
beadstructure1.AddBead(&testbead3);
beadstructure1.AddBead(&testbead4);
beadstructure1.AddBead(&testbead5);
beadstructure1.AddBead(&testbead6);
beadstructure1.AddBead(&testbead7);
beadstructure1.AddBead(&testbead8);
// At this point non of the beads are connected so should return a vector of
// size 0
auto v1 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v1.size(), 0);
auto v2 = beadstructure1.getNeighBeads(2);
BOOST_CHECK_EQUAL(v2.size(), 0);
auto v3 = beadstructure1.getNeighBeads(3);
BOOST_CHECK_EQUAL(v3.size(), 0);
auto v4 = beadstructure1.getNeighBeads(4);
BOOST_CHECK_EQUAL(v4.size(), 0);
auto v5 = beadstructure1.getNeighBeads(5);
BOOST_CHECK_EQUAL(v5.size(), 0);
auto v6 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v6.size(), 0);
auto v7 = beadstructure1.getNeighBeads(7);
BOOST_CHECK_EQUAL(v7.size(), 0);
auto v8 = beadstructure1.getNeighBeads(8);
BOOST_CHECK_EQUAL(v8.size(), 0);
// Connect beads
beadstructure1.ConnectBeads(1, 2);
beadstructure1.ConnectBeads(3, 2);
beadstructure1.ConnectBeads(4, 2);
beadstructure1.ConnectBeads(5, 2);
beadstructure1.ConnectBeads(6, 7);
beadstructure1.ConnectBeads(7, 8);
v1 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v1.size(), 1);
v2 = beadstructure1.getNeighBeads(2);
BOOST_CHECK_EQUAL(v2.size(), 4);
v3 = beadstructure1.getNeighBeads(3);
BOOST_CHECK_EQUAL(v3.size(), 1);
v4 = beadstructure1.getNeighBeads(4);
BOOST_CHECK_EQUAL(v4.size(), 1);
v5 = beadstructure1.getNeighBeads(5);
BOOST_CHECK_EQUAL(v5.size(), 1);
v6 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v6.size(), 1);
v7 = beadstructure1.getNeighBeads(7);
BOOST_CHECK_EQUAL(v7.size(), 2);
v8 = beadstructure1.getNeighBeads(8);
BOOST_CHECK_EQUAL(v8.size(), 1);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_catchError) {
{
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
TestBead testbead6;
testbead6.setName("Hydrogen");
testbead6.setId(5);
BeadStructure<TestBead> beadstructure;
beadstructure.AddBead(&testbead1);
beadstructure.AddBead(&testbead2);
beadstructure.AddBead(&testbead3);
beadstructure.AddBead(&testbead4);
beadstructure.AddBead(&testbead5);
BOOST_CHECK_THROW(beadstructure.AddBead(&testbead6), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(0, 1), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(5, 6), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(1, 1), invalid_argument);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Corrected use of AddBead to reference in beadstructure test<commit_after>/*
* Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE beadstructure_test
#include <boost/test/unit_test.hpp>
#include <stdexcept>
#include <votca/csg/basebead.h>
#include <votca/csg/beadstructure.h> // IWYU pragma: keep
using namespace std;
using namespace votca::csg;
class TestBead : public BaseBead {
public:
TestBead() : BaseBead(){};
};
BOOST_AUTO_TEST_SUITE(beadstructure_test)
BOOST_AUTO_TEST_CASE(test_beadstructure_constructor) {
BeadStructure<TestBead> beadstructure;
}
BOOST_AUTO_TEST_CASE(test_beadstructure_beadcount) {
BeadStructure<TestBead> beadstructure;
BOOST_CHECK_EQUAL(beadstructure.BeadCount(), 0);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_add_and_getbead) {
BeadStructure<TestBead> beadstructure;
TestBead testbead;
testbead.setId(2);
beadstructure.AddBead(testbead);
BOOST_CHECK_EQUAL(beadstructure.BeadCount(), 1);
auto testbead2 = beadstructure.getBead(2);
BOOST_CHECK_EQUAL(testbead2.getId(), testbead.getId());
}
BOOST_AUTO_TEST_CASE(test_beadstructure_ConnectBeads) {
BeadStructure<TestBead> beadstructure;
TestBead testbead1;
testbead1.setId(1);
testbead1.setName("Carbon");
TestBead testbead2;
testbead2.setId(2);
testbead2.setName("Carbon");
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
beadstructure.ConnectBeads(1, 2);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_isSingleStructure) {
BeadStructure<TestBead> beadstructure;
TestBead testbead1;
testbead1.setName("Carbon");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Oxygen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
BOOST_CHECK(!beadstructure.isSingleStructure());
// C - C
beadstructure.ConnectBeads(1, 2);
BOOST_CHECK(beadstructure.isSingleStructure());
// C - C O
beadstructure.AddBead(testbead3);
BOOST_CHECK(!beadstructure.isSingleStructure());
// C - C - O
beadstructure.ConnectBeads(2, 3);
BOOST_CHECK(beadstructure.isSingleStructure());
// C - C - O H - H
beadstructure.AddBead(testbead4);
beadstructure.AddBead(testbead5);
beadstructure.ConnectBeads(4, 5);
BOOST_CHECK(!beadstructure.isSingleStructure());
}
BOOST_AUTO_TEST_CASE(test_beadstructure_isStructureEquivalent) {
BeadStructure<TestBead> beadstructure1;
BeadStructure<TestBead> beadstructure2;
// Beads for bead structure 1
TestBead testbead1;
testbead1.setName("Carbon");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Oxygen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Beads for bead structure 2
TestBead testbead6;
testbead6.setName("Carbon");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Carbon");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Oxygen");
testbead8.setId(8);
TestBead testbead9;
testbead9.setName("Hydrogen");
testbead9.setId(9);
TestBead testbead10;
testbead10.setName("Hydrogen");
testbead10.setId(10);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(testbead1);
BOOST_CHECK(!beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure2.AddBead(testbead6);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(testbead2);
beadstructure2.AddBead(testbead7);
beadstructure1.ConnectBeads(1, 2);
BOOST_CHECK(!beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure2.ConnectBeads(6, 7);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(testbead3);
beadstructure1.AddBead(testbead4);
beadstructure1.AddBead(testbead5);
beadstructure1.ConnectBeads(2, 3);
beadstructure1.ConnectBeads(4, 5);
beadstructure2.AddBead(testbead10);
beadstructure2.AddBead(testbead8);
beadstructure2.AddBead(testbead9);
beadstructure2.ConnectBeads(7, 8);
beadstructure2.ConnectBeads(9, 10);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
}
BOOST_AUTO_TEST_CASE(test_beadstructure_getNeighBeads) {
BeadStructure<TestBead> beadstructure1;
// Beads for bead structure 1
// Make a methane molecule
//
// H
// |
// H - C - H
// |
// H
//
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Make a Water molecule
//
// H - O - H
//
TestBead testbead6;
testbead6.setName("Hydrogen");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Oxygen");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Hydrogen");
testbead8.setId(8);
beadstructure1.AddBead(testbead1);
beadstructure1.AddBead(testbead2);
beadstructure1.AddBead(testbead3);
beadstructure1.AddBead(testbead4);
beadstructure1.AddBead(testbead5);
beadstructure1.AddBead(testbead6);
beadstructure1.AddBead(testbead7);
beadstructure1.AddBead(testbead8);
// At this point non of the beads are connected so should return a vector of
// size 0
auto v1 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v1.size(), 0);
auto v2 = beadstructure1.getNeighBeads(2);
BOOST_CHECK_EQUAL(v2.size(), 0);
auto v3 = beadstructure1.getNeighBeads(3);
BOOST_CHECK_EQUAL(v3.size(), 0);
auto v4 = beadstructure1.getNeighBeads(4);
BOOST_CHECK_EQUAL(v4.size(), 0);
auto v5 = beadstructure1.getNeighBeads(5);
BOOST_CHECK_EQUAL(v5.size(), 0);
auto v6 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v6.size(), 0);
auto v7 = beadstructure1.getNeighBeads(7);
BOOST_CHECK_EQUAL(v7.size(), 0);
auto v8 = beadstructure1.getNeighBeads(8);
BOOST_CHECK_EQUAL(v8.size(), 0);
// Connect beads
beadstructure1.ConnectBeads(1, 2);
beadstructure1.ConnectBeads(3, 2);
beadstructure1.ConnectBeads(4, 2);
beadstructure1.ConnectBeads(5, 2);
beadstructure1.ConnectBeads(6, 7);
beadstructure1.ConnectBeads(7, 8);
v1 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v1.size(), 1);
v2 = beadstructure1.getNeighBeads(2);
BOOST_CHECK_EQUAL(v2.size(), 4);
v3 = beadstructure1.getNeighBeads(3);
BOOST_CHECK_EQUAL(v3.size(), 1);
v4 = beadstructure1.getNeighBeads(4);
BOOST_CHECK_EQUAL(v4.size(), 1);
v5 = beadstructure1.getNeighBeads(5);
BOOST_CHECK_EQUAL(v5.size(), 1);
v6 = beadstructure1.getNeighBeads(1);
BOOST_CHECK_EQUAL(v6.size(), 1);
v7 = beadstructure1.getNeighBeads(7);
BOOST_CHECK_EQUAL(v7.size(), 2);
v8 = beadstructure1.getNeighBeads(8);
BOOST_CHECK_EQUAL(v8.size(), 1);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_catchError) {
{
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
TestBead testbead6;
testbead6.setName("Hydrogen");
testbead6.setId(5);
BeadStructure<TestBead> beadstructure;
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
beadstructure.AddBead(testbead3);
beadstructure.AddBead(testbead4);
beadstructure.AddBead(testbead5);
BOOST_CHECK_THROW(beadstructure.AddBead(testbead6), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(0, 1), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(5, 6), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(1, 1), invalid_argument);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// Peak detection routine.
///
/// The routine detects highest value on an array of values and calculates the
/// precise peak location as a mass-center of the 'hump' around the peak value.
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
//
////////////////////////////////////////////////////////////////////////////////
#include <math.h>
#include <assert.h>
#include "PeakFinder.h"
using namespace soundtouch;
#define max(x, y) (((x) > (y)) ? (x) : (y))
PeakFinder::PeakFinder()
{
minPos = maxPos = 0;
}
// Finds real 'top' of a peak hump from neighnourhood of the given 'peakpos'.
int PeakFinder::findTop(const float *data, int peakpos) const
{
int i;
int start, end;
float refvalue;
refvalue = data[peakpos];
// seek within 10 points
start = peakpos - 10;
if (start < minPos) start = minPos;
end = peakpos + 10;
if (end > maxPos) end = maxPos;
for (i = start; i <= end; i ++)
{
if (data[i] > refvalue)
{
peakpos = i;
refvalue = data[i];
}
}
// failure if max value is at edges of seek range => it's not peak, it's at slope.
if ((peakpos == start) || (peakpos == end)) return 0;
return peakpos;
}
// Finds 'ground level' of a peak hump by starting from 'peakpos' and proceeding
// to direction defined by 'direction' until next 'hump' after minimum value will
// begin
int PeakFinder::findGround(const float *data, int peakpos, int direction) const
{
int lowpos;
int pos;
int climb_count;
float refvalue;
float delta;
climb_count = 0;
refvalue = data[peakpos];
lowpos = peakpos;
pos = peakpos;
while ((pos > minPos+1) && (pos < maxPos-1))
{
int prevpos;
prevpos = pos;
pos += direction;
// calculate derivate
delta = data[pos] - data[prevpos];
if (delta <= 0)
{
// going downhill, ok
if (climb_count)
{
climb_count --; // decrease climb count
}
// check if new minimum found
if (data[pos] < refvalue)
{
// new minimum found
lowpos = pos;
refvalue = data[pos];
}
}
else
{
// going uphill, increase climbing counter
climb_count ++;
if (climb_count > 5) break; // we've been climbing too long => it's next uphill => quit
}
}
return lowpos;
}
// Find offset where the value crosses the given level, when starting from 'peakpos' and
// proceeds to direction defined in 'direction'
int PeakFinder::findCrossingLevel(const float *data, float level, int peakpos, int direction) const
{
float peaklevel;
int pos;
peaklevel = data[peakpos];
assert(peaklevel >= level);
pos = peakpos;
while ((pos >= minPos) && (pos < maxPos))
{
if (data[pos + direction] < level) return pos; // crossing found
pos += direction;
}
return -1; // not found
}
// Calculates the center of mass location of 'data' array items between 'firstPos' and 'lastPos'
double PeakFinder::calcMassCenter(const float *data, int firstPos, int lastPos) const
{
int i;
float sum;
float wsum;
sum = 0;
wsum = 0;
for (i = firstPos; i <= lastPos; i ++)
{
sum += (float)i * data[i];
wsum += data[i];
}
if (wsum < 1e-6) return 0;
return sum / wsum;
}
/// get exact center of peak near given position by calculating local mass of center
double PeakFinder::getPeakCenter(const float *data, int peakpos) const
{
float peakLevel; // peak level
int crosspos1, crosspos2; // position where the peak 'hump' crosses cutting level
float cutLevel; // cutting value
float groundLevel; // ground level of the peak
int gp1, gp2; // bottom positions of the peak 'hump'
// find ground positions.
gp1 = findGround(data, peakpos, -1);
gp2 = findGround(data, peakpos, 1);
groundLevel = 0.5f * (data[gp1] + data[gp2]);
peakLevel = data[peakpos];
// calculate 70%-level of the peak
cutLevel = 0.70f * peakLevel + 0.30f * groundLevel;
// find mid-level crossings
crosspos1 = findCrossingLevel(data, cutLevel, peakpos, -1);
crosspos2 = findCrossingLevel(data, cutLevel, peakpos, 1);
if ((crosspos1 < 0) || (crosspos2 < 0)) return 0; // no crossing, no peak..
// calculate mass center of the peak surroundings
return calcMassCenter(data, crosspos1, crosspos2);
}
double PeakFinder::detectPeak(const float *data, int aminPos, int amaxPos)
{
int i;
int peakpos; // position of peak level
double highPeak, peak;
this->minPos = aminPos;
this->maxPos = amaxPos;
// find absolute peak
peakpos = minPos;
peak = data[minPos];
for (i = minPos + 1; i < maxPos; i ++)
{
if (data[i] > peak)
{
peak = data[i];
peakpos = i;
}
}
// Calculate exact location of the highest peak mass center
highPeak = getPeakCenter(data, peakpos);
peak = highPeak;
// Now check if the highest peak were in fact harmonic of the true base beat peak
// - sometimes the highest peak can be Nth harmonic of the true base peak yet
// just a slightly higher than the true base
int hp = (int)(highPeak + 0.5);
for (i = 3; i < 10; i ++)
{
double peaktmp, harmonic;
int i1,i2;
harmonic = (double)i * 0.5;
peakpos = (int)(highPeak / harmonic + 0.5f);
if (peakpos < minPos) break;
peakpos = findTop(data, peakpos); // seek true local maximum index
if (peakpos == 0) continue; // no local max here
// calculate mass-center of possible harmonic peak
peaktmp = getPeakCenter(data, peakpos);
// accept harmonic peak if
// (a) it is found
// (b) is within 4% of the expected harmonic interval
// (c) has at least half x-corr value of the max. peak
double diff = harmonic * peaktmp / highPeak;
if ((diff < 0.96) || (diff > 1.04)) continue; // peak too afar from expected
// now compare to highest detected peak
i1 = (int)(highPeak + 0.5);
i2 = (int)(peaktmp + 0.5);
if (data[i2] >= 0.4*data[i1])
{
// The harmonic is at least half as high primary peak,
// thus use the harmonic peak instead
peak = peaktmp;
}
}
return peak;
}
<commit_msg>Removed piece of dead code<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// Peak detection routine.
///
/// The routine detects highest value on an array of values and calculates the
/// precise peak location as a mass-center of the 'hump' around the peak value.
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
//
////////////////////////////////////////////////////////////////////////////////
#include <math.h>
#include <assert.h>
#include "PeakFinder.h"
using namespace soundtouch;
#define max(x, y) (((x) > (y)) ? (x) : (y))
PeakFinder::PeakFinder()
{
minPos = maxPos = 0;
}
// Finds real 'top' of a peak hump from neighnourhood of the given 'peakpos'.
int PeakFinder::findTop(const float *data, int peakpos) const
{
int i;
int start, end;
float refvalue;
refvalue = data[peakpos];
// seek within 10 points
start = peakpos - 10;
if (start < minPos) start = minPos;
end = peakpos + 10;
if (end > maxPos) end = maxPos;
for (i = start; i <= end; i ++)
{
if (data[i] > refvalue)
{
peakpos = i;
refvalue = data[i];
}
}
// failure if max value is at edges of seek range => it's not peak, it's at slope.
if ((peakpos == start) || (peakpos == end)) return 0;
return peakpos;
}
// Finds 'ground level' of a peak hump by starting from 'peakpos' and proceeding
// to direction defined by 'direction' until next 'hump' after minimum value will
// begin
int PeakFinder::findGround(const float *data, int peakpos, int direction) const
{
int lowpos;
int pos;
int climb_count;
float refvalue;
float delta;
climb_count = 0;
refvalue = data[peakpos];
lowpos = peakpos;
pos = peakpos;
while ((pos > minPos+1) && (pos < maxPos-1))
{
int prevpos;
prevpos = pos;
pos += direction;
// calculate derivate
delta = data[pos] - data[prevpos];
if (delta <= 0)
{
// going downhill, ok
if (climb_count)
{
climb_count --; // decrease climb count
}
// check if new minimum found
if (data[pos] < refvalue)
{
// new minimum found
lowpos = pos;
refvalue = data[pos];
}
}
else
{
// going uphill, increase climbing counter
climb_count ++;
if (climb_count > 5) break; // we've been climbing too long => it's next uphill => quit
}
}
return lowpos;
}
// Find offset where the value crosses the given level, when starting from 'peakpos' and
// proceeds to direction defined in 'direction'
int PeakFinder::findCrossingLevel(const float *data, float level, int peakpos, int direction) const
{
float peaklevel;
int pos;
peaklevel = data[peakpos];
assert(peaklevel >= level);
pos = peakpos;
while ((pos >= minPos) && (pos < maxPos))
{
if (data[pos + direction] < level) return pos; // crossing found
pos += direction;
}
return -1; // not found
}
// Calculates the center of mass location of 'data' array items between 'firstPos' and 'lastPos'
double PeakFinder::calcMassCenter(const float *data, int firstPos, int lastPos) const
{
int i;
float sum;
float wsum;
sum = 0;
wsum = 0;
for (i = firstPos; i <= lastPos; i ++)
{
sum += (float)i * data[i];
wsum += data[i];
}
if (wsum < 1e-6) return 0;
return sum / wsum;
}
/// get exact center of peak near given position by calculating local mass of center
double PeakFinder::getPeakCenter(const float *data, int peakpos) const
{
float peakLevel; // peak level
int crosspos1, crosspos2; // position where the peak 'hump' crosses cutting level
float cutLevel; // cutting value
float groundLevel; // ground level of the peak
int gp1, gp2; // bottom positions of the peak 'hump'
// find ground positions.
gp1 = findGround(data, peakpos, -1);
gp2 = findGround(data, peakpos, 1);
groundLevel = 0.5f * (data[gp1] + data[gp2]);
peakLevel = data[peakpos];
// calculate 70%-level of the peak
cutLevel = 0.70f * peakLevel + 0.30f * groundLevel;
// find mid-level crossings
crosspos1 = findCrossingLevel(data, cutLevel, peakpos, -1);
crosspos2 = findCrossingLevel(data, cutLevel, peakpos, 1);
if ((crosspos1 < 0) || (crosspos2 < 0)) return 0; // no crossing, no peak..
// calculate mass center of the peak surroundings
return calcMassCenter(data, crosspos1, crosspos2);
}
double PeakFinder::detectPeak(const float *data, int aminPos, int amaxPos)
{
int i;
int peakpos; // position of peak level
double highPeak, peak;
this->minPos = aminPos;
this->maxPos = amaxPos;
// find absolute peak
peakpos = minPos;
peak = data[minPos];
for (i = minPos + 1; i < maxPos; i ++)
{
if (data[i] > peak)
{
peak = data[i];
peakpos = i;
}
}
// Calculate exact location of the highest peak mass center
highPeak = getPeakCenter(data, peakpos);
peak = highPeak;
// Now check if the highest peak were in fact harmonic of the true base beat peak
// - sometimes the highest peak can be Nth harmonic of the true base peak yet
// just a slightly higher than the true base
for (i = 3; i < 10; i ++)
{
double peaktmp, harmonic;
int i1,i2;
harmonic = (double)i * 0.5;
peakpos = (int)(highPeak / harmonic + 0.5f);
if (peakpos < minPos) break;
peakpos = findTop(data, peakpos); // seek true local maximum index
if (peakpos == 0) continue; // no local max here
// calculate mass-center of possible harmonic peak
peaktmp = getPeakCenter(data, peakpos);
// accept harmonic peak if
// (a) it is found
// (b) is within 4% of the expected harmonic interval
// (c) has at least half x-corr value of the max. peak
double diff = harmonic * peaktmp / highPeak;
if ((diff < 0.96) || (diff > 1.04)) continue; // peak too afar from expected
// now compare to highest detected peak
i1 = (int)(highPeak + 0.5);
i2 = (int)(peaktmp + 0.5);
if (data[i2] >= 0.4*data[i1])
{
// The harmonic is at least half as high primary peak,
// thus use the harmonic peak instead
peak = peaktmp;
}
}
return peak;
}
<|endoftext|>
|
<commit_before>/**
* @file Cosa/Driver/DHT11.hh
* @version 1.0
*
* @section License
* Copyright (C) 2012-2013, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_DRIVER_DHT11_HH__
#define __COSA_DRIVER_DHT11_HH__
#include "Cosa/Types.h"
#include "Cosa/Pins.hh"
#include "Cosa/Linkage.hh"
/**
* DHT11 Humidity & Temperature Sensor device driver. Subclass
* and implement the event handler, on_event(), to allow periodic
* read of device (attach to watchdog timeout queue).
*
* @section Circuit
* Connect DHT11 to pin, VCC and ground. A pullup resistor from
* the pin to VCC should be used. Most DHT11 modules have a built-in
* pullup resistor.
*
* @section Limitations
* The driver will turn off interrupt handling during data read
* from the device.
*
* @section See Also
* [1] DHT11 Humidity & Temperature Sensor, Robotics UK,
* www.droboticsonline.com, http://www.micro4you.com/files/sensor/DHT11.pdf<br>
* [2] DHTxx Sensor Tutorial, http://learn.adafruit.com/dht<br>
*/
class DHT11 : private Link {
public:
/** Size of data buffer */
static const uint8_t DATA_MAX = 5;
/** Last data elemement index */
static const uint8_t DATA_LAST = DATA_MAX - 1;
protected:
/**
* Data read from the device.
*/
union data_t {
uint8_t as_byte[DATA_MAX];
struct {
int16_t humidity;
int16_t temperature;
uint8_t chksum;
};
};
/**
* Input/Output pin, data and offset buffer and latest pin level.
*/
IOPin m_pin;
data_t m_data;
data_t m_offset;
uint8_t m_latest;
/**
* Read the next bit from the device given number of level
* changes. Return one(1) if the bit was set, zero(0) if clear,
* otherwise a negative error code.
* @param[in] changes number of level transitions.
* @return one(1) if the bit was set, zero(0) if clear, otherwise
* a negative error code(-1).
*/
int8_t read_bit(uint8_t changes);
/**
* Read data from the device. Return true(1) if successful otherwise
* false(0).
* @return bool.
*/
bool read_data();
/**
* Adjust data from the device.
*/
virtual void adjust_data() {}
public:
/**
* Construct connection to a DHT11 device on given in/output-pin.
* Set humidity and temperature calibration offsets to zero.
* @param[in] pin data.
*/
DHT11(Board::DigitalPin pin) :
Link(),
m_pin(pin)
{
m_offset.humidity = 0;
m_offset.temperature = 0;
}
/**
* Read temperature and humidity from the device. Return true(1) and
* values if successful otherwise false(0).
* @param[out] humidity reading.
* @param[out] temperature reading.
* @return bool.
*/
bool read(int16_t& humidity, int16_t& temperature)
{
if (!read_data()) return (false);
humidity = get_humidity();
temperature = get_temperature();
return (true);
}
/**
* Return temperature from latest read.
* @return temperature.
*/
int16_t get_temperature()
{
return (m_data.temperature + m_offset.temperature);
}
/**
* Return humidity from latest read.
* @return humidity.
*/
int16_t get_humidity()
{
return (m_data.humidity + m_offset.humidity);
}
/**
* Set calibration offset for temperature and humidity readings.
* The given values are added to the values read from the device.
* @param[in] temperature.
* @param[in] humidity.
*/
void calibrate(int16_t humidity, int16_t temperature)
{
m_offset.humidity = humidity;
m_offset.temperature = temperature;
}
/**
* @override
* Default device event handler function. Attach to watchdog
* timer queue, Watchdog::attach(), to allow perodic reading.
* @param[in] type the type of event.
* @param[in] value the event value.
*/
virtual void on_event(uint8_t type, uint16_t value)
{
read_data();
}
};
#endif
<commit_msg>Fixed wrong visibility of const values.<commit_after>/**
* @file Cosa/Driver/DHT11.hh
* @version 1.0
*
* @section License
* Copyright (C) 2012-2013, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_DRIVER_DHT11_HH__
#define __COSA_DRIVER_DHT11_HH__
#include "Cosa/Types.h"
#include "Cosa/Pins.hh"
#include "Cosa/Linkage.hh"
/**
* DHT11 Humidity & Temperature Sensor device driver. Subclass
* and implement the event handler, on_event(), to allow periodic
* read of device (attach to watchdog timeout queue).
*
* @section Circuit
* Connect DHT11 to pin, VCC and ground. A pullup resistor from
* the pin to VCC should be used. Most DHT11 modules have a built-in
* pullup resistor.
*
* @section Limitations
* The driver will turn off interrupt handling during data read
* from the device.
*
* @section See Also
* [1] DHT11 Humidity & Temperature Sensor, Robotics UK,
* www.droboticsonline.com, http://www.micro4you.com/files/sensor/DHT11.pdf<br>
* [2] DHTxx Sensor Tutorial, http://learn.adafruit.com/dht<br>
*/
class DHT11 : private Link {
protected:
/** Size of data buffer */
static const uint8_t DATA_MAX = 5;
/** Last data elemement index */
static const uint8_t DATA_LAST = DATA_MAX - 1;
/**
* Data read from the device.
*/
union data_t {
uint8_t as_byte[DATA_MAX];
struct {
int16_t humidity;
int16_t temperature;
uint8_t chksum;
};
};
/**
* Input/Output pin, data and offset buffer and latest pin level.
*/
IOPin m_pin;
data_t m_data;
data_t m_offset;
uint8_t m_latest;
/**
* Read the next bit from the device given number of level
* changes. Return one(1) if the bit was set, zero(0) if clear,
* otherwise a negative error code.
* @param[in] changes number of level transitions.
* @return one(1) if the bit was set, zero(0) if clear, otherwise
* a negative error code(-1).
*/
int8_t read_bit(uint8_t changes);
/**
* Read data from the device. Return true(1) if successful otherwise
* false(0).
* @return bool.
*/
bool read_data();
/**
* Adjust data from the device.
*/
virtual void adjust_data() {}
public:
/**
* Construct connection to a DHT11 device on given in/output-pin.
* Set humidity and temperature calibration offsets to zero.
* @param[in] pin data.
*/
DHT11(Board::DigitalPin pin) :
Link(),
m_pin(pin)
{
m_offset.humidity = 0;
m_offset.temperature = 0;
}
/**
* Read temperature and humidity from the device. Return true(1) and
* values if successful otherwise false(0).
* @param[out] humidity reading.
* @param[out] temperature reading.
* @return bool.
*/
bool read(int16_t& humidity, int16_t& temperature)
{
if (!read_data()) return (false);
humidity = get_humidity();
temperature = get_temperature();
return (true);
}
/**
* Return temperature from latest read.
* @return temperature.
*/
int16_t get_temperature()
{
return (m_data.temperature + m_offset.temperature);
}
/**
* Return humidity from latest read.
* @return humidity.
*/
int16_t get_humidity()
{
return (m_data.humidity + m_offset.humidity);
}
/**
* Set calibration offset for temperature and humidity readings.
* The given values are added to the values read from the device.
* @param[in] temperature.
* @param[in] humidity.
*/
void calibrate(int16_t humidity, int16_t temperature)
{
m_offset.humidity = humidity;
m_offset.temperature = temperature;
}
/**
* @override
* Default device event handler function. Attach to watchdog
* timer queue, Watchdog::attach(), to allow perodic reading.
* @param[in] type the type of event.
* @param[in] value the event value.
*/
virtual void on_event(uint8_t type, uint16_t value)
{
read_data();
}
};
#endif
<|endoftext|>
|
<commit_before>#include "easyctrl.h"
Easyctrl_Class Easyctrl;
void MonitoredBase::init(const char *name, bool writeable) {
this->name = name;
this->writeable = writeable;
// Add it to the linked list of known monitored variables
this->next = Easyctrl.first;
Easyctrl.first = this;
}
void Easyctrl_Class::writeManifest() {
stream->print(F(".fields "));
stream->println(this->name);
for(MonitoredBase *i = this->first; i != NULL; i = i->next) {
i->describe(*this->stream);
}
stream->println(F(".endfields"));
}
template<>
void Monitored<int>::parse(const char *data) {
this->value = strtol(data, NULL, 0);
}
template<>
void Monitored<int>::printTypeName(Stream &stream) {
stream.print(F("int"));
}
template<>
void Monitored<unsigned int>::parse(const char *data) {
this->value = strtoul(data, NULL, 0);
}
template<>
void Monitored<unsigned int>::printTypeName(Stream &stream) {
stream.print(F("uint"));
}
template<>
void Monitored<long>::parse(const char *data) {
this->value = strtol(data, NULL, 0);
}
template<>
void Monitored<long>::printTypeName(Stream &stream) {
stream.print(F("long"));
}
template<>
void Monitored<unsigned long>::parse(const char *data) {
this->value = strtoul(data, NULL, 0);
}
template<>
void Monitored<unsigned long>::printTypeName(Stream &stream) {
stream.print(F("ulong"));
}
template<>
void Monitored<float>::parse(const char *data) {
this->value = strtod(data, NULL);
}
template<>
void Monitored<float>::printTypeName(Stream &stream) {
stream.print(F("float"));
}
template<>
void Monitored<double>::parse(const char *data) {
this->value = strtod(data, NULL);
}
template<>
void Monitored<double>::printTypeName(Stream &stream) {
stream.print(F("double"));
}
<commit_msg>Added support for monitored booleans<commit_after>#include "easyctrl.h"
Easyctrl_Class Easyctrl;
void MonitoredBase::init(const char *name, bool writeable) {
this->name = name;
this->writeable = writeable;
// Add it to the linked list of known monitored variables
this->next = Easyctrl.first;
Easyctrl.first = this;
}
void Easyctrl_Class::writeManifest() {
stream->print(F(".fields "));
stream->println(this->name);
for(MonitoredBase *i = this->first; i != NULL; i = i->next) {
i->describe(*this->stream);
}
stream->println(F(".endfields"));
}
template<>
void Monitored<int>::parse(const char *data) {
this->value = strtol(data, NULL, 0);
}
template<>
void Monitored<int>::printTypeName(Stream &stream) {
stream.print(F("int"));
}
template<>
void Monitored<unsigned int>::parse(const char *data) {
this->value = strtoul(data, NULL, 0);
}
template<>
void Monitored<unsigned int>::printTypeName(Stream &stream) {
stream.print(F("uint"));
}
template<>
void Monitored<long>::parse(const char *data) {
this->value = strtol(data, NULL, 0);
}
template<>
void Monitored<long>::printTypeName(Stream &stream) {
stream.print(F("long"));
}
template<>
void Monitored<unsigned long>::parse(const char *data) {
this->value = strtoul(data, NULL, 0);
}
template<>
void Monitored<unsigned long>::printTypeName(Stream &stream) {
stream.print(F("ulong"));
}
template<>
void Monitored<float>::parse(const char *data) {
this->value = strtod(data, NULL);
}
template<>
void Monitored<float>::printTypeName(Stream &stream) {
stream.print(F("float"));
}
template<>
void Monitored<double>::parse(const char *data) {
this->value = strtod(data, NULL);
}
template<>
void Monitored<double>::printTypeName(Stream &stream) {
stream.print(F("double"));
}
template<>
void Monitored<bool>::format(Stream &stream) {
if(this->value) {
stream.print(F("true"));
} else {
stream.print(F("false"));
}
}
template<>
void Monitored<bool>::parse(const char *data) {
if(strncasecmp_P(data, PSTR("true"), 4) == 0 || atoi(data) != 0) {
this->value = true;
} else {
this->value = false;
}
}
template<>
void Monitored<bool>::printTypeName(Stream &stream) {
stream.print(F("bool"));
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* 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 Rice University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Elizabeth Fudge */
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/base/spaces/DiscreteStateSpace.h>
#include <ompl/control/spaces/RealVectorControlSpace.h>
#include <ompl/control/SimpleSetup.h>
#include <ompl/config.h>
#include <iostream>
#include <limits>
#include <boost/math/constants/constants.hpp>
namespace ob = ompl::base;
namespace oc = ompl::control;
void propagate(const oc::SpaceInformation *si, const ob::State *state,
const oc::Control* control, const double duration, ob::State *result)
{
static double timeStep = .01;
static double carLength = 20.;
int nsteps = ceil(duration / timeStep);
double dt = duration / nsteps;
const double *u = control->as<oc::RealVectorControlSpace::ControlType>()->values;
ob::CompoundStateSpace::StateType& s = *result->as<ob::CompoundStateSpace::StateType>();
ob::SE2StateSpace::StateType& se2 = *s.as<ob::SE2StateSpace::StateType>(0);
ob::RealVectorStateSpace::StateType& velocity = *s.as<ob::RealVectorStateSpace::StateType>(1);
ob::DiscreteStateSpace::StateType& gear = *s.as<ob::DiscreteStateSpace::StateType>(2);
si->getStateSpace()->copyState(result, state);
for(int i=0; i<nsteps; i++)
{
se2.setX(se2.getX() + timeStep * velocity.values[0] * cos(se2.getYaw()));
se2.setY(se2.getY() + timeStep * velocity.values[0] * sin(se2.getYaw()));
se2.setYaw(se2.getYaw() + timeStep * u[0]);
velocity.values[0] = velocity.values[0] + timeStep * (u[1]*gear.value);
// 'guards' - conditions to change gears
if (gear.value > 0)
{
if (gear.value < 3 && velocity.values[0] > 10*(gear.value + 1))
gear.value++;
else if (gear.value > 1 && velocity.values[0] < 10*gear.value)
gear.value--;
}
if (!si->satisfiesBounds(result))
return;
}
}
// The free space consists of two narrow corridors connected at right angle.
// To make the turn, the car will have to downshift.
bool isStateValid(const oc::SpaceInformation *si, const ob::State *state)
{
const ob::SE2StateSpace::StateType *se2 =
state->as<ob::CompoundState>()->as<ob::SE2StateSpace::StateType>(0);
return si->satisfiesBounds(state) && (se2->getX() < -80. || se2->getY() > 80.);
}
int main(int argc, char* argv[])
{
// plan for hybrid car in SE(2) with discrete gears
ob::StateSpacePtr SE2(new ob::SE2StateSpace());
ob::StateSpacePtr velocity(new ob::RealVectorStateSpace(1));
// set the range for gears: [-1,3] inclusive
ob::StateSpacePtr gear(new ob::DiscreteStateSpace(-1,3));
ob::StateSpacePtr stateSpace = SE2 + velocity + gear;
// set the bounds for the R^2 part of SE(2)
ob::RealVectorBounds bounds(2);
bounds.setLow(-100);
bounds.setHigh(100);
SE2->as<ob::SE2StateSpace>()->setBounds(bounds);
// set the bounds for the velocity
ob::RealVectorBounds velocityBound(1);
velocityBound.setLow(0);
velocityBound.setHigh(60);
velocity->as<ob::RealVectorStateSpace>()->setBounds(velocityBound);
// create start and goal states
ob::ScopedState<> start(stateSpace);
ob::ScopedState<> goal(stateSpace);
// Both start and goal are states with high velocity with the car in third gear.
// However, to make the turn, the car cannot stay in third gear and will have to
// shift to first gear.
start[0] = start[1] = -90.; // position
start[2] = boost::math::constants::pi<double>()/2; // orientation
start[3] = 40.; // velocity
start->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2)->value = 3; // gear
goal[0] = goal[1] = 90.; // position
goal[2] = 0.; // orientation
goal[3] = 40.; // velocity
goal->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2)->value = 3; // gear
oc::ControlSpacePtr cmanifold(new oc::RealVectorControlSpace(stateSpace, 2));
// set the bounds for the control manifold
ob::RealVectorBounds cbounds(2);
// bounds for steering input
cbounds.setLow(0, -1.);
cbounds.setHigh(0, 1.);
// bounds for brake/gas input
cbounds.setLow(1, -20.);
cbounds.setHigh(1, 20.);
cmanifold->as<oc::RealVectorControlSpace>()->setBounds(cbounds);
oc::SimpleSetup setup(cmanifold);
setup.setStartAndGoalStates(start, goal, 5.);
setup.setStateValidityChecker(boost::bind(
&isStateValid, setup.getSpaceInformation().get(), _1));
setup.setStatePropagator(boost::bind(
&propagate, setup.getSpaceInformation().get(), _1, _2, _3, _4));
setup.getSpaceInformation()->setPropagationStepSize(.1);
setup.getSpaceInformation()->setMinMaxControlDuration(2, 3);
// try to solve the problem
if (setup.solve(30))
{
// print the (approximate) solution path: print states along the path
// and controls required to get from one state to the next
oc::PathControl& path(setup.getSolutionPath());
// print out full state on solution path
// (format: x, y, theta, v, u0, u1, dt)
for(unsigned int i=0; i<path.getStateCount(); ++i)
{
const ob::State* state = path.getState(i);
const ob::SE2StateSpace::StateType *se2 =
state->as<ob::CompoundState>()->as<ob::SE2StateSpace::StateType>(0);
const ob::RealVectorStateSpace::StateType *velocity =
state->as<ob::CompoundState>()->as<ob::RealVectorStateSpace::StateType>(1);
const ob::DiscreteStateSpace::StateType *gear =
state->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2);
std::cout << se2->getX() << ' ' << se2->getY() << ' ' << se2->getYaw()
<< ' ' << velocity->values[0] << ' ' << gear->value << ' ';
if (i==0)
// null controls applied for zero seconds to get to start state
std::cout << "0 0 0";
else
{
// print controls and control duration needed to get from state i-1 to state i
const double* u =
path.getControl(i-1)->as<oc::RealVectorControlSpace::ControlType>()->values;
std::cout << u[0] << ' ' << u[1] << ' ' << path.getControlDuration(i-1);
}
std::cout << std::endl;
}
if (!setup.haveExactSolutionPath())
{
std::cout << "Solution is approximate. Distance to actual goal is " <<
setup.getProblemDefinition()->getSolutionDifference() << std::endl;
}
}
return 0;
}
<commit_msg>fix trivial bug<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* 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 Rice University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Elizabeth Fudge */
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/base/spaces/DiscreteStateSpace.h>
#include <ompl/control/spaces/RealVectorControlSpace.h>
#include <ompl/control/SimpleSetup.h>
#include <ompl/config.h>
#include <iostream>
#include <limits>
#include <boost/math/constants/constants.hpp>
namespace ob = ompl::base;
namespace oc = ompl::control;
void propagate(const oc::SpaceInformation *si, const ob::State *state,
const oc::Control* control, const double duration, ob::State *result)
{
static double timeStep = .01;
static double carLength = 20.;
int nsteps = ceil(duration / timeStep);
double dt = duration / nsteps;
const double *u = control->as<oc::RealVectorControlSpace::ControlType>()->values;
ob::CompoundStateSpace::StateType& s = *result->as<ob::CompoundStateSpace::StateType>();
ob::SE2StateSpace::StateType& se2 = *s.as<ob::SE2StateSpace::StateType>(0);
ob::RealVectorStateSpace::StateType& velocity = *s.as<ob::RealVectorStateSpace::StateType>(1);
ob::DiscreteStateSpace::StateType& gear = *s.as<ob::DiscreteStateSpace::StateType>(2);
si->getStateSpace()->copyState(result, state);
for(int i=0; i<nsteps; i++)
{
se2.setX(se2.getX() + dt * velocity.values[0] * cos(se2.getYaw()));
se2.setY(se2.getY() + dt * velocity.values[0] * sin(se2.getYaw()));
se2.setYaw(se2.getYaw() + dt * u[0]);
velocity.values[0] = velocity.values[0] + dt * (u[1]*gear.value);
// 'guards' - conditions to change gears
if (gear.value > 0)
{
if (gear.value < 3 && velocity.values[0] > 10*(gear.value + 1))
gear.value++;
else if (gear.value > 1 && velocity.values[0] < 10*gear.value)
gear.value--;
}
if (!si->satisfiesBounds(result))
return;
}
}
// The free space consists of two narrow corridors connected at right angle.
// To make the turn, the car will have to downshift.
bool isStateValid(const oc::SpaceInformation *si, const ob::State *state)
{
const ob::SE2StateSpace::StateType *se2 =
state->as<ob::CompoundState>()->as<ob::SE2StateSpace::StateType>(0);
return si->satisfiesBounds(state) && (se2->getX() < -80. || se2->getY() > 80.);
}
int main(int argc, char* argv[])
{
// plan for hybrid car in SE(2) with discrete gears
ob::StateSpacePtr SE2(new ob::SE2StateSpace());
ob::StateSpacePtr velocity(new ob::RealVectorStateSpace(1));
// set the range for gears: [-1,3] inclusive
ob::StateSpacePtr gear(new ob::DiscreteStateSpace(-1,3));
ob::StateSpacePtr stateSpace = SE2 + velocity + gear;
// set the bounds for the R^2 part of SE(2)
ob::RealVectorBounds bounds(2);
bounds.setLow(-100);
bounds.setHigh(100);
SE2->as<ob::SE2StateSpace>()->setBounds(bounds);
// set the bounds for the velocity
ob::RealVectorBounds velocityBound(1);
velocityBound.setLow(0);
velocityBound.setHigh(60);
velocity->as<ob::RealVectorStateSpace>()->setBounds(velocityBound);
// create start and goal states
ob::ScopedState<> start(stateSpace);
ob::ScopedState<> goal(stateSpace);
// Both start and goal are states with high velocity with the car in third gear.
// However, to make the turn, the car cannot stay in third gear and will have to
// shift to first gear.
start[0] = start[1] = -90.; // position
start[2] = boost::math::constants::pi<double>()/2; // orientation
start[3] = 40.; // velocity
start->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2)->value = 3; // gear
goal[0] = goal[1] = 90.; // position
goal[2] = 0.; // orientation
goal[3] = 40.; // velocity
goal->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2)->value = 3; // gear
oc::ControlSpacePtr cmanifold(new oc::RealVectorControlSpace(stateSpace, 2));
// set the bounds for the control manifold
ob::RealVectorBounds cbounds(2);
// bounds for steering input
cbounds.setLow(0, -1.);
cbounds.setHigh(0, 1.);
// bounds for brake/gas input
cbounds.setLow(1, -20.);
cbounds.setHigh(1, 20.);
cmanifold->as<oc::RealVectorControlSpace>()->setBounds(cbounds);
oc::SimpleSetup setup(cmanifold);
setup.setStartAndGoalStates(start, goal, 5.);
setup.setStateValidityChecker(boost::bind(
&isStateValid, setup.getSpaceInformation().get(), _1));
setup.setStatePropagator(boost::bind(
&propagate, setup.getSpaceInformation().get(), _1, _2, _3, _4));
setup.getSpaceInformation()->setPropagationStepSize(.1);
setup.getSpaceInformation()->setMinMaxControlDuration(2, 3);
// try to solve the problem
if (setup.solve(30))
{
// print the (approximate) solution path: print states along the path
// and controls required to get from one state to the next
oc::PathControl& path(setup.getSolutionPath());
// print out full state on solution path
// (format: x, y, theta, v, u0, u1, dt)
for(unsigned int i=0; i<path.getStateCount(); ++i)
{
const ob::State* state = path.getState(i);
const ob::SE2StateSpace::StateType *se2 =
state->as<ob::CompoundState>()->as<ob::SE2StateSpace::StateType>(0);
const ob::RealVectorStateSpace::StateType *velocity =
state->as<ob::CompoundState>()->as<ob::RealVectorStateSpace::StateType>(1);
const ob::DiscreteStateSpace::StateType *gear =
state->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2);
std::cout << se2->getX() << ' ' << se2->getY() << ' ' << se2->getYaw()
<< ' ' << velocity->values[0] << ' ' << gear->value << ' ';
if (i==0)
// null controls applied for zero seconds to get to start state
std::cout << "0 0 0";
else
{
// print controls and control duration needed to get from state i-1 to state i
const double* u =
path.getControl(i-1)->as<oc::RealVectorControlSpace::ControlType>()->values;
std::cout << u[0] << ' ' << u[1] << ' ' << path.getControlDuration(i-1);
}
std::cout << std::endl;
}
if (!setup.haveExactSolutionPath())
{
std::cout << "Solution is approximate. Distance to actual goal is " <<
setup.getProblemDefinition()->getSolutionDifference() << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef MUNCHAR
#define MUNCHAR
#include <cstddef>
namespace Munchar {
// Unconditional success
struct Success {
const char* operator()(const char* b, const char* e) const {
return b;
}
};
// Unconditional failure
struct Failure {
const char* operator()(const char* b, const char* e) const {
return nullptr;
}
};
// Arbitrary character
struct Any_Char {
const char* operator()(const char* b, const char* e) const {
return b != e ? b+1 : nullptr;
}
};
// Character constant
class Char {
const char c_;
public:
constexpr Char(const char c) : c_(c) { }
const char* operator()(const char* b, const char* e) const {
return b != e && *b == c_ ? b+1 : nullptr;
}
};
constexpr Char operator"" _lit(const char c) {
return Char { c };
}
// String constant
template<typename Ptr = const char*>
class Str {
Ptr s_;
size_t len_;
public:
constexpr Str(Ptr s, size_t len) : s_(s), len_(len) { }
const char* operator()(const char* b, const char* e) const {
Ptr s = s_;
for (size_t i = 0; i < len_; ++i, ++b, ++s) {
if ((b == e) || (*s_ != *b)) return nullptr;
}
return b;
}
};
constexpr Str<> operator"" _lit(const char* c, size_t len) {
return Str<> { c, len };
}
// Character class
template<typename Ptr = const char*>
class Char_Class {
Ptr s_;
size_t len_;
public:
constexpr Char_Class(Ptr s, size_t len) : s_(s), len_(len) { }
const char* operator()(const char* b, const char* e) const {
if (b == e) return nullptr;
Ptr s = s_;
for (size_t i = 0; i < len_; ++i, ++s) if (*s == *b) return b+1;
return nullptr;
}
};
constexpr Char_Class<> operator"" _cls(const char* c, size_t len) {
return Char_Class<> { c, len };
}
// Base class for unary combinators
template<typename M>
class Unary {
protected:
const M m_;
public:
constexpr Unary(const M& m) : m_(m) { }
};
// Base class for binary combinators
template<typename L, typename R>
class Binary {
protected:
const L l_;
const R r_;
public:
constexpr Binary(const L& l, const R& r) : l_(l), r_(r) { }
};
// Sequencing
template<typename L, typename R>
class Sequence : public Binary<L, R> {
public:
using Binary<L, R>::Binary;
const char* operator()(const char* b, const char* e) const {
return (b = this->l_(b, e)) ? this->r_(b, e) : nullptr;
}
};
template<typename L, typename R>
constexpr Sequence<L, R> operator^(const L& l, const R& r) {
return Sequence<L, R> { l, r };
}
// Alternation
template<typename L, typename R>
class Alternation : public Binary<L, R> {
public:
using Binary<L, R>::Binary;
const char* operator()(const char* b, const char* e) const {
return (b = this->l_(b, e)) ? b : this->r_(b, e);
}
};
template<typename L, typename R>
constexpr Alternation<L, R> operator|(const L& l, const R& r) {
return Alternation<L, R> { l, r };
}
// Option
template<typename M>
constexpr auto operator~(const M& m)
-> decltype(m | Success { }) {
return m | Success { };
}
// Repetition
template<typename M>
class Zero_Or_More : public Unary<M> {
public:
using Unary<M>::Unary;
const char* operator()(const char* b, const char* e) const {
for (const char* p = b; (p = this->m_(b, e)); b = p) ;
return b;
}
};
template<typename M>
constexpr Zero_Or_More<M> operator*(const M& m) {
return Zero_Or_More<M> { m };
}
template<typename M>
constexpr auto operator+(const M& m)
-> decltype(m ^ *m) {
return m ^ *m;
}
// Bounded repetition
template<typename M>
class Exactly_N_Times : public Unary<M> {
size_t n_;
public:
constexpr Exactly_N_Times(const M& m, size_t n) : Unary<M> { m }, n_(n) { }
const char* operator()(const char* b, const char* e) const {
size_t i;
for (i = 0; i < n_ && (b = this->m_(b, e)); ++i) ;
return i == n_ ? b : nullptr;
}
};
template<typename M>
constexpr Exactly_N_Times<M> operator==(const M& m, size_t n) {
return Exactly_N_Times<M> { m, n };
}
template<typename M>
constexpr auto operator>(const M& m, size_t n)
-> decltype((m == n) ^ +m) {
return (m == n) ^ +m;
}
template<typename M>
constexpr auto operator>=(const M& m, size_t n)
-> decltype((m == n) ^ *m) {
return (m == n) ^ *m;
}
template<typename M>
constexpr auto operator<(const M& m, size_t n)
-> decltype((m == n-1) | *m) {
return (m == n-1) | *m;
}
template<typename M>
constexpr auto operator<=(const M& m, size_t n)
-> decltype((m == n) | *m) {
return (m == n) | *m;
}
template<typename M>
constexpr auto between(size_t a, size_t b, const M& m)
-> decltype((m == a) ^ (m <= b)) {
return (m == a) ^ (m <= b);
}
// Negation
template<typename M>
class Negation : Unary<M> {
public:
using Unary<M>::Unary;
const char* operator()(const char* b, const char* e) const {
return this->m_(b, e) ? nullptr : b;
}
};
template<typename M>
constexpr Negation<M> operator!(const M& m) {
return Negation<M> { m };
}
// Lookahead
template<typename M>
class Lookahead : Unary<M> {
public:
using Unary<M>::Unary;
const char* operator()(const char* b, const char* e) const {
return this->m_(b, e) ? b : nullptr;
}
};
template<typename M>
constexpr Lookahead<M> operator&(const M& m) {
return Lookahead<M> { m };
}
// Predicate
template<typename P>
class Predicate {
const P p_;
public:
constexpr Predicate(const P& p) : p_(p) { }
const char* operator()(const char* b, const char* e) const {
return (b != e) && p_(*b) ? b+1 : nullptr;
}
};
template<typename I, typename O>
class Predicate<O(*)(I)> {
O (*const p_)(I);
public:
constexpr Predicate(O (*const p)(I)) : p_(p) { }
const char* operator()(const char* b, const char* e) const {
return (b != e) && p_(*b) ? b+1 : nullptr;
}
};
template<typename PT>
constexpr Predicate<PT> P(const PT& p) {
return Predicate<PT> { p };
}
template<typename I, typename O>
constexpr Predicate<O(*)(I)> P(O (*const p)(I)) {
return Predicate<O(*)(I)> { p };
}
}
#endif<commit_msg>tweaks<commit_after>#ifndef MUNCHAR
#define MUNCHAR
#include <cstddef>
namespace Munchar {
// Unconditional success
struct Success {
const char* operator()(const char* b, const char* e) const {
return b;
}
};
// Unconditional failure
struct Failure {
const char* operator()(const char* b, const char* e) const {
return nullptr;
}
};
// Arbitrary character
struct Any_Char {
const char* operator()(const char* b, const char* e) const {
return b != e ? b+1 : nullptr;
}
};
// Character constant
class Char {
const char c_;
public:
constexpr Char(const char c) : c_(c) { }
const char* operator()(const char* b, const char* e) const {
return b != e && *b == c_ ? b+1 : nullptr;
}
};
constexpr Char operator"" _lit(const char c) {
return Char { c };
}
// String constant
template<typename Ptr = const char*>
class Str {
Ptr s_;
size_t len_;
public:
constexpr Str(Ptr s, size_t len) : s_(s), len_(len) { }
const char* operator()(const char* b, const char* e) const {
Ptr s = s_;
for (size_t i = 0; i < len_; ++i, ++b, ++s) {
if ((b == e) || (*s_ != *b)) return nullptr;
}
return b;
}
};
constexpr Str<> operator"" _lit(const char* c, size_t len) {
return Str<> { c, len };
}
// Character class
template<typename Ptr = const char*>
class Char_Class {
Ptr s_;
size_t len_;
public:
constexpr Char_Class(Ptr s, size_t len) : s_(s), len_(len) { }
const char* operator()(const char* b, const char* e) const {
if (b == e) return nullptr;
Ptr s = s_;
for (size_t i = 0; i < len_; ++i, ++s) if (*s == *b) return b+1;
return nullptr;
}
};
constexpr Char_Class<> operator"" _cls(const char* c, size_t len) {
return Char_Class<> { c, len };
}
// Base class for unary combinators
template<typename M>
class Unary {
protected:
const M m_;
public:
constexpr Unary(const M& m) : m_(m) { }
};
// Base class for binary combinators
template<typename L, typename R>
class Binary {
protected:
const L l_;
const R r_;
public:
constexpr Binary(const L& l, const R& r) : l_(l), r_(r) { }
};
// Sequencing
template<typename L, typename R>
class Sequence : public Binary<L, R> {
public:
using Binary<L, R>::Binary;
const char* operator()(const char* b, const char* e) const {
return (b = this->l_(b, e)) ? this->r_(b, e) : nullptr;
}
};
template<typename L, typename R>
constexpr Sequence<L, R> operator^(const L& l, const R& r) {
return Sequence<L, R> { l, r };
}
// Alternation
template<typename L, typename R>
class Alternation : public Binary<L, R> {
public:
using Binary<L, R>::Binary;
const char* operator()(const char* b, const char* e) const {
return (b = this->l_(b, e)) ? b : this->r_(b, e);
}
};
template<typename L, typename R>
constexpr Alternation<L, R> operator|(const L& l, const R& r) {
return Alternation<L, R> { l, r };
}
// Option
template<typename M>
constexpr auto operator~(const M& m)
-> decltype(m | Success { }) {
return m | Success { };
}
// Repetition
template<typename M>
class Zero_Or_More : public Unary<M> {
public:
using Unary<M>::Unary;
const char* operator()(const char* b, const char* e) const {
for (const char* p = b; (p = this->m_(b, e)); b = p) ;
return b;
}
};
template<typename M>
constexpr Zero_Or_More<M> operator*(const M& m) {
return Zero_Or_More<M> { m };
}
template<typename M>
constexpr auto operator+(const M& m)
-> decltype(m ^ *m) {
return m ^ *m;
}
// Bounded repetition
template<typename M>
class Exactly_N_Times : public Unary<M> {
size_t n_;
public:
constexpr Exactly_N_Times(const M& m, size_t n) : Unary<M> { m }, n_(n) { }
const char* operator()(const char* b, const char* e) const {
size_t i;
for (i = 0; i < n_ && (b = this->m_(b, e)); ++i) ;
return i == n_ ? b : nullptr;
}
};
template<typename M>
constexpr Exactly_N_Times<M> operator==(const M& m, size_t n) {
return Exactly_N_Times<M> { m, n };
}
template<typename M>
constexpr auto operator>(const M& m, size_t n)
-> decltype((m == n) ^ +m) {
return (m == n) ^ +m;
}
template<typename M>
constexpr auto operator>=(const M& m, size_t n)
-> decltype((m == n) ^ *m) {
return (m == n) ^ *m;
}
template<typename M>
constexpr auto operator<(const M& m, size_t n)
-> decltype((m == n-1) | *m) {
return (m == n-1) | *m;
}
template<typename M>
constexpr auto operator<=(const M& m, size_t n)
-> decltype((m == n) | *m) {
return (m == n) | *m;
}
template<typename M>
constexpr auto between(size_t a, size_t b, const M& m)
-> decltype((m == a) ^ (m <= b)) {
return (m == a) ^ (m <= b);
}
// Negation
template<typename M>
class Negation : Unary<M> {
public:
using Unary<M>::Unary;
const char* operator()(const char* b, const char* e) const {
return this->m_(b, e) ? nullptr : b;
}
};
template<typename M>
constexpr Negation<M> operator!(const M& m) {
return Negation<M> { m };
}
// Lookahead
template<typename M>
class Lookahead : Unary<M> {
public:
using Unary<M>::Unary;
const char* operator()(const char* b, const char* e) const {
return this->m_(b, e) ? b : nullptr;
}
};
template<typename M>
constexpr Lookahead<M> operator&(const M& m) {
return Lookahead<M> { m };
}
// Predicate
template<typename P>
class Predicate {
const P p_;
public:
constexpr Predicate(const P& p) : p_(p) { }
const char* operator()(const char* b, const char* e) const {
return (b != e) && p_(*b) ? b+1 : nullptr;
}
};
template<typename I, typename O>
class Predicate<O (*)(I)> {
O (*const p_)(I);
public:
constexpr Predicate(O (*const p)(I)) : p_(p) { }
const char* operator()(const char* b, const char* e) const {
return (b != e) && p_(*b) ? b+1 : nullptr;
}
};
template<typename PT>
constexpr Predicate<PT> P(const PT& p) {
return Predicate<PT> { p };
}
template<typename I, typename O>
constexpr Predicate<O (*)(I)> P(O (*const p)(I)) {
return Predicate<O (*)(I)> { p };
}
}
#endif<|endoftext|>
|
<commit_before>// 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 __PROCESS_WINDOWS_SUBPROCESS_HPP__
#define __PROCESS_WINDOWS_SUBPROCESS_HPP__
#include <signal.h>
#include <string>
#include <glog/logging.h>
#include <process/subprocess.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/hashset.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/os/close.hpp>
#include <stout/os/environment.hpp>
#include <userEnv.h>
namespace process {
using InputFileDescriptors = Subprocess::IO::InputFileDescriptors;
using OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;
namespace internal {
inline void close(const hashset<HANDLE>& fds)
{
foreach (HANDLE fd, fds) {
if (fd != INVALID_HANDLE_VALUE) {
os::close(fd);
}
}
}
// This function will invoke `os::close` on all specified file
// descriptors that are valid (i.e., not `None` and >= 0).
inline void close(
const InputFileDescriptors& stdinfds,
const OutputFileDescriptors& stdoutfds,
const OutputFileDescriptors& stderrfds)
{
close({
stdinfds.read,
stdinfds.write.getOrElse(INVALID_HANDLE_VALUE),
stdoutfds.read.getOrElse(INVALID_HANDLE_VALUE),
stdoutfds.write,
stderrfds.read.getOrElse(INVALID_HANDLE_VALUE),
stderrfds.write
});
}
// Retrieves system environment in a `std::map`, ignoring
// the current process's environment variables.
inline Option<map<string, string>> getSystemEnvironment()
{
std::wstring_convert<std::codecvt<wchar_t, char, mbstate_t>,
wchar_t> converter;
map<string, string> systemEnvironment;
wchar_t* environmentEntry = nullptr;
// Get the system environment.
// The third parameter (bool) tells the function *not* to inherit
// variables from the current process.
if (!CreateEnvironmentBlock((LPVOID*)&environmentEntry, nullptr, FALSE)) {
return None();
}
// Save the environment block in order to destroy it later.
wchar_t* environmentBlock = environmentEntry;
while (*environmentEntry != L'\0') {
// Each environment block contains the environment variables as follows:
// Var1=Value1\0
// Var2=Value2\0
// Var3=Value3\0
// ...
// VarN=ValueN\0\0
// The name of an environment variable cannot include an equal sign (=).
wchar_t * separator = wcschr(environmentEntry, L'=');
std::wstring varName = std::wstring(environmentEntry, separator);
std::wstring varVal = std::wstring(separator + 1);
// Mesos variables are upper case. Convert system variables to
// match the name provided by the scheduler in case of a collision.
std::transform(varName.begin(), varName.end(), varName.begin(), ::towupper);
// The system environment has priority. Force `ANSI` usage until the code
// is converted to UNICODE.
systemEnvironment.insert_or_assign(
converter.to_bytes(varName.c_str()),
converter.to_bytes(varVal.c_str()));
environmentEntry += varName.length() + varVal.length() + 2;
}
DestroyEnvironmentBlock(environmentBlock);
return systemEnvironment;
}
// Creates a null-terminated array of null-terminated strings that will be
// passed to `CreateProcess` as the `lpEnvironment` argument, as described by
// MSDN[1]. This array needs to be sorted in alphabetical order, but the `map`
// already takes care of that. Note that this function does not handle Unicode
// environments, so it should not be used in conjunction with the
// `CREATE_UNICODE_ENVIRONMENT` flag.
//
// NOTE: This function will add the system's environment variables into
// the returned string. These variables take precedence over the provided
// `env` and are generally necessary in order to launch things on Windows.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
inline Option<string> createProcessEnvironment(
const Option<map<string, string>>& env)
{
if (env.isNone() || (env.isSome() && env.get().size() == 0)) {
return None();
}
Option<map<string, string>> systemEnvironment = getSystemEnvironment();
// The system environment must be non-empty.
// No subprocesses will be able to launch if the system environment is blank.
CHECK(systemEnvironment.isSome() && systemEnvironment.get().size() > 0);
map<string, string> combinedEnvironment = env.get();
foreachpair(const string& key, const string& value, systemEnvironment.get()) {
combinedEnvironment[key] = value;
}
string environmentString;
foreachpair (const string& key, const string& value, combinedEnvironment) {
environmentString += key + '=' + value + '\0';
}
return environmentString;
}
inline Try<PROCESS_INFORMATION> createChildProcess(
const string& path,
const vector<string>& argv,
const Option<map<string, string>>& environment,
const InputFileDescriptors stdinfds,
const OutputFileDescriptors stdoutfds,
const OutputFileDescriptors stderrfds)
{
// Construct the environment that will be passed to `CreateProcess`.
Option<string> environmentString = createProcessEnvironment(environment);
const char* processEnvironment = environmentString.isNone()
? nullptr
: environmentString.get().c_str();
PROCESS_INFORMATION processInfo;
STARTUPINFO startupInfo;
::ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));
::ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
// Hook up the `stdin`/`stdout`/`stderr` pipes and use the
// `STARTF_USESTDHANDLES` flag to instruct the child to use them[1]. A more
// user-friendly example can be found in [2].
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx
// [2] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
startupInfo.cb = sizeof(STARTUPINFO);
startupInfo.hStdInput = stdinfds.read;
startupInfo.hStdOutput = stdoutfds.write;
startupInfo.hStdError = stderrfds.write;
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
// Build command to pass to `::CreateProcess`.
//
// NOTE: We are expecting that components of `argv` that need to be quoted
// (for example, paths with spaces in them like `C:\"Program Files"\foo.exe`)
// to have been already quoted correctly before we generate `command`.
// Incorrectly-quoted command arguments will probably lead the child process
// to terminate with an error. See also NOTE on `process::subprocess`.
string command = strings::join(" ", argv);
// Escape the quotes in `command`.
//
// TODO(dpravat): Add tests cases that cover this functionality. See
// MESOS-5418.
command = strings::replace(command, "\"", "\\\"");
// NOTE: If Mesos is built against the ANSI version of this function, the
// environment is limited to 32,767 characters. See[1].
//
// TODO(hausdorff): Figure out how to map the `path` and `args` arguments of
// this function into a call to `::CreateProcess` that is more general
// purpose. In particular, on POSIX, we expect that calls to `subprocess` can
// be called with relative `path` (e.g., it could simply be `sh`). However,
// on Windows, unlike the calls to (e.g.) `exec`, `::CreateProcess` will
// expect that this argument be a fully-qualified path. In the end, we'd like
// the calls to `subprocess` to have similar command formats to minimize
// confusion and mistakes.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
BOOL createProcessResult = CreateProcess(
nullptr,
(LPSTR)command.data(),
nullptr, // Default security attributes.
nullptr, // Default primary thread security attributes.
TRUE, // Inherited parent process handles.
0, // Normal thread priority.
(LPVOID)processEnvironment,
nullptr, // Use parent's current directory.
&startupInfo, // STARTUPINFO pointer.
&processInfo); // PROCESS_INFORMATION pointer.
if (!createProcessResult) {
return WindowsError("createChildProcess: failed to call 'CreateProcess'");
}
return processInfo;
}
} // namespace internal {
} // namespace process {
#endif // __PROCESS_WINDOWS_SUBPROCESS_HPP__
<commit_msg>Windows: Qualified string, map, and vector in `subprocess.hpp`.<commit_after>// 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 __PROCESS_WINDOWS_SUBPROCESS_HPP__
#define __PROCESS_WINDOWS_SUBPROCESS_HPP__
#include <signal.h>
#include <string>
#include <glog/logging.h>
#include <process/subprocess.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/hashset.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/os/close.hpp>
#include <stout/os/environment.hpp>
#include <userEnv.h>
namespace process {
using InputFileDescriptors = Subprocess::IO::InputFileDescriptors;
using OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;
namespace internal {
inline void close(const hashset<HANDLE>& fds)
{
foreach (HANDLE fd, fds) {
if (fd != INVALID_HANDLE_VALUE) {
os::close(fd);
}
}
}
// This function will invoke `os::close` on all specified file
// descriptors that are valid (i.e., not `None` and >= 0).
inline void close(
const InputFileDescriptors& stdinfds,
const OutputFileDescriptors& stdoutfds,
const OutputFileDescriptors& stderrfds)
{
close({
stdinfds.read,
stdinfds.write.getOrElse(INVALID_HANDLE_VALUE),
stdoutfds.read.getOrElse(INVALID_HANDLE_VALUE),
stdoutfds.write,
stderrfds.read.getOrElse(INVALID_HANDLE_VALUE),
stderrfds.write
});
}
// Retrieves system environment in a `std::map`, ignoring
// the current process's environment variables.
inline Option<std::map<std::string, std::string>> getSystemEnvironment()
{
std::wstring_convert<std::codecvt<wchar_t, char, mbstate_t>,
wchar_t> converter;
std::map<std::string, std::string> systemEnvironment;
wchar_t* environmentEntry = nullptr;
// Get the system environment.
// The third parameter (bool) tells the function *not* to inherit
// variables from the current process.
if (!CreateEnvironmentBlock((LPVOID*)&environmentEntry, nullptr, FALSE)) {
return None();
}
// Save the environment block in order to destroy it later.
wchar_t* environmentBlock = environmentEntry;
while (*environmentEntry != L'\0') {
// Each environment block contains the environment variables as follows:
// Var1=Value1\0
// Var2=Value2\0
// Var3=Value3\0
// ...
// VarN=ValueN\0\0
// The name of an environment variable cannot include an equal sign (=).
wchar_t * separator = wcschr(environmentEntry, L'=');
std::wstring varName = std::wstring(environmentEntry, separator);
std::wstring varVal = std::wstring(separator + 1);
// Mesos variables are upper case. Convert system variables to
// match the name provided by the scheduler in case of a collision.
std::transform(varName.begin(), varName.end(), varName.begin(), ::towupper);
// The system environment has priority. Force `ANSI` usage until the code
// is converted to UNICODE.
systemEnvironment.insert_or_assign(
converter.to_bytes(varName.c_str()),
converter.to_bytes(varVal.c_str()));
environmentEntry += varName.length() + varVal.length() + 2;
}
DestroyEnvironmentBlock(environmentBlock);
return systemEnvironment;
}
// Creates a null-terminated array of null-terminated strings that will be
// passed to `CreateProcess` as the `lpEnvironment` argument, as described by
// MSDN[1]. This array needs to be sorted in alphabetical order, but the `map`
// already takes care of that. Note that this function does not handle Unicode
// environments, so it should not be used in conjunction with the
// `CREATE_UNICODE_ENVIRONMENT` flag.
//
// NOTE: This function will add the system's environment variables into
// the returned string. These variables take precedence over the provided
// `env` and are generally necessary in order to launch things on Windows.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
inline Option<std::string> createProcessEnvironment(
const Option<std::map<std::string, std::string>>& env)
{
if (env.isNone() || (env.isSome() && env.get().size() == 0)) {
return None();
}
Option<std::map<std::string, std::string>> systemEnvironment =
getSystemEnvironment();
// The system environment must be non-empty.
// No subprocesses will be able to launch if the system environment is blank.
CHECK(systemEnvironment.isSome() && systemEnvironment.get().size() > 0);
std::map<std::string, std::string> combinedEnvironment = env.get();
foreachpair (const std::string& key,
const std::string& value,
systemEnvironment.get()) {
combinedEnvironment[key] = value;
}
std::string environmentString;
foreachpair (const std::string& key,
const std::string& value,
combinedEnvironment) {
environmentString += key + '=' + value + '\0';
}
return environmentString;
}
inline Try<PROCESS_INFORMATION> createChildProcess(
const std::string& path,
const std::vector<std::string>& argv,
const Option<std::map<std::string, std::string>>& environment,
const InputFileDescriptors stdinfds,
const OutputFileDescriptors stdoutfds,
const OutputFileDescriptors stderrfds)
{
// Construct the environment that will be passed to `CreateProcess`.
Option<std::string> environmentString = createProcessEnvironment(environment);
const char* processEnvironment = environmentString.isNone()
? nullptr
: environmentString.get().c_str();
PROCESS_INFORMATION processInfo;
STARTUPINFO startupInfo;
::ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));
::ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
// Hook up the `stdin`/`stdout`/`stderr` pipes and use the
// `STARTF_USESTDHANDLES` flag to instruct the child to use them[1]. A more
// user-friendly example can be found in [2].
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx
// [2] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
startupInfo.cb = sizeof(STARTUPINFO);
startupInfo.hStdInput = stdinfds.read;
startupInfo.hStdOutput = stdoutfds.write;
startupInfo.hStdError = stderrfds.write;
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
// Build command to pass to `::CreateProcess`.
//
// NOTE: We are expecting that components of `argv` that need to be quoted
// (for example, paths with spaces in them like `C:\"Program Files"\foo.exe`)
// to have been already quoted correctly before we generate `command`.
// Incorrectly-quoted command arguments will probably lead the child process
// to terminate with an error. See also NOTE on `process::subprocess`.
std::string command = strings::join(" ", argv);
// Escape the quotes in `command`.
//
// TODO(dpravat): Add tests cases that cover this functionality. See
// MESOS-5418.
command = strings::replace(command, "\"", "\\\"");
// NOTE: If Mesos is built against the ANSI version of this function, the
// environment is limited to 32,767 characters. See[1].
//
// TODO(hausdorff): Figure out how to map the `path` and `args` arguments of
// this function into a call to `::CreateProcess` that is more general
// purpose. In particular, on POSIX, we expect that calls to `subprocess` can
// be called with relative `path` (e.g., it could simply be `sh`). However,
// on Windows, unlike the calls to (e.g.) `exec`, `::CreateProcess` will
// expect that this argument be a fully-qualified path. In the end, we'd like
// the calls to `subprocess` to have similar command formats to minimize
// confusion and mistakes.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
BOOL createProcessResult = CreateProcess(
nullptr,
(LPSTR)command.data(),
nullptr, // Default security attributes.
nullptr, // Default primary thread security attributes.
TRUE, // Inherited parent process handles.
0, // Normal thread priority.
(LPVOID)processEnvironment,
nullptr, // Use parent's current directory.
&startupInfo, // STARTUPINFO pointer.
&processInfo); // PROCESS_INFORMATION pointer.
if (!createProcessResult) {
return WindowsError("createChildProcess: failed to call 'CreateProcess'");
}
return processInfo;
}
} // namespace internal {
} // namespace process {
#endif // __PROCESS_WINDOWS_SUBPROCESS_HPP__
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlgname.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:18:08 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#include <tools/ref.hxx>
#include <tools/list.hxx>
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#include "dialogs.hrc"
#include "dlgname.hxx"
#include "defdlgname.hxx" //CHINA001
#include "dlgname.hrc"
#include "dialmgr.hxx"
#define MAX_DESCRIPTION_LINES ((long)5)
/*************************************************************************
|*
|* Dialog zum Editieren eines Namens
|*
\************************************************************************/
SvxNameDialog::SvxNameDialog( Window* pWindow, const String& rName, const String& rDesc ) :
ModalDialog ( pWindow, ResId( RID_SVXDLG_NAME, DIALOG_MGR() ) ),
aFtDescription ( this, ResId( FT_DESCRIPTION ) ),
aEdtName ( this, ResId( EDT_STRING ) ),
aBtnOK ( this, ResId( BTN_OK ) ),
aBtnCancel ( this, ResId( BTN_CANCEL ) ),
aBtnHelp ( this, ResId( BTN_HELP ) )
{
FreeResource();
aFtDescription.SetText( rDesc );
aEdtName.SetText( rName );
aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX));
ModifyHdl(&aEdtName);
aEdtName.SetModifyHdl(LINK(this, SvxNameDialog, ModifyHdl));
// dynamic height of the description field
Size aSize = aFtDescription.GetSizePixel();
long nTxtWidth = aFtDescription.GetCtrlTextWidth( rDesc );
if ( nTxtWidth > aSize.Width() )
{
long nLines = Min( ( nTxtWidth / aSize.Width() + 1 ), MAX_DESCRIPTION_LINES );
long nHeight = aSize.Height();
aSize.Height() = nHeight * nLines;
aFtDescription.SetSizePixel( aSize );
Point aPnt = aEdtName.GetPosPixel();
aPnt.Y() += ( aSize.Height() - nHeight );
aEdtName.SetPosPixel( aPnt );
}
}
/* -----------------------------27.02.2002 15:22------------------------------
---------------------------------------------------------------------------*/
IMPL_LINK(SvxNameDialog, ModifyHdl, Edit*, EMPTYARG)
{
if(aCheckNameHdl.IsSet())
aBtnOK.Enable(aCheckNameHdl.Call(this) > 0);
return 0;
}
/*************************************************************************
|*
|* Dialog zum Abbrechen, Speichern oder Hinzufuegen
|*
\************************************************************************/
SvxMessDialog::SvxMessDialog( Window* pWindow, const String& rText, const String& rDesc, Image* pImg ) :
ModalDialog ( pWindow, ResId( RID_SVXDLG_MESSBOX, DIALOG_MGR() ) ),
aFtDescription ( this, ResId( FT_DESCRIPTION ) ),
aBtn1 ( this, ResId( BTN_1 ) ),
aBtn2 ( this, ResId( BTN_2 ) ),
aBtnCancel ( this, ResId( BTN_CANCEL ) ),
aFtImage ( this )
{
FreeResource();
if( pImg )
{
pImage = new Image( *pImg );
aFtImage.SetImage( *pImage );
aFtImage.SetStyle( ( aFtImage.GetStyle()/* | WB_NOTABSTOP */) & ~WB_3DLOOK );
aFtImage.SetPosSizePixel( LogicToPixel( Point( 3, 6 ), MAP_APPFONT ),
aFtImage.GetImage().GetSizePixel() );
aFtImage.Show();
}
SetText( rText );
aFtDescription.SetText( rDesc );
aBtn1.SetClickHdl( LINK( this, SvxMessDialog, Button1Hdl ) );
aBtn2.SetClickHdl( LINK( this, SvxMessDialog, Button2Hdl ) );
}
SvxMessDialog::~SvxMessDialog()
{
if( pImage )
delete pImage;
}
/*************************************************************************/
IMPL_LINK_INLINE_START( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )
{
EndDialog( RET_BTN_1 );
return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )
/*************************************************************************/
IMPL_LINK_INLINE_START( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )
{
EndDialog( RET_BTN_2 );
return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )
/*************************************************************************/
void SvxMessDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt )
{
switch ( nBtnId )
{
case MESS_BTN_1:
aBtn1.SetText( rNewTxt );
break;
case MESS_BTN_2:
aBtn2.SetText( rNewTxt );
break;
default:
DBG_ERROR( "Falsche Button-Nummer!!!" );
}
}
<commit_msg>INTEGRATION: CWS aw038 (1.9.150); FILE MERGED 2006/12/06 15:53:59 aw 1.9.150.3: #i68101# adapted dialogs for ObjectName and ObjectTitleDescription 2006/12/05 10:33:58 aw 1.9.150.2: #i68101# 2nd version of dialogs 2006/12/01 17:43:06 aw 1.9.150.1: #i68101# SdrObject core support for Title, Description added, support for Name reworked. UNO API support for Title Description added as xShape property. Rudimentary created new NameTitleDesc dialog<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlgname.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: ihi $ $Date: 2006-12-19 17:45:38 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#include <tools/ref.hxx>
#include <tools/list.hxx>
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#include "dialogs.hrc"
#include "dlgname.hxx"
#include "defdlgname.hxx" //CHINA001
#include "dlgname.hrc"
#include "dialmgr.hxx"
#define MAX_DESCRIPTION_LINES ((long)5)
/*************************************************************************
|*
|* Dialog zum Editieren eines Namens
|*
\************************************************************************/
SvxNameDialog::SvxNameDialog( Window* pWindow, const String& rName, const String& rDesc ) :
ModalDialog ( pWindow, ResId( RID_SVXDLG_NAME, DIALOG_MGR() ) ),
aFtDescription ( this, ResId( FT_DESCRIPTION ) ),
aEdtName ( this, ResId( EDT_STRING ) ),
aBtnOK ( this, ResId( BTN_OK ) ),
aBtnCancel ( this, ResId( BTN_CANCEL ) ),
aBtnHelp ( this, ResId( BTN_HELP ) )
{
FreeResource();
aFtDescription.SetText( rDesc );
aEdtName.SetText( rName );
aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX));
ModifyHdl(&aEdtName);
aEdtName.SetModifyHdl(LINK(this, SvxNameDialog, ModifyHdl));
// dynamic height of the description field
Size aSize = aFtDescription.GetSizePixel();
long nTxtWidth = aFtDescription.GetCtrlTextWidth( rDesc );
if ( nTxtWidth > aSize.Width() )
{
long nLines = Min( ( nTxtWidth / aSize.Width() + 1 ), MAX_DESCRIPTION_LINES );
long nHeight = aSize.Height();
aSize.Height() = nHeight * nLines;
aFtDescription.SetSizePixel( aSize );
Point aPnt = aEdtName.GetPosPixel();
aPnt.Y() += ( aSize.Height() - nHeight );
aEdtName.SetPosPixel( aPnt );
}
}
/* -----------------------------27.02.2002 15:22------------------------------
---------------------------------------------------------------------------*/
IMPL_LINK(SvxNameDialog, ModifyHdl, Edit*, EMPTYARG)
{
if(aCheckNameHdl.IsSet())
aBtnOK.Enable(aCheckNameHdl.Call(this) > 0);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// #i68101#
// Dialog for editing Object Name
// plus uniqueness-callback-linkHandler
SvxObjectNameDialog::SvxObjectNameDialog(
Window* pWindow,
const String& rName)
: ModalDialog(pWindow, ResId(RID_SVXDLG_OBJECT_NAME, DIALOG_MGR())),
aFtName(this, ResId(NTD_FT_NAME)),
aEdtName(this, ResId(NTD_EDT_NAME)),
aFlSeparator(this, ResId(FL_SEPARATOR_A)),
aBtnHelp(this, ResId(BTN_HELP)),
aBtnOK(this, ResId(BTN_OK)),
aBtnCancel(this, ResId(BTN_CANCEL))
{
FreeResource();
// set name
aEdtName.SetText(rName);
// activate name
aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX));
ModifyHdl(&aEdtName);
aEdtName.SetModifyHdl(LINK(this, SvxObjectNameDialog, ModifyHdl));
}
IMPL_LINK(SvxObjectNameDialog, ModifyHdl, Edit*, EMPTYARG)
{
if(aCheckNameHdl.IsSet())
{
aBtnOK.Enable(aCheckNameHdl.Call(this) > 0);
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// #i68101#
// Dialog for editing Object Title and Description
SvxObjectTitleDescDialog::SvxObjectTitleDescDialog(
Window* pWindow,
const String& rTitle,
const String& rDescription)
: ModalDialog(pWindow, ResId(RID_SVXDLG_OBJECT_TITLE_DESC, DIALOG_MGR())),
aFtTitle(this, ResId(NTD_FT_TITLE)),
aEdtTitle(this, ResId(NTD_EDT_TITLE)),
aFtDescription(this, ResId(NTD_FT_DESC)),
aEdtDescription(this, ResId(NTD_EDT_DESC)),
aFlSeparator(this, ResId(FL_SEPARATOR_B)),
aBtnHelp(this, ResId(BTN_HELP)),
aBtnOK(this, ResId(BTN_OK)),
aBtnCancel(this, ResId(BTN_CANCEL))
{
FreeResource();
// set title & desc
aEdtTitle.SetText(rTitle);
aEdtDescription.SetText(rDescription);
// activate title
aEdtTitle.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX));
}
///////////////////////////////////////////////////////////////////////////////////////////////
/*************************************************************************
|*
|* Dialog zum Abbrechen, Speichern oder Hinzufuegen
|*
\************************************************************************/
SvxMessDialog::SvxMessDialog( Window* pWindow, const String& rText, const String& rDesc, Image* pImg ) :
ModalDialog ( pWindow, ResId( RID_SVXDLG_MESSBOX, DIALOG_MGR() ) ),
aFtDescription ( this, ResId( FT_DESCRIPTION ) ),
aBtn1 ( this, ResId( BTN_1 ) ),
aBtn2 ( this, ResId( BTN_2 ) ),
aBtnCancel ( this, ResId( BTN_CANCEL ) ),
aFtImage ( this )
{
FreeResource();
if( pImg )
{
pImage = new Image( *pImg );
aFtImage.SetImage( *pImage );
aFtImage.SetStyle( ( aFtImage.GetStyle()/* | WB_NOTABSTOP */) & ~WB_3DLOOK );
aFtImage.SetPosSizePixel( LogicToPixel( Point( 3, 6 ), MAP_APPFONT ),
aFtImage.GetImage().GetSizePixel() );
aFtImage.Show();
}
SetText( rText );
aFtDescription.SetText( rDesc );
aBtn1.SetClickHdl( LINK( this, SvxMessDialog, Button1Hdl ) );
aBtn2.SetClickHdl( LINK( this, SvxMessDialog, Button2Hdl ) );
}
SvxMessDialog::~SvxMessDialog()
{
if( pImage )
delete pImage;
}
/*************************************************************************/
IMPL_LINK_INLINE_START( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )
{
EndDialog( RET_BTN_1 );
return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )
/*************************************************************************/
IMPL_LINK_INLINE_START( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )
{
EndDialog( RET_BTN_2 );
return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )
/*************************************************************************/
void SvxMessDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt )
{
switch ( nBtnId )
{
case MESS_BTN_1:
aBtn1.SetText( rNewTxt );
break;
case MESS_BTN_2:
aBtn2.SetText( rNewTxt );
break;
default:
DBG_ERROR( "Falsche Button-Nummer!!!" );
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <iostream>
#include "mutation_partition.hh"
#include "keys.hh"
#include "schema.hh"
#include "dht/i_partitioner.hh"
class mutation final {
private:
schema_ptr _schema;
dht::decorated_key _dk;
mutation_partition _p;
public:
mutation(dht::decorated_key key, schema_ptr schema);
mutation(partition_key key, schema_ptr schema);
mutation(schema_ptr schema, dht::decorated_key key, mutation_partition mp);
mutation(mutation&&) = default;
mutation(const mutation&) = default;
mutation& operator=(mutation&& x) = default;
void set_static_cell(const column_definition& def, atomic_cell_or_collection value);
void set_static_cell(const bytes& name, const boost::any& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection value);
void set_clustered_cell(const clustering_key& key, const bytes& name, const boost::any& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection value);
void set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const boost::any& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection value);
std::experimental::optional<atomic_cell_or_collection> get_cell(const clustering_key& rkey, const column_definition& def) const;
const partition_key& key() const { return _dk._key; };
const dht::decorated_key& decorated_key() const { return _dk; };
const dht::token token() const { return _dk._token; }
const schema_ptr& schema() const { return _schema; }
const mutation_partition& partition() const { return _p; }
mutation_partition& partition() { return _p; }
const utils::UUID& column_family_id() const { return _schema->id(); }
bool operator==(const mutation&) const;
bool operator!=(const mutation&) const;
public:
query::result query(const query::partition_slice&, gc_clock::time_point now = gc_clock::now(), uint32_t row_limit = query::max_rows) const;
// See mutation_partition::live_row_count()
size_t live_row_count(gc_clock::time_point query_time = gc_clock::time_point::min()) const;
private:
friend std::ostream& operator<<(std::ostream& os, const mutation& m);
};
struct mutation_decorated_key_less_comparator {
bool operator()(const mutation& m1, const mutation& m2) const;
};
using mutation_opt = std::experimental::optional<mutation>;
inline
void apply(mutation_opt& dst, mutation&& src) {
if (!dst) {
dst = std::move(src);
} else {
dst->partition().apply(*src.schema(), src.partition());
}
}
inline
void apply(mutation_opt& dst, mutation_opt&& src) {
if (src) {
apply(dst, std::move(*src));
}
}
// Returns a range into partitions containing mutations covered by the range.
// partitions must be sorted according to decorated key.
// range must not wrap around.
boost::iterator_range<std::vector<mutation>::const_iterator> slice(
const std::vector<mutation>& partitions,
const query::partition_range&);
<commit_msg>mutation: Fix token() getter<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <iostream>
#include "mutation_partition.hh"
#include "keys.hh"
#include "schema.hh"
#include "dht/i_partitioner.hh"
class mutation final {
private:
schema_ptr _schema;
dht::decorated_key _dk;
mutation_partition _p;
public:
mutation(dht::decorated_key key, schema_ptr schema);
mutation(partition_key key, schema_ptr schema);
mutation(schema_ptr schema, dht::decorated_key key, mutation_partition mp);
mutation(mutation&&) = default;
mutation(const mutation&) = default;
mutation& operator=(mutation&& x) = default;
void set_static_cell(const column_definition& def, atomic_cell_or_collection value);
void set_static_cell(const bytes& name, const boost::any& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection value);
void set_clustered_cell(const clustering_key& key, const bytes& name, const boost::any& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection value);
void set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const boost::any& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection value);
std::experimental::optional<atomic_cell_or_collection> get_cell(const clustering_key& rkey, const column_definition& def) const;
const partition_key& key() const { return _dk._key; };
const dht::decorated_key& decorated_key() const { return _dk; };
const dht::token& token() const { return _dk._token; }
const schema_ptr& schema() const { return _schema; }
const mutation_partition& partition() const { return _p; }
mutation_partition& partition() { return _p; }
const utils::UUID& column_family_id() const { return _schema->id(); }
bool operator==(const mutation&) const;
bool operator!=(const mutation&) const;
public:
query::result query(const query::partition_slice&, gc_clock::time_point now = gc_clock::now(), uint32_t row_limit = query::max_rows) const;
// See mutation_partition::live_row_count()
size_t live_row_count(gc_clock::time_point query_time = gc_clock::time_point::min()) const;
private:
friend std::ostream& operator<<(std::ostream& os, const mutation& m);
};
struct mutation_decorated_key_less_comparator {
bool operator()(const mutation& m1, const mutation& m2) const;
};
using mutation_opt = std::experimental::optional<mutation>;
inline
void apply(mutation_opt& dst, mutation&& src) {
if (!dst) {
dst = std::move(src);
} else {
dst->partition().apply(*src.schema(), src.partition());
}
}
inline
void apply(mutation_opt& dst, mutation_opt&& src) {
if (src) {
apply(dst, std::move(*src));
}
}
// Returns a range into partitions containing mutations covered by the range.
// partitions must be sorted according to decorated key.
// range must not wrap around.
boost::iterator_range<std::vector<mutation>::const_iterator> slice(
const std::vector<mutation>& partitions,
const query::partition_range&);
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
/*
* 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 <iostream>
#include "mutation_partition.hh"
#include "keys.hh"
#include "schema.hh"
#include "dht/i_partitioner.hh"
class mutation final {
private:
struct data {
schema_ptr _schema;
dht::decorated_key _dk;
mutation_partition _p;
data(dht::decorated_key&& key, schema_ptr&& schema);
data(partition_key&& key, schema_ptr&& schema);
data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp);
data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp);
};
std::unique_ptr<data> _ptr;
private:
mutation() = default;
public:
mutation(dht::decorated_key key, schema_ptr schema)
: _ptr(std::make_unique<data>(std::move(key), std::move(schema)))
{ }
mutation(partition_key key_, schema_ptr schema)
: _ptr(std::make_unique<data>(std::move(key_), std::move(schema)))
{ }
mutation(schema_ptr schema, dht::decorated_key key, const mutation_partition& mp)
: _ptr(std::make_unique<data>(std::move(schema), std::move(key), mp))
{ }
mutation(schema_ptr schema, dht::decorated_key key, mutation_partition&& mp)
: _ptr(std::make_unique<data>(std::move(schema), std::move(key), std::move(mp)))
{ }
mutation(const mutation& m)
: _ptr(std::make_unique<data>(schema_ptr(m.schema()), dht::decorated_key(m.decorated_key()), m.partition()))
{ }
mutation(mutation&&) = default;
mutation& operator=(mutation&& x) = default;
void set_static_cell(const column_definition& def, atomic_cell_or_collection&& value);
void set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value);
void set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value);
void set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value);
std::experimental::optional<atomic_cell_or_collection> get_cell(const clustering_key& rkey, const column_definition& def) const;
const partition_key& key() const { return _ptr->_dk._key; };
const dht::decorated_key& decorated_key() const { return _ptr->_dk; };
const dht::token& token() const { return _ptr->_dk._token; }
const schema_ptr& schema() const { return _ptr->_schema; }
const mutation_partition& partition() const { return _ptr->_p; }
mutation_partition& partition() { return _ptr->_p; }
const utils::UUID& column_family_id() const { return _ptr->_schema->id(); }
bool operator==(const mutation&) const;
bool operator!=(const mutation&) const;
public:
query::result query(const query::partition_slice&, gc_clock::time_point now = gc_clock::now(), uint32_t row_limit = query::max_rows) const;
// See mutation_partition::live_row_count()
size_t live_row_count(gc_clock::time_point query_time = gc_clock::time_point::min()) const;
private:
friend std::ostream& operator<<(std::ostream& os, const mutation& m);
friend class mutation_opt;
};
struct mutation_decorated_key_less_comparator {
bool operator()(const mutation& m1, const mutation& m2) const;
};
class mutation_opt {
private:
mutation _mutation;
public:
mutation_opt() = default;
mutation_opt(std::experimental::nullopt_t) noexcept { }
mutation_opt(const mutation& obj) : _mutation(obj) { }
mutation_opt(mutation&& obj) noexcept : _mutation(std::move(obj)) { }
mutation_opt(std::experimental::optional<mutation>&& obj) noexcept {
if (obj) {
_mutation = std::move(*obj);
}
}
mutation_opt(const mutation_opt&) = default;
mutation_opt(mutation_opt&&) = default;
mutation_opt& operator=(std::experimental::nullopt_t) noexcept {
_mutation = mutation();
return *this;
}
template<typename T>
std::enable_if_t<std::is_same<std::decay_t<T>, mutation>::value, mutation_opt&>
operator=(T&& obj) noexcept {
_mutation = std::forward<T>(obj);
return *this;
}
mutation_opt& operator=(mutation_opt&&) = default;
explicit operator bool() const noexcept {
return bool(_mutation._ptr);
}
mutation* operator->() noexcept { return &_mutation; }
const mutation* operator->() const noexcept { return &_mutation; }
mutation& operator*() noexcept { return _mutation; }
const mutation& operator*() const noexcept { return _mutation; }
bool operator==(const mutation_opt& other) const {
if (!*this && !other) {
return true;
}
if (!*this || !other) {
return false;
}
return _mutation == other._mutation;
}
bool operator!=(const mutation_opt& other) const {
return !(*this == other);
}
};
inline mutation_opt move_and_disengage(mutation_opt& opt) {
return std::move(opt);
}
inline
void apply(mutation_opt& dst, mutation&& src) {
if (!dst) {
dst = std::move(src);
} else {
dst->partition().apply(*src.schema(), src.partition());
}
}
inline
void apply(mutation_opt& dst, mutation_opt&& src) {
if (src) {
apply(dst, std::move(*src));
}
}
// Returns a range into partitions containing mutations covered by the range.
// partitions must be sorted according to decorated key.
// range must not wrap around.
boost::iterator_range<std::vector<mutation>::const_iterator> slice(
const std::vector<mutation>& partitions,
const query::partition_range&);
<commit_msg>mutation: Introduce ring_position()<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
/*
* 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 <iostream>
#include "mutation_partition.hh"
#include "keys.hh"
#include "schema.hh"
#include "dht/i_partitioner.hh"
class mutation final {
private:
struct data {
schema_ptr _schema;
dht::decorated_key _dk;
mutation_partition _p;
data(dht::decorated_key&& key, schema_ptr&& schema);
data(partition_key&& key, schema_ptr&& schema);
data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp);
data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp);
};
std::unique_ptr<data> _ptr;
private:
mutation() = default;
public:
mutation(dht::decorated_key key, schema_ptr schema)
: _ptr(std::make_unique<data>(std::move(key), std::move(schema)))
{ }
mutation(partition_key key_, schema_ptr schema)
: _ptr(std::make_unique<data>(std::move(key_), std::move(schema)))
{ }
mutation(schema_ptr schema, dht::decorated_key key, const mutation_partition& mp)
: _ptr(std::make_unique<data>(std::move(schema), std::move(key), mp))
{ }
mutation(schema_ptr schema, dht::decorated_key key, mutation_partition&& mp)
: _ptr(std::make_unique<data>(std::move(schema), std::move(key), std::move(mp)))
{ }
mutation(const mutation& m)
: _ptr(std::make_unique<data>(schema_ptr(m.schema()), dht::decorated_key(m.decorated_key()), m.partition()))
{ }
mutation(mutation&&) = default;
mutation& operator=(mutation&& x) = default;
void set_static_cell(const column_definition& def, atomic_cell_or_collection&& value);
void set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value);
void set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value);
void set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl = {});
void set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value);
std::experimental::optional<atomic_cell_or_collection> get_cell(const clustering_key& rkey, const column_definition& def) const;
const partition_key& key() const { return _ptr->_dk._key; };
const dht::decorated_key& decorated_key() const { return _ptr->_dk; };
dht::ring_position ring_position() const { return { decorated_key() }; }
const dht::token& token() const { return _ptr->_dk._token; }
const schema_ptr& schema() const { return _ptr->_schema; }
const mutation_partition& partition() const { return _ptr->_p; }
mutation_partition& partition() { return _ptr->_p; }
const utils::UUID& column_family_id() const { return _ptr->_schema->id(); }
bool operator==(const mutation&) const;
bool operator!=(const mutation&) const;
public:
query::result query(const query::partition_slice&, gc_clock::time_point now = gc_clock::now(), uint32_t row_limit = query::max_rows) const;
// See mutation_partition::live_row_count()
size_t live_row_count(gc_clock::time_point query_time = gc_clock::time_point::min()) const;
private:
friend std::ostream& operator<<(std::ostream& os, const mutation& m);
friend class mutation_opt;
};
struct mutation_decorated_key_less_comparator {
bool operator()(const mutation& m1, const mutation& m2) const;
};
class mutation_opt {
private:
mutation _mutation;
public:
mutation_opt() = default;
mutation_opt(std::experimental::nullopt_t) noexcept { }
mutation_opt(const mutation& obj) : _mutation(obj) { }
mutation_opt(mutation&& obj) noexcept : _mutation(std::move(obj)) { }
mutation_opt(std::experimental::optional<mutation>&& obj) noexcept {
if (obj) {
_mutation = std::move(*obj);
}
}
mutation_opt(const mutation_opt&) = default;
mutation_opt(mutation_opt&&) = default;
mutation_opt& operator=(std::experimental::nullopt_t) noexcept {
_mutation = mutation();
return *this;
}
template<typename T>
std::enable_if_t<std::is_same<std::decay_t<T>, mutation>::value, mutation_opt&>
operator=(T&& obj) noexcept {
_mutation = std::forward<T>(obj);
return *this;
}
mutation_opt& operator=(mutation_opt&&) = default;
explicit operator bool() const noexcept {
return bool(_mutation._ptr);
}
mutation* operator->() noexcept { return &_mutation; }
const mutation* operator->() const noexcept { return &_mutation; }
mutation& operator*() noexcept { return _mutation; }
const mutation& operator*() const noexcept { return _mutation; }
bool operator==(const mutation_opt& other) const {
if (!*this && !other) {
return true;
}
if (!*this || !other) {
return false;
}
return _mutation == other._mutation;
}
bool operator!=(const mutation_opt& other) const {
return !(*this == other);
}
};
inline mutation_opt move_and_disengage(mutation_opt& opt) {
return std::move(opt);
}
inline
void apply(mutation_opt& dst, mutation&& src) {
if (!dst) {
dst = std::move(src);
} else {
dst->partition().apply(*src.schema(), src.partition());
}
}
inline
void apply(mutation_opt& dst, mutation_opt&& src) {
if (src) {
apply(dst, std::move(*src));
}
}
// Returns a range into partitions containing mutations covered by the range.
// partitions must be sorted according to decorated key.
// range must not wrap around.
boost::iterator_range<std::vector<mutation>::const_iterator> slice(
const std::vector<mutation>& partitions,
const query::partition_range&);
<|endoftext|>
|
<commit_before>#include "gum/Anim2SymLoader.h"
#include "gum/FilepathHelper.h"
#include "gum/EasyAnim2Loader.h"
#include "gum/SpineAnim2Loader.h"
#include "gum/SymbolPool.h"
#include "gum/ExtendSymFile.h"
#include <sprite2/Anim2Symbol.h>
#include <simp/NodeAnim2.h>
#include <bimp/typedef.h>
#include <fstream>
#include <string.h>
namespace gum
{
Anim2SymLoader::Anim2SymLoader(s2::Anim2Symbol& sym,
const std::shared_ptr<const SymbolLoader>& sym_loader)
: m_sym(sym)
, m_sym_loader(sym_loader)
{
}
void Anim2SymLoader::LoadJson(const CU_STR& filepath)
{
CU_STR dir = FilepathHelper::Dir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
int type = ExtendSymFile::GetType(val);
switch (type)
{
case SYM_SPINE:
{
SpineAnim2Loader loader(m_sym, m_sym_loader);
loader.LoadJson(val, dir);
}
break;
case SYM_UNKNOWN:
{
EasyAnim2Loader loader(m_sym, m_sym_loader);
loader.LoadJson(val, dir);
}
break;
}
}
static void LoadBinSRT(rg_pose_srt& dst, const simp::NodeAnim2::Srt& src)
{
dst.trans[0] = src.trans.x;
dst.trans[1] = src.trans.y;
dst.rot = src.rot;
dst.scale[0] = src.scale.x;
dst.scale[1] = src.scale.y;
}
void Anim2SymLoader::LoadBin(const simp::NodeAnim2* node)
{
int sz = CalcNodeSize(node);
void* buf = malloc(sz);
uint8_t* ptr = static_cast<uint8_t*>(buf);
rg_animation* anim = (rg_animation*)ptr;
anim->max_frame = 0;
ptr += SIZEOF_RG_ANIM;
// skeleton
rg_skeleton* sk = (rg_skeleton*)ptr;
anim->sk = sk;
ptr += SIZEOF_RG_SKELETON;
sk->joint_count = node->joint_count;
sk->ik_count = node->ik_count;
sk->root = node->root;
sk->slot_count = node->slot_count;
sk->skin_count = node->skin_count;
//// skins
m_sym.ClearCachedSym();
for (int i = 0; i < sk->skin_count; ++i)
{
const simp::NodeAnim2::Skin& src = node->skins[i];
rg_skin* dst = &sk->skins[i];
dst->type = src.type;
LoadBinSRT(dst->local, src.local);
auto sym = SymbolPool::Instance()->Fetch(src.node);
m_sym.AddCachedSym(sym);
dst->ud = static_cast<void*>(sym.get());
ptr += SIZEOF_RG_SKIN;
}
//// slots
sk->slots = (rg_slot*)ptr;
for (int i = 0; i < sk->slot_count; ++i)
{
sk->slots[i].joint = node->slots[i].joint;
sk->slots[i].skin = node->slots[i].skin;
}
ptr += SIZEOF_RG_SLOT * sk->slot_count;
//// iks
sk->iks = (rg_ik*)ptr;
for (int i = 0; i < sk->ik_count; ++i)
{
const simp::NodeAnim2::IK& src = node->iks[i];
rg_ik* dst = &sk->iks[i];
dst->joints[0] = src.joints[0];
dst->joints[1] = src.joints[1];
dst->target = src.target;
dst->bend_positive = src.bend_positive;
dst->length[0] = src.length[0];
dst->length[1] = src.length[1];
}
ptr += SIZEOF_RG_IK * sk->ik_count;
//// joints
sk->joints = (rg_joint**)ptr;
ptr += sizeof(rg_joint*) * sk->joint_count;
for (int i = 0; i < sk->joint_count; ++i)
{
sk->joints[i] = (rg_joint*)ptr;
ptr += SIZEOF_RG_JOINT;
const simp::NodeAnim2::Joint& src = node->joints[i];
rg_joint* dst = sk->joints[i];
rg_pose_mat_identity(&dst->world_pose);
LoadBinSRT(dst->local_pose, src.local);
dst->parent = src.parent;
dst->children_count = src.chlidren_count;
ptr += ALIGN_4BYTE(sizeof(uint16_t) * dst->children_count);
}
InitJointChildren(sk);
// timeline
//// tl joints
anim->timeline.joints = (rg_tl_joint**)ptr;
ptr += sizeof(rg_tl_joint*) * sk->joint_count;
for (int i = 0; i < sk->joint_count; ++i)
{
anim->timeline.joints[i] = (rg_tl_joint*)ptr;
ptr += SIZEOF_RG_TIMELINE_JOINT;
const simp::NodeAnim2::TL_Joint& src = *node->tl_joints[i];
rg_tl_joint* dst = anim->timeline.joints[i];
dst->type = src.type;
int count = 0;
for (int j = 0; j < simp::NodeAnim2::DIM_COUNT; ++j) {
dst->dims_count[j] = src.dims_count[j];
count += dst->dims_count[j];
}
for (int j = 0; j < count; ++j)
{
dst->samples[j].time = src.samples[j].time;
dst->samples[j].lerp = src.samples[j].lerp;
dst->samples[j].data = src.samples[j].data;
if (dst->samples[j].time > anim->max_frame) {
anim->max_frame = dst->samples[j].time;
}
}
ptr += SIZEOF_RG_JOINT_SAMPLE * count;
}
//// tl skins
anim->timeline.skins = (rg_tl_skin**)ptr;
ptr += sizeof(rg_tl_skin*) * sk->slot_count;
for (int i = 0; i < sk->slot_count; ++i)
{
anim->timeline.skins[i] = (rg_tl_skin*)ptr;
ptr += SIZEOF_RG_TIMELINE_SKIN;
const simp::NodeAnim2::TL_Skin& src = *node->tl_skins[i];
rg_tl_skin* dst = anim->timeline.skins[i];
dst->skin_count = src.count;
for (int j = 0; j < dst->skin_count; ++j) {
dst->skins[j].time = src.samples[j].time;
dst->skins[j].skin = src.samples[j].skin;
}
ptr += SIZEOF_RG_SKIN_SAMPLE * dst->skin_count;
}
//// tl deforms
anim->timeline.deforms = (rg_tl_deform**)ptr;
ptr += sizeof(rg_tl_deform*) * sk->skin_count;
for (int i = 0; i < sk->skin_count; ++i)
{
anim->timeline.deforms[i] = (rg_tl_deform*)ptr;
ptr += SIZEOF_RG_TIMELINE_DEFORM;
const simp::NodeAnim2::TL_Deform& src = *node->tl_deforms[i];
rg_tl_deform* dst = anim->timeline.deforms[i];
dst->count = src.count;
for (int j = 0; j < dst->count; ++j)
{
dst->samples[j].time = src.samples[j]->time;
dst->samples[j].offset = src.samples[j]->offset;
dst->samples[j].count = src.samples[j]->count;
dst->samples[j].data = nullptr;
}
ptr += SIZEOF_RG_DEFORM_SAMPLE * dst->count;
for (int j = 0; j < dst->count; ++j)
{
if (dst->samples[j].count == 0) {
dst->samples[j].data = nullptr;
} else {
dst->samples[j].data = (float*)ptr;
int sz = sizeof(float) * 2 * dst->samples[j].count;
memcpy(dst->samples[j].data, src.samples[j]->vertices, sz);
ptr += sz;
}
}
}
m_sym.SetAnim(anim);
}
int Anim2SymLoader::CalcNodeSize(const simp::NodeAnim2* node)
{
int sz = 0;
// rg_animation
sz += SIZEOF_RG_ANIM;
// rg_skeleton
sz += SIZEOF_RG_SKELETON;
// joints
sz += sizeof(rg_joint*) * node->joint_count;
for (int i = 0; i < node->joint_count; ++i) {
sz += SIZEOF_RG_JOINT;
sz += ALIGN_4BYTE(sizeof(uint16_t) * node->joints[i].chlidren_count);
}
// iks
sz += SIZEOF_RG_IK * node->ik_count;
// slots
sz += SIZEOF_RG_SLOT * node->slot_count;
// skins
sz += SIZEOF_RG_SKIN * node->skin_count;
// tl joints
sz += sizeof(rg_tl_joint*) * node->joint_count;
for (int i = 0; i < node->joint_count; ++i)
{
sz += SIZEOF_RG_TIMELINE_JOINT;
simp::NodeAnim2::TL_Joint* src = node->tl_joints[i];
int count = 0;
for (int j = 0; j < simp::NodeAnim2::DIM_COUNT; ++j) {
count += src->dims_count[j];
}
sz += SIZEOF_RG_JOINT_SAMPLE * count;
}
// tl skins
sz += sizeof(rg_tl_skin*) * node->slot_count;
for (int i = 0; i < node->slot_count; ++i)
{
sz += SIZEOF_RG_TIMELINE_SKIN;
sz += SIZEOF_RG_SKIN_SAMPLE * node->tl_skins[i]->count;
}
// tl deforms
sz += sizeof(rg_tl_deform*) * node->skin_count;
for (int i = 0; i < node->skin_count; ++i)
{
sz += SIZEOF_RG_TIMELINE_DEFORM;
for (int j = 0; j < node->tl_deforms[i]->count; ++j) {
sz += SIZEOF_RG_DEFORM_SAMPLE;
sz += sizeof(float) * 2 * node->tl_deforms[i]->samples[j]->count;
}
}
return sz;
}
void Anim2SymLoader::InitJointChildren(rg_skeleton* sk)
{
CU_VEC<int> node_tag;
node_tag.resize(sk->joint_count, 0);
for (int i = 0; i < sk->joint_count; ++i) {
int parent = sk->joints[i]->parent;
if (parent != RG_JOINT_UNKNOWN) {
sk->joints[parent]->children[node_tag[parent]++] = i;
}
}
}
}<commit_msg>[ADDED] load anim2 's curve<commit_after>#include "gum/Anim2SymLoader.h"
#include "gum/FilepathHelper.h"
#include "gum/EasyAnim2Loader.h"
#include "gum/SpineAnim2Loader.h"
#include "gum/SymbolPool.h"
#include "gum/ExtendSymFile.h"
#include <sprite2/Anim2Symbol.h>
#include <simp/NodeAnim2.h>
#include <bimp/typedef.h>
#include <fstream>
#include <string.h>
#include <assert.h>
namespace gum
{
Anim2SymLoader::Anim2SymLoader(s2::Anim2Symbol& sym,
const std::shared_ptr<const SymbolLoader>& sym_loader)
: m_sym(sym)
, m_sym_loader(sym_loader)
{
}
void Anim2SymLoader::LoadJson(const CU_STR& filepath)
{
CU_STR dir = FilepathHelper::Dir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
int type = ExtendSymFile::GetType(val);
switch (type)
{
case SYM_SPINE:
{
SpineAnim2Loader loader(m_sym, m_sym_loader);
loader.LoadJson(val, dir);
}
break;
case SYM_UNKNOWN:
{
EasyAnim2Loader loader(m_sym, m_sym_loader);
loader.LoadJson(val, dir);
}
break;
}
}
static void LoadBinSRT(rg_pose_srt& dst, const simp::NodeAnim2::Srt& src)
{
dst.trans[0] = src.trans.x;
dst.trans[1] = src.trans.y;
dst.rot = src.rot;
dst.scale[0] = src.scale.x;
dst.scale[1] = src.scale.y;
}
void Anim2SymLoader::LoadBin(const simp::NodeAnim2* node)
{
int sz = CalcNodeSize(node);
void* buf = malloc(sz);
uint8_t* ptr = static_cast<uint8_t*>(buf);
rg_animation* anim = (rg_animation*)ptr;
anim->max_frame = 0;
ptr += SIZEOF_RG_ANIM;
// skeleton
rg_skeleton* sk = (rg_skeleton*)ptr;
anim->sk = sk;
ptr += SIZEOF_RG_SKELETON;
sk->joint_count = node->joint_count;
sk->ik_count = node->ik_count;
sk->root = node->root;
sk->slot_count = node->slot_count;
sk->skin_count = node->skin_count;
//// skins
m_sym.ClearCachedSym();
for (int i = 0; i < sk->skin_count; ++i)
{
const simp::NodeAnim2::Skin& src = node->skins[i];
rg_skin* dst = &sk->skins[i];
dst->type = src.type;
LoadBinSRT(dst->local, src.local);
auto sym = SymbolPool::Instance()->Fetch(src.node);
m_sym.AddCachedSym(sym);
dst->ud = static_cast<void*>(sym.get());
ptr += SIZEOF_RG_SKIN;
}
//// slots
sk->slots = (rg_slot*)ptr;
for (int i = 0; i < sk->slot_count; ++i)
{
sk->slots[i].joint = node->slots[i].joint;
sk->slots[i].skin = node->slots[i].skin;
}
ptr += SIZEOF_RG_SLOT * sk->slot_count;
//// iks
sk->iks = (rg_ik*)ptr;
for (int i = 0; i < sk->ik_count; ++i)
{
const simp::NodeAnim2::IK& src = node->iks[i];
rg_ik* dst = &sk->iks[i];
dst->joints[0] = src.joints[0];
dst->joints[1] = src.joints[1];
dst->target = src.target;
dst->bend_positive = src.bend_positive;
dst->length[0] = src.length[0];
dst->length[1] = src.length[1];
}
ptr += SIZEOF_RG_IK * sk->ik_count;
//// joints
sk->joints = (rg_joint**)ptr;
ptr += sizeof(rg_joint*) * sk->joint_count;
for (int i = 0; i < sk->joint_count; ++i)
{
sk->joints[i] = (rg_joint*)ptr;
ptr += SIZEOF_RG_JOINT;
const simp::NodeAnim2::Joint& src = node->joints[i];
rg_joint* dst = sk->joints[i];
rg_pose_mat_identity(&dst->world_pose);
LoadBinSRT(dst->local_pose, src.local);
dst->parent = src.parent;
dst->children_count = src.chlidren_count;
ptr += ALIGN_4BYTE(sizeof(uint16_t) * dst->children_count);
}
InitJointChildren(sk);
// timeline
//// tl joints
anim->timeline.joints = (rg_tl_joint**)ptr;
ptr += sizeof(rg_tl_joint*) * sk->joint_count;
for (int i = 0; i < sk->joint_count; ++i)
{
anim->timeline.joints[i] = (rg_tl_joint*)ptr;
ptr += SIZEOF_RG_TIMELINE_JOINT;
const simp::NodeAnim2::TL_Joint& src = *node->tl_joints[i];
rg_tl_joint* dst = anim->timeline.joints[i];
dst->type = src.type;
int count = 0;
for (int j = 0; j < simp::NodeAnim2::DIM_COUNT; ++j) {
dst->dims_count[j] = src.dims_count[j];
count += dst->dims_count[j];
}
for (int j = 0; j < count; ++j)
{
dst->samples[j].time = src.samples[j].time;
dst->samples[j].lerp = src.samples[j].lerp;
dst->samples[j].curve = src.samples[j].curve;
dst->samples[j].data = src.samples[j].data;
if (dst->samples[j].time > anim->max_frame) {
anim->max_frame = dst->samples[j].time;
}
}
ptr += SIZEOF_RG_JOINT_SAMPLE * count;
}
//// tl skins
anim->timeline.skins = (rg_tl_skin**)ptr;
ptr += sizeof(rg_tl_skin*) * sk->slot_count;
for (int i = 0; i < sk->slot_count; ++i)
{
anim->timeline.skins[i] = (rg_tl_skin*)ptr;
ptr += SIZEOF_RG_TIMELINE_SKIN;
const simp::NodeAnim2::TL_Skin& src = *node->tl_skins[i];
rg_tl_skin* dst = anim->timeline.skins[i];
dst->skin_count = src.count;
for (int j = 0; j < dst->skin_count; ++j) {
dst->skins[j].time = src.samples[j].time;
dst->skins[j].skin = src.samples[j].skin;
}
ptr += SIZEOF_RG_SKIN_SAMPLE * dst->skin_count;
}
//// tl deforms
anim->timeline.deforms = (rg_tl_deform**)ptr;
ptr += sizeof(rg_tl_deform*) * sk->skin_count;
for (int i = 0; i < sk->skin_count; ++i)
{
anim->timeline.deforms[i] = (rg_tl_deform*)ptr;
ptr += SIZEOF_RG_TIMELINE_DEFORM;
const simp::NodeAnim2::TL_Deform& src = *node->tl_deforms[i];
rg_tl_deform* dst = anim->timeline.deforms[i];
dst->count = src.count;
for (int j = 0; j < dst->count; ++j)
{
dst->samples[j].time = src.samples[j]->time;
dst->samples[j].offset = src.samples[j]->offset;
dst->samples[j].curve = src.samples[j]->curve;
dst->samples[j].count = src.samples[j]->count;
dst->samples[j].data = nullptr;
}
ptr += SIZEOF_RG_DEFORM_SAMPLE * dst->count;
for (int j = 0; j < dst->count; ++j)
{
if (dst->samples[j].count == 0) {
dst->samples[j].data = nullptr;
} else {
dst->samples[j].data = (float*)ptr;
int sz = sizeof(float) * 2 * dst->samples[j].count;
memcpy(dst->samples[j].data, src.samples[j]->vertices, sz);
ptr += sz;
}
}
}
//// curves
anim->curve_count = node->curve_count;
anim->curves = (rg_curve**)ptr;
ptr += sizeof(rg_curve*) * anim->curve_count;
for (int i = 0; i < anim->curve_count; ++i)
{
anim->curves[i] = (rg_curve*)ptr;
ptr += SIZEOF_RG_CURVE;
auto& src = node->curves[i];
auto& dst = anim->curves[i];
dst->x0 = src.x0;
dst->y0 = src.y0;
dst->x1 = src.x1;
dst->y1 = src.y1;
}
assert(ptr - buf == sz);
m_sym.SetAnim(anim);
}
int Anim2SymLoader::CalcNodeSize(const simp::NodeAnim2* node)
{
int sz = 0;
// rg_animation
sz += SIZEOF_RG_ANIM;
// rg_skeleton
sz += SIZEOF_RG_SKELETON;
// joints
sz += sizeof(rg_joint*) * node->joint_count;
for (int i = 0; i < node->joint_count; ++i) {
sz += SIZEOF_RG_JOINT;
sz += ALIGN_4BYTE(sizeof(uint16_t) * node->joints[i].chlidren_count);
}
// iks
sz += SIZEOF_RG_IK * node->ik_count;
// slots
sz += SIZEOF_RG_SLOT * node->slot_count;
// skins
sz += SIZEOF_RG_SKIN * node->skin_count;
// tl joints
sz += sizeof(rg_tl_joint*) * node->joint_count;
for (int i = 0; i < node->joint_count; ++i)
{
sz += SIZEOF_RG_TIMELINE_JOINT;
simp::NodeAnim2::TL_Joint* src = node->tl_joints[i];
int count = 0;
for (int j = 0; j < simp::NodeAnim2::DIM_COUNT; ++j) {
count += src->dims_count[j];
}
sz += SIZEOF_RG_JOINT_SAMPLE * count;
}
// tl skins
sz += sizeof(rg_tl_skin*) * node->slot_count;
for (int i = 0; i < node->slot_count; ++i)
{
sz += SIZEOF_RG_TIMELINE_SKIN;
sz += SIZEOF_RG_SKIN_SAMPLE * node->tl_skins[i]->count;
}
// tl deforms
sz += sizeof(rg_tl_deform*) * node->skin_count;
for (int i = 0; i < node->skin_count; ++i)
{
sz += SIZEOF_RG_TIMELINE_DEFORM;
for (int j = 0; j < node->tl_deforms[i]->count; ++j) {
sz += SIZEOF_RG_DEFORM_SAMPLE;
sz += sizeof(float) * 2 * node->tl_deforms[i]->samples[j]->count;
}
}
// curves
sz += sizeof(rg_curve*) * node->curve_count;
sz += SIZEOF_RG_CURVE * node->curve_count;
return sz;
}
void Anim2SymLoader::InitJointChildren(rg_skeleton* sk)
{
CU_VEC<int> node_tag;
node_tag.resize(sk->joint_count, 0);
for (int i = 0; i < sk->joint_count; ++i) {
int parent = sk->joints[i]->parent;
if (parent != RG_JOINT_UNKNOWN) {
sk->joints[parent]->children[node_tag[parent]++] = i;
}
}
}
}<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include "elements.h"
using namespace std;
/**
* @elementspage The Gaussian Optimization Analytical Tool (GOAT)
*
* Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
* Users may find relevant info related to this program, a program designed to provide
* structural analyses of biomolecules successfully optimized using Gaussian software.
*
* @short elements program
* @file elements.cpp
* @author Hananh Lozano
* @param none
* @return
*
* The purpose of this program is to identify the first eighteen elements, hydrogen to argon, and assign them a number starting with 1. Then it will take the enum and string files and build upon those to determine how many bonds between atoms there will be.**/
enum elements_hydrogen_to_argon {
HYDROGEN = 1,
HELIUM,
LITHIUM,
BERLLYIUM,
BORON,
CARBON,
NITROGEN,
OXYGEN,
FLUORINE,
NEON,
SODIUM,
MAGNESIUM,
ALUMINUM,
SILICON,
PHOSPHOROUS,
SULFUR,
CHLORINE,
ARGON,
};
elements_hydrogen_to_argon element;
string elements_to_string (elements_hydrogen_to_argon d) {
if (element == HYDROGEN ) return "Hydrogen";
if (element == HELIUM ) return "Helium";
if (element == LITHIUM ) return "Lithium";
if (element == BERLLYIUM ) return "Beryllium";
if (element == BORON ) return "Boron";
if (element == CARBON ) return "Carbon";
if (element == NITROGEN ) return "Nitrogen";
if (element == OXYGEN ) return "Oxygen";
if (element == FLUORINE ) return "Fluorine";
if (element == NEON ) return "Neon";
if (element == SODIUM ) return "Sodium";
if (element == MAGNESIUM ) return "Magnesium";
if (element == ALUMINUM ) return "Aluminum";
if (element == SILICON ) return "Silicon";
if (element == PHOSPHOROUS) return "Phosphorous";
if (element == SULFUR ) return "Sulfur";
if (element == CHLORINE ) return "Chlorine";
if (element == ARGON ) return "Argon";
};
//access coordinates.csv file array/struct
//read .csv array file
int main() {
if Hydrogen, Lithium, or Sodium return "1 bond H,Li,Na";
if Beryllium or Magnesium return "2 bonds Be,Mg";
if Boron or Aluminum return "3 bonds B,Al";
if Carbon or Silicon return "4 bonds C,Si";
if Nitrogen or Phosphorous return "3 bonds N,P";
if Oxygen or Sulfur return "2 bonds O,S";
if Fluorine or Chlorine return "1 bond F, Cl";
if Helium, Neon, or Argon return "0 bonds He,Ne,Ar";
}
return null;
}
<commit_msg>added Doxygen documentation header<commit_after>#include <iostream>
#include <string>
#include "elements.h"
using namespace std;
/**
* @file elements.cpp
* @author Hananh Lozano
* @param none
* @return 0 if success
*
* The purpose of this program is to identify the first eighteen elements,
* hydrogen to argon, and assign them a number starting with 1. Then it will
* take the enum and string files and build upon those to determine how many * bonds between atoms there will be.
**/
enum elements_hydrogen_to_argon {
HYDROGEN = 1,
HELIUM,
LITHIUM,
BERLLYIUM,
BORON,
CARBON,
NITROGEN,
OXYGEN,
FLUORINE,
NEON,
SODIUM,
MAGNESIUM,
ALUMINUM,
SILICON,
PHOSPHOROUS,
SULFUR,
CHLORINE,
ARGON,
};
elements_hydrogen_to_argon element;
string elements_to_string (elements_hydrogen_to_argon d) {
if (element == HYDROGEN ) return "Hydrogen";
if (element == HELIUM ) return "Helium";
if (element == LITHIUM ) return "Lithium";
if (element == BERLLYIUM ) return "Beryllium";
if (element == BORON ) return "Boron";
if (element == CARBON ) return "Carbon";
if (element == NITROGEN ) return "Nitrogen";
if (element == OXYGEN ) return "Oxygen";
if (element == FLUORINE ) return "Fluorine";
if (element == NEON ) return "Neon";
if (element == SODIUM ) return "Sodium";
if (element == MAGNESIUM ) return "Magnesium";
if (element == ALUMINUM ) return "Aluminum";
if (element == SILICON ) return "Silicon";
if (element == PHOSPHOROUS) return "Phosphorous";
if (element == SULFUR ) return "Sulfur";
if (element == CHLORINE ) return "Chlorine";
if (element == ARGON ) return "Argon";
};
//access coordinates.csv file array/struct
//read .csv array file
int main() {
if Hydrogen, Lithium, or Sodium return "1 bond H,Li,Na";
if Beryllium or Magnesium return "2 bonds Be,Mg";
if Boron or Aluminum return "3 bonds B,Al";
if Carbon or Silicon return "4 bonds C,Si";
if Nitrogen or Phosphorous return "3 bonds N,P";
if Oxygen or Sulfur return "2 bonds O,S";
if Fluorine or Chlorine return "1 bond F, Cl";
if Helium, Neon, or Argon return "0 bonds He,Ne,Ar";
}
return null;
}
<|endoftext|>
|
<commit_before>/** \file test_csv_convert.cpp
* Executable to convert dictionary CSV file from source pattern to destination pattern, which conversion rule is defined in a configuration file, such as "csv-convert-ipa-juman-eucjp.def".
* Below is the usage examples:
* \code
* The encoding type of those CSV files in source directory is predefined by the "dictionary-charset" entry of "dicrc" file.
* While the encoding type of binary files in destination directory could be set to "eucjp", "sjis" or "utf8" like below, which is "eucjp" defaultly.
* $ ./jma_csv_convert --config ../db/config/csv-convert-ipa-juman-eucjp.def --output ipa_proper.csv ../db/ipadic/src/Noun.proper.csv ../db/ipadic/src/Noun.name.csv ../db/ipadic/src/Noun.org.csv ../db/ipadic/src/Noun.place.csv
* \endcode
*
* \author Jun Jiang
* \version 0.1
* \date Sep 18, 2009
*/
#include "dictionary_rewriter.h"
#include "utils.h"
#include "common.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cstdlib>
#include <cstring>
using namespace std;
using namespace MeCab;
namespace
{
/**
* Print the test usage.
*/
void printUsage()
{
cerr << "Usage: ./jma_csv_convert --config DEF_FILE --output DEST_FILE SOURCE_CSV..." << endl;
}
/**
* Check whether the command \e option matches the \e name.
* \param str the command option string given by user.
* \param option the standard option name.
* \attention if the match is failed, print out the command usage information, and terminate the whole pragram.
*/
void checkOptionName(const char* str, const char* option)
{
if(strcmp(str, option) != 0)
{
cerr << "unknown command option " << str << ", which should be " << option << endl;
printUsage();
exit(1);
}
}
/**
* Append the rule in string \e str to the rule vector \e r.
* \param r the rule vector.
* \param str the rule string consisting of source and destination pattern.
*/
void append_rewrite_rule(RewriteRules *r, char* str)
{
char *col[3];
const size_t n = tokenize2(str, " \t", col, 3);
CHECK_DIE(n >= 2) << "format error: " << str;
r->resize(r->size() + 1);
string tmp;
if (n >= 3) {
tmp = col[1];
tmp += ' ';
tmp += col[2];
col[1] = const_cast<char *>(tmp.c_str());
}
r->back().set_pattern(col[0], col[1]);
}
/**
* Rewrite dictionary CSV file.
*/
class CSVRewriter
{
private:
/** rules consisting of source and destination pattern */
RewriteRules rules_;
public:
/**
* Open configuration file, which defines the source and destination patterns.
* \param fileName configuration file name
* \return true for success, false for failure.
*/
bool open(const char* fileName);
/**
* Rewrite the string \e src to \e dest, basing on the patterns in configuration file by \e open().
* \param src source string to convert from
* \param dest destination string as output
* \return true for success, false for failure.
*/
bool rewrite(const string& src, string& dest) const;
};
bool CSVRewriter::open(const char* fileName)
{
ifstream ifs(fileName);
if(! ifs)
{
cerr << "fail to open CSVRewriter configuration file: " << fileName << endl;
return false;
}
string line;
while(getline(ifs, line))
{
if(line.empty() || line[0] == '#')
{
continue;
}
char* str = const_cast<char*>(line.c_str());
append_rewrite_rule(&rules_, str);
}
return true;
}
bool CSVRewriter::rewrite(const string& src, string& dest) const
{
char buf[BUF_SIZE];
char *col[BUF_SIZE];
CHECK_DIE(src.size() < sizeof(buf) - 1) << "too many characters in CSV entry";
strncpy(buf, src.c_str(), sizeof(buf) - 1);
size_t n = tokenizeCSV(buf, col, sizeof(col));
CHECK_DIE(n < sizeof(col)) << "too many columns in CSV entry";
return rules_.rewrite(n, const_cast<const char **>(col), &dest);
}
}
/**
* Main function.
*/
int main(int argc, char* argv[])
{
if(argc < 6)
{
printUsage();
exit(1);
}
checkOptionName(argv[1], "--config");
checkOptionName(argv[3], "--output");
const char* configFile = argv[2];
cout << "config file: " << configFile << endl;
// CSV file rewriter
CSVRewriter rewriter;
if(! rewriter.open(configFile))
{
cerr << "fail to open config file: " << configFile << endl;
exit(1);
}
const char* destFile = argv[4];
ofstream to(destFile);
if(! to)
{
cerr << "failed to create file " << destFile << endl;
exit(1);
}
unsigned int count = 0;
unsigned int ignore = 0;
for(int i=5; i<argc; ++i)
{
const char* sourceFile = argv[i];
cout << "converting source file: " << sourceFile << endl;
ifstream from(sourceFile);
if(! from)
{
cerr << "failed to open source file: " << sourceFile << endl;
exit(1);
}
string line, dest;
while(getline(from, line))
{
if(line.empty())
continue;
if(! rewriter.rewrite(line, dest))
{
cerr << "as no pattern is matched, ignoring line: " << line << endl;
++ignore;
continue;
}
to << dest << endl;
++count;
}
}
cout << "succeeded output to " << destFile << endl;
cout << "total ignored entries: " << ignore << endl;
cout << "total converted entries: " << count << endl;
return 0;
}
<commit_msg>add common nouns from IPA to Juman dictionary.<commit_after>/** \file test_csv_convert.cpp
* Executable to convert dictionary CSV file from source pattern to destination pattern, which conversion rule is defined in a configuration file, such as "csv-convert-ipa-juman-eucjp.def".
* Below is the usage examples:
* \code
* The configuration file defining conversion rules is "../db/config/csv-convert-ipa-juman-eucjp.def",
* the source CSV files are "Noun.proper.csv", "Noun.name.csv", "Noun.org.csv" and "Noun.place.csv" in IPA dictionary,
* the destination CSV file is "ipa_proper_noun.csv".
* $ ./jma_csv_convert --config ../db/config/csv-convert-ipa-juman-eucjp.def --output ipa_proper_noun.csv ../db/ipadic/src/Noun.proper.csv ../db/ipadic/src/Noun.name.csv ../db/ipadic/src/Noun.org.csv ../db/ipadic/src/Noun.place.csv
* \endcode
*
* \author Jun Jiang
* \version 0.1
* \date Sep 18, 2009
*/
#include "dictionary_rewriter.h"
#include "utils.h"
#include "common.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cstdlib>
#include <cstring>
using namespace std;
using namespace MeCab;
namespace
{
/**
* Print the test usage.
*/
void printUsage()
{
cerr << "Usage: ./jma_csv_convert --config DEF_FILE --output DEST_FILE SOURCE_CSV..." << endl;
}
/**
* Check whether the command \e option matches the \e name.
* \param str the command option string given by user.
* \param option the standard option name.
* \attention if the match is failed, print out the command usage information, and terminate the whole pragram.
*/
void checkOptionName(const char* str, const char* option)
{
if(strcmp(str, option) != 0)
{
cerr << "unknown command option " << str << ", which should be " << option << endl;
printUsage();
exit(1);
}
}
/**
* Append the rule in string \e str to the rule vector \e r.
* \param r the rule vector.
* \param str the rule string consisting of source and destination pattern.
*/
void append_rewrite_rule(RewriteRules *r, char* str)
{
char *col[3];
const size_t n = tokenize2(str, " \t", col, 3);
CHECK_DIE(n >= 2) << "format error: " << str;
r->resize(r->size() + 1);
string tmp;
if (n >= 3) {
tmp = col[1];
tmp += ' ';
tmp += col[2];
col[1] = const_cast<char *>(tmp.c_str());
}
r->back().set_pattern(col[0], col[1]);
}
/**
* Rewrite dictionary CSV file.
*/
class CSVRewriter
{
private:
/** rules consisting of source and destination pattern */
RewriteRules rules_;
public:
/**
* Open configuration file, which defines the source and destination patterns.
* \param fileName configuration file name
* \return true for success, false for failure.
*/
bool open(const char* fileName);
/**
* Rewrite the string \e src to \e dest, basing on the patterns in configuration file by \e open().
* \param src source string to convert from
* \param dest destination string as output
* \return true for success, false for failure.
*/
bool rewrite(const string& src, string& dest) const;
};
bool CSVRewriter::open(const char* fileName)
{
ifstream ifs(fileName);
if(! ifs)
{
cerr << "fail to open CSVRewriter configuration file: " << fileName << endl;
return false;
}
string line;
while(getline(ifs, line))
{
if(line.empty() || line[0] == '#')
{
continue;
}
char* str = const_cast<char*>(line.c_str());
append_rewrite_rule(&rules_, str);
}
return true;
}
bool CSVRewriter::rewrite(const string& src, string& dest) const
{
char buf[BUF_SIZE];
char *col[BUF_SIZE];
CHECK_DIE(src.size() < sizeof(buf) - 1) << "too many characters in CSV entry";
strncpy(buf, src.c_str(), sizeof(buf) - 1);
size_t n = tokenizeCSV(buf, col, sizeof(col));
CHECK_DIE(n < sizeof(col)) << "too many columns in CSV entry";
return rules_.rewrite(n, const_cast<const char **>(col), &dest);
}
}
/**
* Main function.
*/
int main(int argc, char* argv[])
{
if(argc < 6)
{
printUsage();
exit(1);
}
checkOptionName(argv[1], "--config");
checkOptionName(argv[3], "--output");
const char* configFile = argv[2];
cout << "config file: " << configFile << endl;
// CSV file rewriter
CSVRewriter rewriter;
if(! rewriter.open(configFile))
{
cerr << "fail to open config file: " << configFile << endl;
exit(1);
}
const char* destFile = argv[4];
ofstream to(destFile);
if(! to)
{
cerr << "failed to create file " << destFile << endl;
exit(1);
}
unsigned int count = 0;
unsigned int ignore = 0;
for(int i=5; i<argc; ++i)
{
const char* sourceFile = argv[i];
cout << "converting source file: " << sourceFile << endl;
ifstream from(sourceFile);
if(! from)
{
cerr << "failed to open source file: " << sourceFile << endl;
exit(1);
}
string line, dest;
while(getline(from, line))
{
if(line.empty())
continue;
if(! rewriter.rewrite(line, dest))
{
cerr << "as no pattern is matched, ignoring line: " << line << endl;
++ignore;
continue;
}
to << dest << endl;
++count;
}
}
cout << "succeeded output to " << destFile << endl;
cout << "total ignored entries: " << ignore << endl;
cout << "total converted entries: " << count << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <arc/loader/Plugin.h>
#include <arc/message/PayloadSOAP.h>
#include <stdio.h>
#define R_NO_REMAP 1
#include <R.h>
#include <Rembedded.h>
#include <Rinternals.h>
#include "eqtlservice.h"
typedef enum {
PARSE_NULL,
PARSE_OK,
PARSE_INCOMPLETE,
PARSE_ERROR,
PARSE_EOF
} ParseStatus;
extern "C" SEXP R_ParseVector(SEXP, int, ParseStatus *);
/**
* Initializes the expression qtl service and returns it.
*/
static Arc::Plugin* get_service(Arc::PluginArgument* arg)
{
Arc::ServicePluginArgument* mccarg = dynamic_cast<Arc::ServicePluginArgument*>(arg);
if(!mccarg) return NULL;
return new ArcService::ExpressionQtlService((Arc::Config*)(*mccarg));
}
/**
* This PLUGINS_TABLE_NAME is defining basic entities of the implemented .
* service. It is used to get the correct entry point to the plugin.
* FORMAT: {name, kind, version, constructor}, null terminated
*/
Arc::PluginDescriptor PLUGINS_TABLE_NAME[] = {
{"eQTL","HED:SERVICE",1,&get_service},
{ NULL, NULL, 0, NULL }
};
using namespace Arc;
namespace ArcService
{
ExpressionQtlService::ExpressionQtlService(Arc::Config *cfg) : Service(cfg),logger(Logger::rootLogger, "eQTL"),
mysql("eQTL_Stockholm","localhost","root","")
{
// synchronize this with eqtl_arc.wsdl
ns_["arc"]="http://uni-luebeck.de/eqtl/arc/";
// init embedded R
char *argv[] = {"REmbeddedPostgres", "--gui=none", "--silent"};
Rf_initEmbeddedR(sizeof(argv)/sizeof(argv[0]), argv);
// read config like this: prefix_=(std::string)((*cfg)["prefix"]);
}
ExpressionQtlService::~ExpressionQtlService(void)
{
}
/**
* Method which creates a fault payload
*/
Arc::MCC_Status ExpressionQtlService::makeFault(Arc::Message& outmsg, const std::string &reason)
{
logger.msg(Arc::WARNING, "Creating fault! Reason: \"%s\"",reason);
// The boolean true indicates that inside of PayloadSOAP,
// an object SOAPFault will be created inside.
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns_,true);
Arc::SOAPFault* fault = outpayload->Fault();
if(fault) {
fault->Code(Arc::SOAPFault::Sender);
fault->Reason(reason);
};
outmsg.Payload(outpayload);
return Arc::MCC_Status(Arc::STATUS_OK);
}
/**
* Processes the incoming message and generates an outgoing message.
* @param inmsg incoming message
* @param outmsg outgoing message
* @return Status of the result achieved
*/
Arc::MCC_Status ExpressionQtlService::process(Arc::Message& inmsg, Arc::Message& outmsg)
{
logger.msg(Arc::DEBUG, "eQTL service started...");
/** Extracting incoming payload */
Arc::PayloadSOAP* inpayload = NULL;
try {
inpayload = dynamic_cast<Arc::PayloadSOAP*>(inmsg.Payload());
} catch(std::exception& e) { };
if(!inpayload) {
//FIXME: causes compile error. dunno why logger.msg(Arc::ERROR,"Input is not SOAP");
return makeFault(outmsg, "Received message was not a valid SOAP message.");
};
/** */
/** Analyzing and execute request */
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns_);
Arc::XMLNode requestNode = inpayload->Child();
logger.msg(Arc::DEBUG, "Called WSDL Operation: \"%s\"",requestNode.Name());
if( requestNode.Name() == "QTL_FindByPosition" || requestNode.Name() == "QTL_FindByPosition_R" ) {
bool searchMarker = true;
bool searchGene = true;
if( ((std::string)requestNode["searchType"]).length() ) {
std::string searchType = (std::string) requestNode["searchType"];
if(searchType == "marker") searchGene = false;
if(searchType == "gene") searchMarker = false;
}
Arc::XMLNode searchRequest = requestNode["searchRequest"];
mysqlpp::Query sql = mysql.query();
sql << "SELECT * FROM hajo_qtl_nocov WHERE 1 ";
if( ((std::string)searchRequest["lodScore"]["from"]).length() )
sql << " AND lod >= " << mysqlpp::quote << (std::string) searchRequest["lodScore"]["from"];
if( ((std::string)searchRequest["lodScore"]["to"]).length() )
sql << " AND lod <= " << mysqlpp::quote << (std::string) searchRequest["lodScore"]["to"];
Arc::XMLNode position = searchRequest["position"];
if( position.Size()>0 ) {
sql << " AND ( FALSE ";
while(position) {
if( searchMarker ) {
sql << " OR ( marker_chromosome=" << mysqlpp::quote << (std::string) position["chromosome"];
if( ((std::string)position["fromBP"]).length() )
sql << " AND marker_positionBP >= " << mysqlpp::quote << (std::string) position["fromBP"];
if( ((std::string)position["toBP"]).length() )
sql << " AND marker_positionBP <= " << mysqlpp::quote << (std::string) position["toBP"];
sql << ") ";
}
if( searchGene ) {
sql << " OR ( genePosition_chromosome=" << mysqlpp::quote << (std::string) position["chromosome"];
if( ((std::string)position["fromBP"]).length() )
sql << " AND genePosition_toBP >= " << mysqlpp::quote << (std::string) position["fromBP"];
if( ((std::string)position["toBP"]).length() )
sql << " AND genePosition_fromBP <= " << mysqlpp::quote << (std::string) position["toBP"];
sql << ") ";
}
++position;
}
sql << " ) ";
}
if( ((std::string)searchRequest["sameChromosome"]).length() ) {
int what = atoi( ((std::string) searchRequest["sameChromosome"]).c_str() );
if( what == 1 ) sql << " AND sameChromosome='1' ";
else if( what == -1 ) sql << " AND sameChromosome='0' ";
}
if( ((std::string)searchRequest["locusToGeneDistance"]["from"]).length() )
sql << " AND locusToGeneDistance >= " << mysqlpp::quote << (std::string) searchRequest["locusToGeneDistance"]["from"];
if( ((std::string)searchRequest["locusToGeneDistance"]["to"]).length() )
sql << " AND locusToGeneDistance <= " << mysqlpp::quote << (std::string) searchRequest["locusToGeneDistance"]["to"];
std::string orderBy = "lod DESC";
if( ((std::string)searchRequest["orderBy"]).length() ) {
std::string order = searchRequest["orderBy"];
if( order == "LodScore" ) orderBy = "lod DESC";
}
sql << " ORDER BY " << orderBy;
if( ((std::string)searchRequest["maxNumResults"]).length() )
sql << " LIMIT "<< atoi( ((std::string) searchRequest["maxNumResults"]).c_str() );
logger.msg(Arc::DEBUG, "SQL Query: \"%s\"",sql.str());
mysqlpp::StoreQueryResult res;
try{
res = sql.store();
}catch(mysqlpp::Exception e) {
return makeFault(outmsg, e.what());
}
logger.msg(Arc::DEBUG, "Number of results: \"%d\"",res.num_rows());
if( requestNode.Name() == "QTL_FindByPosition" ) {
Arc::XMLNode addToMe = outpayload->NewChild("arc:QTL_FindByPositionResponse");
for(size_t i=0;i<res.num_rows();i++) {
Arc::XMLNode curAdd = addToMe.NewChild("qtls");
curAdd.NewChild("lod") = res[i]["lod"];
curAdd.NewChild("marker");
curAdd["marker"].NewChild("name") = res[i]["marker_name"];
curAdd["marker"].NewChild("chromosome") = res[i]["marker_chromosome"];
curAdd["marker"].NewChild("positionBP") = res[i]["marker_positionBP"];
curAdd.NewChild("genePosition");
curAdd["genePosition"].NewChild("chromosome") = res[i]["genePosition_chromosome"];
curAdd["genePosition"].NewChild("fromBP") = res[i]["genePosition_fromBP"];
curAdd["genePosition"].NewChild("toBP") = res[i]["genePosition_toBP"];
curAdd.NewChild("geneEntrezID") = res[i]["geneEntrezID"];
curAdd.NewChild("statistics");
curAdd["statistics"].NewChild("mean") = res[i]["statistics_mean"];
curAdd["statistics"].NewChild("sd") = res[i]["statistics_sd"];
curAdd["statistics"].NewChild("median") = res[i]["statistics_median"];
curAdd["statistics"].NewChild("variance") = res[i]["statistics_variance"];
}
} else if( requestNode.Name() == "QTL_FindByPosition_R" ) {
Arc::XMLNode addToMe = outpayload->NewChild("arc:QTL_FindByPosition_RResponse");
int numCol = 1+3+3+1+4;
int numRow = res.num_rows();
SEXP dataForR = Rf_allocMatrix(VECSXP, numRow, numCol);
PROTECT( dataForR ); //we dont want R to garbage collect this
for(size_t i=0;i<res.num_rows();i++) {
int rowOff = i * numCol;
SET_VECTOR_ELT(dataForR, rowOff+0, Rf_mkString(res[i]["lod"]));
SET_VECTOR_ELT(dataForR, rowOff+1, Rf_mkString(res[i]["marker_name"]));
SET_VECTOR_ELT(dataForR, rowOff+2, Rf_mkString(res[i]["marker_chromosome"]));
SET_VECTOR_ELT(dataForR, rowOff+3, Rf_mkString(res[i]["marker_positionBP"]));
SET_VECTOR_ELT(dataForR, rowOff+4, Rf_mkString(res[i]["genePosition_chromosome"]));
SET_VECTOR_ELT(dataForR, rowOff+5, Rf_mkString(res[i]["genePosition_fromBP"]));
SET_VECTOR_ELT(dataForR, rowOff+6, Rf_mkString(res[i]["genePosition_toBP"]));
SET_VECTOR_ELT(dataForR, rowOff+7, Rf_mkString(res[i]["geneEntrezID"]));
SET_VECTOR_ELT(dataForR, rowOff+8, Rf_mkString(res[i]["statistics_mean"]));
SET_VECTOR_ELT(dataForR, rowOff+9, Rf_mkString(res[i]["statistics_sd"]));
SET_VECTOR_ELT(dataForR, rowOff+10, Rf_mkString(res[i]["statistics_median"]));
SET_VECTOR_ELT(dataForR, rowOff+11, Rf_mkString(res[i]["statistics_variance"]));
}
/*
SEXP colnames = Rf_GetColNames(dataForR);
SET_VECTOR_ELT(colnames, 0, Rf_mkString("lod"));
SET_VECTOR_ELT(colnames, 1, Rf_mkString("marker_name"));
SET_VECTOR_ELT(colnames, 2, Rf_mkString("marker_chromosome"));
SET_VECTOR_ELT(colnames, 3, Rf_mkString("marker_positionBP"));
SET_VECTOR_ELT(colnames, 4, Rf_mkString("genePosition_chromosome"));
SET_VECTOR_ELT(colnames, 5, Rf_mkString("genePosition_fromBP"));
SET_VECTOR_ELT(colnames, 6, Rf_mkString("genePosition_toBP"));
SET_VECTOR_ELT(colnames, 7, Rf_mkString("geneEntrezID"));
SET_VECTOR_ELT(colnames, 8, Rf_mkString("statistics_mean"));
SET_VECTOR_ELT(colnames, 9, Rf_mkString("statistics_sd"));
SET_VECTOR_ELT(colnames, 10, Rf_mkString("statistics_median"));
SET_VECTOR_ELT(colnames, 11, Rf_mkString("statistics_variance"));
*/
logger.msg(Arc::DEBUG, "Registring data into R...");
Rf_defineVar(Rf_install("data"), dataForR, R_GlobalEnv);
logger.msg(Arc::DEBUG, "Variable \"data\" set.");
ParseStatus status;
const char* commandStr = ((std::string)requestNode["script"]).c_str();
logger.msg(Arc::DEBUG, "R script : %s", commandStr);
SEXP str = Rf_mkString(commandStr);
logger.msg(Arc::DEBUG, "mkString succeeded");
SEXP commands = R_ParseVector(str, -1, &status);
logger.msg(Arc::DEBUG, "parseString succeeded");
PROTECT(commands);
Rf_PrintValue(commands);
int errorStatus;
SEXP result = R_tryEval(commands, R_GlobalEnv, &errorStatus);
Rf_PrintValue(result);
UNPROTECT(2); //commands + dataForR
addToMe = "done";
}
}
logger.msg(Arc::DEBUG, "eQTL service done...");
outmsg.Payload(outpayload);
return Arc::MCC_Status(Arc::STATUS_OK);
}
}//namespace
<commit_msg>R interface seems to work in valgrind. i rock :)<commit_after>#include <arc/loader/Plugin.h>
#include <arc/message/PayloadSOAP.h>
#include <stdio.h>
#define R_NO_REMAP 1
#include <R.h>
#include <Rembedded.h>
#include <Rinternals.h>
#include "eqtlservice.h"
typedef enum {
PARSE_NULL,
PARSE_OK,
PARSE_INCOMPLETE,
PARSE_ERROR,
PARSE_EOF
} ParseStatus;
extern "C" SEXP R_ParseVector(SEXP, int, ParseStatus *, SEXP);
/**
* Initializes the expression qtl service and returns it.
*/
static Arc::Plugin* get_service(Arc::PluginArgument* arg)
{
Arc::ServicePluginArgument* mccarg = dynamic_cast<Arc::ServicePluginArgument*>(arg);
if(!mccarg) return NULL;
return new ArcService::ExpressionQtlService((Arc::Config*)(*mccarg));
}
/**
* This PLUGINS_TABLE_NAME is defining basic entities of the implemented .
* service. It is used to get the correct entry point to the plugin.
* FORMAT: {name, kind, version, constructor}, null terminated
*/
Arc::PluginDescriptor PLUGINS_TABLE_NAME[] = {
{"eQTL","HED:SERVICE",1,&get_service},
{ NULL, NULL, 0, NULL }
};
using namespace Arc;
namespace ArcService
{
ExpressionQtlService::ExpressionQtlService(Arc::Config *cfg) : Service(cfg),logger(Logger::rootLogger, "eQTL"),
mysql("eQTL_Stockholm","localhost","root","")
{
// synchronize this with eqtl_arc.wsdl
ns_["arc"]="http://uni-luebeck.de/eqtl/arc/";
// init embedded R
char *argv[] = {"R", "--gui=none", "--silent"};
Rf_initEmbeddedR(sizeof(argv)/sizeof(argv[0]), argv);
// read config like this: prefix_=(std::string)((*cfg)["prefix"]);
}
ExpressionQtlService::~ExpressionQtlService(void)
{
}
/**
* Method which creates a fault payload
*/
Arc::MCC_Status ExpressionQtlService::makeFault(Arc::Message& outmsg, const std::string &reason)
{
logger.msg(Arc::WARNING, "Creating fault! Reason: \"%s\"",reason);
// The boolean true indicates that inside of PayloadSOAP,
// an object SOAPFault will be created inside.
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns_,true);
Arc::SOAPFault* fault = outpayload->Fault();
if(fault) {
fault->Code(Arc::SOAPFault::Sender);
fault->Reason(reason);
};
outmsg.Payload(outpayload);
return Arc::MCC_Status(Arc::STATUS_OK);
}
/**
* Processes the incoming message and generates an outgoing message.
* @param inmsg incoming message
* @param outmsg outgoing message
* @return Status of the result achieved
*/
Arc::MCC_Status ExpressionQtlService::process(Arc::Message& inmsg, Arc::Message& outmsg)
{
logger.msg(Arc::DEBUG, "eQTL service started...");
/** Extracting incoming payload */
Arc::PayloadSOAP* inpayload = NULL;
try {
inpayload = dynamic_cast<Arc::PayloadSOAP*>(inmsg.Payload());
} catch(std::exception& e) { };
if(!inpayload) {
//FIXME: causes compile error. dunno why logger.msg(Arc::ERROR,"Input is not SOAP");
return makeFault(outmsg, "Received message was not a valid SOAP message.");
};
/** */
/** Analyzing and execute request */
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns_);
Arc::XMLNode requestNode = inpayload->Child();
logger.msg(Arc::DEBUG, "Called WSDL Operation: \"%s\"",requestNode.Name());
if( requestNode.Name() == "QTL_FindByPosition" || requestNode.Name() == "QTL_FindByPosition_R" ) {
bool searchMarker = true;
bool searchGene = true;
if( ((std::string)requestNode["searchType"]).length() ) {
std::string searchType = (std::string) requestNode["searchType"];
if(searchType == "marker") searchGene = false;
if(searchType == "gene") searchMarker = false;
}
Arc::XMLNode searchRequest = requestNode["searchRequest"];
mysqlpp::Query sql = mysql.query();
sql << "SELECT * FROM hajo_qtl_nocov WHERE 1 ";
if( ((std::string)searchRequest["lodScore"]["from"]).length() )
sql << " AND lod >= " << mysqlpp::quote << (std::string) searchRequest["lodScore"]["from"];
if( ((std::string)searchRequest["lodScore"]["to"]).length() )
sql << " AND lod <= " << mysqlpp::quote << (std::string) searchRequest["lodScore"]["to"];
Arc::XMLNode position = searchRequest["position"];
if( position.Size()>0 ) {
sql << " AND ( FALSE ";
while(position) {
if( searchMarker ) {
sql << " OR ( marker_chromosome=" << mysqlpp::quote << (std::string) position["chromosome"];
if( ((std::string)position["fromBP"]).length() )
sql << " AND marker_positionBP >= " << mysqlpp::quote << (std::string) position["fromBP"];
if( ((std::string)position["toBP"]).length() )
sql << " AND marker_positionBP <= " << mysqlpp::quote << (std::string) position["toBP"];
sql << ") ";
}
if( searchGene ) {
sql << " OR ( genePosition_chromosome=" << mysqlpp::quote << (std::string) position["chromosome"];
if( ((std::string)position["fromBP"]).length() )
sql << " AND genePosition_toBP >= " << mysqlpp::quote << (std::string) position["fromBP"];
if( ((std::string)position["toBP"]).length() )
sql << " AND genePosition_fromBP <= " << mysqlpp::quote << (std::string) position["toBP"];
sql << ") ";
}
++position;
}
sql << " ) ";
}
if( ((std::string)searchRequest["sameChromosome"]).length() ) {
int what = atoi( ((std::string) searchRequest["sameChromosome"]).c_str() );
if( what == 1 ) sql << " AND sameChromosome='1' ";
else if( what == -1 ) sql << " AND sameChromosome='0' ";
}
if( ((std::string)searchRequest["locusToGeneDistance"]["from"]).length() )
sql << " AND locusToGeneDistance >= " << mysqlpp::quote << (std::string) searchRequest["locusToGeneDistance"]["from"];
if( ((std::string)searchRequest["locusToGeneDistance"]["to"]).length() )
sql << " AND locusToGeneDistance <= " << mysqlpp::quote << (std::string) searchRequest["locusToGeneDistance"]["to"];
std::string orderBy = "lod DESC";
if( ((std::string)searchRequest["orderBy"]).length() ) {
std::string order = searchRequest["orderBy"];
if( order == "LodScore" ) orderBy = "lod DESC";
}
sql << " ORDER BY " << orderBy;
if( ((std::string)searchRequest["maxNumResults"]).length() )
sql << " LIMIT "<< atoi( ((std::string) searchRequest["maxNumResults"]).c_str() );
logger.msg(Arc::DEBUG, "SQL Query: \"%s\"",sql.str());
mysqlpp::StoreQueryResult res;
try{
res = sql.store();
}catch(mysqlpp::Exception e) {
return makeFault(outmsg, e.what());
}
logger.msg(Arc::DEBUG, "Number of results: \"%d\"",res.num_rows());
if( requestNode.Name() == "QTL_FindByPosition" ) {
Arc::XMLNode addToMe = outpayload->NewChild("arc:QTL_FindByPositionResponse");
for(size_t i=0;i<res.num_rows();i++) {
Arc::XMLNode curAdd = addToMe.NewChild("qtls");
curAdd.NewChild("lod") = res[i]["lod"];
curAdd.NewChild("marker");
curAdd["marker"].NewChild("name") = res[i]["marker_name"];
curAdd["marker"].NewChild("chromosome") = res[i]["marker_chromosome"];
curAdd["marker"].NewChild("positionBP") = res[i]["marker_positionBP"];
curAdd.NewChild("genePosition");
curAdd["genePosition"].NewChild("chromosome") = res[i]["genePosition_chromosome"];
curAdd["genePosition"].NewChild("fromBP") = res[i]["genePosition_fromBP"];
curAdd["genePosition"].NewChild("toBP") = res[i]["genePosition_toBP"];
curAdd.NewChild("geneEntrezID") = res[i]["geneEntrezID"];
curAdd.NewChild("statistics");
curAdd["statistics"].NewChild("mean") = res[i]["statistics_mean"];
curAdd["statistics"].NewChild("sd") = res[i]["statistics_sd"];
curAdd["statistics"].NewChild("median") = res[i]["statistics_median"];
curAdd["statistics"].NewChild("variance") = res[i]["statistics_variance"];
}
} else if( requestNode.Name() == "QTL_FindByPosition_R" ) {
Arc::XMLNode addToMe = outpayload->NewChild("arc:QTL_FindByPosition_RResponse");
int numCol = 1+3+3+1+4;
int numRow = res.num_rows();
SEXP dataForR = Rf_allocMatrix(VECSXP, numRow, numCol);
PROTECT( dataForR ); //we dont want R to garbage collect this
for(size_t i=0;i<res.num_rows();i++) {
int rowOff = i * numCol;
SET_VECTOR_ELT(dataForR, rowOff+0, Rf_mkString(res[i]["lod"]));
SET_VECTOR_ELT(dataForR, rowOff+1, Rf_mkString(res[i]["marker_name"]));
SET_VECTOR_ELT(dataForR, rowOff+2, Rf_mkString(res[i]["marker_chromosome"]));
SET_VECTOR_ELT(dataForR, rowOff+3, Rf_mkString(res[i]["marker_positionBP"]));
SET_VECTOR_ELT(dataForR, rowOff+4, Rf_mkString(res[i]["genePosition_chromosome"]));
SET_VECTOR_ELT(dataForR, rowOff+5, Rf_mkString(res[i]["genePosition_fromBP"]));
SET_VECTOR_ELT(dataForR, rowOff+6, Rf_mkString(res[i]["genePosition_toBP"]));
SET_VECTOR_ELT(dataForR, rowOff+7, Rf_mkString(res[i]["geneEntrezID"]));
SET_VECTOR_ELT(dataForR, rowOff+8, Rf_mkString(res[i]["statistics_mean"]));
SET_VECTOR_ELT(dataForR, rowOff+9, Rf_mkString(res[i]["statistics_sd"]));
SET_VECTOR_ELT(dataForR, rowOff+10, Rf_mkString(res[i]["statistics_median"]));
SET_VECTOR_ELT(dataForR, rowOff+11, Rf_mkString(res[i]["statistics_variance"]));
}
/*
SEXP colnames = Rf_GetColNames(dataForR);
SET_VECTOR_ELT(colnames, 0, Rf_mkString("lod"));
SET_VECTOR_ELT(colnames, 1, Rf_mkString("marker_name"));
SET_VECTOR_ELT(colnames, 2, Rf_mkString("marker_chromosome"));
SET_VECTOR_ELT(colnames, 3, Rf_mkString("marker_positionBP"));
SET_VECTOR_ELT(colnames, 4, Rf_mkString("genePosition_chromosome"));
SET_VECTOR_ELT(colnames, 5, Rf_mkString("genePosition_fromBP"));
SET_VECTOR_ELT(colnames, 6, Rf_mkString("genePosition_toBP"));
SET_VECTOR_ELT(colnames, 7, Rf_mkString("geneEntrezID"));
SET_VECTOR_ELT(colnames, 8, Rf_mkString("statistics_mean"));
SET_VECTOR_ELT(colnames, 9, Rf_mkString("statistics_sd"));
SET_VECTOR_ELT(colnames, 10, Rf_mkString("statistics_median"));
SET_VECTOR_ELT(colnames, 11, Rf_mkString("statistics_variance"));
*/
logger.msg(Arc::DEBUG, "Registring data into R...");
Rf_defineVar(Rf_install("data"), dataForR, R_GlobalEnv);
logger.msg(Arc::DEBUG, "Variable \"data\" set.");
ParseStatus status;
char* commandStr = strdup( ((std::string)requestNode["script"]).c_str() );
logger.msg(Arc::DEBUG, "R script: %s", commandStr);
SEXP str = Rf_mkString(commandStr);
free(commandStr);
PROTECT(str);
//Rf_PrintValue(str);
SEXP commands = R_ParseVector(str, -1, &status, R_NilValue);
if( status == PARSE_OK )
logger.msg(Arc::DEBUG, "R_ParseVector succeeded.");
else {
logger.msg(Arc::DEBUG, "R_ParseVector failed with status %d.", status);
return makeFault(outmsg, "The script you provided could not be parsed by R using R_ParseVector.");
}
PROTECT(commands);
int nCommands = Rf_length(commands);
for(int i=0;i<nCommands;i++) {
Arc::XMLNode lineResult = addToMe.NewChild("scriptResults");
int errorStatus;
SEXP curCommand = VECTOR_ELT(commands,i);
//Rf_PrintValue(curCommand);
SEXP result = R_tryEval(curCommand, R_GlobalEnv, &errorStatus);
logger.msg(Arc::DEBUG, "R_tryEval number %d of %d returned error status %d.", i+1, nCommands, errorStatus);
if( errorStatus == 0 ) {
//Rf_PrintValue(result);
logger.msg(Arc::DEBUG, "Returned SEXP is of type %d.", TYPEOF(result));
if( ! Rf_isNull(result) ) {
SEXP printExpr = Rf_allocVector(EXPRSXP, 1);
PROTECT(printExpr);
SET_VECTOR_ELT(printExpr, 0, result);
//Rf_PrintValue(printExpr);
SEXP printCall, tmp;
PROTECT(tmp = printCall = Rf_allocList(2));
SET_TYPEOF(printCall, LANGSXP);
SETCAR(tmp, Rf_install("capture.output"));
tmp = CDR(tmp);
SETCAR(tmp, printExpr);
//Rf_PrintValue(printCall);
SEXP capturedString = R_tryEval(printCall, R_GlobalEnv, &errorStatus);
logger.msg(Arc::DEBUG, "R_tryEval to format result returned error status %d.", errorStatus);
UNPROTECT(2); // printCall + printExpr
if(errorStatus == 0) {
logger.msg(Arc::DEBUG, "capturedString is of type %d.", TYPEOF(capturedString));
int nLines = Rf_length(capturedString);
for(int j=0;j<nLines;j++)
lineResult.NewChild("output") = Rf_translateCharUTF8(STRING_ELT(capturedString,j));
}
}
} else {
std::stringstream statusStr;
statusStr << errorStatus;
lineResult.NewChild("errorStatus") = statusStr.str();
}
}
UNPROTECT(3); //command str + commands + dataForR
}
}
logger.msg(Arc::DEBUG, "eQTL service done...");
outmsg.Payload(outpayload);
return Arc::MCC_Status(Arc::STATUS_OK);
}
}//namespace
<|endoftext|>
|
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2018 Michael Fink
//
/// \file GeoTagTool\MainFrame.cpp GeoTagTool main frame
//
#include "stdafx.h"
#include "res/Ribbon.h"
#include "resource.h"
#include "AboutDlg.hpp"
#include "GeoTagToolView.hpp"
#include "MainFrame.hpp"
#include "SerialPortDlg.hpp"
BOOL MainFrame::PreTranslateMessage(MSG* pMsg)
{
if (CRibbonFrameWindowImpl<MainFrame>::PreTranslateMessage(pMsg))
return TRUE;
return m_tabView.PreTranslateMessage(pMsg);
}
BOOL MainFrame::OnIdle()
{
return FALSE;
}
LRESULT MainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
m_cmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD);
m_cmdBar.AttachMenu(GetMenu());
m_cmdBar.LoadImages(IDR_MAINFRAME);
CreateSimpleStatusBar();
m_hWndClient = m_tabView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
// create tab views
//m_view.Create(m_tabView);
//m_tabView.AddPage(m_satelliteInfoView.m_hWnd, _T("Geo Tagging"));
m_satelliteInfoView.Create(m_tabView);
m_tabView.AddPage(m_satelliteInfoView.m_hWnd, _T("Satellite Info"));
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
ShowRibbonUI(true);
return 0;
}
LRESULT MainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT MainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT MainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
AboutDlg dlg;
dlg.DoModal();
return 0;
}
LRESULT MainFrame::OnDataSourceOpenGPSReceiver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if (m_liveTrack == nullptr)
{
m_liveTrack = std::make_unique<GPS::Track>();
}
SerialPortDlg dlg;
if (IDOK != dlg.DoModal(m_hWnd))
return 0;
m_gpsReceiver = std::make_unique<GPS::Receiver>();
m_gpsReceiver->Configure(dlg.GetSerialPortDeviceName());
m_view.OnStartingGPSReceiver(*m_gpsReceiver);
try
{
m_gpsReceiver->Start(*m_liveTrack.get());
}
catch (const std::exception& ex)
{
CString text;
text.Format(_T("Error while opening serial port: %hs"), ex.what());
AtlMessageBox(m_hWnd, text.GetString());
return 0;
}
return 0;
}
LRESULT MainFrame::OnDataSourceImportTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT MainFrame::OnActionsTagImages(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT MainFrame::OnActionsSaveLiveTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
return 0;
}
<commit_msg>added file open dialog and track importing<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2018 Michael Fink
//
/// \file GeoTagTool\MainFrame.cpp GeoTagTool main frame
//
#include "stdafx.h"
#include "res/Ribbon.h"
#include "resource.h"
#include "AboutDlg.hpp"
#include "GeoTagToolView.hpp"
#include "MainFrame.hpp"
#include "SerialPortDlg.hpp"
#include "Import/TrackImport.hpp"
BOOL MainFrame::PreTranslateMessage(MSG* pMsg)
{
if (CRibbonFrameWindowImpl<MainFrame>::PreTranslateMessage(pMsg))
return TRUE;
return m_tabView.PreTranslateMessage(pMsg);
}
BOOL MainFrame::OnIdle()
{
return FALSE;
}
LRESULT MainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
m_cmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD);
m_cmdBar.AttachMenu(GetMenu());
m_cmdBar.LoadImages(IDR_MAINFRAME);
CreateSimpleStatusBar();
m_hWndClient = m_tabView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
// create tab views
//m_view.Create(m_tabView);
//m_tabView.AddPage(m_satelliteInfoView.m_hWnd, _T("Geo Tagging"));
m_satelliteInfoView.Create(m_tabView);
m_tabView.AddPage(m_satelliteInfoView.m_hWnd, _T("Satellite Info"));
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
ShowRibbonUI(true);
return 0;
}
LRESULT MainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT MainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT MainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
AboutDlg dlg;
dlg.DoModal();
return 0;
}
LRESULT MainFrame::OnDataSourceOpenGPSReceiver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if (m_liveTrack == nullptr)
{
m_liveTrack = std::make_unique<GPS::Track>();
}
SerialPortDlg dlg;
if (IDOK != dlg.DoModal(m_hWnd))
return 0;
m_gpsReceiver = std::make_unique<GPS::Receiver>();
m_gpsReceiver->Configure(dlg.GetSerialPortDeviceName());
m_view.OnStartingGPSReceiver(*m_gpsReceiver);
try
{
m_gpsReceiver->Start(*m_liveTrack.get());
}
catch (const std::exception& ex)
{
CString text;
text.Format(_T("Error while opening serial port: %hs"), ex.what());
AtlMessageBox(m_hWnd, text.GetString());
return 0;
}
return 0;
}
LRESULT MainFrame::OnDataSourceImportTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CFileDialog dlg(TRUE,
NULL,
_T(""),
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
_T("GPX Files (*.gpx)\0*.gpx\0")
_T("NMEA 0183 Log Files (*.txt; *.nmea)\0*.txt;*.nmea\0")
_T("All Files (*.*)\0*.*\0"),
m_hWnd);
int ret = dlg.DoModal(m_hWnd);
if (ret != IDOK)
return 0;
CString filename = dlg.m_szFileName;
try
{
GPS::Track track;
Import::TrackImport::ImportTrack(filename, track);
// TODO add to list
}
catch (const std::exception& ex)
{
CString text;
text.Format(_T("Error while opening serial port: %hs"), ex.what());
AtlMessageBox(m_hWnd, text.GetString());
}
return 0;
}
LRESULT MainFrame::OnActionsTagImages(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT MainFrame::OnActionsSaveLiveTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
return 0;
}
<|endoftext|>
|
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/cpu/processor.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
X_STATUS xeExGetXConfigSetting(uint16_t category, uint16_t setting,
void* buffer, uint16_t buffer_size,
uint16_t* required_size) {
uint16_t setting_size = 0;
uint32_t value = 0;
// TODO(benvanik): have real structs here that just get copied from.
// http://free60.org/XConfig
// http://freestyledash.googlecode.com/svn/trunk/Freestyle/Tools/Generic/ExConfig.h
switch (category) {
case 0x0002:
// XCONFIG_SECURED_CATEGORY
switch (setting) {
case 0x0002: // XCONFIG_SECURED_AV_REGION
setting_size = 4;
value = 0x00001000; // USA/Canada
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
case 0x0003:
// XCONFIG_USER_CATEGORY
switch (setting) {
case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS
case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME
case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME
case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE
case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE
case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS
case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x0009: // XCONFIG_USER_LANGUAGE
setting_size = 4;
value = 0x00000001; // English
break;
case 0x000A: // XCONFIG_USER_VIDEO_FLAGS
setting_size = 4;
value = 0x00040000;
break;
case 0x000C: // XCONFIG_USER_RETAIL_FLAGS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x000E: // XCONFIG_USER_COUNTRY
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
default:
assert_unhandled_case(category);
return X_STATUS_INVALID_PARAMETER_1;
}
if (buffer_size < setting_size) {
return X_STATUS_BUFFER_TOO_SMALL;
}
if (!buffer && buffer_size) {
return X_STATUS_INVALID_PARAMETER_3;
}
if (buffer) {
xe::store_and_swap<uint32_t>(buffer, value);
}
if (required_size) {
*required_size = setting_size;
}
return X_STATUS_SUCCESS;
}
SHIM_CALL ExGetXConfigSetting_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint16_t category = SHIM_GET_ARG_16(0);
uint16_t setting = SHIM_GET_ARG_16(1);
uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
uint16_t buffer_size = SHIM_GET_ARG_16(3);
uint32_t required_size_ptr = SHIM_GET_ARG_32(4);
XELOGD("ExGetXConfigSetting(%.4X, %.4X, %.8X, %.4X, %.8X)", category, setting,
buffer_ptr, buffer_size, required_size_ptr);
void* buffer = buffer_ptr ? SHIM_MEM_ADDR(buffer_ptr) : NULL;
uint16_t required_size = 0;
X_STATUS result = xeExGetXConfigSetting(category, setting, buffer,
buffer_size, &required_size);
if (required_size_ptr) {
SHIM_SET_MEM_16(required_size_ptr, required_size);
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexCheckExecutablePrivilege_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t privilege = SHIM_GET_ARG_32(0);
XELOGD("XexCheckExecutablePrivilege(%.8X)", privilege);
// BOOL
// DWORD Privilege
// Privilege is bit position in xe_xex2_system_flags enum - so:
// Privilege=6 -> 0x00000040 -> XEX_SYSTEM_INSECURE_SOCKETS
uint32_t mask = 1 << privilege;
auto module = kernel_state->GetExecutableModule();
if (!module) {
SHIM_SET_RETURN_32(0);
return;
}
uint32_t flags = 0;
module->GetOptHeader<uint32_t>(XEX_HEADER_SYSTEM_FLAGS, &flags);
SHIM_SET_RETURN_32((flags & mask) > 0);
}
SHIM_CALL XexGetModuleHandle_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t hmodule_ptr = SHIM_GET_ARG_32(1);
XELOGD("XexGetModuleHandle(%s, %.8X)", module_name, hmodule_ptr);
object_ref<XModule> module;
if (!module_name) {
module = kernel_state->GetExecutableModule();
} else {
module = kernel_state->GetModule(module_name);
}
if (!module) {
SHIM_SET_MEM_32(hmodule_ptr, 0);
SHIM_SET_RETURN_32(X_ERROR_NOT_FOUND);
return;
}
// NOTE: we don't retain the handle for return.
SHIM_SET_MEM_32(hmodule_ptr, module->hmodule_ptr());
SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}
SHIM_CALL XexGetModuleSection_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t hmodule = SHIM_GET_ARG_32(0);
uint32_t name_ptr = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
uint32_t data_ptr = SHIM_GET_ARG_32(2);
uint32_t size_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexGetModuleSection(%.8X, %s, %.8X, %.8X)", hmodule, name, data_ptr,
size_ptr);
X_STATUS result = X_STATUS_SUCCESS;
auto module = XModule::GetFromHModule(kernel_state, SHIM_MEM_ADDR(hmodule));
if (module) {
uint32_t section_data = 0;
uint32_t section_size = 0;
result = module->GetSection(name, §ion_data, §ion_size);
if (XSUCCEEDED(result)) {
SHIM_SET_MEM_32(data_ptr, section_data);
SHIM_SET_MEM_32(size_ptr, section_size);
}
} else {
result = X_STATUS_INVALID_HANDLE;
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexLoadImage_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_flags = SHIM_GET_ARG_32(1);
uint32_t min_version = SHIM_GET_ARG_32(2);
uint32_t hmodule_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexLoadImage(%s, %.8X, %.8X, %.8X)", module_name, module_flags,
min_version, hmodule_ptr);
X_STATUS result = X_STATUS_NO_SUCH_FILE;
uint32_t hmodule = 0;
auto module = kernel_state->GetModule(module_name);
if (module) {
// Existing module found.
hmodule = module->hmodule_ptr();
result = X_STATUS_SUCCESS;
} else {
// Not found; attempt to load as a user module.
auto user_module = kernel_state->LoadUserModule(module_name);
if (user_module) {
user_module->RetainHandle();
hmodule = user_module->hmodule_ptr();
result = X_STATUS_SUCCESS;
}
}
// Increment the module's load count.
if (hmodule) {
auto ldr_data =
kernel_memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(hmodule);
ldr_data->load_count++;
}
SHIM_SET_MEM_32(hmodule_ptr, hmodule);
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexUnloadImage_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t hmodule = SHIM_GET_ARG_32(0);
XELOGD("XexUnloadImage(%.8X)", hmodule);
auto module = XModule::GetFromHModule(kernel_state, SHIM_MEM_ADDR(hmodule));
if (!module) {
SHIM_SET_RETURN_32(X_STATUS_INVALID_HANDLE);
return;
}
// Can't unload kernel modules from user code.
if (module->module_type() != XModule::ModuleType::kKernelModule) {
auto ldr_data =
kernel_state->memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(
hmodule);
if (--ldr_data->load_count == 0) {
// No more references, free it.
kernel_state->object_table()->RemoveHandle(module->handle());
}
}
SHIM_SET_RETURN_32(X_STATUS_SUCCESS);
}
SHIM_CALL XexGetProcedureAddress_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t hmodule = SHIM_GET_ARG_32(0);
uint32_t ordinal = SHIM_GET_ARG_32(1);
uint32_t out_function_ptr = SHIM_GET_ARG_32(2);
// May be entry point?
assert_not_zero(ordinal);
bool is_string_name = (ordinal & 0xFFFF0000) != 0;
auto string_name = reinterpret_cast<const char*>(SHIM_MEM_ADDR(ordinal));
if (is_string_name) {
XELOGD("XexGetProcedureAddress(%.8X, %.8X(%s), %.8X)", hmodule, ordinal,
string_name, out_function_ptr);
} else {
XELOGD("XexGetProcedureAddress(%.8X, %.8X, %.8X)", hmodule, ordinal,
out_function_ptr);
}
X_STATUS result = X_STATUS_INVALID_HANDLE;
object_ref<XModule> module;
if (!hmodule) {
module = kernel_state->GetExecutableModule();
} else {
module = XModule::GetFromHModule(kernel_state, SHIM_MEM_ADDR(hmodule));
}
if (module) {
uint32_t ptr;
if (is_string_name) {
ptr = module->GetProcAddressByName(string_name);
} else {
ptr = module->GetProcAddressByOrdinal(ordinal);
}
if (ptr) {
SHIM_SET_MEM_32(out_function_ptr, ptr);
result = X_STATUS_SUCCESS;
} else {
XELOGW("ERROR: XexGetProcedureAddress ordinal not found!");
SHIM_SET_MEM_32(out_function_ptr, 0);
result = X_STATUS_DRIVER_ORDINAL_NOT_FOUND;
}
}
SHIM_SET_RETURN_32(result);
}
void AppendParam(StringBuffer& string_buffer,
pointer_t<X_EX_TITLE_TERMINATE_REGISTRATION> reg) {
string_buffer.AppendFormat("%.8X(%.8X, %.8X)", reg.guest_address(),
reg->notification_routine, reg->priority);
}
void ExRegisterTitleTerminateNotification(
pointer_t<X_EX_TITLE_TERMINATE_REGISTRATION> reg, dword_t create) {
if (create) {
// Adding.
kernel_state()->RegisterTitleTerminateNotification(
reg->notification_routine, reg->priority);
} else {
// Removing.
kernel_state()->RemoveTitleTerminateNotification(reg->notification_routine);
}
}
DECLARE_XBOXKRNL_EXPORT(ExRegisterTitleTerminateNotification,
ExportTag::kImplemented);
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterModuleExports(
xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {
SHIM_SET_MAPPING("xboxkrnl.exe", ExGetXConfigSetting, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexCheckExecutablePrivilege, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleHandle, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleSection, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexLoadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexUnloadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetProcedureAddress, state);
}
<commit_msg>module Retain instead of RetainHandle<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/cpu/processor.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
X_STATUS xeExGetXConfigSetting(uint16_t category, uint16_t setting,
void* buffer, uint16_t buffer_size,
uint16_t* required_size) {
uint16_t setting_size = 0;
uint32_t value = 0;
// TODO(benvanik): have real structs here that just get copied from.
// http://free60.org/XConfig
// http://freestyledash.googlecode.com/svn/trunk/Freestyle/Tools/Generic/ExConfig.h
switch (category) {
case 0x0002:
// XCONFIG_SECURED_CATEGORY
switch (setting) {
case 0x0002: // XCONFIG_SECURED_AV_REGION
setting_size = 4;
value = 0x00001000; // USA/Canada
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
case 0x0003:
// XCONFIG_USER_CATEGORY
switch (setting) {
case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS
case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME
case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME
case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE
case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE
case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS
case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x0009: // XCONFIG_USER_LANGUAGE
setting_size = 4;
value = 0x00000001; // English
break;
case 0x000A: // XCONFIG_USER_VIDEO_FLAGS
setting_size = 4;
value = 0x00040000;
break;
case 0x000C: // XCONFIG_USER_RETAIL_FLAGS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x000E: // XCONFIG_USER_COUNTRY
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
default:
assert_unhandled_case(category);
return X_STATUS_INVALID_PARAMETER_1;
}
if (buffer_size < setting_size) {
return X_STATUS_BUFFER_TOO_SMALL;
}
if (!buffer && buffer_size) {
return X_STATUS_INVALID_PARAMETER_3;
}
if (buffer) {
xe::store_and_swap<uint32_t>(buffer, value);
}
if (required_size) {
*required_size = setting_size;
}
return X_STATUS_SUCCESS;
}
SHIM_CALL ExGetXConfigSetting_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint16_t category = SHIM_GET_ARG_16(0);
uint16_t setting = SHIM_GET_ARG_16(1);
uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
uint16_t buffer_size = SHIM_GET_ARG_16(3);
uint32_t required_size_ptr = SHIM_GET_ARG_32(4);
XELOGD("ExGetXConfigSetting(%.4X, %.4X, %.8X, %.4X, %.8X)", category, setting,
buffer_ptr, buffer_size, required_size_ptr);
void* buffer = buffer_ptr ? SHIM_MEM_ADDR(buffer_ptr) : NULL;
uint16_t required_size = 0;
X_STATUS result = xeExGetXConfigSetting(category, setting, buffer,
buffer_size, &required_size);
if (required_size_ptr) {
SHIM_SET_MEM_16(required_size_ptr, required_size);
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexCheckExecutablePrivilege_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t privilege = SHIM_GET_ARG_32(0);
XELOGD("XexCheckExecutablePrivilege(%.8X)", privilege);
// BOOL
// DWORD Privilege
// Privilege is bit position in xe_xex2_system_flags enum - so:
// Privilege=6 -> 0x00000040 -> XEX_SYSTEM_INSECURE_SOCKETS
uint32_t mask = 1 << privilege;
auto module = kernel_state->GetExecutableModule();
if (!module) {
SHIM_SET_RETURN_32(0);
return;
}
uint32_t flags = 0;
module->GetOptHeader<uint32_t>(XEX_HEADER_SYSTEM_FLAGS, &flags);
SHIM_SET_RETURN_32((flags & mask) > 0);
}
SHIM_CALL XexGetModuleHandle_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t hmodule_ptr = SHIM_GET_ARG_32(1);
XELOGD("XexGetModuleHandle(%s, %.8X)", module_name, hmodule_ptr);
object_ref<XModule> module;
if (!module_name) {
module = kernel_state->GetExecutableModule();
} else {
module = kernel_state->GetModule(module_name);
}
if (!module) {
SHIM_SET_MEM_32(hmodule_ptr, 0);
SHIM_SET_RETURN_32(X_ERROR_NOT_FOUND);
return;
}
// NOTE: we don't retain the handle for return.
SHIM_SET_MEM_32(hmodule_ptr, module->hmodule_ptr());
SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}
SHIM_CALL XexGetModuleSection_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t hmodule = SHIM_GET_ARG_32(0);
uint32_t name_ptr = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
uint32_t data_ptr = SHIM_GET_ARG_32(2);
uint32_t size_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexGetModuleSection(%.8X, %s, %.8X, %.8X)", hmodule, name, data_ptr,
size_ptr);
X_STATUS result = X_STATUS_SUCCESS;
auto module = XModule::GetFromHModule(kernel_state, SHIM_MEM_ADDR(hmodule));
if (module) {
uint32_t section_data = 0;
uint32_t section_size = 0;
result = module->GetSection(name, §ion_data, §ion_size);
if (XSUCCEEDED(result)) {
SHIM_SET_MEM_32(data_ptr, section_data);
SHIM_SET_MEM_32(size_ptr, section_size);
}
} else {
result = X_STATUS_INVALID_HANDLE;
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexLoadImage_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_flags = SHIM_GET_ARG_32(1);
uint32_t min_version = SHIM_GET_ARG_32(2);
uint32_t hmodule_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexLoadImage(%s, %.8X, %.8X, %.8X)", module_name, module_flags,
min_version, hmodule_ptr);
X_STATUS result = X_STATUS_NO_SUCH_FILE;
uint32_t hmodule = 0;
auto module = kernel_state->GetModule(module_name);
if (module) {
// Existing module found.
hmodule = module->hmodule_ptr();
result = X_STATUS_SUCCESS;
} else {
// Not found; attempt to load as a user module.
auto user_module = kernel_state->LoadUserModule(module_name);
if (user_module) {
user_module->Retain();
hmodule = user_module->hmodule_ptr();
result = X_STATUS_SUCCESS;
}
}
// Increment the module's load count.
if (hmodule) {
auto ldr_data =
kernel_memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(hmodule);
ldr_data->load_count++;
}
SHIM_SET_MEM_32(hmodule_ptr, hmodule);
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexUnloadImage_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t hmodule = SHIM_GET_ARG_32(0);
XELOGD("XexUnloadImage(%.8X)", hmodule);
auto module = XModule::GetFromHModule(kernel_state, SHIM_MEM_ADDR(hmodule));
if (!module) {
SHIM_SET_RETURN_32(X_STATUS_INVALID_HANDLE);
return;
}
// Can't unload kernel modules from user code.
if (module->module_type() != XModule::ModuleType::kKernelModule) {
auto ldr_data =
kernel_state->memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(
hmodule);
if (--ldr_data->load_count == 0) {
// No more references, free it.
module->Release();
kernel_state->object_table()->RemoveHandle(module->handle());
}
}
SHIM_SET_RETURN_32(X_STATUS_SUCCESS);
}
SHIM_CALL XexGetProcedureAddress_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t hmodule = SHIM_GET_ARG_32(0);
uint32_t ordinal = SHIM_GET_ARG_32(1);
uint32_t out_function_ptr = SHIM_GET_ARG_32(2);
// May be entry point?
assert_not_zero(ordinal);
bool is_string_name = (ordinal & 0xFFFF0000) != 0;
auto string_name = reinterpret_cast<const char*>(SHIM_MEM_ADDR(ordinal));
if (is_string_name) {
XELOGD("XexGetProcedureAddress(%.8X, %.8X(%s), %.8X)", hmodule, ordinal,
string_name, out_function_ptr);
} else {
XELOGD("XexGetProcedureAddress(%.8X, %.8X, %.8X)", hmodule, ordinal,
out_function_ptr);
}
X_STATUS result = X_STATUS_INVALID_HANDLE;
object_ref<XModule> module;
if (!hmodule) {
module = kernel_state->GetExecutableModule();
} else {
module = XModule::GetFromHModule(kernel_state, SHIM_MEM_ADDR(hmodule));
}
if (module) {
uint32_t ptr;
if (is_string_name) {
ptr = module->GetProcAddressByName(string_name);
} else {
ptr = module->GetProcAddressByOrdinal(ordinal);
}
if (ptr) {
SHIM_SET_MEM_32(out_function_ptr, ptr);
result = X_STATUS_SUCCESS;
} else {
XELOGW("ERROR: XexGetProcedureAddress ordinal not found!");
SHIM_SET_MEM_32(out_function_ptr, 0);
result = X_STATUS_DRIVER_ORDINAL_NOT_FOUND;
}
}
SHIM_SET_RETURN_32(result);
}
void AppendParam(StringBuffer& string_buffer,
pointer_t<X_EX_TITLE_TERMINATE_REGISTRATION> reg) {
string_buffer.AppendFormat("%.8X(%.8X, %.8X)", reg.guest_address(),
reg->notification_routine, reg->priority);
}
void ExRegisterTitleTerminateNotification(
pointer_t<X_EX_TITLE_TERMINATE_REGISTRATION> reg, dword_t create) {
if (create) {
// Adding.
kernel_state()->RegisterTitleTerminateNotification(
reg->notification_routine, reg->priority);
} else {
// Removing.
kernel_state()->RemoveTitleTerminateNotification(reg->notification_routine);
}
}
DECLARE_XBOXKRNL_EXPORT(ExRegisterTitleTerminateNotification,
ExportTag::kImplemented);
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterModuleExports(
xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {
SHIM_SET_MAPPING("xboxkrnl.exe", ExGetXConfigSetting, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexCheckExecutablePrivilege, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleHandle, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleSection, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexLoadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexUnloadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetProcedureAddress, state);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ccoll.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:37:33 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "cmdid.h"
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#include "swmodule.hxx"
#include "view.hxx"
#include "wrtsh.hxx"
#include "globals.hrc"
#include "helpid.h"
#ifndef _SFX_STYFITEM_HXX //autogen
#include <sfx2/styfitem.hxx>
#endif
#include "uitool.hxx"
#include "ccoll.hxx"
#include "fmtcol.hxx"
#include "hintids.hxx"
#include "docsh.hxx"
#include "docstyle.hxx"
#include "hints.hxx"
#include "chrdlg.hrc"
#include "ccoll.hrc"
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#define C2U(x) rtl::OUString::createFromAscii(x)
// ******************************************************************
//!! order of entries has to be the same as in
//!! CommandStruct SwCondCollItem::aCmds[]
const char *aCommandContext[COND_COMMAND_COUNT] =
{
"TableHeader",
"Table",
"Frame",
"Section",
"Footnote",
"Endnote",
"Header",
"Footer",
"OutlineLevel1",
"OutlineLevel2",
"OutlineLevel3",
"OutlineLevel4",
"OutlineLevel5",
"OutlineLevel6",
"OutlineLevel7",
"OutlineLevel8",
"OutlineLevel9",
"OutlineLevel10",
"NumberingLevel1",
"NumberingLevel2",
"NumberingLevel3",
"NumberingLevel4",
"NumberingLevel5",
"NumberingLevel6",
"NumberingLevel7",
"NumberingLevel8",
"NumberingLevel9",
"NumberingLevel10"
};
sal_Int16 GetCommandContextIndex( const rtl::OUString &rContextName )
{
sal_Int16 nRes = -1;
for (sal_Int16 i = 0; nRes == -1 && i < COND_COMMAND_COUNT; ++i)
{
if (rContextName.equalsAscii( aCommandContext[i] ))
nRes = i;
}
return nRes;
}
rtl::OUString GetCommandContextByIndex( sal_Int16 nIndex )
{
rtl::OUString aRes;
if (0 <= nIndex && nIndex < COND_COMMAND_COUNT)
{
aRes = C2U( aCommandContext[ nIndex ] );
}
return aRes;
}
// Globals ******************************************************************
//CHINA001 static USHORT __FAR_DATA aPageRg[] = {
//CHINA001 FN_COND_COLL, FN_COND_COLL,
//CHINA001 0
//CHINA001 };
// Achtung im Code wird dieses Array direkt (0, 1, ...) indiziert
//CHINA001 static long nTabs[] =
//CHINA001 { 2, // Number of Tabs
//CHINA001 0, 100
//CHINA001 };
CommandStruct SwCondCollItem::aCmds[] = {
PARA_IN_TABLEHEAD, 0,
PARA_IN_TABLEBODY, 0,
PARA_IN_FRAME, 0,
PARA_IN_SECTION, 0,
PARA_IN_FOOTENOTE, 0,
PARA_IN_ENDNOTE, 0,
PARA_IN_HEADER, 0,
PARA_IN_FOOTER, 0,
PARA_IN_OUTLINE, 0,
PARA_IN_OUTLINE, 1,
PARA_IN_OUTLINE, 2,
PARA_IN_OUTLINE, 3,
PARA_IN_OUTLINE, 4,
PARA_IN_OUTLINE, 5,
PARA_IN_OUTLINE, 6,
PARA_IN_OUTLINE, 7,
PARA_IN_OUTLINE, 8,
PARA_IN_OUTLINE, 9,
PARA_IN_LIST, 0,
PARA_IN_LIST, 1,
PARA_IN_LIST, 2,
PARA_IN_LIST, 3,
PARA_IN_LIST, 4,
PARA_IN_LIST, 5,
PARA_IN_LIST, 6,
PARA_IN_LIST, 7,
PARA_IN_LIST, 8,
PARA_IN_LIST, 9
};
TYPEINIT1_AUTOFACTORY(SwCondCollItem, SfxPoolItem)
/****************************************************************************
Page: Ctor
****************************************************************************/
//CHINA001 SwCondCollPage::SwCondCollPage(Window *pParent, const SfxItemSet &rSet)
//CHINA001
//CHINA001 : SfxTabPage(pParent, SW_RES(TP_CONDCOLL), rSet),
//CHINA001 aConditionFL( this, ResId( FL_CONDITION )),
//CHINA001 aConditionCB( this, ResId( CB_CONDITION ) ),
//CHINA001 aContextFT ( this, ResId( FT_CONTEXT ) ),
//CHINA001 aUsedFT ( this, ResId( FT_USED ) ),
//CHINA001 aTbLinks( this, ResId( TB_CONDCOLLS ) ),
//CHINA001 aStyleFT ( this, ResId( FT_STYLE ) ),
//CHINA001 aStyleLB ( this, ResId( LB_STYLE ) ),
//CHINA001 aFilterLB ( this, ResId( LB_FILTER ) ),
//CHINA001 aRemovePB ( this, ResId( PB_REMOVE ) ),
//CHINA001 aAssignPB ( this, ResId( PB_ASSIGN ) ),
//CHINA001 sNoTmpl ( ResId( STR_NOTEMPL ) ),
//CHINA001 aStrArr ( ResId( STR_REGIONS ) ),
//CHINA001 rSh(::GetActiveView()->GetWrtShell()),
//CHINA001 pFmt(0),
//CHINA001 pCmds( SwCondCollItem::GetCmds() ),
//CHINA001 bNewTemplate(FALSE)
//CHINA001 {
//CHINA001 FreeResource();
//CHINA001 SetExchangeSupport();
//CHINA001
//CHINA001 // Handler installieren
//CHINA001 aConditionCB.SetClickHdl( LINK(this, SwCondCollPage, OnOffHdl));
//CHINA001 aTbLinks.SetDoubleClickHdl( LINK(this, SwCondCollPage, AssignRemoveHdl ));
//CHINA001 aStyleLB.SetDoubleClickHdl( LINK(this, SwCondCollPage, AssignRemoveHdl ));
//CHINA001 aRemovePB.SetClickHdl( LINK(this, SwCondCollPage, AssignRemoveHdl ));
//CHINA001 aAssignPB.SetClickHdl( LINK(this, SwCondCollPage, AssignRemoveHdl ));
//CHINA001 aTbLinks.SetSelectHdl( LINK(this, SwCondCollPage, SelectHdl));
//CHINA001 aStyleLB.SetSelectHdl( LINK(this, SwCondCollPage, SelectHdl));
//CHINA001 aFilterLB.SetSelectHdl( LINK(this, SwCondCollPage, SelectHdl));
//CHINA001
//CHINA001 aTbLinks.SetWindowBits(WB_HSCROLL|WB_CLIPCHILDREN);
//CHINA001 aTbLinks.SetSelectionMode( SINGLE_SELECTION );
//CHINA001 aTbLinks.SetTabs( &nTabs[0], MAP_APPFONT );
//CHINA001 aTbLinks.Resize(); // OS: Hack fuer richtige Selektion
//CHINA001 aTbLinks.SetSpaceBetweenEntries( 0 );
//CHINA001 aTbLinks.SetHelpId(HID_COND_COLL_TABLIST);
//CHINA001
//CHINA001 SfxStyleFamilies aFamilies(SW_RES(DLG_STYLE_DESIGNER));
//CHINA001 const SfxStyleFamilyItem* pFamilyItem;
//CHINA001 USHORT nCount = aFamilies.Count();
//CHINA001 USHORT i;
//CHINA001
//CHINA001 for( i = 0; i < nCount; ++i)
//CHINA001 {
//CHINA001 if(SFX_STYLE_FAMILY_PARA == (USHORT)(pFamilyItem = aFamilies.GetObject(i))->GetFamily())
//CHINA001 break;
//CHINA001 }
//CHINA001
//CHINA001 const SfxStyleFilter& rFilterList = pFamilyItem->GetFilterList();
//CHINA001 for( i = 0; i < rFilterList.Count(); ++i)
//CHINA001 {
//CHINA001 aFilterLB.InsertEntry(rFilterList.GetObject(i)->aName);
//CHINA001 USHORT* pFilter = new USHORT(rFilterList.GetObject(i)->nFlags);
//CHINA001 aFilterLB.SetEntryData(i, pFilter);
//CHINA001 }
//CHINA001 aFilterLB.SelectEntryPos(1);
//CHINA001
//CHINA001 aTbLinks.Show();
//CHINA001
//CHINA001 }
/****************************************************************************
Page: Dtor
****************************************************************************/
//CHINA001 __EXPORT SwCondCollPage::~SwCondCollPage()
//CHINA001 {
//CHINA001 for(USHORT i = 0; i < aFilterLB.GetEntryCount(); ++i)
//CHINA001 delete (USHORT*)aFilterLB.GetEntryData(i);
//CHINA001
//CHINA001 }
//CHINA001 int __EXPORT SwCondCollPage::DeactivatePage(SfxItemSet * pSet)
//CHINA001 {
//CHINA001 if( pSet )
//CHINA001 FillItemSet(*pSet);
//CHINA001
//CHINA001 return LEAVE_PAGE;
//CHINA001 }
/****************************************************************************
Page: Factory
****************************************************************************/
//CHINA001 SfxTabPage* __EXPORT SwCondCollPage::Create(Window *pParent, const SfxItemSet &rSet)
//CHINA001 {
//CHINA001 return new SwCondCollPage(pParent, rSet);
//CHINA001 }
/****************************************************************************
Page: FillItemSet-Overload
****************************************************************************/
//CHINA001 BOOL __EXPORT SwCondCollPage::FillItemSet(SfxItemSet &rSet)
//CHINA001 {
//CHINA001 BOOL bModified = TRUE;
//CHINA001 SwCondCollItem aCondItem;
//CHINA001 for(USHORT i = 0; i < aStrArr.Count(); i++)
//CHINA001 {
//CHINA001 String sEntry = aTbLinks.GetEntryText(i, 1);
//CHINA001 aCondItem.SetStyle( &sEntry, i);
//CHINA001 }
//CHINA001 rSet.Put(aCondItem);
//CHINA001 return bModified;
//CHINA001 }
/****************************************************************************
Page: Reset-Overload
****************************************************************************/
//CHINA001 void __EXPORT SwCondCollPage::Reset(const SfxItemSet &rSet)
//CHINA001 {
//CHINA001 if(bNewTemplate)
//CHINA001 aConditionCB.Enable();
//CHINA001 if(RES_CONDTXTFMTCOLL == pFmt->Which())
//CHINA001 aConditionCB.Check();
//CHINA001 OnOffHdl(&aConditionCB);
//CHINA001
//CHINA001 aTbLinks.Clear();
//CHINA001
//CHINA001 SfxStyleSheetBasePool* pPool = rSh.GetView().GetDocShell()->GetStyleSheetPool();
//CHINA001 pPool->SetSearchMask(SFX_STYLE_FAMILY_PARA, SFXSTYLEBIT_ALL);
//CHINA001 aStyleLB.Clear();
//CHINA001 const SfxStyleSheetBase* pBase = pPool->First();
//CHINA001 while( pBase )
//CHINA001 {
//CHINA001 if(!pFmt || pBase->GetName() != pFmt->GetName())
//CHINA001 aStyleLB.InsertEntry(pBase->GetName());
//CHINA001 pBase = pPool->Next();
//CHINA001 }
//CHINA001 aStyleLB.SelectEntryPos(0);
//CHINA001
//CHINA001 for( USHORT n = 0; n < aStrArr.Count(); n++)
//CHINA001 {
//CHINA001 String aEntry( aStrArr.GetString(n) );
//CHINA001 aEntry += '\t';
//CHINA001
//CHINA001 const SwCollCondition* pCond;
//CHINA001 if( pFmt && RES_CONDTXTFMTCOLL == pFmt->Which() &&
//CHINA001 0 != ( pCond = ((SwConditionTxtFmtColl*)pFmt)->
//CHINA001 HasCondition( SwCollCondition( 0, pCmds[n].nCnd, pCmds[n].nSubCond ) ) )
//CHINA001 && pCond->GetTxtFmtColl() )
//CHINA001 {
//CHINA001 aEntry += pCond->GetTxtFmtColl()->GetName();
//CHINA001 }
//CHINA001
//CHINA001 SvLBoxEntry* pE = aTbLinks.InsertEntry( aEntry, n );
//CHINA001 if(0 == n)
//CHINA001 aTbLinks.Select(pE);
//CHINA001 }
//CHINA001
//CHINA001 }
/****************************************************************************
****************************************************************************/
//CHINA001 USHORT* __EXPORT SwCondCollPage::GetRanges()
//CHINA001 {
//CHINA001 return aPageRg;
//CHINA001 }
/****************************************************************************
****************************************************************************/
//CHINA001 IMPL_LINK( SwCondCollPage, OnOffHdl, CheckBox*, pBox )
//CHINA001 {
//CHINA001 const BOOL bEnable = pBox->IsChecked();
//CHINA001 aContextFT.Enable( bEnable );
//CHINA001 aUsedFT .Enable( bEnable );
//CHINA001 aTbLinks .Enable( bEnable );
//CHINA001 aStyleFT .Enable( bEnable );
//CHINA001 aStyleLB .Enable( bEnable );
//CHINA001 aFilterLB .Enable( bEnable );
//CHINA001 aRemovePB .Enable( bEnable );
//CHINA001 aAssignPB .Enable( bEnable );
//CHINA001 if( bEnable )
//CHINA001 SelectHdl(0);
//CHINA001 return 0;
//CHINA001 }
//CHINA001
/****************************************************************************
****************************************************************************/
//CHINA001 IMPL_LINK( SwCondCollPage, AssignRemoveHdl, PushButton*, pBtn)
//CHINA001 {
//CHINA001 SvLBoxEntry* pE = aTbLinks.FirstSelected();
//CHINA001 ULONG nPos;
//CHINA001 if( !pE || LISTBOX_ENTRY_NOTFOUND ==
//CHINA001 ( nPos = aTbLinks.GetModel()->GetAbsPos( pE ) ) )
//CHINA001 {
//CHINA001 ASSERT( pE, "wo kommt der leere Eintrag her?" );
//CHINA001 return 0;
//CHINA001 }
//CHINA001
//CHINA001 String sSel = aStrArr.GetString( USHORT(nPos) );
//CHINA001 sSel += '\t';
//CHINA001
//CHINA001 const BOOL bAssEnabled = pBtn != &aRemovePB && aAssignPB.IsEnabled();
//CHINA001 aAssignPB.Enable( !bAssEnabled );
//CHINA001 aRemovePB.Enable( bAssEnabled );
//CHINA001 if ( bAssEnabled )
//CHINA001 sSel += aStyleLB.GetSelectEntry();
//CHINA001
//CHINA001 aTbLinks.SetUpdateMode(FALSE);
//CHINA001 aTbLinks.GetModel()->Remove(pE);
//CHINA001 pE = aTbLinks.InsertEntry(sSel, nPos);
//CHINA001 aTbLinks.Select(pE);
//CHINA001 aTbLinks.MakeVisible(pE);
//CHINA001 aTbLinks.SetUpdateMode(TRUE);
//CHINA001 return 0;
//CHINA001 }
//CHINA001
/****************************************************************************
****************************************************************************/
//CHINA001 IMPL_LINK( SwCondCollPage, SelectHdl, ListBox*, pBox)
//CHINA001 {
//CHINA001 if(pBox == &aFilterLB)
//CHINA001 {
//CHINA001 aStyleLB.Clear();
//CHINA001 USHORT nSearchFlags = pBox->GetSelectEntryPos();
//CHINA001 nSearchFlags = *(USHORT*)aFilterLB.GetEntryData(nSearchFlags);
//CHINA001 SfxStyleSheetBasePool* pPool = rSh.GetView().GetDocShell()->GetStyleSheetPool();
//CHINA001 pPool->SetSearchMask(SFX_STYLE_FAMILY_PARA, nSearchFlags);
//CHINA001 const SfxStyleSheetBase* pBase = pPool->First();
//CHINA001 while( pBase )
//CHINA001 {
//CHINA001 if(!pFmt || pBase->GetName() != pFmt->GetName())
//CHINA001 aStyleLB.InsertEntry(pBase->GetName());
//CHINA001 pBase = pPool->Next();
//CHINA001 }
//CHINA001 aStyleLB.SelectEntryPos(0);
//CHINA001 SelectHdl(&aStyleLB);
//CHINA001
//CHINA001 }
//CHINA001 else
//CHINA001 {
//CHINA001 String sTbEntry;
//CHINA001 SvLBoxEntry* pE = aTbLinks.FirstSelected();
//CHINA001 if(pE)
//CHINA001 sTbEntry = aTbLinks.GetEntryText(pE);
//CHINA001 sTbEntry = sTbEntry.GetToken(1, '\t');
//CHINA001 String sStyle = aStyleLB.GetSelectEntry();
//CHINA001
//CHINA001 aAssignPB.Enable( sStyle != sTbEntry && aConditionCB.IsChecked() );
//CHINA001
//CHINA001 if(pBox != &aStyleLB)
//CHINA001 aRemovePB.Enable( aConditionCB.IsChecked() && sTbEntry.Len() );
//CHINA001 }
//CHINA001 return 0;
//CHINA001 }
/****************************************************************************
****************************************************************************/
//CHINA001 void SwCondCollPage::SetCollection( SwFmt* pFormat, BOOL bNew )
//CHINA001 {
//CHINA001 pFmt = pFormat;
//CHINA001 bNewTemplate = bNew;
//CHINA001 }
/****************************************************************************
Item fuer den Transport der Bedingungstabelle
****************************************************************************/
SwCondCollItem::SwCondCollItem(USHORT nWhich ) :
SfxPoolItem(nWhich)
{
}
/****************************************************************************
****************************************************************************/
SwCondCollItem::~SwCondCollItem()
{
}
/****************************************************************************
****************************************************************************/
SfxPoolItem* SwCondCollItem::Clone( SfxItemPool *pPool ) const
{
return new SwCondCollItem(*this);
}
/****************************************************************************
****************************************************************************/
int SwCondCollItem::operator==( const SfxPoolItem& rItem) const
{
DBG_ASSERT( SfxPoolItem::operator==(rItem), "unterschiedliche Typen" );
BOOL bReturn = TRUE;
for(USHORT i = 0; i < COND_COMMAND_COUNT; i++)
if(sStyles[i] != ((SwCondCollItem&)rItem).sStyles[i])
{
bReturn = FALSE;
break;
}
return bReturn;
}
/****************************************************************************
****************************************************************************/
const String& SwCondCollItem::GetStyle(USHORT nPos) const
{
#ifndef IRIX
return nPos < COND_COMMAND_COUNT ? sStyles[nPos] : aEmptyStr;
#else
return nPos < COND_COMMAND_COUNT ? (String)sStyles[nPos] : aEmptyStr;
#endif
}
/****************************************************************************
****************************************************************************/
void SwCondCollItem::SetStyle(const String* pStyle, USHORT nPos)
{
if( nPos < COND_COMMAND_COUNT )
#ifndef IRIX
sStyles[nPos] = pStyle ? *pStyle : aEmptyStr;
#else
sStyles[nPos] = pStyle ? (String)*pStyle : aEmptyStr;
#endif
}
/****************************************************************************
****************************************************************************/
const CommandStruct* SwCondCollItem::GetCmds()
{
return aCmds;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.13.222); FILE MERGED 2007/06/01 07:17:40 tl 1.13.222.5: #i69287# warning-free code 2007/04/13 12:17:44 tl 1.13.222.4: #i69287# binfilter related comments removed 2007/04/03 13:01:01 tl 1.13.222.3: #i69287# warning-free code 2007/03/26 12:08:47 tl 1.13.222.2: #i69287# warning-free code 2007/03/05 12:45:38 tl 1.13.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ccoll.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2007-09-27 10:19:10 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "cmdid.h"
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#include "swmodule.hxx"
#include "view.hxx"
#include "wrtsh.hxx"
#include "globals.hrc"
#include "helpid.h"
#ifndef _SFX_STYFITEM_HXX //autogen
#include <sfx2/styfitem.hxx>
#endif
#include "uitool.hxx"
#include "ccoll.hxx"
#include "fmtcol.hxx"
#include "hintids.hxx"
#include "docsh.hxx"
#include "docstyle.hxx"
#include "hints.hxx"
#include "chrdlg.hrc"
#include "ccoll.hrc"
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#include <unomid.h>
// ******************************************************************
//!! order of entries has to be the same as in
//!! CommandStruct SwCondCollItem::aCmds[]
const char *aCommandContext[COND_COMMAND_COUNT] =
{
"TableHeader",
"Table",
"Frame",
"Section",
"Footnote",
"Endnote",
"Header",
"Footer",
"OutlineLevel1",
"OutlineLevel2",
"OutlineLevel3",
"OutlineLevel4",
"OutlineLevel5",
"OutlineLevel6",
"OutlineLevel7",
"OutlineLevel8",
"OutlineLevel9",
"OutlineLevel10",
"NumberingLevel1",
"NumberingLevel2",
"NumberingLevel3",
"NumberingLevel4",
"NumberingLevel5",
"NumberingLevel6",
"NumberingLevel7",
"NumberingLevel8",
"NumberingLevel9",
"NumberingLevel10"
};
sal_Int16 GetCommandContextIndex( const rtl::OUString &rContextName )
{
sal_Int16 nRes = -1;
for (sal_Int16 i = 0; nRes == -1 && i < COND_COMMAND_COUNT; ++i)
{
if (rContextName.equalsAscii( aCommandContext[i] ))
nRes = i;
}
return nRes;
}
rtl::OUString GetCommandContextByIndex( sal_Int16 nIndex )
{
rtl::OUString aRes;
if (0 <= nIndex && nIndex < COND_COMMAND_COUNT)
{
aRes = C2U( aCommandContext[ nIndex ] );
}
return aRes;
}
// Globals ******************************************************************
CommandStruct SwCondCollItem::aCmds[] =
{
{ PARA_IN_TABLEHEAD, 0 },
{ PARA_IN_TABLEBODY, 0 },
{ PARA_IN_FRAME, 0 },
{ PARA_IN_SECTION, 0 },
{ PARA_IN_FOOTENOTE, 0 },
{ PARA_IN_ENDNOTE, 0 },
{ PARA_IN_HEADER, 0 },
{ PARA_IN_FOOTER, 0 },
{ PARA_IN_OUTLINE, 0 },
{ PARA_IN_OUTLINE, 1 },
{ PARA_IN_OUTLINE, 2 },
{ PARA_IN_OUTLINE, 3 },
{ PARA_IN_OUTLINE, 4 },
{ PARA_IN_OUTLINE, 5 },
{ PARA_IN_OUTLINE, 6 },
{ PARA_IN_OUTLINE, 7 },
{ PARA_IN_OUTLINE, 8 },
{ PARA_IN_OUTLINE, 9 },
{ PARA_IN_LIST, 0 },
{ PARA_IN_LIST, 1 },
{ PARA_IN_LIST, 2 },
{ PARA_IN_LIST, 3 },
{ PARA_IN_LIST, 4 },
{ PARA_IN_LIST, 5 },
{ PARA_IN_LIST, 6 },
{ PARA_IN_LIST, 7 },
{ PARA_IN_LIST, 8 },
{ PARA_IN_LIST, 9 }
};
TYPEINIT1_AUTOFACTORY(SwCondCollItem, SfxPoolItem)
/****************************************************************************
Item fuer den Transport der Bedingungstabelle
****************************************************************************/
SwCondCollItem::SwCondCollItem(USHORT _nWhich ) :
SfxPoolItem(_nWhich)
{
}
/****************************************************************************
****************************************************************************/
SwCondCollItem::~SwCondCollItem()
{
}
/****************************************************************************
****************************************************************************/
SfxPoolItem* SwCondCollItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwCondCollItem(*this);
}
/****************************************************************************
****************************************************************************/
int SwCondCollItem::operator==( const SfxPoolItem& rItem) const
{
DBG_ASSERT( SfxPoolItem::operator==(rItem), "unterschiedliche Typen" );
BOOL bReturn = TRUE;
for(USHORT i = 0; i < COND_COMMAND_COUNT; i++)
if(sStyles[i] != ((SwCondCollItem&)rItem).sStyles[i])
{
bReturn = FALSE;
break;
}
return bReturn;
}
/****************************************************************************
****************************************************************************/
const String& SwCondCollItem::GetStyle(USHORT nPos) const
{
#ifndef IRIX
return nPos < COND_COMMAND_COUNT ? sStyles[nPos] : aEmptyStr;
#else
return nPos < COND_COMMAND_COUNT ? (String)sStyles[nPos] : aEmptyStr;
#endif
}
/****************************************************************************
****************************************************************************/
void SwCondCollItem::SetStyle(const String* pStyle, USHORT nPos)
{
if( nPos < COND_COMMAND_COUNT )
#ifndef IRIX
sStyles[nPos] = pStyle ? *pStyle : aEmptyStr;
#else
sStyles[nPos] = pStyle ? (String)*pStyle : aEmptyStr;
#endif
}
/****************************************************************************
****************************************************************************/
const CommandStruct* SwCondCollItem::GetCmds()
{
return aCmds;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/Character.h"
#include "../Characters/String.h"
#include "../Characters/StringBuilder.h"
#include "../Containers/Common.h"
#include "../Debug/Trace.h"
#include "InputStream.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Streams;
using Characters::Character;
using Characters::String;
using Characters::StringBuilder;
using Memory::BLOB;
using Memory::Byte;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
************************* Streams::InputStream<ELEMENT_TYPE> *******************
********************************************************************************
*/
template <>
template <>
String InputStream<Character>::ReadLine () const
{
Require (IsSeekable ());
StringBuilder result;
while (true) {
Character c = ReadCharacter ();
if (c.GetCharacterCode () == '\0') {
// EOF
return result.str ();
}
result.push_back (c);
if (c == '\n') {
return result.str ();
}
else if (c == '\r') {
Character c = ReadCharacter ();
// if CR is follwed by LF, append that to result too before returning. Otherwise, put the character back
if (c == '\n') {
result.push_back (c);
return result.str ();
}
else {
Seek (Whence::eFromCurrent, -1);
}
return result.str ();
}
}
}
template <>
template <>
Characters::Character InputStream<Characters::Character>::ReadCharacter () const
{
Characters::Character c;
if (Read (&c, &c + 1) == 1) {
return c;
}
return '\0';
}
template <>
template <>
Traversal::Iterable<String> InputStream<Character>::ReadLines () const
{
InputStream<Character> copyOfStream = *this;
return Traversal::CreateGenerator<String> ([copyOfStream] () -> Memory::Optional<String> {
String line = copyOfStream.ReadLine ();
if (line.empty ())
{
return Memory::Optional<String> ();
}
else {
return line;
}
});
}
template <>
template <>
String InputStream<Character>::ReadAll (size_t upTo) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"InputStream<Character>::ReadAll");
DbgTrace (L"(upTo: %u)", upTo);
#endif
Characters::StringBuilder result;
size_t nEltsLeft = upTo;
while (nEltsLeft > 0) {
Character buf[16 * 1024];
Character* s = std::begin (buf);
Character* e = std::end (buf);
if (nEltsLeft < NEltsOf (buf)) {
e = s + nEltsLeft;
}
size_t n = Read (s, e);
Assert (0 <= n and n <= nEltsLeft);
Assert (0 <= n and n <= NEltsOf (buf));
if (n == 0) {
break;
}
else {
Assert (n <= nEltsLeft);
nEltsLeft -= n;
result.Append (s, s + n);
}
}
return result.str ();
}
template <>
template <>
Memory::BLOB InputStream<Byte>::ReadAll (size_t upTo) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"InputStream<Byte>::ReadAll");
DbgTrace (L"(upTo: %u)", upTo);
#endif
if (IsSeekable ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("Seekable case");
#endif
SeekOffsetType size = GetOffsetToEndOfStream ();
if (size >= numeric_limits<size_t>::max ()) {
Execution::Throw (bad_alloc ());
}
size_t sb = static_cast<size_t> (size);
sb = min (sb, upTo);
if (sb == 0) {
return BLOB ();
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("Seekable case: sb=%d", sb);
#endif
// @todo this isn't crazy worse than SmallStackBuffer, because if sb is the size read and wouldn't
// fit in a small stack buffer (stack part) - we avoid a second allocation.
// But - on balance - thats a lot of iffs. And we probably should use SmallStackBuffer and just
// do another alloc if needed. Maybe use an artificially large stack allocaiton here so we are likely to
// actually use the stack, or new stl 'get_temporeary_buffer' or wahtever the new routine is for stack allocs
//
Byte* b = new Byte[sb]; // if this fails, we had no way to create the BLOB
try {
size_t n = this->Read (b, b + sb);
Assert (n <= sb);
return BLOB::Attach (b, b + n);
}
catch (...) {
delete[] (b);
Execution::ReThrow ();
}
}
else {
// Less efficient implementation
vector<Byte> r;
for (size_t nEltsLeft = upTo; nEltsLeft != 0; ) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("Unseekable case: nEltsLeft=%d", nEltsLeft);
#endif
Byte buf[64 * 1024];
Byte* s = std::begin (buf);
Byte* e = std::end (buf);
if (nEltsLeft < NEltsOf (buf)) {
e = s + nEltsLeft;
}
Assert (s < e);
size_t n = Read (s, e);
Assert (0 <= n and n <= nEltsLeft);
Assert (0 <= n and n <= NEltsOf (buf));
if (n == 0) {
break;
}
else {
// @todo???
// could also maintain linked list - std::list<> - of BLOBs, and then construct BLOB from
// list of BLOBs - that would be quite efficeint too - maybe more
Containers::ReserveSpeedTweekAddNCapacity (r, n, 32 * 1024); // grow exponentially, so not too many reallocs
Assert (n <= nEltsLeft);
nEltsLeft -= n;
r.insert (r.end (), s, s + n);
}
}
return BLOB (r);
}
}
<commit_msg>improved DBGTrace code for InputStream::ReadAll logic; Tightened some assertions; and fixed important bug (still not perfrect) on InputStream<Byte>::ReadAll() seekable case<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/Character.h"
#include "../Characters/String.h"
#include "../Characters/StringBuilder.h"
#include "../Containers/Common.h"
#include "../Debug/Trace.h"
#include "InputStream.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Streams;
using Characters::Character;
using Characters::String;
using Characters::StringBuilder;
using Memory::BLOB;
using Memory::Byte;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
************************* Streams::InputStream<ELEMENT_TYPE> *******************
********************************************************************************
*/
template <>
template <>
String InputStream<Character>::ReadLine () const
{
Require (IsSeekable ());
StringBuilder result;
while (true) {
Character c = ReadCharacter ();
if (c.GetCharacterCode () == '\0') {
// EOF
return result.str ();
}
result.push_back (c);
if (c == '\n') {
return result.str ();
}
else if (c == '\r') {
Character c = ReadCharacter ();
// if CR is follwed by LF, append that to result too before returning. Otherwise, put the character back
if (c == '\n') {
result.push_back (c);
return result.str ();
}
else {
Seek (Whence::eFromCurrent, -1);
}
return result.str ();
}
}
}
template <>
template <>
Characters::Character InputStream<Characters::Character>::ReadCharacter () const
{
Characters::Character c;
if (Read (&c, &c + 1) == 1) {
return c;
}
return '\0';
}
template <>
template <>
Traversal::Iterable<String> InputStream<Character>::ReadLines () const
{
InputStream<Character> copyOfStream = *this;
return Traversal::CreateGenerator<String> ([copyOfStream] () -> Memory::Optional<String> {
String line = copyOfStream.ReadLine ();
if (line.empty ())
{
return Memory::Optional<String> ();
}
else {
return line;
}
});
}
template <>
template <>
String InputStream<Character>::ReadAll (size_t upTo) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"InputStream<Character>::ReadAll");
DbgTrace (L"(upTo: %u)", upTo);
#endif
Characters::StringBuilder result;
size_t nEltsLeft = upTo;
while (nEltsLeft > 0) {
Character buf[16 * 1024];
Character* s = std::begin (buf);
Character* e = std::end (buf);
if (nEltsLeft < NEltsOf (buf)) {
e = s + nEltsLeft;
}
size_t n = Read (s, e);
Assert (0 <= n and n <= nEltsLeft);
Assert (0 <= n and n < NEltsOf (buf));
if (n == 0) {
break;
}
else {
Assert (n <= nEltsLeft);
nEltsLeft -= n;
result.Append (s, s + n);
}
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"Returning %d characters", result.GetLength ());
#endif
return result.str ();
}
template <>
template <>
Memory::BLOB InputStream<Byte>::ReadAll (size_t upTo) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"InputStream<Byte>::ReadAll");
DbgTrace (L"(upTo: %u)", upTo);
#endif
if (IsSeekable ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("Seekable case");
#endif
SeekOffsetType size = GetOffsetToEndOfStream ();
if (size >= numeric_limits<size_t>::max ()) {
Execution::Throw (bad_alloc ());
}
size_t sb = static_cast<size_t> (size);
sb = min (sb, upTo);
if (sb == 0) {
return BLOB ();
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("(should be able to read)sb=%u", sb);
#endif
// @todo this isn't crazy worse than SmallStackBuffer, because if sb is the size read and wouldn't
// fit in a small stack buffer (stack part) - we avoid a second allocation.
// But - on balance - thats a lot of iffs. And we probably should use SmallStackBuffer and just
// do another alloc if needed. Maybe use an artificially large stack allocaiton here so we are likely to
// actually use the stack, or new stl 'get_temporeary_buffer' or wahtever the new routine is for stack allocs
//
Byte* b = new Byte[sb]; // if this fails, we had no way to create the BLOB
try {
// Even though we've allocated a large enough buffer, the guarnatee of Read () is that it will return
// > 0, or less or equal than args buf size, but only 0 means EOF, so must re-read if more out there.
#if 1
size_t bytesLeft = sb;
Byte* pi = b;
while (bytesLeft > 0) {
size_t n = Read (pi, pi + bytesLeft);
Assert (n <= bytesLeft);
bytesLeft -= n;
pi += n;
if (n == 0) {
AssertNotReached (); // @todo decide how to handle this - means stream changed size - doesnt work with this
// algorithm, but not necesarily SB disallowed.
// for now - hack
sb -= bytesLeft;
}
}
#else
// WRONG
size_t n = Read (b, b + sb);
Assert (n <= sb);
#endif
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("returning %u bytes", sb);
#endif
return BLOB::Attach (b, b + sb);
}
catch (...) {
delete[] (b);
Execution::ReThrow ();
}
}
else {
// Less efficient implementation
vector<Byte> r;
for (size_t nEltsLeft = upTo; nEltsLeft != 0; ) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace ("Unseekable case: nEltsLeft=%u", nEltsLeft);
#endif
Byte buf[64 * 1024];
Byte* s = std::begin (buf);
Byte* e = std::end (buf);
if (nEltsLeft < NEltsOf (buf)) {
e = s + nEltsLeft;
}
Assert (s < e);
size_t n = Read (s, e);
Assert (0 <= n and n <= nEltsLeft);
Assert (0 <= n and n < NEltsOf (buf));
if (n == 0) {
break;
}
else {
// @todo???
// could also maintain linked list - std::list<> - of BLOBs, and then construct BLOB from
// list of BLOBs - that would be quite efficeint too - maybe more
Containers::ReserveSpeedTweekAddNCapacity (r, n, 32 * 1024); // grow exponentially, so not too many reallocs
Assert (n <= nEltsLeft);
nEltsLeft -= n;
r.insert (r.end (), s, s + n);
}
}
return BLOB (r);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mailmrge.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2007-07-05 07:41:35 $
*
* 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 _MAILMRGE_HXX
#define _MAILMRGE_HXX
#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
class SwWrtShell;
class SwModuleOptions;
class SwXSelChgLstnr_Impl;
struct SwMailMergeDlg_Impl;
namespace com{namespace sun{namespace star{
namespace frame{
class XFrame;
}
namespace sdbc{
class XResultSet;
class XConnection;
}
}}}
class SwMailMergeDlg : public SvxStandardDialog
{
friend class SwXSelChgLstnr_Impl;
Window* pBeamerWin;
RadioButton aAllRB;
RadioButton aMarkedRB;
RadioButton aFromRB;
NumericField aFromNF;
FixedText aBisFT;
NumericField aToNF;
FixedLine aRecordFL;
FixedLine aSeparatorFL;
RadioButton aPrinterRB;
RadioButton aMailingRB;
RadioButton aFileRB;
CheckBox aSingleJobsCB;
FixedLine aSaveMergedDocumentFL;
RadioButton aSaveSingleDocRB;
RadioButton aSaveIndividualRB;
CheckBox aGenerateFromDataBaseCB;
FixedText aColumnFT;
ListBox aColumnLB;
FixedText aPathFT;
Edit aPathED;
PushButton aPathPB;
FixedText aFilterFT;
ListBox aFilterLB;
ListBox aAddressFldLB;
FixedText aSubjectFT;
Edit aSubjectED;
FixedText aFormatFT;
FixedText aAttachFT;
Edit aAttachED;
PushButton aAttachPB;
CheckBox aFormatHtmlCB;
CheckBox aFormatRtfCB;
CheckBox aFormatSwCB;
FixedLine aDestFL;
FixedLine aBottomSeparatorFL;
OKButton aOkBTN;
CancelButton aCancelBTN;
HelpButton aHelpBTN;
SwMailMergeDlg_Impl* pImpl;
SwWrtShell& rSh;
SwModuleOptions* pModOpt;
const String& rDBName;
const String& rTableName;
USHORT nMergeType;
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > m_aSelection;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;
Size m_aDialogSize;
::rtl::OUString m_sSaveFilter;
DECL_LINK( ButtonHdl, Button* pBtn );
DECL_LINK( InsertPathHdl, PushButton * );
DECL_LINK( AttachFileHdl, PushButton * );
DECL_LINK( OutputTypeHdl, RadioButton* pBtn );
DECL_LINK( FilenameHdl, CheckBox* pBtn );
DECL_LINK( ModifyHdl, NumericField* pLB );
DECL_LINK( SaveTypeHdl, RadioButton* pBtn );
virtual void Apply();
virtual void Resize();
bool ExecQryShell();
public:
SwMailMergeDlg(Window* pParent, SwWrtShell& rSh,
const String& rSourceName,
const String& rTblName,
sal_Int32 nCommandType,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& xConnection,
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >* pSelection = 0);
~SwMailMergeDlg();
inline USHORT GetMergeType() { return nMergeType; }
const ::rtl::OUString& GetSaveFilter() const {return m_sSaveFilter;}
inline const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > GetSelection() const { return m_aSelection; }
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> GetResultSet() const;
};
/* -----------------27.11.2002 12:05-----------------
*
* --------------------------------------------------*/
class SwMailMergeCreateFromDlg : public ModalDialog
{
FixedLine aCreateFromFL;
RadioButton aThisDocRB;
RadioButton aUseTemplateRB;
OKButton aOK;
CancelButton aCancel;
HelpButton aHelp;
public:
SwMailMergeCreateFromDlg(Window* pParent);
~SwMailMergeCreateFromDlg();
BOOL IsThisDocument() const {return aThisDocRB.IsChecked();}
};
/* -----------------04.02.2003 13:41-----------------
*
* --------------------------------------------------*/
class SwMailMergeFieldConnectionsDlg : public ModalDialog
{
FixedLine aConnectionsFL;
RadioButton aUseExistingRB;
RadioButton aCreateNewRB;
FixedInfo aInfoFI;
OKButton aOK;
CancelButton aCancel;
HelpButton aHelp;
public:
SwMailMergeFieldConnectionsDlg(Window* pParent);
~SwMailMergeFieldConnectionsDlg();
BOOL IsUseExistingConnections() const {return aUseExistingRB.IsChecked();}
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.12.710); FILE MERGED 2007/08/20 15:52:56 tl 1.12.710.2: RESYNC: (1.12-1.13); FILE MERGED 2007/03/26 12:09:08 tl 1.12.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mailmrge.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:04:46 $
*
* 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 _MAILMRGE_HXX
#define _MAILMRGE_HXX
#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
class SwWrtShell;
class SwModuleOptions;
class SwXSelChgLstnr_Impl;
struct SwMailMergeDlg_Impl;
namespace com{namespace sun{namespace star{
namespace frame{
class XFrame;
}
namespace sdbc{
class XResultSet;
class XConnection;
}
}}}
class SwMailMergeDlg : public SvxStandardDialog
{
friend class SwXSelChgLstnr_Impl;
Window* pBeamerWin;
RadioButton aAllRB;
RadioButton aMarkedRB;
RadioButton aFromRB;
NumericField aFromNF;
FixedText aBisFT;
NumericField aToNF;
FixedLine aRecordFL;
FixedLine aSeparatorFL;
RadioButton aPrinterRB;
RadioButton aMailingRB;
RadioButton aFileRB;
CheckBox aSingleJobsCB;
FixedLine aSaveMergedDocumentFL;
RadioButton aSaveSingleDocRB;
RadioButton aSaveIndividualRB;
CheckBox aGenerateFromDataBaseCB;
FixedText aColumnFT;
ListBox aColumnLB;
FixedText aPathFT;
Edit aPathED;
PushButton aPathPB;
FixedText aFilterFT;
ListBox aFilterLB;
ListBox aAddressFldLB;
FixedText aSubjectFT;
Edit aSubjectED;
FixedText aFormatFT;
FixedText aAttachFT;
Edit aAttachED;
PushButton aAttachPB;
CheckBox aFormatHtmlCB;
CheckBox aFormatRtfCB;
CheckBox aFormatSwCB;
FixedLine aDestFL;
FixedLine aBottomSeparatorFL;
OKButton aOkBTN;
CancelButton aCancelBTN;
HelpButton aHelpBTN;
SwMailMergeDlg_Impl* pImpl;
SwWrtShell& rSh;
SwModuleOptions* pModOpt;
const String& rDBName;
const String& rTableName;
USHORT nMergeType;
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > m_aSelection;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;
Size m_aDialogSize;
::rtl::OUString m_sSaveFilter;
DECL_LINK( ButtonHdl, Button* pBtn );
DECL_LINK( InsertPathHdl, PushButton * );
DECL_LINK( AttachFileHdl, PushButton * );
DECL_LINK( OutputTypeHdl, RadioButton* pBtn );
DECL_LINK( FilenameHdl, CheckBox* pBtn );
DECL_LINK( ModifyHdl, NumericField* pLB );
DECL_LINK( SaveTypeHdl, RadioButton* pBtn );
virtual void Apply();
virtual void Resize();
bool ExecQryShell();
public:
SwMailMergeDlg(Window* pParent, SwWrtShell& rSh,
const String& rSourceName,
const String& rTblName,
sal_Int32 nCommandType,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& xConnection,
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >* pSelection = 0);
~SwMailMergeDlg();
inline USHORT GetMergeType() { return nMergeType; }
const ::rtl::OUString& GetSaveFilter() const {return m_sSaveFilter;}
inline const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > GetSelection() const { return m_aSelection; }
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> GetResultSet() const;
};
/* -----------------27.11.2002 12:05-----------------
*
* --------------------------------------------------*/
class SwMailMergeCreateFromDlg : public ModalDialog
{
FixedLine aCreateFromFL;
RadioButton aThisDocRB;
RadioButton aUseTemplateRB;
OKButton aOK;
CancelButton aCancel;
HelpButton aHelp;
public:
SwMailMergeCreateFromDlg(Window* pParent);
~SwMailMergeCreateFromDlg();
BOOL IsThisDocument() const {return aThisDocRB.IsChecked();}
};
/* -----------------04.02.2003 13:41-----------------
*
* --------------------------------------------------*/
class SwMailMergeFieldConnectionsDlg : public ModalDialog
{
FixedLine aConnectionsFL;
RadioButton aUseExistingRB;
RadioButton aCreateNewRB;
FixedInfo aInfoFI;
OKButton aOK;
CancelButton aCancel;
HelpButton aHelp;
public:
SwMailMergeFieldConnectionsDlg(Window* pParent);
~SwMailMergeFieldConnectionsDlg();
BOOL IsUseExistingConnections() const {return aUseExistingRB.IsChecked();}
};
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006-2008 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#include "Arithmetic/Def/SubDef.h"
#include "fwSignal.h"
using namespace OPT_LEVEL;
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s )(const Fw16s* pSrc1, const Fw16s* pSrc2, Fw16s* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(0);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> > (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32f )(const Fw32f* pSrc1, const Fw32f* pSrc2, Fw32f* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_32f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32f> (data, pSrc1, pSrc2, pDst, len);
}
//Begin:[SKiran] Sub_64s declaration
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64s )(const Fw64s* pSrc1, const Fw64s* pSrc2, Fw64s* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_64s data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64s> (data, pSrc1, pSrc2, pDst, len);
}
//End:[SKiran] Sub_64s declaration
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64f )(const Fw64f* pSrc1, const Fw64f* pSrc2, Fw64f* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_64f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64f> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32fc )(const Fw32fc* pSrc1, const Fw32fc* pSrc2, Fw32fc* pDst,int len)
{
DEF_SUB::SUB::C1::Sub_32fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32fc> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64fc )(const Fw64fc* pSrc1, const Fw64fc* pSrc2, Fw64fc* pDst,int len)
{
DEF_SUB::SUB::C1::Sub_64fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64fc> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s_I )(const Fw16s* pSrc, Fw16s* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(0);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32f_I )(const Fw32f* pSrc, Fw32f* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_32f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32f>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64f_I )(const Fw64f* pSrc, Fw64f* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_64f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64f>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32fc_I )(const Fw32fc* pSrc, Fw32fc* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_32fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32fc>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64fc_I )(const Fw64fc* pSrc, Fw64fc* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_64fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64fc>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_8u_Sfs )(const Fw8u* pSrc1, const Fw8u* pSrc2, Fw8u* pDst,int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_8u<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<0> > (data, pSrc1, pSrc2, pDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_8u<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<-1> >(data, pSrc1, pSrc2, pDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_8u<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<1> > (data, pSrc1, pSrc2, pDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s_Sfs )(const Fw16s* pSrc1, const Fw16s* pSrc2, Fw16s*pDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> > (data, pSrc1, pSrc2, pDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16s<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<-1> >(data, pSrc1, pSrc2, pDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16s<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<1> > (data, pSrc1, pSrc2, pDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32s_Sfs )(const Fw32s* pSrc1, const Fw32s* pSrc2, Fw32s*pDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32s data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32s> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16sc_Sfs )(const Fw16sc* pSrc1, const Fw16sc* pSrc2, Fw16sc* pDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16sc<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<0> > (data, pSrc1, pSrc2, pDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16sc<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<-1> >(data, pSrc1, pSrc2, pDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16sc<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<1> > (data, pSrc1, pSrc2, pDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32sc_Sfs )(const Fw32sc* pSrc1, const Fw32sc* pSrc2, Fw32sc* pDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32sc data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32sc> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_8u_ISfs )(const Fw8u* pSrc, Fw8u* pSrcDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_8u<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_8u<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<-1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_8u<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s_ISfs )(const Fw16s* pSrc, Fw16s* pSrcDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16s<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<-1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16s<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32s_ISfs )(const Fw32s* pSrc, Fw32s* pSrcDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32s data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32s>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16sc_ISfs )(const Fw16sc* pSrc, Fw16sc* pSrcDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16sc<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16sc<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<-1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16sc<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32sc_ISfs )(const Fw32sc* pSrc, Fw32sc* pSrcDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32sc data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32sc>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s32f )(const Fw16s* pSrc1, const Fw16s* pSrc2, Fw32f* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_16s32f data(0);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s32f >(data, pSrc1, pSrc2, pDst, len);
}
// Please do NOT remove the above line for CPP files that need to be multipass compiled
// OREFR OSSE2 OF10H
<commit_msg>Removed comments around sub_64s function definition.<commit_after>/*
Copyright (c) 2006-2008 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#include "Arithmetic/Def/SubDef.h"
#include "fwSignal.h"
using namespace OPT_LEVEL;
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s )(const Fw16s* pSrc1, const Fw16s* pSrc2, Fw16s* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(0);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> > (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32f )(const Fw32f* pSrc1, const Fw32f* pSrc2, Fw32f* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_32f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32f> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64s )(const Fw64s* pSrc1, const Fw64s* pSrc2, Fw64s* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_64s data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64s> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64f )(const Fw64f* pSrc1, const Fw64f* pSrc2, Fw64f* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_64f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64f> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32fc )(const Fw32fc* pSrc1, const Fw32fc* pSrc2, Fw32fc* pDst,int len)
{
DEF_SUB::SUB::C1::Sub_32fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32fc> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64fc )(const Fw64fc* pSrc1, const Fw64fc* pSrc2, Fw64fc* pDst,int len)
{
DEF_SUB::SUB::C1::Sub_64fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64fc> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s_I )(const Fw16s* pSrc, Fw16s* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(0);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32f_I )(const Fw32f* pSrc, Fw32f* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_32f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32f>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64f_I )(const Fw64f* pSrc, Fw64f* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_64f data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64f>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32fc_I )(const Fw32fc* pSrc, Fw32fc* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_32fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32fc>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_64fc_I )(const Fw64fc* pSrc, Fw64fc* pSrcDst, int len)
{
DEF_SUB::SUB::C1::Sub_64fc data;
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_64fc>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_8u_Sfs )(const Fw8u* pSrc1, const Fw8u* pSrc2, Fw8u* pDst,int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_8u<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<0> > (data, pSrc1, pSrc2, pDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_8u<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<-1> >(data, pSrc1, pSrc2, pDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_8u<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<1> > (data, pSrc1, pSrc2, pDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s_Sfs )(const Fw16s* pSrc1, const Fw16s* pSrc2, Fw16s*pDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> > (data, pSrc1, pSrc2, pDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16s<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<-1> >(data, pSrc1, pSrc2, pDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16s<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<1> > (data, pSrc1, pSrc2, pDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32s_Sfs )(const Fw32s* pSrc1, const Fw32s* pSrc2, Fw32s*pDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32s data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32s> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16sc_Sfs )(const Fw16sc* pSrc1, const Fw16sc* pSrc2, Fw16sc* pDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16sc<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<0> > (data, pSrc1, pSrc2, pDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16sc<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<-1> >(data, pSrc1, pSrc2, pDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16sc<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<1> > (data, pSrc1, pSrc2, pDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32sc_Sfs )(const Fw32sc* pSrc1, const Fw32sc* pSrc2, Fw32sc* pDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32sc data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32sc> (data, pSrc1, pSrc2, pDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_8u_ISfs )(const Fw8u* pSrc, Fw8u* pSrcDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_8u<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_8u<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<-1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_8u<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_8u<1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s_ISfs )(const Fw16s* pSrc, Fw16s* pSrcDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16s<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16s<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<-1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16s<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s<1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32s_ISfs )(const Fw32s* pSrc, Fw32s* pSrcDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32s data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32s>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16sc_ISfs )(const Fw16sc* pSrc, Fw16sc* pSrcDst, int len, int scaleFactor)
{
if(scaleFactor == 0)
{
DEF_SUB::SUB::C1::Sub_16sc<0> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<0> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else if(scaleFactor < 0)
{
DEF_SUB::SUB::C1::Sub_16sc<-1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<-1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
else
{
DEF_SUB::SUB::C1::Sub_16sc<1> data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16sc<1> >(data, pSrc, pSrcDst, pSrcDst, len);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_32sc_ISfs )(const Fw32sc* pSrc, Fw32sc* pSrcDst, int len, int scaleFactor)
{
DEF_SUB::SUB::C1::Sub_32sc data(scaleFactor);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_32sc>(data, pSrc, pSrcDst, pSrcDst, len);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwsSub_16s32f )(const Fw16s* pSrc1, const Fw16s* pSrc2, Fw32f* pDst, int len)
{
DEF_SUB::SUB::C1::Sub_16s32f data(0);
return OPT_LEVEL::fe< DEF_SUB::SUB::C1::Sub_16s32f >(data, pSrc1, pSrc2, pDst, len);
}
// Please do NOT remove the above line for CPP files that need to be multipass compiled
// OREFR OSSE2 OF10H
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: paminit.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: jp $ $Date: 2002-02-01 12:37:59 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _PAMTYP_HXX
#include <pamtyp.hxx>
#endif
static SwMoveFnCollection aFwrd = {
/* fnNd */ &GoNext,
/* fnNds */ &GoNextNds,
/* fnDoc */ &GoEndDoc,
/* fnSections */ &GoEndSection,
/* fnCmpOp */ &SwPosition::operator<,
/* fnGetHint */ &GetFrwrdTxtHint,
/* fnSearch */ &utl::TextSearch::SearchFrwrd,
/* fnSection */ &SwNodes::GoStartOfSection
};
static SwMoveFnCollection aBwrd = {
/* fnNd */ &GoPrevious,
/* fnNds */ &GoPreviousNds,
/* fnDoc */ &GoStartDoc,
/* fnSections */ &GoStartSection,
/* fnCmpOp */ &SwPosition::operator>,
/* fnGetHint */ &GetBkwrdTxtHint,
/* fnSearch */ &utl::TextSearch::SearchBkwrd,
/* fnSection */ &SwNodes::GoEndOfSection
};
SwGoInDoc fnGoDoc = &GoInDoc;
SwGoInDoc fnGoSection = &GoInSection;
SwGoInDoc fnGoNode = &GoInNode;
SwGoInDoc fnGoCntnt = &GoInCntnt;
SwGoInDoc fnGoCntntCells= &GoInCntntCells;
SwWhichPara fnParaPrev = &GoPrevPara;
SwWhichPara fnParaCurr = &GoCurrPara;
SwWhichPara fnParaNext = &GoNextPara;
SwPosPara fnParaStart = &aFwrd;
SwPosPara fnParaEnd = &aBwrd;
SwWhichSection fnSectionPrev = &GoPrevSection;
SwWhichSection fnSectionCurr = &GoCurrSection;
SwWhichSection fnSectionNext = &GoNextSection;
SwPosSection fnSectionStart = &aFwrd;
SwPosSection fnSectionEnd = &aBwrd;
// Travelling in Tabellen
FASTBOOL GotoPrevTable( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
FASTBOOL GotoCurrTable( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
FASTBOOL GotoNextTable( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
SwWhichTable fnTablePrev = &GotoPrevTable;
SwWhichTable fnTableCurr = &GotoCurrTable;
SwWhichTable fnTableNext = &GotoNextTable;
SwPosTable fnTableStart = &aFwrd;
SwPosTable fnTableEnd = &aBwrd;
// Travelling in Bereichen
FASTBOOL GotoPrevRegion( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
FASTBOOL GotoCurrRegion( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
FASTBOOL GotoCurrRegionAndSkip( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
FASTBOOL GotoNextRegion( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
SwWhichRegion fnRegionPrev = &GotoPrevRegion;
SwWhichRegion fnRegionCurr = &GotoCurrRegion;
SwWhichRegion fnRegionCurrAndSkip = &GotoCurrRegionAndSkip;
SwWhichRegion fnRegionNext = &GotoNextRegion;
SwPosRegion fnRegionStart = &aFwrd;
SwPosRegion fnRegionEnd = &aBwrd;
SwMoveFn fnMoveBackward = &aBwrd;
SwMoveFn fnMoveForward = &aFwrd;
#ifdef USED
// JP 30.11.95:
// war fuer die CFRONT-Compiler noetig, jetzt sollte das nicht mehr
// benoetigt werden.
void _InitPam()
{
aBwrd.fnNd = &GoPrevious;
aBwrd.fnNds = &GoPreviousNds;
aBwrd.fnDoc = &GoStartDoc;
aBwrd.fnSections= &GoStartSection;
aBwrd.fnCmpOp = &SwPosition::operator>;
aBwrd.fnGetHint = &GetBkwrdTxtHint;
aBwrd.fnSearch = &SearchText::SearchBkwrd;
aBwrd.fnSection = &SwNodes::GoEndOfSection;
aFwrd.fnNd = &GoNext;
aFwrd.fnNds = &GoNextNds;
aFwrd.fnDoc = &GoEndDoc;
aFwrd.fnSections= &GoEndSection;
aFwrd.fnCmpOp = &SwPosition::operator<;
aFwrd.fnGetHint = &GetFrwrdTxtHint;
aFwrd.fnSearch = &SearchText::SearchFrwrd;
aFwrd.fnSection = &SwNodes::GoStartOfSection;
}
#endif
<commit_msg>INTEGRATION: CWS os8 (1.3.150); FILE MERGED 2003/04/03 07:09:44 os 1.3.150.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
*
* $RCSfile: paminit.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-17 13:46:20 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _PAMTYP_HXX
#include <pamtyp.hxx>
#endif
static SwMoveFnCollection aFwrd = {
/* fnNd */ &GoNext,
/* fnNds */ &GoNextNds,
/* fnDoc */ &GoEndDoc,
/* fnSections */ &GoEndSection,
/* fnCmpOp */ &SwPosition::operator<,
/* fnGetHint */ &GetFrwrdTxtHint,
/* fnSearch */ &utl::TextSearch::SearchFrwrd,
/* fnSection */ &SwNodes::GoStartOfSection
};
static SwMoveFnCollection aBwrd = {
/* fnNd */ &GoPrevious,
/* fnNds */ &GoPreviousNds,
/* fnDoc */ &GoStartDoc,
/* fnSections */ &GoStartSection,
/* fnCmpOp */ &SwPosition::operator>,
/* fnGetHint */ &GetBkwrdTxtHint,
/* fnSearch */ &utl::TextSearch::SearchBkwrd,
/* fnSection */ &SwNodes::GoEndOfSection
};
SwGoInDoc fnGoDoc = &GoInDoc;
SwGoInDoc fnGoSection = &GoInSection;
SwGoInDoc fnGoNode = &GoInNode;
SwGoInDoc fnGoCntnt = &GoInCntnt;
SwGoInDoc fnGoCntntCells= &GoInCntntCells;
SwWhichPara fnParaPrev = &GoPrevPara;
SwWhichPara fnParaCurr = &GoCurrPara;
SwWhichPara fnParaNext = &GoNextPara;
SwPosPara fnParaStart = &aFwrd;
SwPosPara fnParaEnd = &aBwrd;
SwWhichSection fnSectionPrev = &GoPrevSection;
SwWhichSection fnSectionCurr = &GoCurrSection;
SwWhichSection fnSectionNext = &GoNextSection;
SwPosSection fnSectionStart = &aFwrd;
SwPosSection fnSectionEnd = &aBwrd;
// Travelling in Tabellen
FASTBOOL GotoPrevTable( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
FASTBOOL GotoCurrTable( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
FASTBOOL GotoNextTable( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
SwWhichTable fnTablePrev = &GotoPrevTable;
SwWhichTable fnTableCurr = &GotoCurrTable;
SwWhichTable fnTableNext = &GotoNextTable;
SwPosTable fnTableStart = &aFwrd;
SwPosTable fnTableEnd = &aBwrd;
// Travelling in Bereichen
FASTBOOL GotoPrevRegion( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
FASTBOOL GotoCurrRegion( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
FASTBOOL GotoCurrRegionAndSkip( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
FASTBOOL GotoNextRegion( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
SwWhichRegion fnRegionPrev = &GotoPrevRegion;
SwWhichRegion fnRegionCurr = &GotoCurrRegion;
SwWhichRegion fnRegionCurrAndSkip = &GotoCurrRegionAndSkip;
SwWhichRegion fnRegionNext = &GotoNextRegion;
SwPosRegion fnRegionStart = &aFwrd;
SwPosRegion fnRegionEnd = &aBwrd;
SwMoveFn fnMoveBackward = &aBwrd;
SwMoveFn fnMoveForward = &aFwrd;
#ifdef USED
// JP 30.11.95:
// war fuer die CFRONT-Compiler noetig, jetzt sollte das nicht mehr
// benoetigt werden.
void _InitPam()
{
aBwrd.fnNd = &GoPrevious;
aBwrd.fnNds = &GoPreviousNds;
aBwrd.fnDoc = &GoStartDoc;
aBwrd.fnSections= &GoStartSection;
aBwrd.fnCmpOp = &SwPosition::operator>;
aBwrd.fnGetHint = &GetBkwrdTxtHint;
aBwrd.fnSearch = &SearchText::SearchBkwrd;
aBwrd.fnSection = &SwNodes::GoEndOfSection;
aFwrd.fnNd = &GoNext;
aFwrd.fnNds = &GoNextNds;
aFwrd.fnDoc = &GoEndDoc;
aFwrd.fnSections= &GoEndSection;
aFwrd.fnCmpOp = &SwPosition::operator<;
aFwrd.fnGetHint = &GetFrwrdTxtHint;
aFwrd.fnSearch = &SearchText::SearchFrwrd;
aFwrd.fnSection = &SwNodes::GoStartOfSection;
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************
* Solution to question 2.2 - Return Kth to Last
*
* Status: INCOMPLETE
*************************************************/
#include <iostream>
#include "../snode.h"
#include "../slist.h"
using namespace std;
using namespace ctci;
class SListSub : public SList {
public:
SListSub(int data);
~SListSub();
SNode * kth_to_last(size_t k);
};
SListSub::SListSub(int data) : SList(data) {}
SListSub::~SListSub() {}
SNode * SListSub::kth_to_last(size_t k) {
SNode *target = this->head;
for (size_t i = 0; i < (this->size - k); i++) {
target = target->getNext();
}
return target;
}
void print_slist(ostream &file, SListSub &slist) {
SNode *ptr = slist.getHead();
do {
file << ptr->getData() << endl;
ptr = ptr->getNext();
}
while (ptr != NULL);
}
int main(void) {
SListSub slist(7);
slist.add(4);
slist.add(2); // Target
slist.add(1); // 2nd to last
slist.add(5);
size_t k = 3;
SNode *node = slist.kth_to_last(k);
cout << "Retrieving k = " << k << " from last node" << endl;
cout << node->getData() << endl;
return EXIT_SUCCESS;
}
<commit_msg>Updated comments for question 2.2<commit_after>/*************************************************
* Solution to question 2.2 - Return Kth to Last
*
* This solution assumes that the list size
* is known.
*
* Status: COMPLETE
*************************************************/
#include <iostream>
#include "../snode.h"
#include "../slist.h"
using namespace std;
using namespace ctci;
class SListSub : public SList {
public:
SListSub(int data);
~SListSub();
SNode * kth_to_last(size_t k);
};
SListSub::SListSub(int data) : SList(data) {}
SListSub::~SListSub() {}
SNode * SListSub::kth_to_last(size_t k) {
SNode *target = this->head;
for (size_t i = 0; i < (this->size - k); i++) {
target = target->getNext();
}
return target;
}
void print_slist(ostream &file, SListSub &slist) {
SNode *ptr = slist.getHead();
do {
file << ptr->getData() << endl;
ptr = ptr->getNext();
}
while (ptr != NULL);
}
int main(void) {
SListSub slist(7);
slist.add(4);
slist.add(2); // Target
slist.add(1); // 2nd to last
slist.add(5);
size_t k = 3;
SNode *node = slist.kth_to_last(k);
cout << "Retrieving k = " << k << " from last node" << endl;
cout << node->getData() << endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: node2lay.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:51:24 $
*
* 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 _NODE2LAY_HXX
#define _NODE2LAY_HXX
/* -----------------23.02.99 11:33-------------------
* Die Klasse SwNode2Layout stellt die Verbindung von Nodes zum Layout her.
* Sie liefert einen intelligenten Iterator ueber die zum Node oder Nodebereich
* gehoerenden Frames. Je nach Zweck der Iteration, z.B. um vor oder hinter
* den Frames andere Frames einzufuegen, werden Master/Follows erkannt und nur
* die relevanten zurueckgegeben. Auch wiederholte Tabellenueberschriften werden
* beachtet.
* Es ist auch moeglich, ueber SectionNodes zu iterieren, die durch Schachtelung
* manchmal gar keinem SectionFrm direkt zugeordnet sind, manchmal aber sogar
* mehreren.
* SwNode2Layout ist ein Schnittstelle zwischen der aufrufenden Methode und
* einem SwClientIter, sie waehlt je nach Aufgabenstellung das richtige
* SwModify aus, erzeugt einen SwClientIter und filtert dessen Iterationen
* je nach Aufgabenstellung.
* Die Aufgabenstellung wird durch die Wahl des Ctors bestimmt.
* 1. Das Einsammeln der UpperFrms, damit spaeter RestoreUpperFrms wird,
* wird von MakeFrms gerufen, wenn es keinen PrevNext gibt, vor/hinter den
* die Frames gehaengt werden koennen.
* 2. Die Lieferung der Frames hinter/vor die die neuen Frames eines Nodes
* gehaengt werden muessen, ebenfalls von MakeFrms gerufen.
* --------------------------------------------------*/
class SwNode2LayImpl;
class SwFrm;
class SwLayoutFrm;
class SwNode;
class SwNode2Layout
{
SwNode2LayImpl *pImpl;
public:
// Dieser Ctor ist zum Einsammeln der UpperFrms gedacht.
SwNode2Layout( const SwNode& rNd );
// Dieser Ctor ist fuer das Einfuegen vor oder hinter rNd gedacht,
// nIdx ist der Index des einzufuegenden Nodes
SwNode2Layout( const SwNode& rNd, ULONG nIdx );
~SwNode2Layout();
SwFrm* NextFrm();
SwLayoutFrm* UpperFrm( SwFrm* &rpFrm, const SwNode& rNode );
void RestoreUpperFrms( SwNodes& rNds, ULONG nStt, ULONG nEnd );
SwFrm *GetFrm( const Point* pDocPos = 0,
const SwPosition *pPos = 0,
const BOOL bCalcFrm = TRUE ) const;
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.2.710); FILE MERGED 2007/02/27 13:07:04 tl 1.2.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: node2lay.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:57:37 $
*
* 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 _NODE2LAY_HXX
#define _NODE2LAY_HXX
#include <tools/solar.h>
/* -----------------23.02.99 11:33-------------------
* Die Klasse SwNode2Layout stellt die Verbindung von Nodes zum Layout her.
* Sie liefert einen intelligenten Iterator ueber die zum Node oder Nodebereich
* gehoerenden Frames. Je nach Zweck der Iteration, z.B. um vor oder hinter
* den Frames andere Frames einzufuegen, werden Master/Follows erkannt und nur
* die relevanten zurueckgegeben. Auch wiederholte Tabellenueberschriften werden
* beachtet.
* Es ist auch moeglich, ueber SectionNodes zu iterieren, die durch Schachtelung
* manchmal gar keinem SectionFrm direkt zugeordnet sind, manchmal aber sogar
* mehreren.
* SwNode2Layout ist ein Schnittstelle zwischen der aufrufenden Methode und
* einem SwClientIter, sie waehlt je nach Aufgabenstellung das richtige
* SwModify aus, erzeugt einen SwClientIter und filtert dessen Iterationen
* je nach Aufgabenstellung.
* Die Aufgabenstellung wird durch die Wahl des Ctors bestimmt.
* 1. Das Einsammeln der UpperFrms, damit spaeter RestoreUpperFrms wird,
* wird von MakeFrms gerufen, wenn es keinen PrevNext gibt, vor/hinter den
* die Frames gehaengt werden koennen.
* 2. Die Lieferung der Frames hinter/vor die die neuen Frames eines Nodes
* gehaengt werden muessen, ebenfalls von MakeFrms gerufen.
* --------------------------------------------------*/
class SwNode2LayImpl;
class SwFrm;
class SwLayoutFrm;
class SwNode;
class SwNodes;
class Point;
struct SwPosition;
class SwNode2Layout
{
SwNode2LayImpl *pImpl;
public:
// Dieser Ctor ist zum Einsammeln der UpperFrms gedacht.
SwNode2Layout( const SwNode& rNd );
// Dieser Ctor ist fuer das Einfuegen vor oder hinter rNd gedacht,
// nIdx ist der Index des einzufuegenden Nodes
SwNode2Layout( const SwNode& rNd, ULONG nIdx );
~SwNode2Layout();
SwFrm* NextFrm();
SwLayoutFrm* UpperFrm( SwFrm* &rpFrm, const SwNode& rNode );
void RestoreUpperFrms( SwNodes& rNds, ULONG nStt, ULONG nEnd );
SwFrm *GetFrm( const Point* pDocPos = 0,
const SwPosition *pPos = 0,
const BOOL bCalcFrm = TRUE ) const;
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: glshell.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:07:18 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFX_PRINTER_HXX //autogen
#include <sfx2/printer.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXSIDS_HRC //autogen
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _SVX_SRCHITEM_HXX
#include <svx/srchitem.hxx>
#endif
#ifndef _SFXMACITEM_HXX
#include <svtools/macitem.hxx>
#endif
#ifndef _GLOSHDL_HXX
#include <gloshdl.hxx>
#endif
#include <svx/acorrcfg.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/viewfrm.hxx>
#ifndef _UITOOL_HXX
#include <uitool.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _GLSHELL_HXX
#include <glshell.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _GLOSDOC_HXX
#include <glosdoc.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _INITUI_HXX
#include <initui.hxx> // fuer ::GetGlossaries()
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _SWERROR_H
#include <swerror.h>
#endif
#ifndef _MISC_HRC
#include <misc.hrc>
#endif
#define SwWebGlosDocShell
#define SwGlosDocShell
#ifndef _ITEMDEF_HXX
#include <itemdef.hxx>
#endif
#ifndef _SWSLOTS_HXX
#include <swslots.hxx>
#endif
SFX_IMPL_INTERFACE( SwGlosDocShell, SwDocShell, SW_RES(0) )
{
}
SFX_IMPL_INTERFACE( SwWebGlosDocShell, SwWebDocShell, SW_RES(0) )
{
}
TYPEINIT1( SwGlosDocShell, SwDocShell );
TYPEINIT1( SwWebGlosDocShell, SwWebDocShell );
void lcl_Execute( SwDocShell& rSh, SfxRequest& rReq )
{
if ( rReq.GetSlot() == SID_SAVEDOC )
{
if( !rSh.HasName() )
{
rReq.SetReturnValue( SfxBoolItem( 0, rSh.Save() ) );
}
else
{
const SfxBoolItem* pRes = ( const SfxBoolItem* )
rSh.ExecuteSlot( rReq,
rSh.SfxObjectShell::GetInterface() );
if( pRes->GetValue() )
rSh.GetDoc()->ResetModified();
}
}
}
void lcl_GetState( SwDocShell& rSh, SfxItemSet& rSet )
{
if( SFX_ITEM_AVAILABLE >= rSet.GetItemState( SID_SAVEDOC, FALSE ))
{
if( !rSh.GetDoc()->IsModified() )
rSet.DisableItem( SID_SAVEDOC );
else
rSet.Put( SfxStringItem( SID_SAVEDOC, SW_RESSTR(STR_SAVE_GLOSSARY)));
}
}
BOOL lcl_Save( SwWrtShell& rSh, const String& rGroupName,
const String& rShortNm, const String& rLongNm )
{
const SvxAutoCorrCfg* pCfg = SvxAutoCorrCfg::Get();
SwTextBlocks * pBlock = ::GetGlossaries()->GetGroupDoc( rGroupName );
SvxMacro aStart(aEmptyStr, aEmptyStr);
SvxMacro aEnd(aEmptyStr, aEmptyStr);
SwGlossaryHdl* pGlosHdl;
pGlosHdl = rSh.GetView().GetGlosHdl();
pGlosHdl->GetMacros( rShortNm, aStart, aEnd, pBlock );
USHORT nRet = rSh.SaveGlossaryDoc( *pBlock, rLongNm, rShortNm,
pCfg->IsSaveRelFile(), pCfg->IsSaveRelNet(),
pBlock->IsOnlyTextBlock( rShortNm ) );
if(aStart.GetMacName().Len() || aEnd.GetMacName().Len() )
{
SvxMacro* pStart = aStart.GetMacName().Len() ? &aStart : 0;
SvxMacro* pEnd = aEnd.GetMacName().Len() ? &aEnd : 0;
pGlosHdl->SetMacros( rShortNm, pStart, pEnd, pBlock );
}
rSh.EnterStdMode();
if( USHRT_MAX != nRet )
rSh.ResetModified();
delete pBlock;
return nRet != USHRT_MAX;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwGlosDocShell::SwGlosDocShell( sal_Bool bNewShow)
: bShow ( bNewShow )
, SwDocShell( bShow ? SFX_CREATE_MODE_STANDARD : SFX_CREATE_MODE_INTERNAL )
{
SetHelpId(SW_GLOSDOCSHELL);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwGlosDocShell::~SwGlosDocShell( )
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwGlosDocShell::Execute( SfxRequest& rReq )
{
::lcl_Execute( *this, rReq );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwGlosDocShell::GetState( SfxItemSet& rSet )
{
::lcl_GetState( *this, rSet );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
BOOL SwGlosDocShell::Save()
{
// In case of an API object which holds this document, it is possible that the WrtShell is already
// dead. For instance, if the doc is modified via this API object, and then, upon office shutdown,
// the document's view is closed (by the SFX framework) _before_ the API object is release and
// tries to save the doc, again.
// 96380 - 2002-03-03 - fs@openoffice.org
if ( GetWrtShell() )
return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName );
else
{
SetModified( FALSE );
return FALSE;
}
}
/**/
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwWebGlosDocShell::SwWebGlosDocShell()
: SwWebDocShell( SFX_CREATE_MODE_STANDARD )
{
SetHelpId(SW_WEBGLOSDOCSHELL);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwWebGlosDocShell::~SwWebGlosDocShell( )
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwWebGlosDocShell::Execute( SfxRequest& rReq )
{
::lcl_Execute( *this, rReq );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwWebGlosDocShell::GetState( SfxItemSet& rSet )
{
::lcl_GetState( *this, rSet );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
BOOL SwWebGlosDocShell::Save()
{
// same comment as in SwGlosDocShell::Save - see there
if ( GetWrtShell() )
return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName );
else
{
SetModified( FALSE );
return FALSE;
}
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SV_IMPL_REF ( SwDocShell )
SwDocShellRef SwGlossaries::EditGroupDoc( const String& rGroup, const String& rShortName, BOOL bShow )
{
SwDocShellRef xDocSh;
SwTextBlocks* pGroup = GetGroupDoc( rGroup );
if( pGroup && pGroup->GetCount() )
{
// erfrage welche View registriert ist. Im WebWriter gibts es keine
// normale View
USHORT nViewId = 0 != &SwView::Factory() ? 2 : 6;
String sLongName = pGroup->GetLongName(pGroup->GetIndex( rShortName ));
if( 6 == nViewId )
{
SwWebGlosDocShell* pDocSh = new SwWebGlosDocShell();
xDocSh = pDocSh;
pDocSh->DoInitNew( 0 );
pDocSh->SetLongName( sLongName );
pDocSh->SetShortName( rShortName);
pDocSh->SetGroupName( rGroup );
}
else
{
SwGlosDocShell* pDocSh = new SwGlosDocShell(bShow);
xDocSh = pDocSh;
pDocSh->DoInitNew( 0 );
pDocSh->SetLongName( sLongName );
pDocSh->SetShortName( rShortName );
pDocSh->SetGroupName( rGroup );
}
// Dokumenttitel setzen
SfxViewFrame* pFrame = SfxViewFrame::CreateViewFrame( *xDocSh, nViewId, !bShow );
String aDocTitle(SW_RES( STR_GLOSSARY ));
aDocTitle += ' ';
aDocTitle += sLongName;
BOOL bDoesUndo = xDocSh->GetDoc()->DoesUndo();
xDocSh->GetDoc()->DoUndo( FALSE );
xDocSh->GetWrtShell()->InsertGlossary( *pGroup, rShortName );
if( !xDocSh->GetDoc()->getPrinter( false ) )
{
// wir erzeugen einen default SfxPrinter.
// Das ItemSet wird vom Sfx geloescht!
SfxItemSet *pSet = new SfxItemSet( xDocSh->GetDoc()->GetAttrPool(),
FN_PARAM_ADDPRINTER, FN_PARAM_ADDPRINTER,
SID_PRINTER_NOTFOUND_WARN, SID_PRINTER_NOTFOUND_WARN,
SID_PRINTER_CHANGESTODOC, SID_PRINTER_CHANGESTODOC,
0 );
SfxPrinter* pPrinter = new SfxPrinter( pSet );
// und haengen ihn ans Dokument.
xDocSh->GetDoc()->setPrinter( pPrinter, true, true );
}
xDocSh->SetTitle( aDocTitle );
xDocSh->GetDoc()->DoUndo( bDoesUndo );
xDocSh->GetDoc()->ResetModified();
if ( bShow )
pFrame->GetFrame()->Appear();
delete pGroup;
}
return xDocSh;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.15.222); FILE MERGED 2007/03/26 12:09:13 tl 1.15.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: glshell.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:20:32 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFX_PRINTER_HXX //autogen
#include <sfx2/printer.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXSIDS_HRC //autogen
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _SVX_SRCHITEM_HXX
#include <svx/srchitem.hxx>
#endif
#ifndef _SFXMACITEM_HXX
#include <svtools/macitem.hxx>
#endif
#ifndef _GLOSHDL_HXX
#include <gloshdl.hxx>
#endif
#include <svx/acorrcfg.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/viewfrm.hxx>
#ifndef _UITOOL_HXX
#include <uitool.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _GLSHELL_HXX
#include <glshell.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _GLOSDOC_HXX
#include <glosdoc.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _INITUI_HXX
#include <initui.hxx> // fuer ::GetGlossaries()
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _SWERROR_H
#include <swerror.h>
#endif
#ifndef _MISC_HRC
#include <misc.hrc>
#endif
#define SwWebGlosDocShell
#define SwGlosDocShell
#ifndef _ITEMDEF_HXX
#include <itemdef.hxx>
#endif
#ifndef _SWSLOTS_HXX
#include <swslots.hxx>
#endif
SFX_IMPL_INTERFACE( SwGlosDocShell, SwDocShell, SW_RES(0) )
{
}
SFX_IMPL_INTERFACE( SwWebGlosDocShell, SwWebDocShell, SW_RES(0) )
{
}
TYPEINIT1( SwGlosDocShell, SwDocShell );
TYPEINIT1( SwWebGlosDocShell, SwWebDocShell );
void lcl_Execute( SwDocShell& rSh, SfxRequest& rReq )
{
if ( rReq.GetSlot() == SID_SAVEDOC )
{
if( !rSh.HasName() )
{
rReq.SetReturnValue( SfxBoolItem( 0, rSh.Save() ) );
}
else
{
const SfxBoolItem* pRes = ( const SfxBoolItem* )
rSh.ExecuteSlot( rReq,
rSh.SfxObjectShell::GetInterface() );
if( pRes->GetValue() )
rSh.GetDoc()->ResetModified();
}
}
}
void lcl_GetState( SwDocShell& rSh, SfxItemSet& rSet )
{
if( SFX_ITEM_AVAILABLE >= rSet.GetItemState( SID_SAVEDOC, FALSE ))
{
if( !rSh.GetDoc()->IsModified() )
rSet.DisableItem( SID_SAVEDOC );
else
rSet.Put( SfxStringItem( SID_SAVEDOC, SW_RESSTR(STR_SAVE_GLOSSARY)));
}
}
BOOL lcl_Save( SwWrtShell& rSh, const String& rGroupName,
const String& rShortNm, const String& rLongNm )
{
const SvxAutoCorrCfg* pCfg = SvxAutoCorrCfg::Get();
SwTextBlocks * pBlock = ::GetGlossaries()->GetGroupDoc( rGroupName );
SvxMacro aStart(aEmptyStr, aEmptyStr);
SvxMacro aEnd(aEmptyStr, aEmptyStr);
SwGlossaryHdl* pGlosHdl;
pGlosHdl = rSh.GetView().GetGlosHdl();
pGlosHdl->GetMacros( rShortNm, aStart, aEnd, pBlock );
USHORT nRet = rSh.SaveGlossaryDoc( *pBlock, rLongNm, rShortNm,
pCfg->IsSaveRelFile(),
pBlock->IsOnlyTextBlock( rShortNm ) );
if(aStart.GetMacName().Len() || aEnd.GetMacName().Len() )
{
SvxMacro* pStart = aStart.GetMacName().Len() ? &aStart : 0;
SvxMacro* pEnd = aEnd.GetMacName().Len() ? &aEnd : 0;
pGlosHdl->SetMacros( rShortNm, pStart, pEnd, pBlock );
}
rSh.EnterStdMode();
if( USHRT_MAX != nRet )
rSh.ResetModified();
delete pBlock;
return nRet != USHRT_MAX;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwGlosDocShell::SwGlosDocShell( sal_Bool bNewShow)
:
SwDocShell( bShow ? SFX_CREATE_MODE_STANDARD : SFX_CREATE_MODE_INTERNAL )
,bShow ( bNewShow )
{
SetHelpId(SW_GLOSDOCSHELL);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwGlosDocShell::~SwGlosDocShell( )
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwGlosDocShell::Execute( SfxRequest& rReq )
{
::lcl_Execute( *this, rReq );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwGlosDocShell::GetState( SfxItemSet& rSet )
{
::lcl_GetState( *this, rSet );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
BOOL SwGlosDocShell::Save()
{
// In case of an API object which holds this document, it is possible that the WrtShell is already
// dead. For instance, if the doc is modified via this API object, and then, upon office shutdown,
// the document's view is closed (by the SFX framework) _before_ the API object is release and
// tries to save the doc, again.
// 96380 - 2002-03-03 - fs@openoffice.org
if ( GetWrtShell() )
return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName );
else
{
SetModified( FALSE );
return FALSE;
}
}
/**/
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwWebGlosDocShell::SwWebGlosDocShell()
: SwWebDocShell( SFX_CREATE_MODE_STANDARD )
{
SetHelpId(SW_WEBGLOSDOCSHELL);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwWebGlosDocShell::~SwWebGlosDocShell( )
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwWebGlosDocShell::Execute( SfxRequest& rReq )
{
::lcl_Execute( *this, rReq );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwWebGlosDocShell::GetState( SfxItemSet& rSet )
{
::lcl_GetState( *this, rSet );
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
BOOL SwWebGlosDocShell::Save()
{
// same comment as in SwGlosDocShell::Save - see there
if ( GetWrtShell() )
return ::lcl_Save( *GetWrtShell(), aGroupName, aShortName, aLongName );
else
{
SetModified( FALSE );
return FALSE;
}
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SV_IMPL_REF ( SwDocShell )
SwDocShellRef SwGlossaries::EditGroupDoc( const String& rGroup, const String& rShortName, BOOL bShow )
{
SwDocShellRef xDocSh;
SwTextBlocks* pGroup = GetGroupDoc( rGroup );
if( pGroup && pGroup->GetCount() )
{
// erfrage welche View registriert ist. Im WebWriter gibts es keine
// normale View
USHORT nViewId = 0 != &SwView::Factory() ? 2 : 6;
String sLongName = pGroup->GetLongName(pGroup->GetIndex( rShortName ));
if( 6 == nViewId )
{
SwWebGlosDocShell* pDocSh = new SwWebGlosDocShell();
xDocSh = pDocSh;
pDocSh->DoInitNew( 0 );
pDocSh->SetLongName( sLongName );
pDocSh->SetShortName( rShortName);
pDocSh->SetGroupName( rGroup );
}
else
{
SwGlosDocShell* pDocSh = new SwGlosDocShell(bShow);
xDocSh = pDocSh;
pDocSh->DoInitNew( 0 );
pDocSh->SetLongName( sLongName );
pDocSh->SetShortName( rShortName );
pDocSh->SetGroupName( rGroup );
}
// Dokumenttitel setzen
SfxViewFrame* pFrame = SfxViewFrame::CreateViewFrame( *xDocSh, nViewId, !bShow );
String aDocTitle(SW_RES( STR_GLOSSARY ));
aDocTitle += ' ';
aDocTitle += sLongName;
BOOL bDoesUndo = xDocSh->GetDoc()->DoesUndo();
xDocSh->GetDoc()->DoUndo( FALSE );
xDocSh->GetWrtShell()->InsertGlossary( *pGroup, rShortName );
if( !xDocSh->GetDoc()->getPrinter( false ) )
{
// wir erzeugen einen default SfxPrinter.
// Das ItemSet wird vom Sfx geloescht!
SfxItemSet *pSet = new SfxItemSet( xDocSh->GetDoc()->GetAttrPool(),
FN_PARAM_ADDPRINTER, FN_PARAM_ADDPRINTER,
SID_PRINTER_NOTFOUND_WARN, SID_PRINTER_NOTFOUND_WARN,
SID_PRINTER_CHANGESTODOC, SID_PRINTER_CHANGESTODOC,
0 );
SfxPrinter* pPrinter = new SfxPrinter( pSet );
// und haengen ihn ans Dokument.
xDocSh->GetDoc()->setPrinter( pPrinter, true, true );
}
xDocSh->SetTitle( aDocTitle );
xDocSh->GetDoc()->DoUndo( bDoesUndo );
xDocSh->GetDoc()->ResetModified();
if ( bShow )
pFrame->GetFrame()->Appear();
delete pGroup;
}
return xDocSh;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2011-10-16
// Updated : 2011-10-16
// Licence : This source is under MIT License
// File : test/core/core_func_swizzle.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#define GLM_MESSAGES
#define GLM_SWIZZLE
#include <glm/glm.hpp>
int test_ivec2_swizzle()
{
int Error = 0;
glm::ivec2 A(1, 2);
glm::ivec2 B = A.xy();
glm::ivec2 C(0);
C.xy() = B.xy();
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int test_ivec3_swizzle()
{
int Error = 0;
glm::ivec3 A(1, 2, 3);
glm::ivec3 B = A.xyz();
glm::ivec3 C(0);
C.xyz() = B.xyz();
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int test_ivec4_swizzle()
{
int Error = 0;
glm::ivec4 A(1, 2, 3, 4);
glm::ivec4 B = A.xyzw();
glm::ivec4 C(0);
C.xyzw() = B.xyzw();
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int test_vec4_swizzle()
{
int Error = 0;
glm::vec4 A(1, 2, 3, 4);
glm::vec4 B = A.xyzw();
glm::vec4 C(0);
//C.xyzw() = B.xyzw();
float f = glm::dot(C.wzyx(), C.xyzw());
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
static_assert(sizeof(int) <= 4, "Test");
return Error;
}
int main()
{
int Error = 0;
Error += test_ivec2_swizzle();
Error += test_ivec3_swizzle();
Error += test_ivec4_swizzle();
Error += test_vec4_swizzle();
return Error;
}
<commit_msg>Removed a static_assert<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2011-10-16
// Updated : 2011-10-16
// Licence : This source is under MIT License
// File : test/core/core_func_swizzle.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#define GLM_MESSAGES
#define GLM_SWIZZLE
#include <glm/glm.hpp>
int test_ivec2_swizzle()
{
int Error = 0;
glm::ivec2 A(1, 2);
glm::ivec2 B = A.xy();
glm::ivec2 C(0);
C.xy() = B.xy();
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int test_ivec3_swizzle()
{
int Error = 0;
glm::ivec3 A(1, 2, 3);
glm::ivec3 B = A.xyz();
glm::ivec3 C(0);
C.xyz() = B.xyz();
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int test_ivec4_swizzle()
{
int Error = 0;
glm::ivec4 A(1, 2, 3, 4);
glm::ivec4 B = A.xyzw();
glm::ivec4 C(0);
C.xyzw() = B.xyzw();
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int test_vec4_swizzle()
{
int Error = 0;
glm::vec4 A(1, 2, 3, 4);
glm::vec4 B = A.xyzw();
glm::vec4 C(0);
//C.xyzw() = B.xyzw();
float f = glm::dot(C.wzyx(), C.xyzw());
Error += A == B ? 0 : 1;
Error += A == C ? 0 : 1;
return Error;
}
int main()
{
int Error = 0;
Error += test_ivec2_swizzle();
Error += test_ivec3_swizzle();
Error += test_ivec4_swizzle();
Error += test_vec4_swizzle();
return Error;
}
<|endoftext|>
|
<commit_before>#include "devicesConfigurationWidget.h"
#include <QtWidgets/QBoxLayout>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLabel>
#include <interpreterBase/robotModel/robotModelInterface.h>
using namespace interpreterCore::ui;
using namespace interpreterBase::robotModel;
DevicesConfigurationWidget::DevicesConfigurationWidget(QWidget *parent, bool autosaveMode)
: QScrollArea(parent)
, mAutosaveMode(autosaveMode)
, mSaving(false)
, mRefreshing(false)
{
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setFrameShadow(QFrame::Sunken);
setMinimumHeight(140);
}
void DevicesConfigurationWidget::loadRobotModels(QList<RobotModelInterface *> const &models)
{
for (RobotModelInterface * const model : models) {
QString const name = model->name();
mRobotModels[name] = model;
QWidget * const configurer = configurerForRobotModel(*model);
mRobotModelConfigurers[name] = configurer;
}
}
void DevicesConfigurationWidget::selectRobotModel(RobotModelInterface &robotModel)
{
QString const robotModelId = robotModel.name();
mCurrentModel = robotModelId;
takeWidget();
if (mRobotModels.contains(robotModelId)) {
setWidget(mRobotModelConfigurers[robotModelId]);
refresh();
}
}
QWidget *DevicesConfigurationWidget::configurerForRobotModel(RobotModelInterface &robotModel)
{
/// @todo: What if robot model has no configurable sensors?
QWidget *result = new QWidget;
QVBoxLayout * const layout = new QVBoxLayout;
result->setLayout(layout);
QList<PortInfo> const configurablePorts = robotModel.configurablePorts();
for (PortInfo const &port : configurablePorts) {
layout->addLayout(initPort(robotModel.name(), port, robotModel.allowedDevices(port)));
}
return result;
}
QLayout *DevicesConfigurationWidget::initPort(QString const &robotModel
, PortInfo const &port, QList<DeviceInfo> const &sensors)
{
QLabel * const portLabel = new QLabel(tr("Port %1:").arg(port.name()), this);
QComboBox * const comboBox = new QComboBox(this);
comboBox->setProperty("robotModel", robotModel);
comboBox->setProperty("port", QVariant::fromValue(port));
mConfigurers << comboBox;
comboBox->addItem(tr("Unused"), QVariant::fromValue(DeviceInfo()));
for (DeviceInfo const &sensor : sensors) {
comboBox->addItem(sensor.friendlyName(), QVariant::fromValue(sensor));
}
if (mAutosaveMode) {
connect(comboBox, &QComboBox::currentTextChanged, this, &DevicesConfigurationWidget::save);
}
QHBoxLayout * const layout = new QHBoxLayout;
layout->addWidget(portLabel);
layout->addWidget(comboBox);
layout->setStretch(0, 0);
layout->setStretch(1, 1);
return layout;
}
void DevicesConfigurationWidget::onDeviceConfigurationChanged(QString const &robotModel
, PortInfo const &port, DeviceInfo const &sensor)
{
Q_UNUSED(robotModel)
Q_UNUSED(port)
Q_UNUSED(sensor)
// This method can be called when we did not accomplish processing all combo boxes during saving.
// So ignoring such case.
if (!mSaving) {
refresh();
}
}
void DevicesConfigurationWidget::refresh()
{
mRefreshing = true;
for (QComboBox * const box : mConfigurers) {
PortInfo const port = box->property("port").value<PortInfo>();
DeviceInfo const device = currentConfiguration(mCurrentModel, port);
if (device.isNull()) {
box->setCurrentIndex(0);
} else {
for (int index = 0; index < box->count(); ++index) {
if (box->itemData(index).value<DeviceInfo>().isA(device)) {
box->setCurrentIndex(index);
break;
}
}
}
}
mRefreshing = false;
}
void DevicesConfigurationWidget::save()
{
// Refreshing may affect combobox current index. No saving is needed then.
if (mRefreshing) {
return;
}
mSaving = true;
for (QComboBox * const box : mConfigurers) {
if (!box->isVisible()) {
continue;
}
QString const robotModel = box->property("robotModel").toString();
PortInfo const port = box->property("port").value<PortInfo>();
DeviceInfo const device = box->itemData(box->currentIndex()).value<DeviceInfo>();
if (currentConfiguration(robotModel, port) != device) {
propagateChanges(port, device);
}
}
mSaving = false;
}
void DevicesConfigurationWidget::propagateChanges(PortInfo const &port, DeviceInfo const &sensor)
{
for (QString const &robotModelId : mRobotModels.keys()) {
RobotModelInterface const *robotModel = mRobotModels[robotModelId];
for (PortInfo const &otherPort : robotModel->configurablePorts()) {
if (areConvertible(port, otherPort)) {
if (sensor.isNull()) {
deviceConfigurationChanged(robotModelId, otherPort, DeviceInfo());
} else {
DeviceInfo const otherDevice = convertibleDevice(robotModel, otherPort, sensor);
if (!otherDevice.isNull()) {
deviceConfigurationChanged(robotModelId, otherPort, otherDevice);
}
}
}
}
}
}
bool DevicesConfigurationWidget::areConvertible(PortInfo const &port1, PortInfo const &port2) const
{
return (port1.name() == port2.name()
|| port1.nameAliases().contains(port2.name())
|| port2.nameAliases().contains(port1.name()))
&& port1.direction() == port2.direction();
}
DeviceInfo DevicesConfigurationWidget::convertibleDevice(RobotModelInterface const *robotModel
, PortInfo const &port, DeviceInfo const &device) const
{
QList<DeviceInfo> const convertibleBases = robotModel->convertibleBases();
for (DeviceInfo const &allowedDevice : robotModel->allowedDevices(port)) {
for (DeviceInfo const &convertibleBase : convertibleBases) {
if (device.isA(convertibleBase) && allowedDevice.isA(convertibleBase)) {
return allowedDevice;
}
}
}
return DeviceInfo();
}
<commit_msg>Device configurator`s background made transparent<commit_after>#include "devicesConfigurationWidget.h"
#include <QtWidgets/QBoxLayout>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLabel>
#include <interpreterBase/robotModel/robotModelInterface.h>
using namespace interpreterCore::ui;
using namespace interpreterBase::robotModel;
DevicesConfigurationWidget::DevicesConfigurationWidget(QWidget *parent, bool autosaveMode)
: QScrollArea(parent)
, mAutosaveMode(autosaveMode)
, mSaving(false)
, mRefreshing(false)
{
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setMinimumHeight(125);
setFrameShape(QFrame::NoFrame);
setWidgetResizable(true);
QPalette palette = this->palette();
palette.setColor(QPalette::Background, Qt::transparent);
setPalette(palette);
}
void DevicesConfigurationWidget::loadRobotModels(QList<RobotModelInterface *> const &models)
{
for (RobotModelInterface * const model : models) {
QString const name = model->name();
mRobotModels[name] = model;
QWidget * const configurer = configurerForRobotModel(*model);
mRobotModelConfigurers[name] = configurer;
}
}
void DevicesConfigurationWidget::selectRobotModel(RobotModelInterface &robotModel)
{
QString const robotModelId = robotModel.name();
mCurrentModel = robotModelId;
takeWidget();
if (mRobotModels.contains(robotModelId)) {
setWidget(mRobotModelConfigurers[robotModelId]);
refresh();
}
}
QWidget *DevicesConfigurationWidget::configurerForRobotModel(RobotModelInterface &robotModel)
{
/// @todo: What if robot model has no configurable sensors?
QWidget *result = new QWidget;
QPalette palette = result->palette();
palette.setColor(QPalette::Background, Qt::transparent);
result->setPalette(palette);
QVBoxLayout * const layout = new QVBoxLayout;
result->setLayout(layout);
QList<PortInfo> const configurablePorts = robotModel.configurablePorts();
for (PortInfo const &port : configurablePorts) {
layout->addLayout(initPort(robotModel.name(), port, robotModel.allowedDevices(port)));
}
return result;
}
QLayout *DevicesConfigurationWidget::initPort(QString const &robotModel
, PortInfo const &port, QList<DeviceInfo> const &sensors)
{
QLabel * const portLabel = new QLabel(tr("Port %1:").arg(port.name()), this);
QComboBox * const comboBox = new QComboBox(this);
comboBox->setProperty("robotModel", robotModel);
comboBox->setProperty("port", QVariant::fromValue(port));
mConfigurers << comboBox;
comboBox->addItem(tr("Unused"), QVariant::fromValue(DeviceInfo()));
for (DeviceInfo const &sensor : sensors) {
comboBox->addItem(sensor.friendlyName(), QVariant::fromValue(sensor));
}
if (mAutosaveMode) {
connect(comboBox, &QComboBox::currentTextChanged, this, &DevicesConfigurationWidget::save);
}
QHBoxLayout * const layout = new QHBoxLayout;
layout->addWidget(portLabel);
layout->addWidget(comboBox);
layout->setStretch(0, 0);
layout->setStretch(1, 1);
return layout;
}
void DevicesConfigurationWidget::onDeviceConfigurationChanged(QString const &robotModel
, PortInfo const &port, DeviceInfo const &sensor)
{
Q_UNUSED(robotModel)
Q_UNUSED(port)
Q_UNUSED(sensor)
// This method can be called when we did not accomplish processing all combo boxes during saving.
// So ignoring such case.
if (!mSaving) {
refresh();
}
}
void DevicesConfigurationWidget::refresh()
{
mRefreshing = true;
for (QComboBox * const box : mConfigurers) {
PortInfo const port = box->property("port").value<PortInfo>();
DeviceInfo const device = currentConfiguration(mCurrentModel, port);
if (device.isNull()) {
box->setCurrentIndex(0);
} else {
for (int index = 0; index < box->count(); ++index) {
if (box->itemData(index).value<DeviceInfo>().isA(device)) {
box->setCurrentIndex(index);
break;
}
}
}
}
mRefreshing = false;
}
void DevicesConfigurationWidget::save()
{
// Refreshing may affect combobox current index. No saving is needed then.
if (mRefreshing) {
return;
}
mSaving = true;
for (QComboBox * const box : mConfigurers) {
if (!box->isVisible()) {
continue;
}
QString const robotModel = box->property("robotModel").toString();
PortInfo const port = box->property("port").value<PortInfo>();
DeviceInfo const device = box->itemData(box->currentIndex()).value<DeviceInfo>();
if (currentConfiguration(robotModel, port) != device) {
propagateChanges(port, device);
}
}
mSaving = false;
}
void DevicesConfigurationWidget::propagateChanges(PortInfo const &port, DeviceInfo const &sensor)
{
for (QString const &robotModelId : mRobotModels.keys()) {
RobotModelInterface const *robotModel = mRobotModels[robotModelId];
for (PortInfo const &otherPort : robotModel->configurablePorts()) {
if (areConvertible(port, otherPort)) {
if (sensor.isNull()) {
deviceConfigurationChanged(robotModelId, otherPort, DeviceInfo());
} else {
DeviceInfo const otherDevice = convertibleDevice(robotModel, otherPort, sensor);
if (!otherDevice.isNull()) {
deviceConfigurationChanged(robotModelId, otherPort, otherDevice);
}
}
}
}
}
}
bool DevicesConfigurationWidget::areConvertible(PortInfo const &port1, PortInfo const &port2) const
{
return (port1.name() == port2.name()
|| port1.nameAliases().contains(port2.name())
|| port2.nameAliases().contains(port1.name()))
&& port1.direction() == port2.direction();
}
DeviceInfo DevicesConfigurationWidget::convertibleDevice(RobotModelInterface const *robotModel
, PortInfo const &port, DeviceInfo const &device) const
{
QList<DeviceInfo> const convertibleBases = robotModel->convertibleBases();
for (DeviceInfo const &allowedDevice : robotModel->allowedDevices(port)) {
for (DeviceInfo const &convertibleBase : convertibleBases) {
if (device.isA(convertibleBase) && allowedDevice.isA(convertibleBase)) {
return allowedDevice;
}
}
}
return DeviceInfo();
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <mutex>
#include "../Containers/Mapping.h"
#include "../Debug/Trace.h"
#include "../Containers/Concrete/Queue_Array.h"
#include "BlockingQueue.h"
#include "Thread.h"
#include "SignalHandlers.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using Containers::Mapping;
using Containers::Queue;
using Containers::Set;
// maybe useful while debugging signal code, but VERY unsafe
// and could easily be the source of bugs/deadlocks!
#ifndef qDoDbgTraceOnSignalHandlers_
#define qDoDbgTraceOnSignalHandlers_ 0
#endif
struct SignalHandlerRegistry::SafeSignalsManager::Rep_ {
Rep_ ();
~Rep_ ();
Containers::Mapping<SignalID, Containers::Set<SignalHandler>> fHandlers_;
BlockingQueue<SignalID> fIncomingSafeSignals_;
Thread fBlockingQueuePusherThread_;
};
namespace {
bool IsSigIgnore_ (const Set<SignalHandler>& sigSet)
{
return sigSet.size () == 1 and sigSet.Contains (SignalHandlerRegistry::kIGNORED);
}
}
/*
********************************************************************************
*********** Execution::SignalHandlerRegistry::SafeSignalsManager ***************
********************************************************************************
*/
namespace {
Queue<SignalID> mkQ_ ()
{
Containers::Concrete::Queue_Array<SignalID> signalQ;
signalQ.SetCapacity (100); // quite arbitrary - @todo make configurable somehow...
return signalQ;
}
}
SignalHandlerRegistry::SafeSignalsManager::Rep_::Rep_ ()
: fIncomingSafeSignals_ (mkQ_ ())
, fBlockingQueuePusherThread_ ()
{
Thread watcherThread ([this] () {
// This is a safe context
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::Signals::{}::fBlockingQueueDelegatorThread_"));
while (true) {
Debug::TraceContextBumper trcCtx (SDKSTR ("waiting for next signal"));
SignalID i = fIncomingSafeSignals_.RemoveHead ();
DbgTrace (L"got signal: %s; ... delegating to safe handlers...", SignalToName (i).c_str ());
for (SignalHandler sh : SignalHandlerRegistry::Get ().GetSignalHandlers (i)) {
if (sh.GetType () == SignalHandler::Type::eSafe) {
IgnoreExceptionsExceptThreadAbortForCall (sh (i));
}
}
}
});
watcherThread.SetThreadName (L"Signal Handler Safe Execution Thread");
watcherThread.Start ();
fBlockingQueuePusherThread_ = std::move (watcherThread);
}
SignalHandlerRegistry::SafeSignalsManager::Rep_::~Rep_ ()
{
fBlockingQueuePusherThread_.AbortAndWaitForDone ();
}
/*
********************************************************************************
*********** Execution::SignalHandlerRegistry::SafeSignalsManager ***************
********************************************************************************
*/
shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> SignalHandlerRegistry::SafeSignalsManager::sThe_;
SignalHandlerRegistry::SafeSignalsManager::SafeSignalsManager ()
{
Assert (sThe_ == nullptr);
sThe_ = shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> (new Rep_ ());
}
SignalHandlerRegistry::SafeSignalsManager::~SafeSignalsManager ()
{
Assert (sThe_ != nullptr);
sThe_->fBlockingQueuePusherThread_.AbortAndWaitForDone ();
sThe_.reset ();
}
/*
********************************************************************************
******************** Execution::SignalHandlerRegistry **************************
********************************************************************************
*/
const SignalHandler SignalHandlerRegistry::kIGNORED = SignalHandler (SIG_IGN, SignalHandler::Type::eDirect);
SignalHandlerRegistry& SignalHandlerRegistry::Get ()
{
static SignalHandlerRegistry sThe_;
return sThe_;
}
SignalHandlerRegistry::SignalHandlerRegistry ()
: fDirectHandlers_ ()
{
}
SignalHandlerRegistry::~SignalHandlerRegistry ()
{
Assert (SafeSignalsManager::sThe_ == nullptr); // must be cleared first
}
Set<SignalID> SignalHandlerRegistry::GetHandledSignals () const
{
// @todo redo using Mapping<>::Keys () when implemented...
Set<SignalID> result;
for (auto i : fDirectHandlers_) {
result.Add (i.fKey);
}
shared_ptr<SafeSignalsManager::Rep_> tmp = SafeSignalsManager::sThe_;
if (tmp != nullptr) {
for (auto i : tmp->fHandlers_) {
result.Add (i.fKey);
}
}
return result;
}
Set<SignalHandler> SignalHandlerRegistry::GetSignalHandlers (SignalID signal) const
{
Set<SignalHandler> result = fDirectHandlers_.LookupValue (signal);
shared_ptr<SafeSignalsManager::Rep_> tmp = SafeSignalsManager::sThe_;
if (tmp != nullptr) {
result += tmp->fHandlers_.LookupValue (signal);
}
return result;
}
void SignalHandlerRegistry::SetSignalHandlers (SignalID signal)
{
SetSignalHandlers (signal, Set<SignalHandler> ());
}
void SignalHandlerRegistry::SetSignalHandlers (SignalID signal, SignalHandler handler)
{
SetSignalHandlers (signal, Set<SignalHandler> ({handler}));
}
void SignalHandlerRegistry::SetSignalHandlers (SignalID signal, const Set<SignalHandler>& handlers)
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::Signals::{}::SetSignalHandlers"));
DbgTrace (L"(signal = %s, handlers.size () = %d, ....)", SignalToName (signal).c_str (), handlers.size ());
shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> tmp = SignalHandlerRegistry::SafeSignalsManager::sThe_;
if (handlers.empty ()) {
/*
* No handlers means use default.
*/
fDirectHandlers_.Remove (signal);
if (tmp != nullptr) {
tmp->fHandlers_.Remove (signal);
}
(void)::signal (signal, SIG_DFL);
}
else if (IsSigIgnore_ (handlers)) {
Assert (handlers.size () == 1);
fDirectHandlers_.Add (signal, handlers);
if (tmp != nullptr) {
tmp->fHandlers_.Remove (signal);
}
(void)::signal (signal, SIG_IGN);
}
else {
Set<SignalHandler> directHandlers;
Set<SignalHandler> safeHandlers;
handlers.Apply ([&directHandlers, &safeHandlers] (SignalHandler si) {
switch (si.GetType ()) {
case SignalHandler::Type::eDirect: {
directHandlers.Add (si);
}
break;
case SignalHandler::Type::eSafe: {
safeHandlers.Add (si);
}
break;
}
});
Assert (directHandlers.size () + safeHandlers.size () == handlers.size ());
fDirectHandlers_.Add (signal, directHandlers);
if (not safeHandlers.empty ()) {
// To use safe signal handlers, you must have a SignalHandlerRegistry::SafeSignalsManager
// defined first. It is recommended that you define an instance of
// SignalHandlerRegistry::SafeSignalsManager handler; should be defined in main ()
Require (SafeSignalsManager::sThe_ != nullptr);
}
if (tmp != nullptr) {
tmp->fHandlers_.Add (signal, safeHandlers);
}
(void)::signal (signal, FirstPassSignalHandler_);
}
}
void SignalHandlerRegistry::AddSignalHandler (SignalID signal, SignalHandler handler)
{
Set<SignalHandler> s = GetSignalHandlers (signal);
s.Add (handler);
SetSignalHandlers (signal, s);
}
void SignalHandlerRegistry::RemoveSignalHandler (SignalID signal, SignalHandler handler)
{
Set<SignalHandler> s = GetSignalHandlers (signal);
Require (s.Contains (handler));
s.Remove (handler);
SetSignalHandlers (signal, s);
}
void SignalHandlerRegistry::DefaultCrashSignalHandler (SignalID signal)
{
DbgTrace (L"Serious Signal Error trapped: %s ... Aborting", SignalToName (signal).c_str ());
abort ();
}
void SignalHandlerRegistry::SetStandardCrashHandlerSignals (SignalHandler handler, const Set<SignalID>& excludedSignals)
{
if (not excludedSignals.Contains (SIGINT)) { SetSignalHandlers (SIGINT, handler); }
if (not excludedSignals.Contains (SIGILL)) { SetSignalHandlers (SIGILL, handler); }
if (not excludedSignals.Contains (SIGFPE)) { SetSignalHandlers (SIGFPE, handler); }
if (not excludedSignals.Contains (SIGSEGV)) { SetSignalHandlers (SIGSEGV, handler); }
if (not excludedSignals.Contains (SIGTERM)) { SetSignalHandlers (SIGTERM, handler); }
#if qPlatform_POSIX
if (not excludedSignals.Contains (SIGSYS)) { SetSignalHandlers (SIGSYS, handler); }
if (not excludedSignals.Contains (SIGBUS)) { SetSignalHandlers (SIGBUS, handler); }
if (not excludedSignals.Contains (SIGQUIT)) { SetSignalHandlers (SIGQUIT, handler); }
if (not excludedSignals.Contains (SIGPIPE)) { SetSignalHandlers (SIGPIPE, handler); }
if (not excludedSignals.Contains (SIGHUP)) { SetSignalHandlers (SIGHUP, handler); }
if (not excludedSignals.Contains (SIGXCPU)) { SetSignalHandlers (SIGXCPU, handler); }
if (not excludedSignals.Contains (SIGXFSZ)) { SetSignalHandlers (SIGXFSZ, handler); }
#endif
}
void SignalHandlerRegistry::FirstPassSignalHandler_ (SignalID signal)
{
#if qDoDbgTraceOnSignalHandlers_
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::Signals::{}::FirstPassSignalHandler_"));
DbgTrace (L"(signal = %s)", SignalToName (signal).c_str ());
#endif
SignalHandlerRegistry& SHR = Get ();
for (SignalHandler sh : SHR.fDirectHandlers_.LookupValue (signal)) {
sh (signal);
}
shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> tmp = SignalHandlerRegistry::SafeSignalsManager::sThe_;
if (tmp != nullptr) {
tmp->fIncomingSafeSignals_.AddTail (signal);
}
}
#if qPlatform_POSIX
/*
********************************************************************************
************* Execution::ScopedBlockCurrentThreadSignal ************************
********************************************************************************
*/
ScopedBlockCurrentThreadSignal::ScopedBlockCurrentThreadSignal (SignalID signal)
: fSignal_ (signal)
, fRestoreMask_ ()
{
//DbgTrace (L"ScopedBlockCurrentThreadSignal blocking signals for %s", SignalToName (signal).c_str ());
sigset_t mySet;
sigemptyset (&mySet);
(void)::sigaddset (&mySet, signal);
sigemptyset (&fRestoreMask_); // Unclear if this emptyset call is needed?
Verify (pthread_sigmask (SIG_BLOCK, &mySet, &fRestoreMask_) == 0);
}
ScopedBlockCurrentThreadSignal::~ScopedBlockCurrentThreadSignal ()
{
//DbgTrace (L"ScopedBlockCurrentThreadSignal restoriing signals for %s", SignalToName (fSignal_).c_str ());
Verify (pthread_sigmask (SIG_SETMASK, &fRestoreMask_, nullptr) == 0);
}
#endif
<commit_msg>cleanups of SignalHandlerRegistry code<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <mutex>
#include "../Containers/Mapping.h"
#include "../Debug/Trace.h"
#include "../Containers/Concrete/Queue_Array.h"
#include "BlockingQueue.h"
#include "Thread.h"
#include "SignalHandlers.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using Containers::Mapping;
using Containers::Queue;
using Containers::Set;
// maybe useful while debugging signal code, but VERY unsafe
// and could easily be the source of bugs/deadlocks!
#ifndef qDoDbgTraceOnSignalHandlers_
#define qDoDbgTraceOnSignalHandlers_ 0
#endif
struct SignalHandlerRegistry::SafeSignalsManager::Rep_ {
Rep_ ();
~Rep_ ();
Containers::Mapping<SignalID, Containers::Set<SignalHandler>> fHandlers_;
BlockingQueue<SignalID> fIncomingSafeSignals_;
Thread fBlockingQueuePusherThread_;
};
namespace {
bool IsSigIgnore_ (const Set<SignalHandler>& sigSet)
{
return sigSet.size () == 1 and sigSet.Contains (SignalHandlerRegistry::kIGNORED);
}
}
/*
********************************************************************************
*********** Execution::SignalHandlerRegistry::SafeSignalsManager ***************
********************************************************************************
*/
namespace {
Queue<SignalID> mkQ_ ()
{
Containers::Concrete::Queue_Array<SignalID> signalQ;
signalQ.SetCapacity (100); // quite arbitrary - @todo make configurable somehow...
return signalQ;
}
}
SignalHandlerRegistry::SafeSignalsManager::Rep_::Rep_ ()
: fHandlers_ ()
, fIncomingSafeSignals_ (mkQ_ ())
, fBlockingQueuePusherThread_ ()
{
Thread watcherThread ([this] () {
// This is a safe context
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::Signals::{}::fBlockingQueueDelegatorThread_"));
while (true) {
Debug::TraceContextBumper trcCtx1 (SDKSTR ("waiting for next signal"));
SignalID i = fIncomingSafeSignals_.RemoveHead ();
Debug::TraceContextBumper trcCtx2 (SDKSTR ("Invoking SAFE signal handlers"));
DbgTrace (L"(signal: %s)", SignalToName (i).c_str ());
for (SignalHandler sh : fHandlers_.LookupValue (i)) {
if (sh.GetType () == SignalHandler::Type::eSafe) {
IgnoreExceptionsExceptThreadAbortForCall (sh (i));
}
}
}
});
watcherThread.SetThreadName (L"Signal Handler Safe Execution Thread");
watcherThread.Start ();
fBlockingQueuePusherThread_ = std::move (watcherThread);
}
SignalHandlerRegistry::SafeSignalsManager::Rep_::~Rep_ ()
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::SafeSignalsManager::Rep_::~Rep_"));
fBlockingQueuePusherThread_.AbortAndWaitForDone ();
}
/*
********************************************************************************
*********** Execution::SignalHandlerRegistry::SafeSignalsManager ***************
********************************************************************************
*/
shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> SignalHandlerRegistry::SafeSignalsManager::sThe_;
SignalHandlerRegistry::SafeSignalsManager::SafeSignalsManager ()
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::CTOR"));
Assert (sThe_ == nullptr);
sThe_ = shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> (new Rep_ ());
}
SignalHandlerRegistry::SafeSignalsManager::~SafeSignalsManager ()
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::DTOR"));
Assert (sThe_ != nullptr);
sThe_->fBlockingQueuePusherThread_.AbortAndWaitForDone ();
sThe_.reset ();
}
/*
********************************************************************************
******************** Execution::SignalHandlerRegistry **************************
********************************************************************************
*/
const SignalHandler SignalHandlerRegistry::kIGNORED = SignalHandler (SIG_IGN, SignalHandler::Type::eDirect);
SignalHandlerRegistry& SignalHandlerRegistry::Get ()
{
static SignalHandlerRegistry sThe_;
return sThe_;
}
SignalHandlerRegistry::SignalHandlerRegistry ()
: fDirectHandlers_ ()
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::CTOR"));
}
SignalHandlerRegistry::~SignalHandlerRegistry ()
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::DTOR"));
Assert (SafeSignalsManager::sThe_ == nullptr); // must be cleared first
}
Set<SignalID> SignalHandlerRegistry::GetHandledSignals () const
{
// @todo redo using Mapping<>::Keys () when implemented...
Set<SignalID> result;
for (auto i : fDirectHandlers_) {
result.Add (i.fKey);
}
shared_ptr<SafeSignalsManager::Rep_> tmp = SafeSignalsManager::sThe_;
if (tmp != nullptr) {
for (auto i : tmp->fHandlers_) {
result.Add (i.fKey);
}
}
return result;
}
Set<SignalHandler> SignalHandlerRegistry::GetSignalHandlers (SignalID signal) const
{
Set<SignalHandler> result = fDirectHandlers_.LookupValue (signal);
shared_ptr<SafeSignalsManager::Rep_> tmp = SafeSignalsManager::sThe_;
if (tmp != nullptr) {
result += tmp->fHandlers_.LookupValue (signal);
}
return result;
}
void SignalHandlerRegistry::SetSignalHandlers (SignalID signal)
{
SetSignalHandlers (signal, Set<SignalHandler> ());
}
void SignalHandlerRegistry::SetSignalHandlers (SignalID signal, SignalHandler handler)
{
SetSignalHandlers (signal, Set<SignalHandler> ({handler}));
}
void SignalHandlerRegistry::SetSignalHandlers (SignalID signal, const Set<SignalHandler>& handlers)
{
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::{}::SetSignalHandlers"));
DbgTrace (L"(signal = %s, handlers.size () = %d, ....)", SignalToName (signal).c_str (), handlers.size ());
shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> tmp = SignalHandlerRegistry::SafeSignalsManager::sThe_;
if (handlers.empty ()) {
/*
* No handlers means use default.
*/
fDirectHandlers_.Remove (signal);
if (tmp != nullptr) {
tmp->fHandlers_.Remove (signal);
}
(void)::signal (signal, SIG_DFL);
}
else if (IsSigIgnore_ (handlers)) {
Assert (handlers.size () == 1);
fDirectHandlers_.Add (signal, handlers);
if (tmp != nullptr) {
tmp->fHandlers_.Remove (signal);
}
(void)::signal (signal, SIG_IGN);
}
else {
Set<SignalHandler> directHandlers;
Set<SignalHandler> safeHandlers;
handlers.Apply ([&directHandlers, &safeHandlers] (SignalHandler si) {
switch (si.GetType ()) {
case SignalHandler::Type::eDirect: {
directHandlers.Add (si);
}
break;
case SignalHandler::Type::eSafe: {
safeHandlers.Add (si);
}
break;
}
});
Assert (directHandlers.size () + safeHandlers.size () == handlers.size ());
fDirectHandlers_.Add (signal, directHandlers);
if (not safeHandlers.empty ()) {
// To use safe signal handlers, you must have a SignalHandlerRegistry::SafeSignalsManager
// defined first. It is recommended that you define an instance of
// SignalHandlerRegistry::SafeSignalsManager handler; should be defined in main ()
Require (SafeSignalsManager::sThe_ != nullptr);
}
if (tmp != nullptr) {
tmp->fHandlers_.Add (signal, safeHandlers);
}
(void)::signal (signal, FirstPassSignalHandler_);
}
}
void SignalHandlerRegistry::AddSignalHandler (SignalID signal, SignalHandler handler)
{
Set<SignalHandler> s = GetSignalHandlers (signal);
s.Add (handler);
SetSignalHandlers (signal, s);
}
void SignalHandlerRegistry::RemoveSignalHandler (SignalID signal, SignalHandler handler)
{
Set<SignalHandler> s = GetSignalHandlers (signal);
Require (s.Contains (handler));
s.Remove (handler);
SetSignalHandlers (signal, s);
}
void SignalHandlerRegistry::DefaultCrashSignalHandler (SignalID signal)
{
DbgTrace (L"Serious Signal Error trapped: %s ... Aborting", SignalToName (signal).c_str ());
abort ();
}
void SignalHandlerRegistry::SetStandardCrashHandlerSignals (SignalHandler handler, const Set<SignalID>& excludedSignals)
{
if (not excludedSignals.Contains (SIGINT)) { SetSignalHandlers (SIGINT, handler); }
if (not excludedSignals.Contains (SIGILL)) { SetSignalHandlers (SIGILL, handler); }
if (not excludedSignals.Contains (SIGFPE)) { SetSignalHandlers (SIGFPE, handler); }
if (not excludedSignals.Contains (SIGSEGV)) { SetSignalHandlers (SIGSEGV, handler); }
if (not excludedSignals.Contains (SIGTERM)) { SetSignalHandlers (SIGTERM, handler); }
#if qPlatform_POSIX
if (not excludedSignals.Contains (SIGSYS)) { SetSignalHandlers (SIGSYS, handler); }
if (not excludedSignals.Contains (SIGBUS)) { SetSignalHandlers (SIGBUS, handler); }
if (not excludedSignals.Contains (SIGQUIT)) { SetSignalHandlers (SIGQUIT, handler); }
if (not excludedSignals.Contains (SIGPIPE)) { SetSignalHandlers (SIGPIPE, handler); }
if (not excludedSignals.Contains (SIGHUP)) { SetSignalHandlers (SIGHUP, handler); }
if (not excludedSignals.Contains (SIGXCPU)) { SetSignalHandlers (SIGXCPU, handler); }
if (not excludedSignals.Contains (SIGXFSZ)) { SetSignalHandlers (SIGXFSZ, handler); }
#endif
}
void SignalHandlerRegistry::FirstPassSignalHandler_ (SignalID signal)
{
#if qDoDbgTraceOnSignalHandlers_
Debug::TraceContextBumper trcCtx (SDKSTR ("Stroika::Foundation::Execution::SignalHandlerRegistry::FirstPassSignalHandler_"));
DbgTrace (L"(signal = %s)", SignalToName (signal).c_str ());
#endif
SignalHandlerRegistry& SHR = Get ();
for (SignalHandler sh : SHR.fDirectHandlers_.LookupValue (signal)) {
sh (signal);
}
shared_ptr<SignalHandlerRegistry::SafeSignalsManager::Rep_> tmp = SignalHandlerRegistry::SafeSignalsManager::sThe_;
if (tmp != nullptr) {
tmp->fIncomingSafeSignals_.AddTail (signal);
}
}
#if qPlatform_POSIX
/*
********************************************************************************
************* Execution::ScopedBlockCurrentThreadSignal ************************
********************************************************************************
*/
ScopedBlockCurrentThreadSignal::ScopedBlockCurrentThreadSignal (SignalID signal)
: fSignal_ (signal)
, fRestoreMask_ ()
{
//DbgTrace (L"ScopedBlockCurrentThreadSignal blocking signals for %s", SignalToName (signal).c_str ());
sigset_t mySet;
sigemptyset (&mySet);
(void)::sigaddset (&mySet, signal);
sigemptyset (&fRestoreMask_); // Unclear if this emptyset call is needed?
Verify (pthread_sigmask (SIG_BLOCK, &mySet, &fRestoreMask_) == 0);
}
ScopedBlockCurrentThreadSignal::~ScopedBlockCurrentThreadSignal ()
{
//DbgTrace (L"ScopedBlockCurrentThreadSignal restoriing signals for %s", SignalToName (fSignal_).c_str ());
Verify (pthread_sigmask (SIG_SETMASK, &fRestoreMask_, nullptr) == 0);
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_SocketAddress_inl_
#define _Stroika_Foundation_IO_Network_SocketAddress_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace IO {
namespace Network {
/*
********************************************************************************
*********************** IO::Network::SocketAddress *****************************
********************************************************************************
*/
inline SocketAddress::SocketAddress ()
: fSocketAddress_ ()
{
::memset (&fSocketAddress_, 0, sizeof (fSocketAddress_));
}
inline SocketAddress::SocketAddress (const sockaddr& iaddr)
: fSocketAddress_ ()
{
Assert (sizeof (fSocketAddress_) == sizeof (sockaddr));
::memcpy (&fSocketAddress_, &iaddr, sizeof (fSocketAddress_));
}
inline SocketAddress::SocketAddress (const sockaddr_in& iaddr)
: fSocketAddress_ ()
{
Assert (sizeof (fSocketAddress_) == sizeof (sockaddr));
Assert (sizeof (fSocketAddress_) == sizeof (sockaddr_in));
::memcpy (&fSocketAddress_, &iaddr, sizeof (fSocketAddress_));
}
inline SocketAddress::SocketAddress (const InternetAddress& iaddr, uint16_t portNumber)
: fSocketAddress_ ()
{
::memset (&fSocketAddress_, 0, sizeof (fSocketAddress_));
switch (iaddr.GetAddressFamily ()) {
case InternetAddress::AddressFamily::V4: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
sockaddr_in& as = reinterpret_cast<sockaddr_in&> (fSocketAddress_);
as.sin_family = AF_INET;
as.sin_port = htons (portNumber);
as.sin_addr = iaddr.As<in_addr> ();
}
break;
case InternetAddress::AddressFamily::V6: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
sockaddr_in6& as = reinterpret_cast<sockaddr_in6&> (fSocketAddress_);
as.sin6_family = AF_INET6;
as.sin6_port = htons (portNumber);
as.sin6_addr = iaddr.As<in6_addr> ();
}
break;
default: {
// just leave blank - no assert?
}
break;
}
}
inline bool SocketAddress::empty () const
{
return fSocketAddress_.sa_family == AF_UNSPEC;
//constexpr sockaddr kZero_ = { 0 };
//return ::memcmp (&fSocketAddress_, &kZero_, sizeof (kZero_)) == 0;
}
inline void SocketAddress::clear ()
{
fSocketAddress_.sa_family = AF_UNSPEC;
//::memset (&fSocketAddress_, 0, sizeof (fSocketAddress_));
}
inline SocketAddress::FamilyType SocketAddress::GetAddressFamily () const
{
return fSocketAddress_.sa_family;
}
inline bool SocketAddress::IsInternetAddress () const
{
return fSocketAddress_.sa_family == AF_INET or fSocketAddress_.sa_family == AF_INET6;
}
inline InternetAddress SocketAddress::GetInternetAddress () const
{
Require (IsInternetAddress ());
switch (fSocketAddress_.sa_family) {
case AF_INET: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
const sockaddr_in& as = reinterpret_cast<const sockaddr_in&> (fSocketAddress_);
return InternetAddress (as.sin_addr);
}
case AF_INET6: {
Assert (sizeof (sockaddr_in6) == sizeof (sockaddr));
const sockaddr_in6& as = reinterpret_cast<const sockaddr_in6&> (fSocketAddress_);
return InternetAddress (as.sin6_addr);
}
default: {
AssertNotReached ();
return InternetAddress ();
}
}
}
inline uint16_t SocketAddress::GetPort () const
{
Require (IsInternetAddress ());
switch (fSocketAddress_.sa_family) {
case AF_INET: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
const sockaddr_in& as = reinterpret_cast<const sockaddr_in&> (fSocketAddress_);
return ntohs (as.sin_port);
}
case AF_INET6: {
Assert (sizeof (sockaddr_in6) == sizeof (sockaddr));
const sockaddr_in6& as = reinterpret_cast<const sockaddr_in6&> (fSocketAddress_);
return ntohs (as.sin6_port);
}
default: {
AssertNotReached ();
return 0;
}
}
}
template <typename T>
T SocketAddress::As () const
{
#if qCompilerAndStdLib_StaticAssertionsInTemplateFunctionsWhichShouldNeverBeExpanded_Buggy
RequireNotReached ();
#else
static_assert (false, "Only specifically specialized variants are supported");
#endif
}
template <>
inline sockaddr SocketAddress::As<sockaddr> () const
{
return fSocketAddress_;
}
template <>
inline sockaddr_in SocketAddress::As<sockaddr_in> () const
{
Assert (sizeof (sockaddr_in) == sizeof (fSocketAddress_));
const sockaddr_in& as = reinterpret_cast<const sockaddr_in&> (fSocketAddress_);
return as;
}
template <>
inline sockaddr_in6 SocketAddress::As<sockaddr_in6> () const
{
Assert (sizeof (sockaddr_in6) == sizeof (fSocketAddress_));
const sockaddr_in6& as = reinterpret_cast<const sockaddr_in6&> (fSocketAddress_);
return as;
}
}
}
}
}
#endif /*_Stroika_Foundation_IO_Network_SocketAddress_inl_*/
<commit_msg>cleanup clang++ warning<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_SocketAddress_inl_
#define _Stroika_Foundation_IO_Network_SocketAddress_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace IO {
namespace Network {
/*
********************************************************************************
*********************** IO::Network::SocketAddress *****************************
********************************************************************************
*/
inline SocketAddress::SocketAddress ()
: fSocketAddress_ ()
{
::memset (&fSocketAddress_, 0, sizeof (fSocketAddress_));
}
inline SocketAddress::SocketAddress (const sockaddr& iaddr)
: fSocketAddress_ ()
{
Assert (sizeof (fSocketAddress_) == sizeof (sockaddr));
::memcpy (&fSocketAddress_, &iaddr, sizeof (fSocketAddress_));
}
inline SocketAddress::SocketAddress (const sockaddr_in& iaddr)
: fSocketAddress_ ()
{
Assert (sizeof (fSocketAddress_) == sizeof (sockaddr));
Assert (sizeof (fSocketAddress_) == sizeof (sockaddr_in));
::memcpy (&fSocketAddress_, &iaddr, sizeof (fSocketAddress_));
}
inline SocketAddress::SocketAddress (const InternetAddress& iaddr, uint16_t portNumber)
: fSocketAddress_ ()
{
::memset (&fSocketAddress_, 0, sizeof (fSocketAddress_));
switch (iaddr.GetAddressFamily ()) {
case InternetAddress::AddressFamily::V4: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
sockaddr_in& as = reinterpret_cast<sockaddr_in&> (fSocketAddress_);
as.sin_family = AF_INET;
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Wdeprecated\""); // macro uses 'register' - htons not deprecated
as.sin_port = htons (portNumber);
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Wdeprecated\"");
as.sin_addr = iaddr.As<in_addr> ();
}
break;
case InternetAddress::AddressFamily::V6: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
sockaddr_in6& as = reinterpret_cast<sockaddr_in6&> (fSocketAddress_);
as.sin6_family = AF_INET6;
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Wdeprecated\""); // macro uses 'register' - htons not deprecated
as.sin6_port = htons (portNumber);
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Wdeprecated\"");
as.sin6_addr = iaddr.As<in6_addr> ();
}
break;
default: {
// just leave blank - no assert?
}
break;
}
}
inline bool SocketAddress::empty () const
{
return fSocketAddress_.sa_family == AF_UNSPEC;
//constexpr sockaddr kZero_ = { 0 };
//return ::memcmp (&fSocketAddress_, &kZero_, sizeof (kZero_)) == 0;
}
inline void SocketAddress::clear ()
{
fSocketAddress_.sa_family = AF_UNSPEC;
//::memset (&fSocketAddress_, 0, sizeof (fSocketAddress_));
}
inline SocketAddress::FamilyType SocketAddress::GetAddressFamily () const
{
return fSocketAddress_.sa_family;
}
inline bool SocketAddress::IsInternetAddress () const
{
return fSocketAddress_.sa_family == AF_INET or fSocketAddress_.sa_family == AF_INET6;
}
inline InternetAddress SocketAddress::GetInternetAddress () const
{
Require (IsInternetAddress ());
switch (fSocketAddress_.sa_family) {
case AF_INET: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
const sockaddr_in& as = reinterpret_cast<const sockaddr_in&> (fSocketAddress_);
return InternetAddress (as.sin_addr);
}
case AF_INET6: {
Assert (sizeof (sockaddr_in6) == sizeof (sockaddr));
const sockaddr_in6& as = reinterpret_cast<const sockaddr_in6&> (fSocketAddress_);
return InternetAddress (as.sin6_addr);
}
default: {
AssertNotReached ();
return InternetAddress ();
}
}
}
inline uint16_t SocketAddress::GetPort () const
{
Require (IsInternetAddress ());
switch (fSocketAddress_.sa_family) {
case AF_INET: {
Assert (sizeof (sockaddr_in) == sizeof (sockaddr));
const sockaddr_in& as = reinterpret_cast<const sockaddr_in&> (fSocketAddress_);
return ntohs (as.sin_port);
}
case AF_INET6: {
Assert (sizeof (sockaddr_in6) == sizeof (sockaddr));
const sockaddr_in6& as = reinterpret_cast<const sockaddr_in6&> (fSocketAddress_);
return ntohs (as.sin6_port);
}
default: {
AssertNotReached ();
return 0;
}
}
}
template <typename T>
T SocketAddress::As () const
{
#if qCompilerAndStdLib_StaticAssertionsInTemplateFunctionsWhichShouldNeverBeExpanded_Buggy
RequireNotReached ();
#else
static_assert (false, "Only specifically specialized variants are supported");
#endif
}
template <>
inline sockaddr SocketAddress::As<sockaddr> () const
{
return fSocketAddress_;
}
template <>
inline sockaddr_in SocketAddress::As<sockaddr_in> () const
{
Assert (sizeof (sockaddr_in) == sizeof (fSocketAddress_));
const sockaddr_in& as = reinterpret_cast<const sockaddr_in&> (fSocketAddress_);
return as;
}
template <>
inline sockaddr_in6 SocketAddress::As<sockaddr_in6> () const
{
Assert (sizeof (sockaddr_in6) == sizeof (fSocketAddress_));
const sockaddr_in6& as = reinterpret_cast<const sockaddr_in6&> (fSocketAddress_);
return as;
}
}
}
}
}
#endif /*_Stroika_Foundation_IO_Network_SocketAddress_inl_*/
<|endoftext|>
|
<commit_before><commit_msg>CppunitTest_sw_rtfimport: disable 3 checks for now<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accgraphic.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:21:32 $
*
* 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 _ACCGRAPHIC_HXX
#define _ACCGRAPHIC_HXX
#ifndef _ACCNOTEXTFRAME_HXX
#include "accnotextframe.hxx"
#endif
class SwAccessibleGraphic : public SwAccessibleNoTextFrame
{
protected:
virtual ~SwAccessibleGraphic();
public:
SwAccessibleGraphic( SwAccessibleMap* pInitMap,
const SwFlyFrm *pFlyFrm );
//===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
/** Return whether the specified service is supported by this class.
*/
virtual sal_Bool SAL_CALL
supportsService (const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services. In this case that is just
the AccessibleContext service.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ====================================================
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.242); FILE MERGED 2008/04/01 12:53:45 thb 1.5.242.2: #i85898# Stripping all external header guards 2008/03/31 16:53:38 rt 1.5.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accgraphic.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _ACCGRAPHIC_HXX
#define _ACCGRAPHIC_HXX
#include "accnotextframe.hxx"
class SwAccessibleGraphic : public SwAccessibleNoTextFrame
{
protected:
virtual ~SwAccessibleGraphic();
public:
SwAccessibleGraphic( SwAccessibleMap* pInitMap,
const SwFlyFrm *pFlyFrm );
//===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
/** Return whether the specified service is supported by this class.
*/
virtual sal_Bool SAL_CALL
supportsService (const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services. In this case that is just
the AccessibleContext service.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ====================================================
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>
#include "LocaleSharedMemory.hpp"
#ifndef SHMMAX
#error "no SHMMAX defined for this system -- look it up with the command: `sysctl -A | grep shm`"
#endif
const int64_t default_locale_reserved_size = (1L << 32);
DEFINE_int64( locale_reserved_size, default_locale_reserved_size, "Shared memory between cores on node, reserved for runtime" );
DEFINE_int64( locale_shared_size, SHMMAX + FLAGS_locale_reserved_size, "Total shared memory between cores on node" );
DECLARE_bool( global_memory_use_hugepages );
// forward declarations
namespace Grappa {
namespace impl {
/// called on failures to backtrace and pause for debugger
extern void failure_function();
/// how much memory do we expect to allocate?
extern int64_t global_memory_size_bytes;
extern int64_t global_bytes_per_core;
extern int64_t global_bytes_per_locale;
}
}
namespace Grappa {
namespace impl {
/// global LocaleSharedMemory instance
LocaleSharedMemory locale_shared_memory;
void LocaleSharedMemory::create() {
region_size = FLAGS_locale_shared_size;
VLOG(2) << "Creating LocaleSharedMemory region " << region_name
<< " with " << region_size << " bytes"
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
// if possible, delete this user's old leftover share memory regions
// if this returns false, either there was nothing to delete or
// there was something owned by somebody else.
bool deleted_one = boost::interprocess::shared_memory_object::remove( region_name.c_str() );
if( deleted_one ) {
VLOG(1) << "Deleted an old, leftover " << region_name.c_str();
}
// now, try to allocate a new one
try {
segment = boost::interprocess::fixed_managed_shared_memory( boost::interprocess::create_only,
region_name.c_str(),
region_size,
base_address);
}
catch(...){
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
failure_function();
throw;
}
VLOG(2) << "Created LocaleSharedMemory region " << region_name
<< " with " << region_size << " bytes"
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
}
void LocaleSharedMemory::attach() {
// first, check that we can create something large enough
CHECK_GE( FLAGS_locale_shared_size, global_bytes_per_locale )
<< "Can't accomodate " << global_bytes_per_locale << " bytes of shared heap per locale with "
<< FLAGS_locale_shared_size << " total shared bytes.";
VLOG(2) << "Attaching to LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
try {
segment = boost::interprocess::fixed_managed_shared_memory( boost::interprocess::open_only,
region_name.c_str(),
base_address );
}
catch(...){
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
failure_function();
throw;
}
VLOG(2) << "Attached to LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
}
void LocaleSharedMemory::destroy() {
VLOG(2) << "Removing LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
VLOG(2) << "Removed LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
}
LocaleSharedMemory::LocaleSharedMemory()
: region_size( FLAGS_locale_shared_size )
, region_name( "GrappaLocaleSharedMemory" )
, base_address( reinterpret_cast<void*>( 0x400000000000L ) )
, segment() // default constructor; initialize later
{
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
// TODO: figure out reasonable region size
// maybe reuse SHMMAX stuff?
}
LocaleSharedMemory::~LocaleSharedMemory() {
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
}
void LocaleSharedMemory::init() {
if( FLAGS_locale_reserved_size != default_locale_reserved_size ) {
FLAGS_locale_shared_size = SHMMAX + FLAGS_locale_reserved_size;
}
}
void LocaleSharedMemory::activate() {
if( Grappa::locale_mycore() == 0 ) { create(); }
global_communicator.barrier();
if( Grappa::locale_mycore() != 0 ) { attach(); }
global_communicator.barrier();
}
void LocaleSharedMemory::finish() {
global_communicator.barrier();
if( Grappa::locale_mycore() == 0 ) { destroy(); }
}
void * LocaleSharedMemory::allocate( size_t size ) {
void * p = NULL;
try {
p = Grappa::impl::locale_shared_memory.segment.allocate( size );
}
catch(...){
LOG(ERROR) << "Allocation failed with size " << size;
failure_function();
throw;
}
return p;
}
void * LocaleSharedMemory::allocate_aligned( size_t size, size_t alignment ) {
void * p = NULL;
try {
p = Grappa::impl::locale_shared_memory.segment.allocate_aligned( size, alignment );
}
catch(...){
LOG(ERROR) << "Aligned allocation failed with size " << size << " alignment " << alignment;
failure_function();
throw;
}
return p;
}
void LocaleSharedMemory::deallocate( void * ptr ) {
try {
Grappa::impl::locale_shared_memory.segment.deallocate( ptr );
}
catch(...){
failure_function();
throw;
}
}
} // namespace impl
} // namespace Grappa
<commit_msg>Add better logging from allocation failures<commit_after>
#include "LocaleSharedMemory.hpp"
#ifndef SHMMAX
#error "no SHMMAX defined for this system -- look it up with the command: `sysctl -A | grep shm`"
#endif
const int64_t default_locale_reserved_size = (1L << 32);
DEFINE_int64( locale_reserved_size, default_locale_reserved_size, "Shared memory between cores on node, reserved for runtime" );
DEFINE_int64( locale_shared_size, SHMMAX + FLAGS_locale_reserved_size, "Total shared memory between cores on node" );
DECLARE_bool( global_memory_use_hugepages );
// forward declarations
namespace Grappa {
namespace impl {
/// called on failures to backtrace and pause for debugger
extern void failure_function();
/// how much memory do we expect to allocate?
extern int64_t global_memory_size_bytes;
extern int64_t global_bytes_per_core;
extern int64_t global_bytes_per_locale;
}
}
namespace Grappa {
namespace impl {
/// global LocaleSharedMemory instance
LocaleSharedMemory locale_shared_memory;
void LocaleSharedMemory::create() {
region_size = FLAGS_locale_shared_size;
VLOG(2) << "Creating LocaleSharedMemory region " << region_name
<< " with " << region_size << " bytes"
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
// if possible, delete this user's old leftover share memory regions
// if this returns false, either there was nothing to delete or
// there was something owned by somebody else.
bool deleted_one = boost::interprocess::shared_memory_object::remove( region_name.c_str() );
if( deleted_one ) {
VLOG(1) << "Deleted an old, leftover " << region_name.c_str();
}
// now, try to allocate a new one
try {
segment = boost::interprocess::fixed_managed_shared_memory( boost::interprocess::create_only,
region_name.c_str(),
region_size,
base_address);
}
catch(...){
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
failure_function();
throw;
}
VLOG(2) << "Created LocaleSharedMemory region " << region_name
<< " with " << region_size << " bytes"
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
}
void LocaleSharedMemory::attach() {
// first, check that we can create something large enough
CHECK_GE( FLAGS_locale_shared_size, global_bytes_per_locale )
<< "Can't accomodate " << global_bytes_per_locale << " bytes of shared heap per locale with "
<< FLAGS_locale_shared_size << " total shared bytes.";
VLOG(2) << "Attaching to LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
try {
segment = boost::interprocess::fixed_managed_shared_memory( boost::interprocess::open_only,
region_name.c_str(),
base_address );
}
catch(...){
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
failure_function();
throw;
}
VLOG(2) << "Attached to LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
}
void LocaleSharedMemory::destroy() {
VLOG(2) << "Removing LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
VLOG(2) << "Removed LocaleSharedMemory region " << region_name
<< " on " << global_communicator.mycore()
<< " of " << global_communicator.cores();
}
LocaleSharedMemory::LocaleSharedMemory()
: region_size( FLAGS_locale_shared_size )
, region_name( "GrappaLocaleSharedMemory" )
, base_address( reinterpret_cast<void*>( 0x400000000000L ) )
, segment() // default constructor; initialize later
{
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
// TODO: figure out reasonable region size
// maybe reuse SHMMAX stuff?
}
LocaleSharedMemory::~LocaleSharedMemory() {
boost::interprocess::shared_memory_object::remove( region_name.c_str() );
}
void LocaleSharedMemory::init() {
if( FLAGS_locale_reserved_size != default_locale_reserved_size ) {
FLAGS_locale_shared_size = SHMMAX + FLAGS_locale_reserved_size;
}
}
void LocaleSharedMemory::activate() {
if( Grappa::locale_mycore() == 0 ) { create(); }
global_communicator.barrier();
if( Grappa::locale_mycore() != 0 ) { attach(); }
global_communicator.barrier();
}
void LocaleSharedMemory::finish() {
global_communicator.barrier();
if( Grappa::locale_mycore() == 0 ) { destroy(); }
}
void * LocaleSharedMemory::allocate( size_t size ) {
void * p = NULL;
try {
p = Grappa::impl::locale_shared_memory.segment.allocate( size );
}
catch(...){
LOG(ERROR) << "Allocation of " << size << " bytes failed with "
<< get_free_memory() << " free.";
failure_function();
throw;
}
return p;
}
void * LocaleSharedMemory::allocate_aligned( size_t size, size_t alignment ) {
void * p = NULL;
try {
p = Grappa::impl::locale_shared_memory.segment.allocate_aligned( size, alignment );
}
catch(...){
LOG(ERROR) << "Allocation of " << size << " bytes with alignment " << alignment
<< " failed with " << get_free_memory() << " free.";
failure_function();
throw;
}
return p;
}
void LocaleSharedMemory::deallocate( void * ptr ) {
try {
Grappa::impl::locale_shared_memory.segment.deallocate( ptr );
}
catch(...){
LOG(ERROR) << "Deallocation of " << ptr
<< " failed with " << get_free_memory() << " free.";
failure_function();
throw;
}
}
} // namespace impl
} // namespace Grappa
<|endoftext|>
|
<commit_before>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_DIRICHLET_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_DIRICHLET_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <vector>
#include <dune/common/shared_ptr.hh>
#if HAVE_DUNE_DETAILED_DISCRETIZATIONS
#include <dune/detailed/discretizations/discretefunction/default.hh>
#endif // HAVE_DUNE_DETAILED_DISCRETIZATIONS
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>
namespace Dune {
namespace Stuff {
namespace DiscreteFunction {
namespace Projection {
namespace Dirichlet {
#if HAVE_DUNE_DETAILED_DISCRETIZATIONS
template< class FunctionType,
class DiscreteFunctionSpaceType, class VectorType >
void project(const Dune::Stuff::Grid::BoundaryInfo::Interface< typename DiscreteFunctionSpaceType::GridViewType >& boundaryInfo,
const FunctionType& function,
Dune::Detailed::Discretizations::DiscreteFunction::Default< DiscreteFunctionSpaceType, VectorType >& discreteFunction)
{
// some types
typedef Dune::Detailed::Discretizations::DiscreteFunction::Default< DiscreteFunctionSpaceType, VectorType > DiscreteFunctionType;
typedef typename DiscreteFunctionSpaceType::GridPartType GridPartType;
typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType;
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename EntityType::Geometry GeometryType;
typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename DiscreteFunctionSpaceType::BaseFunctionSetType BaseFunctionSetType;
typedef typename DiscreteFunctionType::LocalFunctionType LocalFunctionType;
typedef typename DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::RangeType RangeType;
// preparations
RangeType tmpEvaluation(0.0);
const DiscreteFunctionSpaceType& space = discreteFunction.space();
const GridPartType& gridPart = space.gridPart();
discreteFunction.clear();
// walk the grid
for (EntityIteratorType entityIt = gridPart.template begin< 0 >();
entityIt != gridPart.template end< 0 >();
++entityIt)
{
// only consider entities with boundary intersection
const EntityType& entity = *entityIt;
const GeometryType& geometry = entity.geometry();
if(entity.hasBoundaryIntersections()) {
// local function of destination
LocalFunctionType localFunction = discreteFunction.localFunction(entity);
// get the Lagrange point set
typedef typename DiscreteFunctionSpaceType::MapperType::LagrangePointSetType LagrangePointSetType;
const LagrangePointSetType lagrangePointSet = space.map().lagrangePointSet(entity);
// get the lagrange points' coordinates
typedef typename LagrangePointSetType::CoordinateType LagrangePointCoordinateType;
std::vector< LagrangePointCoordinateType > lagrangePointsGlobal(lagrangePointSet.nop(),
LagrangePointCoordinateType(0.0));
for (unsigned int i = 0; i < lagrangePointSet.nop(); ++i)
lagrangePointsGlobal[i] = geometry.global(lagrangePointSet.point(i));
// walk all intersections
for (IntersectionIteratorType intersectionIt = gridPart.ibegin(entity);
intersectionIt != gridPart.iend( entity );
++intersectionIt) {
const IntersectionType& intersection = *intersectionIt;
// only consider dirichlet boundary intersection
if (boundaryInfo.dirichlet(intersection)) {
// loop over all lagrange points
for (unsigned int i = 0; i < lagrangePointSet.nop(); ++i )
{
// if dof lies on the boundary intersection
if (Dune::Stuff::Grid::intersectionContains(intersection, lagrangePointsGlobal[i])) {
// evaluate the function
function.evaluate(lagrangePointsGlobal[i], tmpEvaluation);
// set the corresponding local dof
localFunction.set(i, tmpEvaluation);
} // if dof lies on the boundary intersection
} // loop over all lagrange points
} // only consider dirichlet boundary intersection
} // walk all intersections
} // only consider entities with boundary intersection
} // walk the grid
} // static void project()
#endif // HAVE_DUNE_DETAILED_DISCRETIZATIONS
} // namespace Dirichlet
} // namespace Projection
} // namespace DiscreteFunction
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_DIRICHLET_HH
<commit_msg>[discretefunction.projection.dirichlet] update<commit_after>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_DIRICHLET_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_DIRICHLET_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <vector>
#include <dune/common/shared_ptr.hh>
#if HAVE_DUNE_DETAILED_DISCRETIZATIONS
#include <dune/detailed/discretizations/discretefunction/default.hh>
#endif // HAVE_DUNE_DETAILED_DISCRETIZATIONS
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>
namespace Dune {
namespace Stuff {
namespace DiscreteFunction {
namespace Projection {
namespace Dirichlet {
#if HAVE_DUNE_DETAILED_DISCRETIZATIONS
template< class FunctionType,
class DiscreteFunctionSpaceType, class VectorType >
void project(const Dune::Stuff::GridboundaryInterface< typename DiscreteFunctionSpaceType::GridViewType >& boundaryInfo,
const FunctionType& function,
Dune::Detailed::Discretizations::DiscreteFunction::Default< DiscreteFunctionSpaceType, VectorType >& discreteFunction)
{
// some types
typedef Dune::Detailed::Discretizations::DiscreteFunction::Default< DiscreteFunctionSpaceType, VectorType > DiscreteFunctionType;
typedef typename DiscreteFunctionSpaceType::GridPartType GridPartType;
typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType;
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename EntityType::Geometry GeometryType;
typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename DiscreteFunctionSpaceType::BaseFunctionSetType BaseFunctionSetType;
typedef typename DiscreteFunctionType::LocalFunctionType LocalFunctionType;
typedef typename DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::RangeType RangeType;
// preparations
RangeType tmpEvaluation(0.0);
const DiscreteFunctionSpaceType& space = discreteFunction.space();
const GridPartType& gridPart = space.gridPart();
discreteFunction.clear();
// walk the grid
for (EntityIteratorType entityIt = gridPart.template begin< 0 >();
entityIt != gridPart.template end< 0 >();
++entityIt)
{
// only consider entities with boundary intersection
const EntityType& entity = *entityIt;
const GeometryType& geometry = entity.geometry();
if(entity.hasBoundaryIntersections()) {
// local function of destination
LocalFunctionType localFunction = discreteFunction.localFunction(entity);
// get the Lagrange point set
typedef typename DiscreteFunctionSpaceType::MapperType::LagrangePointSetType LagrangePointSetType;
const LagrangePointSetType lagrangePointSet = space.map().lagrangePointSet(entity);
// get the lagrange points' coordinates
typedef typename LagrangePointSetType::CoordinateType LagrangePointCoordinateType;
std::vector< LagrangePointCoordinateType > lagrangePointsGlobal(lagrangePointSet.nop(),
LagrangePointCoordinateType(0.0));
for (unsigned int i = 0; i < lagrangePointSet.nop(); ++i)
lagrangePointsGlobal[i] = geometry.global(lagrangePointSet.point(i));
// walk all intersections
for (IntersectionIteratorType intersectionIt = gridPart.ibegin(entity);
intersectionIt != gridPart.iend( entity );
++intersectionIt) {
const IntersectionType& intersection = *intersectionIt;
// only consider dirichlet boundary intersection
if (boundaryInfo.dirichlet(intersection)) {
// loop over all lagrange points
for (unsigned int i = 0; i < lagrangePointSet.nop(); ++i )
{
// if dof lies on the boundary intersection
if (Dune::Stuff::Grid::intersectionContains(intersection, lagrangePointsGlobal[i])) {
// evaluate the function
function.evaluate(lagrangePointsGlobal[i], tmpEvaluation);
// set the corresponding local dof
localFunction.set(i, tmpEvaluation);
} // if dof lies on the boundary intersection
} // loop over all lagrange points
} // only consider dirichlet boundary intersection
} // walk all intersections
} // only consider entities with boundary intersection
} // walk the grid
} // static void project()
#endif // HAVE_DUNE_DETAILED_DISCRETIZATIONS
} // namespace Dirichlet
} // namespace Projection
} // namespace DiscreteFunction
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_DIRICHLET_HH
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file test_spectral_connectivity.cpp
* @author Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date May, 2018
*
* @section LICENSE
*
* Copyright (C) 2018, Daniel Strohmeier and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief The spectral connectivity test implementation
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <mne/mne.h>
#include <utils/ioutils.h>
#include "connectivity/metrics/coherence.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtTest>
//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
#include <Eigen/Core>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace Eigen;
using namespace CONNECTIVITYLIB;
using namespace UTILSLIB;
//=============================================================================================================
/**
* DECLARE CLASS TestSpectralConnectivity
*
* @brief The TestSpectralConnectivity class provides spectral connectivity tests
*
*/
class TestSpectralConnectivity: public QObject
{
Q_OBJECT
public:
TestSpectralConnectivity();
private slots:
void initTestCase();
void spectralConnectivityCoherence();
void spectralConnectivityImagCoherence();
void spectralConnectivityPLV();
void spectralConnectivityPLI();
void spectralConnectivityPLI2();
void spectralConnectivityWPLI();
void spectralConnectivityWPLI2();
void cleanupTestCase();
private:
void compareConnectivity();
double epsilon;
RowVectorXd m_ConnectivityOutput;
RowVectorXd m_RefConnectivityOutput;
};
//*************************************************************************************************************
TestSpectralConnectivity::TestSpectralConnectivity()
: epsilon(0.000001)
{
}
//*************************************************************************************************************
void TestSpectralConnectivity::TestSpectralConnectivity()
{
}
//*************************************************************************************************************
void TestSpectralConnectivity::spectralConnectivityCoherence()
{
//*********************************************************************************************************
// Load Data
//*********************************************************************************************************
inputTrials = MatrixXd();
QString dataFileName(QDir::currentPath()+"/mne-cpp-test-data/MEG/sample/data_spectral_connectivity.txt");
IOUtils::read_eigen_matrix(inputTrials, dataFileName);
int iNTrials = inputTrials.rows() / 2;
int iNfft = inputTrials.cols();
QString sWindowType = "hanning";
QList<MatrixXd> matDataList;
for (int i = 0; i < iNTrials; ++i)
{
matDataList.append(inputTrials.middleRows(i * 2, 2));
}
//*********************************************************************************************************
// Compute Connectivity
//*********************************************************************************************************
QVector<MatrixXd> Coh = Coherence::computeCoherence(matDataList, iNfft, sWindowType);
m_ConnectivityOutput = Coh.at(0).row(1);
//*********************************************************************************************************
// Load MNE-PYTHON Results As Reference
//*********************************************************************************************************
refConnectivity = MatrixXd();
QString refFileName(QDir::currentPath()+"/mne-cpp-test-data/Result/ref_spectral_connectivity_coh.txt");
IOUtils::read_eigen_matrix(refConnectivity, refFileName);
m_RefConnectivityOutput = refConnectivity.row(0);
//*********************************************************************************************************
// Compare Connectivity
//*********************************************************************************************************
compareConnectivity();
}
//*************************************************************************************************************
void TestSpectralConnectivity::compareConnectivity()
{
//*********************************************************************************************************
// Compare Spectral Connectvitity Result to MNE-PYTHON
//*********************************************************************************************************
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Compare Spectral Connectivities >>>>>>>>>>>>>>>>>>>>>>>>>\n");
QVERIFY( m_ConnectivityOutput.cols() == m_RefConnectivityOutput.cols() );
for (int i = 0; i < m_ConnectivityOutput.cols(); ++i)
{
QVERIFY( (m_ConnectivityOutput(i) - m_RefConnectivityOutput(i)) / m_RefConnectivityOutput(i) < epsilon );
}
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Compare Spectral Connectivities Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestSpectralConnectivity::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_APPLESS_MAIN(TestSpectralConnectivity)
<commit_msg>added imagcoh test<commit_after>//=============================================================================================================
/**
* @file test_spectral_connectivity.cpp
* @author Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date May, 2018
*
* @section LICENSE
*
* Copyright (C) 2018, Daniel Strohmeier and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief The spectral connectivity test implementation
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <mne/mne.h>
#include <utils/ioutils.h>
#include "connectivity/metrics/coherence.h"
#include "connectivity/metrics/imagcoherence.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtTest>
//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
#include <Eigen/Core>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace Eigen;
using namespace CONNECTIVITYLIB;
using namespace UTILSLIB;
//=============================================================================================================
/**
* DECLARE CLASS TestSpectralConnectivity
*
* @brief The TestSpectralConnectivity class provides spectral connectivity tests
*
*/
class TestSpectralConnectivity: public QObject
{
Q_OBJECT
public:
TestSpectralConnectivity();
private slots:
void initTestCase();
void spectralConnectivityCoherence();
void spectralConnectivityImagCoherence();
void spectralConnectivityPLV();
void spectralConnectivityPLI();
void spectralConnectivityPLI2();
void spectralConnectivityWPLI();
void spectralConnectivityWPLI2();
void cleanupTestCase();
private:
void compareConnectivity();
double epsilon;
RowVectorXd m_ConnectivityOutput;
RowVectorXd m_RefConnectivityOutput;
};
//*************************************************************************************************************
TestSpectralConnectivity::TestSpectralConnectivity()
: epsilon(0.000001)
{
}
//*************************************************************************************************************
void TestSpectralConnectivity::TestSpectralConnectivity()
{
}
//*************************************************************************************************************
void TestSpectralConnectivity::spectralConnectivityCoherence()
{
//*********************************************************************************************************
// Load Data
//*********************************************************************************************************
inputTrials = MatrixXd();
QString dataFileName(QDir::currentPath()+"/mne-cpp-test-data/MEG/sample/data_spectral_connectivity.txt");
IOUtils::read_eigen_matrix(inputTrials, dataFileName);
int iNTrials = inputTrials.rows() / 2;
int iNfft = inputTrials.cols();
QString sWindowType = "hanning";
QList<MatrixXd> matDataList;
for (int i = 0; i < iNTrials; ++i)
{
matDataList.append(inputTrials.middleRows(i * 2, 2));
}
//*********************************************************************************************************
// Compute Connectivity
//*********************************************************************************************************
QVector<MatrixXd> Coh = Coherence::computeCoherence(matDataList, iNfft, sWindowType);
m_ConnectivityOutput = Coh.at(0).row(1);
//*********************************************************************************************************
// Load MNE-PYTHON Results As Reference
//*********************************************************************************************************
refConnectivity = MatrixXd();
QString refFileName(QDir::currentPath()+"/mne-cpp-test-data/Result/Connectivity/ref_spectral_connectivity_coh.txt");
IOUtils::read_eigen_matrix(refConnectivity, refFileName);
m_RefConnectivityOutput = refConnectivity.row(0);
//*********************************************************************************************************
// Compare Connectivity
//*********************************************************************************************************
compareConnectivity();
}
//*************************************************************************************************************
void TestSpectralConnectivity::spectralConnectivityImagCoherence()
{
//*********************************************************************************************************
// Load Data
//*********************************************************************************************************
inputTrials = MatrixXd();
QString dataFileName(QDir::currentPath()+"/mne-cpp-test-data/MEG/sample/data_spectral_connectivity.txt");
IOUtils::read_eigen_matrix(inputTrials, dataFileName);
int iNTrials = inputTrials.rows() / 2;
int iNfft = inputTrials.cols();
QString sWindowType = "hanning";
QList<MatrixXd> matDataList;
for (int i = 0; i < iNTrials; ++i)
{
matDataList.append(inputTrials.middleRows(i * 2, 2));
}
//*********************************************************************************************************
// Compute Connectivity
//*********************************************************************************************************
QVector<MatrixXd> Coh = Coherence::computeImagCoherence(matDataList, iNfft, sWindowType);
m_ConnectivityOutput = Coh.at(0).row(1);
//*********************************************************************************************************
// Load MNE-PYTHON Results As Reference
//*********************************************************************************************************
refConnectivity = MatrixXd();
QString refFileName(QDir::currentPath()+"/mne-cpp-test-data/Result/Connectivty/ref_spectral_connectivity_icoh.txt");
IOUtils::read_eigen_matrix(refConnectivity, refFileName);
m_RefConnectivityOutput = refConnectivity.row(0);
//*********************************************************************************************************
// Compare Connectivity
//*********************************************************************************************************
compareConnectivity();
}
//*************************************************************************************************************
void TestSpectralConnectivity::compareConnectivity()
{
//*********************************************************************************************************
// Compare Spectral Connectvitity Result to MNE-PYTHON
//*********************************************************************************************************
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Compare Spectral Connectivities >>>>>>>>>>>>>>>>>>>>>>>>>\n");
QVERIFY( m_ConnectivityOutput.cols() == m_RefConnectivityOutput.cols() );
for (int i = 0; i < m_ConnectivityOutput.cols(); ++i)
{
QVERIFY( (m_ConnectivityOutput(i) - m_RefConnectivityOutput(i)) / m_RefConnectivityOutput(i) < epsilon );
}
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Compare Spectral Connectivities Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestSpectralConnectivity::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_APPLESS_MAIN(TestSpectralConnectivity)
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include <limits>
#include "ConversationObserver.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/managers/conversation/ConversationManager.h"
#include "server/zone/objects/player/sessions/ConversationSession.h"
ConversationObserverImplementation::ConversationObserverImplementation(ConversationTemplate* conversationTemplate) {
this->conversationTemplate = conversationTemplate;
}
int ConversationObserverImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, long long arg2) {
//Verify needed parameters
if (eventType != ObserverEventType::CONVERSE && eventType != ObserverEventType::STARTCONVERSATION &&
eventType != ObserverEventType::SELECTCONVERSATION && eventType != ObserverEventType::STOPCONVERSATION) {
//Incorrect event type.
return 0;
}
if (observable == NULL || arg1 == NULL) {
return 0;
}
//Try to convert parameters to correct types.
CreatureObject* npc;
CreatureObject* player;
int selectedOption;
try {
npc = cast<CreatureObject* >(observable);
player = cast<CreatureObject* >(arg1);
if (arg2 < std::numeric_limits<int>::min()) {
selectedOption = std::numeric_limits<int>::min();
} else if (arg2 > std::numeric_limits<int>::max()) {
selectedOption = std::numeric_limits<int>::max();
} else {
selectedOption = arg2;
}
}
catch (...) {
//Failed to convert parameters. Keep observer.
return 0;
}
//Call event method if conversation ended.
if (eventType == ObserverEventType::STOPCONVERSATION) {
//Cancel any active session.
cancelConversationSession(player);
//Keep observer.
return 0;
} else {
if (eventType == ObserverEventType::STARTCONVERSATION) {
//Cancel any existing sessions.
cancelConversationSession(player);
//Create a new session.
createConversationSession(player);
}
//Select next conversation screen.
Reference<ConversationScreen*> conversationScreen = getNextConversationScreen(player, selectedOption, npc);
if (conversationScreen != NULL) {
//Modify the conversation screen.
conversationScreen = runScreenHandlers(player, npc, selectedOption, conversationScreen);
}
//Send the conversation screen to the player.
sendConversationScreenToPlayer(player, npc, conversationScreen);
if (conversationScreen == NULL)
cancelConversationSession(player);
}
//Keep the observer.
return 0;
}
void ConversationObserverImplementation::createConversationSession(CreatureObject* conversingPlayer) {
conversingPlayer->addActiveSession(SessionFacadeType::CONVERSATION, new ConversationSession());
}
void ConversationObserverImplementation::cancelConversationSession(CreatureObject* conversingPlayer) {
ManagedReference<Facade*> session = conversingPlayer->getActiveSession(SessionFacadeType::CONVERSATION);
if (session != NULL) {
session->cancelSession();
}
conversingPlayer->dropActiveSession(SessionFacadeType::CONVERSATION);
}
ConversationScreen* ConversationObserverImplementation::getNextConversationScreen(CreatureObject* conversingPlayer, int selectedOption, CreatureObject* conversingNPC) {
//Get screen ID from last conversation screen.
Reference<ConversationSession*> session = cast<ConversationSession* >(conversingPlayer->getActiveSession(SessionFacadeType::CONVERSATION));
/*String lastScreenId = "";
if (session != NULL) {
lastScreenId = session->getLastConversationScreenName();
}*/
//Get last conversation screen.
Reference<ConversationScreen* > lastConversationScreen = session->getLastConversationScreen();
Reference<ConversationScreen* > nextConversationScreen;
if (lastConversationScreen != NULL) {
//Get the linked screen for the selected option.
nextConversationScreen = conversationTemplate->getScreen(lastConversationScreen->getOptionLink(selectedOption));
} else {
//Get the initial screen.
nextConversationScreen = conversationTemplate->getInitialScreen();
}
return nextConversationScreen;
}
ConversationScreen* ConversationObserverImplementation::runScreenHandlers(CreatureObject* conversingPlayer, CreatureObject* conversingNPC, int selectedOption, ConversationScreen* conversationScreen) {
ConversationScreen* modifiedScreen = NULL;
//Loop until a screen has been modified.
while (modifiedScreen == NULL) {
//Call appropriate screen handler.
if (screenHandlers.contains(conversationScreen->getScreenID())) {
//Copy the conversation screen to preserve the template.
modifiedScreen = screenHandlers.get(conversationScreen->getScreenID())->handleScreen(conversingPlayer, conversingNPC, selectedOption, new ConversationScreen(*conversationScreen));
//Check if another screen should be handled
if (modifiedScreen == NULL) {
//Get next screen.
String screenId = screenHandlers.get(conversationScreen->getScreenID())->getNextScreenId();
conversationScreen = getConversationScreen(screenId);
if (conversationScreen == NULL) {
//No new screen found.
return NULL;
}
}
} else {
//No screen handler found for this screen, exit loop and return it unmodified.
modifiedScreen = conversationScreen;
}
}
return modifiedScreen;
}
void ConversationObserverImplementation::sendConversationScreenToPlayer(CreatureObject* conversingPlayer, CreatureObject* conversingNPC, ConversationScreen* conversationScreen) {
if (conversationScreen != NULL) {
//Send the screen to the player.
conversationScreen->sendTo(conversingPlayer, conversingNPC);
} else {
//Clear screen ID from last conversation screen.
ConversationSession* session = cast<ConversationSession* >(conversingPlayer->getActiveSession(SessionFacadeType::CONVERSATION));
if (session != NULL) {
session->setLastConversationScreen(NULL);
}
conversingPlayer->sendMessage(new StopNpcConversation(conversingPlayer, conversingNPC->getObjectID()));
}
}
<commit_msg>[fixed] stability issues<commit_after>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include <limits>
#include "ConversationObserver.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/managers/conversation/ConversationManager.h"
#include "server/zone/objects/player/sessions/ConversationSession.h"
ConversationObserverImplementation::ConversationObserverImplementation(ConversationTemplate* conversationTemplate) {
this->conversationTemplate = conversationTemplate;
}
int ConversationObserverImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, long long arg2) {
//Verify needed parameters
if (eventType != ObserverEventType::CONVERSE && eventType != ObserverEventType::STARTCONVERSATION &&
eventType != ObserverEventType::SELECTCONVERSATION && eventType != ObserverEventType::STOPCONVERSATION) {
//Incorrect event type.
return 0;
}
if (observable == NULL || arg1 == NULL) {
return 0;
}
//Try to convert parameters to correct types.
CreatureObject* npc;
CreatureObject* player;
int selectedOption;
try {
npc = cast<CreatureObject* >(observable);
player = cast<CreatureObject* >(arg1);
if (arg2 < std::numeric_limits<int>::min()) {
selectedOption = std::numeric_limits<int>::min();
} else if (arg2 > std::numeric_limits<int>::max()) {
selectedOption = std::numeric_limits<int>::max();
} else {
selectedOption = arg2;
}
}
catch (...) {
//Failed to convert parameters. Keep observer.
return 0;
}
//Call event method if conversation ended.
if (eventType == ObserverEventType::STOPCONVERSATION) {
//Cancel any active session.
cancelConversationSession(player);
//Keep observer.
return 0;
} else {
if (eventType == ObserverEventType::STARTCONVERSATION) {
//Cancel any existing sessions.
cancelConversationSession(player);
//Create a new session.
createConversationSession(player);
}
//Select next conversation screen.
Reference<ConversationScreen*> conversationScreen = getNextConversationScreen(player, selectedOption, npc);
if (conversationScreen != NULL) {
//Modify the conversation screen.
conversationScreen = runScreenHandlers(player, npc, selectedOption, conversationScreen);
}
//Send the conversation screen to the player.
sendConversationScreenToPlayer(player, npc, conversationScreen);
if (conversationScreen == NULL)
cancelConversationSession(player);
}
//Keep the observer.
return 0;
}
void ConversationObserverImplementation::createConversationSession(CreatureObject* conversingPlayer) {
conversingPlayer->addActiveSession(SessionFacadeType::CONVERSATION, new ConversationSession());
}
void ConversationObserverImplementation::cancelConversationSession(CreatureObject* conversingPlayer) {
ManagedReference<Facade*> session = conversingPlayer->getActiveSession(SessionFacadeType::CONVERSATION);
if (session != NULL) {
session->cancelSession();
}
conversingPlayer->dropActiveSession(SessionFacadeType::CONVERSATION);
}
ConversationScreen* ConversationObserverImplementation::getNextConversationScreen(CreatureObject* conversingPlayer, int selectedOption, CreatureObject* conversingNPC) {
//Get screen ID from last conversation screen.
Reference<ConversationSession*> session = cast<ConversationSession* >(conversingPlayer->getActiveSession(SessionFacadeType::CONVERSATION));
/*String lastScreenId = "";
if (session != NULL) {
lastScreenId = session->getLastConversationScreenName();
}*/
//Get last conversation screen.
Reference<ConversationScreen* > lastConversationScreen;
if (session != NULL)
lastConversationScreen = session->getLastConversationScreen();
Reference<ConversationScreen* > nextConversationScreen;
if (lastConversationScreen != NULL) {
//Get the linked screen for the selected option.
nextConversationScreen = conversationTemplate->getScreen(lastConversationScreen->getOptionLink(selectedOption));
} else {
//Get the initial screen.
nextConversationScreen = conversationTemplate->getInitialScreen();
}
return nextConversationScreen;
}
ConversationScreen* ConversationObserverImplementation::runScreenHandlers(CreatureObject* conversingPlayer, CreatureObject* conversingNPC, int selectedOption, ConversationScreen* conversationScreen) {
ConversationScreen* modifiedScreen = NULL;
//Loop until a screen has been modified.
while (modifiedScreen == NULL) {
//Call appropriate screen handler.
if (screenHandlers.contains(conversationScreen->getScreenID())) {
//Copy the conversation screen to preserve the template.
modifiedScreen = screenHandlers.get(conversationScreen->getScreenID())->handleScreen(conversingPlayer, conversingNPC, selectedOption, new ConversationScreen(*conversationScreen));
//Check if another screen should be handled
if (modifiedScreen == NULL) {
//Get next screen.
String screenId = screenHandlers.get(conversationScreen->getScreenID())->getNextScreenId();
conversationScreen = getConversationScreen(screenId);
if (conversationScreen == NULL) {
//No new screen found.
return NULL;
}
}
} else {
//No screen handler found for this screen, exit loop and return it unmodified.
modifiedScreen = conversationScreen;
}
}
return modifiedScreen;
}
void ConversationObserverImplementation::sendConversationScreenToPlayer(CreatureObject* conversingPlayer, CreatureObject* conversingNPC, ConversationScreen* conversationScreen) {
if (conversationScreen != NULL) {
//Send the screen to the player.
conversationScreen->sendTo(conversingPlayer, conversingNPC);
} else {
//Clear screen ID from last conversation screen.
ConversationSession* session = cast<ConversationSession* >(conversingPlayer->getActiveSession(SessionFacadeType::CONVERSATION));
if (session != NULL) {
session->setLastConversationScreen(NULL);
}
conversingPlayer->sendMessage(new StopNpcConversation(conversingPlayer, conversingNPC->getObjectID()));
}
}
<|endoftext|>
|
<commit_before>
/**
* @file GradientGoalDetector.cpp
*
* Implementation of class GradientGoalDetector
*
*/
#include "GradientGoalDetector.h"
#include "Tools/DataStructures/ArrayQueue.h"
#include "Tools/CameraGeometry.h"
#include "Tools/Debug/Stopwatch.h"
#include "Tools/ImageProcessing/BresenhamLineScan.h"
#include <Representations/Infrastructure/CameraInfoConstants.h>
GradientGoalDetector::GradientGoalDetector()
:
cameraID(CameraInfo::Bottom)
{
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markPeaks", "mark found maximum u-v peaks in image", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:draw_scanlines","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:draw_response","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:draw_difference","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markFootScans","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markFootScanResponse","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markFootScanGoodPoints","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:use_horizon","..", false);
}
void GradientGoalDetector::execute(CameraInfo::CameraID id, bool horizon)
{
cameraID = id;
CANVAS_PX(cameraID);
getGoalPercept().reset();
//if(cameraID == CameraInfo::Top)
{
Vector3d zem = CameraGeometry::imagePixelToWorld(getCameraMatrix(), getImage().cameraInfo,
getImage().cameraInfo.getOpticalCenterX(), getImage().cameraInfo.getOpticalCenterY(),
300);
zem.y = 0;
zem.x = 500;
zem.z = getCameraMatrix().translation.z;
Vector2<int> pp = CameraGeometry::relativePointToImage(getCameraMatrix(), getImage().cameraInfo,zem);
if(pp.x > 40 && pp.x < 640 - 40 && pp.y > 0 && pp.y < 480)
{
LINE_PX(ColorClasses::red, pp.x - 20, pp.y, pp.x+20, pp.y);
}
}
Vector2d p1(0, getImage().cameraInfo.getOpticalCenterY());
Vector2d p2(getImage().cameraInfo.resolutionWidth, getImage().cameraInfo.getOpticalCenterY());
Vector2d direction(1,0);
if(horizon) {
p1 = getArtificialHorizon().begin();
p2 = getArtificialHorizon().end();
direction = getArtificialHorizon().getDirection();
}
int imageBorderOffset = 25;
int heightOfHorizon = (int) ((p1.y + p2.y) * 0.5 + 0.5);
// image over the horizon
if(heightOfHorizon > (int) getImage().cameraInfo.resolutionHeight - 10)
{
return;
}
// adjust the scan height in case of the bottom camera
//if(cameraID == CameraInfo::Bottom)
{
// clamp the scanline
p1.y = Math::clamp((int) p1.y, imageBorderOffset + 5, (int)getImage().cameraInfo.resolutionHeight - imageBorderOffset - 5);
p2.y = Math::clamp((int) p2.y, imageBorderOffset + 5 , (int)getImage().cameraInfo.resolutionHeight - imageBorderOffset - 5);
}
//double horizont = min(p1.y, p2.y);
double threshold = params.gradientThreshold;
double thresholdY = params.minY;
double response = 0.0;
double responseY = 0.0;
double lastResponse = 0.0;
double lastResponseY = 0.0;
Pixel pixel;
int aktIdx = 0;
for(int i = 0; i < 5; i++)
{
features[i].clear();
}
if
(
p1.y > imageBorderOffset &&
p2.y > imageBorderOffset &&
p1.y < (int) getImage().height() - imageBorderOffset &&
p2.y < (int) getImage().height() - imageBorderOffset
)
{
bool isCandidate = false;
bool isObstacle = false;
Feature candidate;
int diffVU = 0;
int lastDiffVU = 0;
for(int y = (int) p1.y - 12; y <= (int) p1.y + 12; y += 6)
{
valueBuffer.init();
valueBufferY.init();
pointBuffer.init();
isCandidate = false;
Vector2<int> pos((int) p1.x + 2, y);
BresenhamLineScan scanner(pos, direction, getImage().cameraInfo);
do
{
pointBuffer.add(pos);
getImage().get(pos.x, pos.y, pixel);
diffVU = (int) pixel.v - (int) pixel.u;
valueBuffer.add(diffVU);
valueBufferY.add(pixel.y);
if(pos.x > 3)
{
response = valueBuffer[4] + 2 * valueBuffer[3] + 4 * valueBuffer[2] + valueBuffer[1] * 2 + valueBuffer[0];
//response = valueBuffer[4] + 2 * valueBuffer[3] - valueBuffer[1] * 2 - valueBuffer[0];
responseY = valueBufferY[2];
response /= 10;
DEBUG_REQUEST("NeoVision:GradientGoalDetector:draw_scanlines",
if(aktIdx == 2)
{
POINT_PX(ColorClasses::yellow, pos.x, pos.y );
}
else
{
POINT_PX(ColorClasses::gray, pos.x, pos.y );
}
);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:draw_difference",
if(aktIdx == 2)
{
LINE_PX(ColorClasses::green, (int) pointBuffer[3].x, (int) pointBuffer[3].y - lastDiffVU, (int) pointBuffer[4].x, (int) pointBuffer[4].y - diffVU);
lastDiffVU = diffVU;
}
);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:draw_response",
if(aktIdx == 2)
{
LINE_PX(ColorClasses::red, (int) pointBuffer[1].x, (int) pointBuffer[1].y - (int) /*fabs*/(lastResponse), (int) pointBuffer[2].x, (int) pointBuffer[2].y - (int)/* fabs*/(response) );
LINE_PX(ColorClasses::white, (int) pointBuffer[1].x, (int) pointBuffer[1].y - (int) fabs(lastResponseY / 3), (int) pointBuffer[2].x, (int) pointBuffer[2].y - (int) fabs(responseY / 3) );
lastResponse = response;
lastResponseY = responseY;
}
);
if(/*fabs*/(response) >= threshold && fabs(responseY) >= thresholdY)
{
if(!isCandidate)
{
candidate.begin = pointBuffer[2];
candidate.center = pointBuffer[2];
candidate.end = pointBuffer[2];
candidate.responseAtBegin.x = response;
candidate.responseAtBegin.y = diffVU;
if(diffVU < 0)
{
isObstacle = true;
}
}
isCandidate = true;
if(isObstacle)
{
candidate.possibleObstacle = isObstacle;
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::orange, pos.x - 2, pos.y);
);
}
else
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::blue, pos.x - 2, pos.y);
);
}
}
else
{
if(isCandidate)
{
candidate.end = pointBuffer[2];
candidate.center = (candidate.end + candidate.begin) / 2;
candidate.responseAtEnd.x = response;
candidate.responseAtEnd.y = diffVU;
features[aktIdx].push_back(candidate);
}
isCandidate = false;
isObstacle = false;
}//end if
}
}
while(scanner.getNextWithCheck(pos));
aktIdx++;
}//end for
}//end if
Vector2<double> dir(-direction.y, direction.x);
memset(&lastTestFeatureIdx, 0, sizeof(lastTestFeatureIdx));
//bool goalPostFound = false;
goalPosts.clear();
//std::cout << std::endl << " ------ " << std::endl;
for(unsigned i = 0; i < features[0].size(); i++)
{
const Feature& candidate = features[0][i];
BresenhamLineScan footPointScanner(candidate.center, dir, getImage().cameraInfo);
int goodPointsCount = 1;
Vector2<int> pos = candidate.center;
valueBuffer.init();
valueBufferY.init();
pointBuffer.init();
Vector2d last(pos);
for(int y = 1; y < 5; y++)
{
bool stop = false;
for(int yy = 0; yy < 5; yy++)
{
if(footPointScanner.getNextWithCheck(pos))
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
POINT_PX(ColorClasses::skyblue, pos.x, pos.y);
);
pointBuffer.add(pos);
getImage().get(pos.x, pos.y, pixel);
int diffVU = (int) pixel.v - (int) pixel.u;
valueBuffer.add(diffVU);
valueBufferY.add(pixel.y);
if(yy > 0)
{
response = valueBuffer[4] + 2 * valueBuffer[3] + 4 * valueBuffer[2] + valueBuffer[1] * 2 + valueBuffer[0];
//response = valueBuffer[4] + 2 * valueBuffer[3] - valueBuffer[1] * 2 - valueBuffer[0];
responseY = valueBufferY[2];
response /= 10;
if(/*fabs*/(response) < params.responseHoldFactor * threshold || fabs(responseY) < params.responseHoldFactor * thresholdY)
{
stop = true;
}
}
}
}
unsigned j = lastTestFeatureIdx[y];
while (!stop && j < features[y].size())
{
int dist = (pos - features[y][j].center).abs();
if(dist < params.dist)
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScanGoodPoints",
POINT_PX(ColorClasses::red, features[y][j].center.x, features[y][j].center.y);
);
lastTestFeatureIdx[y] = j;
goodPointsCount++;
stop = true;
//std::cout << "good (" << i << ") " << dist << " pos: " << pos << " point:" << features[y][j].center << std::endl;
}
j++;
}
}//end for
if(goodPointsCount >= params.minGoodPoints)
{
bool footPointFound = false;
bool stop = false;
Pixel pixel1;
Pixel pixel2;
Pixel pixel3;
int lastDiffVU = 0;
int lastResponse = 0;
while(!stop && footPointScanner.getNextWithCheck(pos))
{
pointBuffer.add(pos);
getImage().get(pos.x, pos.y, pixel);
int diffVU = (int) pixel.v - (int) pixel.u;
valueBuffer.add(diffVU);
valueBufferY.add(pixel.y);
response = valueBuffer[4] + 2 * valueBuffer[3] + 4 * valueBuffer[2] + valueBuffer[1] * 2 + valueBuffer[0];
//response = valueBuffer[4] + 2 * valueBuffer[3] - valueBuffer[1] * 2 - valueBuffer[0];
responseY = valueBufferY[2];
response /= 10;
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
if(getFieldColorPercept().isFieldColor(pixel))
{
POINT_PX(ColorClasses::green, (int) pointBuffer[2].x, (int) pointBuffer[2].y);
}
else
{
POINT_PX(ColorClasses::gray, (int) pointBuffer[2].x, (int) pointBuffer[2].y);
}
);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScanResponse",
LINE_PX(ColorClasses::white, (int) pointBuffer[1].x + lastResponse, (int) pointBuffer[1].y, (int) pointBuffer[2].x + (int) response, (int) pointBuffer[2].y);
LINE_PX(ColorClasses::orange, (int) pointBuffer[1].x + lastDiffVU, (int) pointBuffer[1].y, (int) pointBuffer[2].x + diffVU, (int) pointBuffer[2].y);
);
lastDiffVU = diffVU;
lastResponse = (int) response;
getImage().get((int) pointBuffer[4].x, (int) pointBuffer[4].y, pixel1);
getImage().get((int) pointBuffer[3].x, (int) pointBuffer[3].y, pixel2);
getImage().get((int) pointBuffer[2].x, (int) pointBuffer[2].y, pixel3);
if(/*fabs*/(response) < params.responseHoldFactor * threshold || fabs(responseY) < params.responseHoldFactor * thresholdY)
{
stop = true;
if
(
//c > params.minScanPointsAfterGoodPoints &&
(getFieldColorPercept().isFieldColor(pixel1) || getFieldColorPercept().isFieldColor(pixel2) || getFieldColorPercept().isFieldColor(pixel3))
)
{
footPointFound = true;
}
else
{
int t = 0;
int count = 0;
while( t < 10 && footPointScanner.getNextWithCheck(pos))
{
getImage().get(pos.x, pos.y, pixel);
if(getFieldColorPercept().isFieldColor(pixel))
{
count++;
}
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
if(getFieldColorPercept().isFieldColor(pixel))
{
POINT_PX(ColorClasses::green, pos.x, pos.y);
}
else
{
POINT_PX(ColorClasses::black, pos.x, pos.y);
}
);
t++;
}
if(count > 4)
{
footPointFound = true;
}
}
}
}//end while
if(footPointFound)
{
//goalPostFound = true;
GoalPercept::GoalPost post;
post.basePoint = Vector2<int>(pointBuffer[2]);
CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
post.basePoint.x, post.basePoint.y, 0.0,
post.position);
post.positionReliable = true;
goalPosts.push_back(post);
getGoalPercept().add(post);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
CIRCLE_PX(ColorClasses::yellowOrange, (int) pointBuffer[2].x, (int) pointBuffer[2].y, 10);
);
}
else
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
CIRCLE_PX(ColorClasses::red, (int) pointBuffer[2].x, (int) pointBuffer[2].y, 10);
);
}
}//end if
if(candidate.possibleObstacle)
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::pink, candidate.center.x, candidate.center.y);
);
}
else
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::red, candidate.center.x, candidate.center.y);
);
}
}//end for features[0].size()
// exactly two posts are seen => assign site labels
if(getGoalPercept().getNumberOfSeenPosts() == 2) {
GoalPercept::GoalPost& postOne = getGoalPercept().getPost(0);
GoalPercept::GoalPost& postTwo = getGoalPercept().getPost(1);
// sort: which one is left or right
if(postOne.basePoint.x > postTwo.basePoint.x)
{
postOne.type = GoalPercept::GoalPost::rightPost;
postTwo.type = GoalPercept::GoalPost::leftPost;
} else {
postOne.type = GoalPercept::GoalPost::leftPost;
postTwo.type = GoalPercept::GoalPost::rightPost;
}
}
}//end execute
<commit_msg>added asserts<commit_after>
/**
* @file GradientGoalDetector.cpp
*
* Implementation of class GradientGoalDetector
*
*/
#include "GradientGoalDetector.h"
#include "Tools/DataStructures/ArrayQueue.h"
#include "Tools/CameraGeometry.h"
#include "Tools/Debug/Stopwatch.h"
#include "Tools/ImageProcessing/BresenhamLineScan.h"
#include <Representations/Infrastructure/CameraInfoConstants.h>
#define IMG_GET(x,y,p) \
if(!getImage().isInside(x,y)) { \
std::cout << __FILE__ << ":" << __LINE__ << "SCHEISSE!!!" << std::endl; \
} \
getImage().get(x, y, p);
GradientGoalDetector::GradientGoalDetector()
:
cameraID(CameraInfo::Bottom)
{
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markPeaks", "mark found maximum u-v peaks in image", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:draw_scanlines","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:draw_response","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:draw_difference","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markFootScans","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markFootScanResponse","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:markFootScanGoodPoints","..", false);
DEBUG_REQUEST_REGISTER("NeoVision:GradientGoalDetector:use_horizon","..", false);
}
void GradientGoalDetector::execute(CameraInfo::CameraID id, bool horizon)
{
cameraID = id;
CANVAS_PX(cameraID);
getGoalPercept().reset();
Vector2d p1(0, getImage().cameraInfo.getOpticalCenterY());
Vector2d p2(getImage().cameraInfo.resolutionWidth, getImage().cameraInfo.getOpticalCenterY());
Vector2d direction(1,0);
if(horizon) {
p1 = getArtificialHorizon().begin();
p2 = getArtificialHorizon().end();
direction = getArtificialHorizon().getDirection();
}
int imageBorderOffset = 25;
int heightOfHorizon = (int) ((p1.y + p2.y) * 0.5 + 0.5);
// image over the horizon
if(heightOfHorizon > (int) getImage().cameraInfo.resolutionHeight - 10)
{
return;
}
// adjust the scan height in case of the bottom camera
//if(cameraID == CameraInfo::Bottom)
{
// clamp the scanline
p1.y = Math::clamp((int) p1.y, imageBorderOffset + 5, (int)getImage().cameraInfo.resolutionHeight - imageBorderOffset - 5);
p2.y = Math::clamp((int) p2.y, imageBorderOffset + 5 , (int)getImage().cameraInfo.resolutionHeight - imageBorderOffset - 5);
}
//double horizont = min(p1.y, p2.y);
double threshold = params.gradientThreshold;
double thresholdY = params.minY;
double response = 0.0;
double responseY = 0.0;
double lastResponse = 0.0;
double lastResponseY = 0.0;
Pixel pixel;
int aktIdx = 0;
for(int i = 0; i < 5; i++)
{
features[i].clear();
}
if
(
p1.y > imageBorderOffset &&
p2.y > imageBorderOffset &&
p1.y < (int) getImage().height() - imageBorderOffset &&
p2.y < (int) getImage().height() - imageBorderOffset
)
{
bool isCandidate = false;
bool isObstacle = false;
Feature candidate;
int diffVU = 0;
int lastDiffVU = 0;
for(int y = (int) p1.y - 12; y <= (int) p1.y + 12; y += 6)
{
valueBuffer.init();
valueBufferY.init();
pointBuffer.init();
isCandidate = false;
Vector2<int> pos((int) p1.x + 2, y);
BresenhamLineScan scanner(pos, direction, getImage().cameraInfo);
do
{
pointBuffer.add(pos);
IMG_GET(pos.x, pos.y, pixel);
diffVU = (int) pixel.v - (int) pixel.u;
valueBuffer.add(diffVU);
valueBufferY.add(pixel.y);
if(pointBuffer.isFull())
{
response = valueBuffer[4] + 2 * valueBuffer[3] + 4 * valueBuffer[2] + valueBuffer[1] * 2 + valueBuffer[0];
//response = valueBuffer[4] + 2 * valueBuffer[3] - valueBuffer[1] * 2 - valueBuffer[0];
responseY = valueBufferY[2];
response /= 10;
DEBUG_REQUEST("NeoVision:GradientGoalDetector:draw_scanlines",
if(aktIdx == 2)
{
POINT_PX(ColorClasses::yellow, pos.x, pos.y );
}
else
{
POINT_PX(ColorClasses::gray, pos.x, pos.y );
}
);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:draw_difference",
if(aktIdx == 2)
{
LINE_PX(ColorClasses::green, (int) pointBuffer[3].x, (int) pointBuffer[3].y - lastDiffVU, (int) pointBuffer[4].x, (int) pointBuffer[4].y - diffVU);
lastDiffVU = diffVU;
}
);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:draw_response",
if(aktIdx == 2)
{
LINE_PX(ColorClasses::red, (int) pointBuffer[1].x, (int) pointBuffer[1].y - (int) /*fabs*/(lastResponse), (int) pointBuffer[2].x, (int) pointBuffer[2].y - (int)/* fabs*/(response) );
LINE_PX(ColorClasses::white, (int) pointBuffer[1].x, (int) pointBuffer[1].y - (int) fabs(lastResponseY / 3), (int) pointBuffer[2].x, (int) pointBuffer[2].y - (int) fabs(responseY / 3) );
lastResponse = response;
lastResponseY = responseY;
}
);
if(/*fabs*/(response) >= threshold && fabs(responseY) >= thresholdY)
{
if(!isCandidate)
{
candidate.begin = pointBuffer[2];
candidate.center = pointBuffer[2];
candidate.end = pointBuffer[2];
candidate.responseAtBegin.x = response;
candidate.responseAtBegin.y = diffVU;
if(diffVU < 0)
{
isObstacle = true;
}
}
isCandidate = true;
if(isObstacle)
{
candidate.possibleObstacle = isObstacle;
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::orange, pos.x - 2, pos.y);
);
}
else
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::blue, pos.x - 2, pos.y);
);
}
}
else
{
if(isCandidate)
{
candidate.end = pointBuffer[2];
candidate.center = (candidate.end + candidate.begin) / 2;
candidate.responseAtEnd.x = response;
candidate.responseAtEnd.y = diffVU;
features[aktIdx].push_back(candidate);
}
isCandidate = false;
isObstacle = false;
}//end if
}
}
while(scanner.getNextWithCheck(pos));
aktIdx++;
}//end for
}//end if
Vector2<double> dir(-direction.y, direction.x);
memset(&lastTestFeatureIdx, 0, sizeof(lastTestFeatureIdx));
//bool goalPostFound = false;
goalPosts.clear();
//std::cout << std::endl << " ------ " << std::endl;
for(unsigned i = 0; i < features[0].size(); i++)
{
const Feature& candidate = features[0][i];
BresenhamLineScan footPointScanner(candidate.center, dir, getImage().cameraInfo);
int goodPointsCount = 1;
Vector2<int> pos = candidate.center;
valueBuffer.init();
valueBufferY.init();
pointBuffer.init();
Vector2d last(pos);
for(int y = 1; y < 5; y++)
{
bool stop = false;
for(int yy = 0; yy < 5; yy++)
{
if(footPointScanner.getNextWithCheck(pos))
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
POINT_PX(ColorClasses::skyblue, pos.x, pos.y);
);
pointBuffer.add(pos);
IMG_GET(pos.x, pos.y, pixel);
int diffVU = (int) pixel.v - (int) pixel.u;
valueBuffer.add(diffVU);
valueBufferY.add(pixel.y);
if(yy > 0)
{
response = valueBuffer[4] + 2 * valueBuffer[3] + 4 * valueBuffer[2] + valueBuffer[1] * 2 + valueBuffer[0];
//response = valueBuffer[4] + 2 * valueBuffer[3] - valueBuffer[1] * 2 - valueBuffer[0];
responseY = valueBufferY[2];
response /= 10;
if(/*fabs*/(response) < params.responseHoldFactor * threshold || fabs(responseY) < params.responseHoldFactor * thresholdY)
{
stop = true;
}
}
}
}
unsigned j = lastTestFeatureIdx[y];
while (!stop && j < features[y].size())
{
int dist = (pos - features[y][j].center).abs();
if(dist < params.dist)
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScanGoodPoints",
POINT_PX(ColorClasses::red, features[y][j].center.x, features[y][j].center.y);
);
lastTestFeatureIdx[y] = j;
goodPointsCount++;
stop = true;
//std::cout << "good (" << i << ") " << dist << " pos: " << pos << " point:" << features[y][j].center << std::endl;
}
j++;
}
}//end for
if(goodPointsCount >= params.minGoodPoints)
{
bool footPointFound = false;
bool stop = false;
Pixel pixel1;
Pixel pixel2;
Pixel pixel3;
int lastDiffVU = 0;
int lastResponse = 0;
while(!stop && footPointScanner.getNextWithCheck(pos))
{
pointBuffer.add(pos);
IMG_GET(pos.x, pos.y, pixel);
int diffVU = (int) pixel.v - (int) pixel.u;
valueBuffer.add(diffVU);
valueBufferY.add(pixel.y);
response = valueBuffer[4] + 2 * valueBuffer[3] + 4 * valueBuffer[2] + valueBuffer[1] * 2 + valueBuffer[0];
//response = valueBuffer[4] + 2 * valueBuffer[3] - valueBuffer[1] * 2 - valueBuffer[0];
responseY = valueBufferY[2];
response /= 10;
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
if(getFieldColorPercept().isFieldColor(pixel))
{
POINT_PX(ColorClasses::green, (int) pointBuffer[2].x, (int) pointBuffer[2].y);
}
else
{
POINT_PX(ColorClasses::gray, (int) pointBuffer[2].x, (int) pointBuffer[2].y);
}
);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScanResponse",
LINE_PX(ColorClasses::white, (int) pointBuffer[1].x + lastResponse, (int) pointBuffer[1].y, (int) pointBuffer[2].x + (int) response, (int) pointBuffer[2].y);
LINE_PX(ColorClasses::orange, (int) pointBuffer[1].x + lastDiffVU, (int) pointBuffer[1].y, (int) pointBuffer[2].x + diffVU, (int) pointBuffer[2].y);
);
lastDiffVU = diffVU;
lastResponse = (int) response;
IMG_GET((int) pointBuffer[4].x, (int) pointBuffer[4].y, pixel1);
IMG_GET((int) pointBuffer[3].x, (int) pointBuffer[3].y, pixel2);
IMG_GET((int) pointBuffer[2].x, (int) pointBuffer[2].y, pixel3);
if(/*fabs*/(response) < params.responseHoldFactor * threshold || fabs(responseY) < params.responseHoldFactor * thresholdY)
{
stop = true;
if
(
//c > params.minScanPointsAfterGoodPoints &&
(getFieldColorPercept().isFieldColor(pixel1) || getFieldColorPercept().isFieldColor(pixel2) || getFieldColorPercept().isFieldColor(pixel3))
)
{
footPointFound = true;
}
else
{
int t = 0;
int count = 0;
while( t < 10 && footPointScanner.getNextWithCheck(pos))
{
IMG_GET(pos.x, pos.y, pixel);
if(getFieldColorPercept().isFieldColor(pixel))
{
count++;
}
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
if(getFieldColorPercept().isFieldColor(pixel))
{
POINT_PX(ColorClasses::green, pos.x, pos.y);
}
else
{
POINT_PX(ColorClasses::black, pos.x, pos.y);
}
);
t++;
}
if(count > 4)
{
footPointFound = true;
}
}
}
}//end while
if(footPointFound)
{
//goalPostFound = true;
GoalPercept::GoalPost post;
post.basePoint = Vector2<int>(pointBuffer[2]);
CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
post.basePoint.x, post.basePoint.y, 0.0,
post.position);
post.positionReliable = true;
goalPosts.push_back(post);
getGoalPercept().add(post);
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
CIRCLE_PX(ColorClasses::yellowOrange, (int) pointBuffer[2].x, (int) pointBuffer[2].y, 10);
);
}
else
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markFootScans",
CIRCLE_PX(ColorClasses::red, (int) pointBuffer[2].x, (int) pointBuffer[2].y, 10);
);
}
}//end if
if(candidate.possibleObstacle)
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::pink, candidate.center.x, candidate.center.y);
);
}
else
{
DEBUG_REQUEST("NeoVision:GradientGoalDetector:markPeaks",
POINT_PX(ColorClasses::red, candidate.center.x, candidate.center.y);
);
}
}//end for features[0].size()
// exactly two posts are seen => assign site labels
if(getGoalPercept().getNumberOfSeenPosts() == 2) {
GoalPercept::GoalPost& postOne = getGoalPercept().getPost(0);
GoalPercept::GoalPost& postTwo = getGoalPercept().getPost(1);
// sort: which one is left or right
if(postOne.basePoint.x > postTwo.basePoint.x)
{
postOne.type = GoalPercept::GoalPost::rightPost;
postTwo.type = GoalPercept::GoalPost::leftPost;
} else {
postOne.type = GoalPercept::GoalPost::leftPost;
postTwo.type = GoalPercept::GoalPost::rightPost;
}
}
}//end execute
<|endoftext|>
|
<commit_before>// Copyright 2020 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <atomic>
#include "absl/types/optional.h"
#include "benchmark/benchmark.h"
#include "tcmalloc/central_freelist.h"
#include "tcmalloc/common.h"
#include "tcmalloc/mock_central_freelist.h"
#include "tcmalloc/mock_transfer_cache.h"
#include "tcmalloc/transfer_cache_internals.h"
#include "tcmalloc/transfer_cache_stats.h"
namespace tcmalloc {
namespace {
using TransferCacheEnv =
FakeTransferCacheEnvironment<internal_transfer_cache::TransferCache<
MinimalFakeCentralFreeList, FakeTransferCacheManager>>;
using LockFreeEnv =
FakeTransferCacheEnvironment<internal_transfer_cache::LockFreeTransferCache<
MinimalFakeCentralFreeList, FakeTransferCacheManager>>;
template <typename Env>
void BM_CrossThreadDraining(benchmark::State& state) {
using Manager = typename Env::Manager;
using Cache = typename Env::TransferCache;
const int kBatchSize = Env::kBatchSize;
const int kMaxObjectsToMove = Env::kMaxObjectsToMove;
void* batch[kMaxObjectsToMove];
struct CrossThreadState {
CrossThreadState() : m{}, c{Cache(&m), Cache(&m)} {
c[0].Init(1);
c[1].Init(1);
}
Manager m;
Cache c[2];
};
static CrossThreadState* s = nullptr;
if (state.thread_index == 0) {
s = new CrossThreadState();
for (int i = 0; i < Env::kInitialCapacityInBatches / 2; ++i) {
for (Cache& c : s->c) {
c.freelist().AllocateBatch(batch, kBatchSize);
c.InsertRange(batch, kBatchSize);
}
}
}
int src = state.thread_index % 2;
int dst = (src + 1) % 2;
for (auto iter : state) {
benchmark::DoNotOptimize(batch);
s->c[src].RemoveRange(batch, kBatchSize);
benchmark::DoNotOptimize(batch);
s->c[dst].InsertRange(batch, kBatchSize);
benchmark::DoNotOptimize(batch);
}
if (state.thread_index == 0) {
TransferCacheStats stats{};
for (Cache& c : s->c) {
TransferCacheStats other = c.GetHitRateStats();
stats.insert_hits += other.insert_hits;
stats.insert_misses += other.insert_misses;
stats.remove_hits += other.remove_hits;
stats.remove_misses += other.remove_misses;
}
state.counters["insert_hit_ratio"] =
static_cast<double>(stats.insert_hits) /
(stats.insert_hits + stats.insert_misses);
state.counters["remove_hit_ratio"] =
static_cast<double>(stats.remove_hits) /
(stats.remove_hits + stats.remove_misses);
delete s;
s = nullptr;
}
}
template <typename Env>
void BM_InsertRange(benchmark::State& state) {
const int kBatchSize = Env::kBatchSize;
const int kMaxObjectsToMove = Env::kMaxObjectsToMove;
// optional to have more precise control of when the destruction occurs, as
// we want to avoid polluting the timing with the dtor.
absl::optional<Env> e;
void* batch[kMaxObjectsToMove];
for (auto iter : state) {
state.PauseTiming();
e.emplace();
e->central_freelist().AllocateBatch(batch, kBatchSize);
benchmark::DoNotOptimize(e);
benchmark::DoNotOptimize(batch);
state.ResumeTiming();
e->transfer_cache().InsertRange(batch, kBatchSize);
}
}
template <typename Env>
void BM_RemoveRange(benchmark::State& state) {
const int kBatchSize = Env::kBatchSize;
const int kMaxObjectsToMove = Env::kMaxObjectsToMove;
// optional to have more precise control of when the destruction occurs, as
// we want to avoid polluting the timing with the dtor.
absl::optional<Env> e;
void* batch[kMaxObjectsToMove];
for (auto iter : state) {
state.PauseTiming();
e.emplace();
e->Insert(kBatchSize);
benchmark::DoNotOptimize(e);
state.ResumeTiming();
e->transfer_cache().RemoveRange(batch, kBatchSize);
benchmark::DoNotOptimize(batch);
}
}
BENCHMARK_TEMPLATE(BM_CrossThreadDraining, TransferCacheEnv)
->ThreadRange(2, 128);
BENCHMARK_TEMPLATE(BM_CrossThreadDraining, LockFreeEnv)->ThreadRange(2, 128);
BENCHMARK_TEMPLATE(BM_InsertRange, TransferCacheEnv);
BENCHMARK_TEMPLATE(BM_InsertRange, LockFreeEnv);
BENCHMARK_TEMPLATE(BM_RemoveRange, TransferCacheEnv);
BENCHMARK_TEMPLATE(BM_RemoveRange, LockFreeEnv);
} // namespace
} // namespace tcmalloc
<commit_msg>Make benchmark name shorter and reduce from 128 to 64 threads for the high contention test.<commit_after>// Copyright 2020 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <atomic>
#include "absl/types/optional.h"
#include "benchmark/benchmark.h"
#include "tcmalloc/central_freelist.h"
#include "tcmalloc/common.h"
#include "tcmalloc/mock_central_freelist.h"
#include "tcmalloc/mock_transfer_cache.h"
#include "tcmalloc/transfer_cache_internals.h"
#include "tcmalloc/transfer_cache_stats.h"
namespace tcmalloc {
namespace {
using TransferCacheEnv =
FakeTransferCacheEnvironment<internal_transfer_cache::TransferCache<
MinimalFakeCentralFreeList, FakeTransferCacheManager>>;
using LockFreeEnv =
FakeTransferCacheEnvironment<internal_transfer_cache::LockFreeTransferCache<
MinimalFakeCentralFreeList, FakeTransferCacheManager>>;
template <typename Env>
void BM_CrossThread(benchmark::State& state) {
using Manager = typename Env::Manager;
using Cache = typename Env::TransferCache;
const int kBatchSize = Env::kBatchSize;
const int kMaxObjectsToMove = Env::kMaxObjectsToMove;
void* batch[kMaxObjectsToMove];
struct CrossThreadState {
CrossThreadState() : m{}, c{Cache(&m), Cache(&m)} {
c[0].Init(1);
c[1].Init(1);
}
Manager m;
Cache c[2];
};
static CrossThreadState* s = nullptr;
if (state.thread_index == 0) {
s = new CrossThreadState();
for (int i = 0; i < Env::kInitialCapacityInBatches / 2; ++i) {
for (Cache& c : s->c) {
c.freelist().AllocateBatch(batch, kBatchSize);
c.InsertRange(batch, kBatchSize);
}
}
}
int src = state.thread_index % 2;
int dst = (src + 1) % 2;
for (auto iter : state) {
benchmark::DoNotOptimize(batch);
s->c[src].RemoveRange(batch, kBatchSize);
benchmark::DoNotOptimize(batch);
s->c[dst].InsertRange(batch, kBatchSize);
benchmark::DoNotOptimize(batch);
}
if (state.thread_index == 0) {
TransferCacheStats stats{};
for (Cache& c : s->c) {
TransferCacheStats other = c.GetHitRateStats();
stats.insert_hits += other.insert_hits;
stats.insert_misses += other.insert_misses;
stats.remove_hits += other.remove_hits;
stats.remove_misses += other.remove_misses;
}
state.counters["insert_hit_ratio"] =
static_cast<double>(stats.insert_hits) /
(stats.insert_hits + stats.insert_misses);
state.counters["remove_hit_ratio"] =
static_cast<double>(stats.remove_hits) /
(stats.remove_hits + stats.remove_misses);
delete s;
s = nullptr;
}
}
template <typename Env>
void BM_InsertRange(benchmark::State& state) {
const int kBatchSize = Env::kBatchSize;
const int kMaxObjectsToMove = Env::kMaxObjectsToMove;
// optional to have more precise control of when the destruction occurs, as
// we want to avoid polluting the timing with the dtor.
absl::optional<Env> e;
void* batch[kMaxObjectsToMove];
for (auto iter : state) {
state.PauseTiming();
e.emplace();
e->central_freelist().AllocateBatch(batch, kBatchSize);
benchmark::DoNotOptimize(e);
benchmark::DoNotOptimize(batch);
state.ResumeTiming();
e->transfer_cache().InsertRange(batch, kBatchSize);
}
}
template <typename Env>
void BM_RemoveRange(benchmark::State& state) {
const int kBatchSize = Env::kBatchSize;
const int kMaxObjectsToMove = Env::kMaxObjectsToMove;
// optional to have more precise control of when the destruction occurs, as
// we want to avoid polluting the timing with the dtor.
absl::optional<Env> e;
void* batch[kMaxObjectsToMove];
for (auto iter : state) {
state.PauseTiming();
e.emplace();
e->Insert(kBatchSize);
benchmark::DoNotOptimize(e);
state.ResumeTiming();
e->transfer_cache().RemoveRange(batch, kBatchSize);
benchmark::DoNotOptimize(batch);
}
}
BENCHMARK_TEMPLATE(BM_CrossThread, TransferCacheEnv)->ThreadRange(2, 64);
BENCHMARK_TEMPLATE(BM_CrossThread, LockFreeEnv)->ThreadRange(2, 64);
BENCHMARK_TEMPLATE(BM_InsertRange, TransferCacheEnv);
BENCHMARK_TEMPLATE(BM_InsertRange, LockFreeEnv);
BENCHMARK_TEMPLATE(BM_RemoveRange, TransferCacheEnv);
BENCHMARK_TEMPLATE(BM_RemoveRange, LockFreeEnv);
} // namespace
} // namespace tcmalloc
<|endoftext|>
|
<commit_before>/** \file
Task: Full-automatic 3D tiling acquisition.
\author: Nathan Clack <clackn@janelia.hhmi.org>
\copyright
Copyright 2010 Howard Hughes Medical Institute.
All rights reserved.
Use is subject to Janelia Farm Research Campus Software Copyright 1.1
license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
#include "common.h"
#include "AutoTileAcquisition.h"
#include "TiledAcquisition.h"
#include "StackAcquisition.h"
#include "Video.h"
#include "frame.h"
#include "devices\digitizer.h"
#include "devices\Microscope.h"
#include "devices\tiling.h"
#include "AdaptiveTiledAcquisition.h"
#define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;}
#define WARN(msg) warning("%s(%d)"ENDL"\t%s"ENDL,__FILE__,__LINE__,msg)
#define DBG(...) do{debug("%s(%d)"ENDL "\t",__FILE__,__LINE__); debug(__VA_ARGS__);}while(0)
namespace fetch
{
namespace task
{
//
// AutoTileAcquisition - microscope task
//
namespace microscope {
/** \class AutoTileAcquisition AutoTileAcquisition.h
Microscope task fro automatic 3d tiling of a volume.
The task operates in three phases:
While zpos in bounds:
-# Explore the current slice to determine which tiles to acquire.
- foreach tile in zone:
- move to tile
- acquire single image at probe depth (could use stage system to offset...just need to ensure correct tile is marked)
- classify image
- mark tile
- postprocess marked tiles
- close
- dilate1
-# Run the TiledAcquisition task to collect those tiles.
- since TiledAcquisition is a microscope task, it's run function will be directly
invoked rather than running it asynchronously.
-# Run the Cut (vibratome) task to cut the imaged slice off.
Questions:
-# How to define exploration zone? Z limits.
How to iterate over tiles for exploration.
-# Feedback on marking.
- can see tiles getting marked in view as it happens...view linked to current stage zpos
-# User interuption.
-# Speed? How fast can I explore a given area?
- initially assume I don't need to be efficient (take simple approach)
*/
//Upcasting
unsigned int AutoTileAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));}
unsigned int AutoTileAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));}
unsigned int AutoTileAcquisition::config(device::Microscope *d)
{
return 1; //success
Error:
return 0;
}
static int _handle_wait_for_result(DWORD result, const char *msg)
{
return_val_if( result == WAIT_OBJECT_0 , 0 );
return_val_if( result == WAIT_OBJECT_0+1, 1 );
Guarded_Assert_WinErr( result != WAIT_FAILED );
switch(result)
{ case WAIT_ABANDONED_0: warning("TiledAcquisition: Wait 0 abandoned\r\n\t%s\r\n", msg); break;
case WAIT_ABANDONED_0+1: warning("TiledAcquisition: Wait 1 abandoned\r\n\t%s\r\n", msg); break;
case WAIT_TIMEOUT: warning("TiledAcquisition: Wait timeout\r\n\t%s\r\n", msg); break;
default:
;
}
return -1;
}
// DGA: Function for simulating an ellipsoid (with circular cross sections) in 3D so that we can test, eg., if the explorable region shrinks as desired
static bool insideSimulationOfEllipse(float maxzUm, float targetZUm, Vector3f tilepos)
{
float distanceFromXYCenterUm, ellipseMajorAxisUm = 2000, crossSectionRadiusUm, ellipseMinorAxisUm, zEllipseCenterUm; // DGA: Variables used to create ellipsoid in 3D
ellipseMinorAxisUm = (0.5*(maxzUm - 10000)); //DGA: Assumes initial offset of 10000 um, so want minor axis to be equal to the total height/2
zEllipseCenterUm = 10000 + ellipseMinorAxisUm; //DGA: Center of ellipse in Z
crossSectionRadiusUm = ellipseMajorAxisUm*sqrt(1 - pow((zEllipseCenterUm - targetZUm) / ellipseMinorAxisUm, 2)); //DGA: Calculate the cross section radius
crossSectionRadiusUm = (crossSectionRadiusUm > 250) ? crossSectionRadiusUm : 250; //DGA: Set a minimum cross section since the program will stop if there aren't any detected tiles
distanceFromXYCenterUm = sqrt((tilepos[0] - 50000)*(tilepos[0] - 50000) + (tilepos[1] - 50000)*(tilepos[1] - 50000)); //DGA: Calculate if the current tile is within the circular cross section, centered at (50 mm, 50 mm)
return (distanceFromXYCenterUm < crossSectionRadiusUm); //DGA: If the tile is within the ellipse, return true
}
///// CLASSIFY //////////////////////////////////////////////////
template<class T>
static int _classify(mylib::Array *src, int ichan, double intensity_thresh, double area_thresh)
{ T* data;
mylib::Array tmp=*src,*image=&tmp;
if(ichan>=0)
{ image=mylib::Get_Array_Plane(&tmp,ichan);
}
data = (T*)image->data;
size_t i,count=0;
if(!image->size) return 0;
for(i=0;i<image->size;++i)
count+=(data[i]>intensity_thresh);
#if 0
mylib::Write_Image("classify.tif",image,mylib::DONT_PRESS);
#endif
DBG("Fraction above thresh: %f\n\t\tintensity thresh: %f\n\t\tarea_thresh: %f\n",
count/((double)image->size),
intensity_thresh,
area_thresh);
return (count/((double)image->size))>area_thresh;
}
#define CLASSIFY(type_id,type) case type_id: return _classify<type>(image,ichan,intensity_thresh,area_thresh); break
/**
\returns 0 if background, 1 if foreground
Image could be multiple channels. Channels are assumed to plane-wise.
*/
static int classify(mylib::Array *image, int ichan, double intensity_thresh, double area_thresh)
{
if(image->ndims<3) // check that there are enough dimensions to select a channel
{ ichan=-1;
} else if(ichan>=image->dims[image->ndims-1]) // is ichan sane? If not, use chan 0.
{ ichan=0;
}
switch(image->type)
{
CLASSIFY( mylib::UINT8_TYPE ,uint8_t );
CLASSIFY( mylib::UINT16_TYPE ,uint16_t);
CLASSIFY( mylib::UINT32_TYPE ,uint32_t);
CLASSIFY( mylib::UINT64_TYPE ,uint64_t);
CLASSIFY( mylib::INT8_TYPE , int8_t );
CLASSIFY( mylib::INT16_TYPE , int16_t);
CLASSIFY( mylib::INT32_TYPE , int32_t);
CLASSIFY( mylib::INT64_TYPE , int64_t);
CLASSIFY( mylib::FLOAT32_TYPE ,float );
CLASSIFY( mylib::FLOAT64_TYPE ,double );
default:
return 0;
}
}
#undef CLASSIFY
///// EXPLORE //////////////////////////////////////////////////
/** Tests to make sure the cut/image cycle stays in z bounds.
Only need to test max since stage only moves up as cuts progress.
*/
static int PlaneInBounds(device::Microscope *dc,float maxz)
{ float x,y,z;
dc->stage()->getPos(&x,&y,&z);
return z<maxz;
}
/**
Explores the current plane searching for tiles to image. A heuristic classifier
is used to target a tile for imaging based on a single snapshot acquired at a
given depth (\c dz_um).
Preconditions:
- tiles to explore have been labelled as such
Parameters to get from configuration:
- dz_um: zpiezo offset
- maxz stage units(mm)
- timeout_ms
- ichan: channel to use for classification, -1 uses all channels
- intensity_threshold: use the expected pixel units
- area_threshold: 0 to 1. The fraction of pixels that must be brighter than intensity threshold.
\returns 0 if no tiles were targeted for imaging, otherwise 1.
*/
static int explore(device::Microscope *dc)
{ Vector3f tilepos;
unsigned any_explorable=0,
any_active=0;
cfg::tasks::AutoTile cfg=dc->get_config().autotile();
size_t iplane=dc->stage()->getPosInLattice().z();
device::StageTiling* tiling = dc->stage()->tiling();
tiling->markAddressable(iplane); // make sure the current plane is marked addressable
tiling->setCursorToPlane(iplane);
device::Digitizer::Config digcfg = dc->scanner._scanner2d._digitizer.get_config(); //DGA: Get the configuration of the digitizer to know if it is simulated
device::TileSearchContext *ctx=0;
while( !dc->_agent->is_stopping()
&& tiling->nextSearchPosition(iplane,cfg.search_radius()/*radius - tiles*/,tilepos,&ctx))
//&& tiling->nextInPlaneExplorablePosition(tilepos))
{ mylib::Array *im;
any_explorable=1;
tilepos[2]=dc->stage()->getTarget().z()*1000.0; // convert mm to um
DBG("Exploring tile: %6.1f %6.1f %6.1f",tilepos.x(),tilepos.y(),tilepos.z());
CHKJMP(dc->stage()->setPos(tilepos*0.001)); // convert um to mm
CHKJMP(im=dc->snapshot(cfg.z_um(),cfg.timeout_ms()));
tiling->markExplored();
tiling->markDetected(classify(im,cfg.ichan(),cfg.intensity_threshold(),cfg.area_threshold()));
if (digcfg.kind() == cfg::device::Digitizer_DigitizerType_Simulated){ //DGA: If digitizer is simulated, then simulate an ellipsoidal volume
if (!insideSimulationOfEllipse(cfg.maxz_mm()*1000, dc->stage()->getTarget().z()*1000.0, tilepos)) tiling->markDetected(false); //DGA: If the tile is outside the simulated volume, mark as undetected (by default, simulation mode marks everything as detected)
}
mylib::Free_Array(im);
}
if(!tiling->updateActive(iplane))
{ WARN("No tiles found to image.\n");
goto Error;
}
if(!dc->_agent->is_stopping() && any_explorable)
tiling->dilateActive(iplane);
tiling->fillHolesInActive(iplane);
if(ctx) delete ctx;
return 1;
Error:
if(ctx) delete ctx;
return 0;
}
unsigned int AutoTileAcquisition::run(device::Microscope *dc)
{ unsigned eflag=0; //success
cfg::tasks::AutoTile cfg=dc->get_config().autotile();
TiledAcquisition nonadaptive_tiling;
AdaptiveTiledAcquisition adaptive_tiling;
MicroscopeTask *tile=0;
Cut cut;
device::StageTiling * tiling = dc->stage()->tiling(); //DGA: Pointer to tiling object
tile=cfg.use_adaptive_tiling()?((MicroscopeTask*)&adaptive_tiling):((MicroscopeTask*)&nonadaptive_tiling);
while(!dc->_agent->is_stopping() && PlaneInBounds(dc,cfg.maxz_mm()))
{
if(cfg.use_explore())
CHKJMP(explore(dc)); // will return an error if no explorable tiles found on the plane
CHKJMP( tile->config(dc));
CHKJMP(0==tile->run(dc));
/* Assert the trip detector hasn't gone off.
* Trip detector will signal acq task and microscope tasks to stop, but
* we double check here as extra insurance against any extra cuts.
*/
CHKJMP(dc->trip_detect.ok());
CHKJMP( cut.config(dc));
CHKJMP(0==cut.run(dc));
if(tiling->useTwoDimensionalTiling_) //DGA: If using two dimensional tiling
{
if (PlaneInBounds(dc,cfg.maxz_mm())) tiling->useDoneTilesAsExplorableTilesForTwoDimensionalTiling(); //DGA: If the next position is in bounds (ie, not beyond the max z), then update the tiling, otherwise do nothing.
}
else tiling->useCurrentDoneTilesAsNextExplorableTiles(); //DGA: After imaging tiles, set the next explorable tiles equal to the current done tiles
if(dc->getScheduleStopAfterNextCut()) //DGA: if a stop is scheduled
{
dc->cutCompletedSoStop(); //DGA: Call function to stop autotile
dc->setScheduleStopAfterNextCut(false); //DGA: Uncheck stop after next cut checkbox
}
}
Finalize:
return eflag;
Error:
eflag=1;
goto Finalize;
}
} // namespace microscope
} // namespace task
} // namespace fetch
<commit_msg>fix/TilesSetActiveWhenExploringStopped: Now dilating active tiles after exploration is only performed if the task was not stopped prematurely<commit_after>/** \file
Task: Full-automatic 3D tiling acquisition.
\author: Nathan Clack <clackn@janelia.hhmi.org>
\copyright
Copyright 2010 Howard Hughes Medical Institute.
All rights reserved.
Use is subject to Janelia Farm Research Campus Software Copyright 1.1
license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
#include "common.h"
#include "AutoTileAcquisition.h"
#include "TiledAcquisition.h"
#include "StackAcquisition.h"
#include "Video.h"
#include "frame.h"
#include "devices\digitizer.h"
#include "devices\Microscope.h"
#include "devices\tiling.h"
#include "AdaptiveTiledAcquisition.h"
#define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;}
#define WARN(msg) warning("%s(%d)"ENDL"\t%s"ENDL,__FILE__,__LINE__,msg)
#define DBG(...) do{debug("%s(%d)"ENDL "\t",__FILE__,__LINE__); debug(__VA_ARGS__);}while(0)
namespace fetch
{
namespace task
{
//
// AutoTileAcquisition - microscope task
//
namespace microscope {
/** \class AutoTileAcquisition AutoTileAcquisition.h
Microscope task fro automatic 3d tiling of a volume.
The task operates in three phases:
While zpos in bounds:
-# Explore the current slice to determine which tiles to acquire.
- foreach tile in zone:
- move to tile
- acquire single image at probe depth (could use stage system to offset...just need to ensure correct tile is marked)
- classify image
- mark tile
- postprocess marked tiles
- close
- dilate1
-# Run the TiledAcquisition task to collect those tiles.
- since TiledAcquisition is a microscope task, it's run function will be directly
invoked rather than running it asynchronously.
-# Run the Cut (vibratome) task to cut the imaged slice off.
Questions:
-# How to define exploration zone? Z limits.
How to iterate over tiles for exploration.
-# Feedback on marking.
- can see tiles getting marked in view as it happens...view linked to current stage zpos
-# User interuption.
-# Speed? How fast can I explore a given area?
- initially assume I don't need to be efficient (take simple approach)
*/
//Upcasting
unsigned int AutoTileAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));}
unsigned int AutoTileAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));}
unsigned int AutoTileAcquisition::config(device::Microscope *d)
{
return 1; //success
Error:
return 0;
}
static int _handle_wait_for_result(DWORD result, const char *msg)
{
return_val_if( result == WAIT_OBJECT_0 , 0 );
return_val_if( result == WAIT_OBJECT_0+1, 1 );
Guarded_Assert_WinErr( result != WAIT_FAILED );
switch(result)
{ case WAIT_ABANDONED_0: warning("TiledAcquisition: Wait 0 abandoned\r\n\t%s\r\n", msg); break;
case WAIT_ABANDONED_0+1: warning("TiledAcquisition: Wait 1 abandoned\r\n\t%s\r\n", msg); break;
case WAIT_TIMEOUT: warning("TiledAcquisition: Wait timeout\r\n\t%s\r\n", msg); break;
default:
;
}
return -1;
}
// DGA: Function for simulating an ellipsoid (with circular cross sections) in 3D so that we can test, eg., if the explorable region shrinks as desired
static bool insideSimulationOfEllipse(float maxzUm, float targetZUm, Vector3f tilepos)
{
float distanceFromXYCenterUm, ellipseMajorAxisUm = 2000, crossSectionRadiusUm, ellipseMinorAxisUm, zEllipseCenterUm; // DGA: Variables used to create ellipsoid in 3D
ellipseMinorAxisUm = (0.5*(maxzUm - 10000)); //DGA: Assumes initial offset of 10000 um, so want minor axis to be equal to the total height/2
zEllipseCenterUm = 10000 + ellipseMinorAxisUm; //DGA: Center of ellipse in Z
crossSectionRadiusUm = ellipseMajorAxisUm*sqrt(1 - pow((zEllipseCenterUm - targetZUm) / ellipseMinorAxisUm, 2)); //DGA: Calculate the cross section radius
crossSectionRadiusUm = (crossSectionRadiusUm > 250) ? crossSectionRadiusUm : 250; //DGA: Set a minimum cross section since the program will stop if there aren't any detected tiles
distanceFromXYCenterUm = sqrt((tilepos[0] - 50000)*(tilepos[0] - 50000) + (tilepos[1] - 50000)*(tilepos[1] - 50000)); //DGA: Calculate if the current tile is within the circular cross section, centered at (50 mm, 50 mm)
return (distanceFromXYCenterUm < crossSectionRadiusUm); //DGA: If the tile is within the ellipse, return true
}
///// CLASSIFY //////////////////////////////////////////////////
template<class T>
static int _classify(mylib::Array *src, int ichan, double intensity_thresh, double area_thresh)
{ T* data;
mylib::Array tmp=*src,*image=&tmp;
if(ichan>=0)
{ image=mylib::Get_Array_Plane(&tmp,ichan);
}
data = (T*)image->data;
size_t i,count=0;
if(!image->size) return 0;
for(i=0;i<image->size;++i)
count+=(data[i]>intensity_thresh);
#if 0
mylib::Write_Image("classify.tif",image,mylib::DONT_PRESS);
#endif
DBG("Fraction above thresh: %f\n\t\tintensity thresh: %f\n\t\tarea_thresh: %f\n",
count/((double)image->size),
intensity_thresh,
area_thresh);
return (count/((double)image->size))>area_thresh;
}
#define CLASSIFY(type_id,type) case type_id: return _classify<type>(image,ichan,intensity_thresh,area_thresh); break
/**
\returns 0 if background, 1 if foreground
Image could be multiple channels. Channels are assumed to plane-wise.
*/
static int classify(mylib::Array *image, int ichan, double intensity_thresh, double area_thresh)
{
if(image->ndims<3) // check that there are enough dimensions to select a channel
{ ichan=-1;
} else if(ichan>=image->dims[image->ndims-1]) // is ichan sane? If not, use chan 0.
{ ichan=0;
}
switch(image->type)
{
CLASSIFY( mylib::UINT8_TYPE ,uint8_t );
CLASSIFY( mylib::UINT16_TYPE ,uint16_t);
CLASSIFY( mylib::UINT32_TYPE ,uint32_t);
CLASSIFY( mylib::UINT64_TYPE ,uint64_t);
CLASSIFY( mylib::INT8_TYPE , int8_t );
CLASSIFY( mylib::INT16_TYPE , int16_t);
CLASSIFY( mylib::INT32_TYPE , int32_t);
CLASSIFY( mylib::INT64_TYPE , int64_t);
CLASSIFY( mylib::FLOAT32_TYPE ,float );
CLASSIFY( mylib::FLOAT64_TYPE ,double );
default:
return 0;
}
}
#undef CLASSIFY
///// EXPLORE //////////////////////////////////////////////////
/** Tests to make sure the cut/image cycle stays in z bounds.
Only need to test max since stage only moves up as cuts progress.
*/
static int PlaneInBounds(device::Microscope *dc,float maxz)
{ float x,y,z;
dc->stage()->getPos(&x,&y,&z);
return z<maxz;
}
/**
Explores the current plane searching for tiles to image. A heuristic classifier
is used to target a tile for imaging based on a single snapshot acquired at a
given depth (\c dz_um).
Preconditions:
- tiles to explore have been labelled as such
Parameters to get from configuration:
- dz_um: zpiezo offset
- maxz stage units(mm)
- timeout_ms
- ichan: channel to use for classification, -1 uses all channels
- intensity_threshold: use the expected pixel units
- area_threshold: 0 to 1. The fraction of pixels that must be brighter than intensity threshold.
\returns 0 if no tiles were targeted for imaging, otherwise 1.
*/
static int explore(device::Microscope *dc)
{ Vector3f tilepos;
unsigned any_explorable=0,
any_active=0;
cfg::tasks::AutoTile cfg=dc->get_config().autotile();
size_t iplane=dc->stage()->getPosInLattice().z();
device::StageTiling* tiling = dc->stage()->tiling();
tiling->markAddressable(iplane); // make sure the current plane is marked addressable
tiling->setCursorToPlane(iplane);
device::Digitizer::Config digcfg = dc->scanner._scanner2d._digitizer.get_config(); //DGA: Get the configuration of the digitizer to know if it is simulated
device::TileSearchContext *ctx=0;
while( !dc->_agent->is_stopping()
&& tiling->nextSearchPosition(iplane,cfg.search_radius()/*radius - tiles*/,tilepos,&ctx))
//&& tiling->nextInPlaneExplorablePosition(tilepos))
{ mylib::Array *im;
any_explorable=1;
tilepos[2]=dc->stage()->getTarget().z()*1000.0; // convert mm to um
DBG("Exploring tile: %6.1f %6.1f %6.1f",tilepos.x(),tilepos.y(),tilepos.z());
CHKJMP(dc->stage()->setPos(tilepos*0.001)); // convert um to mm
CHKJMP(im=dc->snapshot(cfg.z_um(),cfg.timeout_ms()));
tiling->markExplored();
tiling->markDetected(classify(im,cfg.ichan(),cfg.intensity_threshold(),cfg.area_threshold()));
if (digcfg.kind() == cfg::device::Digitizer_DigitizerType_Simulated){ //DGA: If digitizer is simulated, then simulate an ellipsoidal volume
if (!insideSimulationOfEllipse(cfg.maxz_mm()*1000, dc->stage()->getTarget().z()*1000.0, tilepos)) tiling->markDetected(false); //DGA: If the tile is outside the simulated volume, mark as undetected (by default, simulation mode marks everything as detected)
}
mylib::Free_Array(im);
}
if(!tiling->updateActive(iplane))
{ WARN("No tiles found to image.\n");
goto Error;
}
if(!dc->_agent->is_stopping() && any_explorable) //DGA: Only dilate active tiles if it is not being stopped
tiling->dilateActive(iplane);
tiling->fillHolesInActive(iplane);
if(ctx) delete ctx;
return 1;
Error:
if(ctx) delete ctx;
return 0;
}
unsigned int AutoTileAcquisition::run(device::Microscope *dc)
{ unsigned eflag=0; //success
cfg::tasks::AutoTile cfg=dc->get_config().autotile();
TiledAcquisition nonadaptive_tiling;
AdaptiveTiledAcquisition adaptive_tiling;
MicroscopeTask *tile=0;
Cut cut;
device::StageTiling * tiling = dc->stage()->tiling(); //DGA: Pointer to tiling object
tile=cfg.use_adaptive_tiling()?((MicroscopeTask*)&adaptive_tiling):((MicroscopeTask*)&nonadaptive_tiling);
while(!dc->_agent->is_stopping() && PlaneInBounds(dc,cfg.maxz_mm()))
{
if(cfg.use_explore())
CHKJMP(explore(dc)); // will return an error if no explorable tiles found on the plane
CHKJMP( tile->config(dc));
CHKJMP(0==tile->run(dc));
/* Assert the trip detector hasn't gone off.
* Trip detector will signal acq task and microscope tasks to stop, but
* we double check here as extra insurance against any extra cuts.
*/
CHKJMP(dc->trip_detect.ok());
CHKJMP( cut.config(dc));
CHKJMP(0==cut.run(dc));
if(tiling->useTwoDimensionalTiling_) //DGA: If using two dimensional tiling
{
if (PlaneInBounds(dc,cfg.maxz_mm())) tiling->useDoneTilesAsExplorableTilesForTwoDimensionalTiling(); //DGA: If the next position is in bounds (ie, not beyond the max z), then update the tiling, otherwise do nothing.
}
else tiling->useCurrentDoneTilesAsNextExplorableTiles(); //DGA: After imaging tiles, set the next explorable tiles equal to the current done tiles
if(dc->getScheduleStopAfterNextCut()) //DGA: if a stop is scheduled
{
dc->cutCompletedSoStop(); //DGA: Call function to stop autotile
dc->setScheduleStopAfterNextCut(false); //DGA: Uncheck stop after next cut checkbox
}
}
Finalize:
return eflag;
Error:
eflag=1;
goto Finalize;
}
} // namespace microscope
} // namespace task
} // namespace fetch
<|endoftext|>
|
<commit_before><commit_msg>Create callback function, add 'static' keyword<commit_after><|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file MCLS_EpetraBlockJacobiPreconditioner.cpp
* \author Stuart R. Slattery
* \brief Block Jacobi preconditioning for Epetra.
*/
//---------------------------------------------------------------------------//
#include <algorithm>
#include "MCLS_EpetraBlockJacobiPreconditioner.hpp"
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_LAPACK.hpp>
#include <Teuchos_OrdinalTraits.hpp>
#include <Epetra_Map.h>
namespace MCLS
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
*/
EpetraBlockJacobiPreconditioner::EpetraBlockJacobiPreconditioner(
const Teuchos::RCP<Teuchos::ParameterList>& params )
: d_plist( params )
{
MCLS_REQUIRE( Teuchos::nonnull(d_plist) );
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the valid parameters for this preconditioner.
*/
Teuchos::RCP<const Teuchos::ParameterList>
EpetraBlockJacobiPreconditioner::getValidParameters() const
{
Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::parameterList();
plist->set<int>("Jacobi Block Size", 0);
return plist;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the current parameters being used for this preconditioner.
*/
Teuchos::RCP<const Teuchos::ParameterList>
EpetraBlockJacobiPreconditioner::getCurrentParameters() const
{
return d_plist;
}
//---------------------------------------------------------------------------//
/*!
* \brief Set the parameters for the preconditioner. The preconditioner will
* modify this list with default parameters that are not defined.
*/
void EpetraBlockJacobiPreconditioner::setParameters(
const Teuchos::RCP<Teuchos::ParameterList>& params )
{
MCLS_REQUIRE( Teuchos::nonnull(params) );
d_plist = params;
}
//---------------------------------------------------------------------------//
/*!
* \brief Set the operator with the preconditioner.
*/
void EpetraBlockJacobiPreconditioner::setOperator(
const Teuchos::RCP<const matrix_type>& A )
{
MCLS_REQUIRE( Teuchos::nonnull(A) );
d_A = A;
}
//---------------------------------------------------------------------------//
/*!
* \brief Build the preconditioner.
*/
void EpetraBlockJacobiPreconditioner::buildPreconditioner()
{
MCLS_REQUIRE( Teuchos::nonnull(d_A) );
MCLS_REQUIRE( d_A->Filled() );
// Get the block size.
int block_size = d_plist->get<int>("Jacobi Block Size");
// We require that all blocks are local.
MCLS_REQUIRE( d_A->NumMyRows() % block_size == 0 );
// Get the number of blocks.
int num_blocks = d_A->NumMyRows() / block_size;
// Build the block preconditioner.
d_preconditioner = Teuchos::rcp(
new Epetra_CrsMatrix( Copy, d_A->RowMatrixRowMap(), block_size ) );
// Populate the preconditioner with inverted blocks.
Teuchos::SerialDenseMatrix<int,double> block( block_size, block_size );
int col_start = 0;
int global_row = 0;
Teuchos::Array<int> block_cols( block_size );
for ( int n = 0; n < num_blocks; ++n )
{
// Starting row/column for the block.
col_start = block_size*n;
// Extract the block. Note that I form the tranposed local block to
// facilitate constructing the preconditioner in the second group of
// loops. I grab each individual element here because I want the
// zero's to build the block, but there's probably a cheaper way of
// doing the extraction.
for ( int i = 0; i < block_size; ++i )
{
global_row = d_A->RowMatrixRowMap().GID(col_start+i);
for ( int j = 0; j < block_size; ++j )
{
block_cols[j] = d_A->RowMatrixColMap().GID(col_start+j);
}
for ( int j = 0; j < block_size; ++j )
{
block(j,i) =
getMatrixComponentFromGlobal( d_A, global_row, block_cols[j] );
}
}
// Invert the block.
invertSerialDenseMatrix( block );
// Add the block to the preconditioner.
for ( int i = 0; i < block_size; ++i )
{
global_row =
d_preconditioner->RowMatrixRowMap().GID(col_start+i);
d_preconditioner->InsertGlobalValues(
global_row, block_size, block[i], block_cols.getRawPtr() );
}
}
d_preconditioner->FillComplete();
MCLS_ENSURE( Teuchos::nonnull(d_preconditioner) );
MCLS_ENSURE( d_preconditioner->Filled() );
}
//---------------------------------------------------------------------------//
/*!
* \brief Invert a Teuchos::SerialDenseMatrix block.
*/
void EpetraBlockJacobiPreconditioner::invertSerialDenseMatrix(
Teuchos::SerialDenseMatrix<int,double>& block )
{
// Make a LAPACK object.
Teuchos::LAPACK<int,double> lapack;
// Compute the LU-factorization of the block.
int ipiv = 0;
int info = 0;
lapack.GETRF( block.numRows(), block.numCols(), block.values(),
block.stride(), &ipiv, &info );
MCLS_CHECK( info == 0 );
// Compute the inverse of the block from the LU-factorization.
Teuchos::Array<double> work( block.numRows() );
lapack.GETRI(
block.numCols(), block.values(), block.stride(),
&ipiv, work.getRawPtr(), work.size(), &info );
MCLS_CHECK( info == 0 );
MCLS_CHECK( work[0] == block.numRows() );
}
//---------------------------------------------------------------------------//
/*!
* \brief Get a local component of an operator given a global row and column
* index.
*/
double EpetraBlockJacobiPreconditioner::getMatrixComponentFromGlobal(
const Teuchos::RCP<const matrix_type>& matrix,
const int global_row, const int global_col )
{
const Epetra_Map row_map = matrix->RowMatrixRowMap();
const Epetra_Map col_map = matrix->RowMatrixColMap();
MCLS_REQUIRE( row_map.MyGID(global_row) );
int local_row = row_map.LID( global_row );
int local_col = col_map.LID( global_col );
// If the block column is not local, then we get a zero for this entry.
if ( local_col == Teuchos::OrdinalTraits<int>::invalid() )
{
return 0.0;
}
int max_size = matrix->MaxNumEntries();
int num_entries = 0;
Teuchos::Array<int> local_indices( max_size );
Teuchos::Array<double> local_values( max_size );
matrix->ExtractMyRowCopy( local_row, max_size, num_entries,
local_values.getRawPtr(),
local_indices.getRawPtr() );
local_values.resize( num_entries );
local_indices.resize( num_entries );
Teuchos::Array<int>::iterator local_idx_it =
std::find( local_indices.begin(), local_indices.end(), local_col );
if ( local_idx_it != local_indices.end() )
{
return local_values[ std::distance( local_indices.begin(),
local_idx_it ) ];
}
return 0.0;
}
//---------------------------------------------------------------------------//
} // end namespace MCLS
//---------------------------------------------------------------------------//
// end MCLS_EpetraBlockJacobiPreconditioner.cpp
//---------------------------------------------------------------------------//
<commit_msg>removing whitespace in blaock jacobi preconditioner<commit_after>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file MCLS_EpetraBlockJacobiPreconditioner.cpp
* \author Stuart R. Slattery
* \brief Block Jacobi preconditioning for Epetra.
*/
//---------------------------------------------------------------------------//
#include <algorithm>
#include "MCLS_EpetraBlockJacobiPreconditioner.hpp"
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_LAPACK.hpp>
#include <Teuchos_OrdinalTraits.hpp>
#include <Epetra_Map.h>
namespace MCLS
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
*/
EpetraBlockJacobiPreconditioner::EpetraBlockJacobiPreconditioner(
const Teuchos::RCP<Teuchos::ParameterList>& params )
: d_plist( params )
{
MCLS_REQUIRE( Teuchos::nonnull(d_plist) );
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the valid parameters for this preconditioner.
*/
Teuchos::RCP<const Teuchos::ParameterList>
EpetraBlockJacobiPreconditioner::getValidParameters() const
{
Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::parameterList();
plist->set<int>("Jacobi Block Size", 1);
return plist;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the current parameters being used for this preconditioner.
*/
Teuchos::RCP<const Teuchos::ParameterList>
EpetraBlockJacobiPreconditioner::getCurrentParameters() const
{
return d_plist;
}
//---------------------------------------------------------------------------//
/*!
* \brief Set the parameters for the preconditioner. The preconditioner will
* modify this list with default parameters that are not defined.
*/
void EpetraBlockJacobiPreconditioner::setParameters(
const Teuchos::RCP<Teuchos::ParameterList>& params )
{
MCLS_REQUIRE( Teuchos::nonnull(params) );
d_plist = params;
}
//---------------------------------------------------------------------------//
/*!
* \brief Set the operator with the preconditioner.
*/
void EpetraBlockJacobiPreconditioner::setOperator(
const Teuchos::RCP<const matrix_type>& A )
{
MCLS_REQUIRE( Teuchos::nonnull(A) );
d_A = A;
}
//---------------------------------------------------------------------------//
/*!
* \brief Build the preconditioner.
*/
void EpetraBlockJacobiPreconditioner::buildPreconditioner()
{
MCLS_REQUIRE( Teuchos::nonnull(d_A) );
MCLS_REQUIRE( d_A->Filled() );
// Get the block size.
int block_size = d_plist->get<int>("Jacobi Block Size");
// We require that all blocks are local.
MCLS_REQUIRE( d_A->NumMyRows() % block_size == 0 );
// Get the number of blocks.
int num_blocks = d_A->NumMyRows() / block_size;
// Build the block preconditioner.
d_preconditioner = Teuchos::rcp(
new Epetra_CrsMatrix( Copy, d_A->RowMatrixRowMap(), block_size ) );
// Populate the preconditioner with inverted blocks.
Teuchos::SerialDenseMatrix<int,double> block( block_size, block_size );
int col_start = 0;
int global_row = 0;
Teuchos::Array<int> block_cols( block_size );
for ( int n = 0; n < num_blocks; ++n )
{
// Starting row/column for the block.
col_start = block_size*n;
// Extract the block. Note that I form the tranposed local block to
// facilitate constructing the preconditioner in the second group of
// loops. I grab each individual element here because I want the
// zero's to build the block, but there's probably a cheaper way of
// doing the extraction.
for ( int i = 0; i < block_size; ++i )
{
global_row = d_A->RowMatrixRowMap().GID(col_start+i);
for ( int j = 0; j < block_size; ++j )
{
block_cols[j] = d_A->RowMatrixColMap().GID(col_start+j);
}
for ( int j = 0; j < block_size; ++j )
{
block(j,i) =
getMatrixComponentFromGlobal( d_A, global_row, block_cols[j] );
}
}
// Invert the block.
invertSerialDenseMatrix( block );
// Add the block to the preconditioner.
for ( int i = 0; i < block_size; ++i )
{
global_row =
d_preconditioner->RowMatrixRowMap().GID(col_start+i);
d_preconditioner->InsertGlobalValues(
global_row, block_size, block[i], block_cols.getRawPtr() );
}
}
d_preconditioner->FillComplete();
MCLS_ENSURE( Teuchos::nonnull(d_preconditioner) );
MCLS_ENSURE( d_preconditioner->Filled() );
}
//---------------------------------------------------------------------------//
/*!
* \brief Invert a Teuchos::SerialDenseMatrix block.
*/
void EpetraBlockJacobiPreconditioner::invertSerialDenseMatrix(
Teuchos::SerialDenseMatrix<int,double>& block )
{
// Make a LAPACK object.
Teuchos::LAPACK<int,double> lapack;
// Compute the LU-factorization of the block.
int ipiv = 0;
int info = 0;
lapack.GETRF( block.numRows(), block.numCols(), block.values(),
block.stride(), &ipiv, &info );
MCLS_CHECK( info == 0 );
// Compute the inverse of the block from the LU-factorization.
Teuchos::Array<double> work( block.numRows() );
lapack.GETRI(
block.numCols(), block.values(), block.stride(),
&ipiv, work.getRawPtr(), work.size(), &info );
MCLS_CHECK( info == 0 );
MCLS_CHECK( work[0] == block.numRows() );
}
//---------------------------------------------------------------------------//
/*!
* \brief Get a local component of an operator given a global row and column
* index.
*/
double EpetraBlockJacobiPreconditioner::getMatrixComponentFromGlobal(
const Teuchos::RCP<const matrix_type>& matrix,
const int global_row, const int global_col )
{
const Epetra_Map row_map = matrix->RowMatrixRowMap();
const Epetra_Map col_map = matrix->RowMatrixColMap();
MCLS_REQUIRE( row_map.MyGID(global_row) );
int local_row = row_map.LID( global_row );
int local_col = col_map.LID( global_col );
// If the block column is not local, then we get a zero for this entry.
if ( local_col == Teuchos::OrdinalTraits<int>::invalid() )
{
return 0.0;
}
int max_size = matrix->MaxNumEntries();
int num_entries = 0;
Teuchos::Array<int> local_indices( max_size );
Teuchos::Array<double> local_values( max_size );
matrix->ExtractMyRowCopy( local_row, max_size, num_entries,
local_values.getRawPtr(),
local_indices.getRawPtr() );
local_values.resize( num_entries );
local_indices.resize( num_entries );
Teuchos::Array<int>::iterator local_idx_it =
std::find( local_indices.begin(), local_indices.end(), local_col );
if ( local_idx_it != local_indices.end() )
{
return local_values[ std::distance( local_indices.begin(),
local_idx_it ) ];
}
return 0.0;
}
//---------------------------------------------------------------------------//
} // end namespace MCLS
//---------------------------------------------------------------------------//
// end MCLS_EpetraBlockJacobiPreconditioner.cpp
//---------------------------------------------------------------------------//
<|endoftext|>
|
<commit_before>#include "Physics.hpp"
#include "../Physics/RigidBody.hpp"
#include "../Physics/Shape.hpp"
#include "../Util/Json.hpp"
namespace Component {
Json::Value Physics::Save() const {
Json::Value component;
component["velocity"] = Json::SaveVec3(velocity);
component["maxVelocity"] = maxVelocity;
component["angularVelocity"] = Json::SaveVec3(angularVelocity);
component["maxAngularVelocity"] = maxAngularVelocity;
component["acceleration"] = Json::SaveVec3(acceleration);
component["angularAcceleration"] = Json::SaveVec3(angularAcceleration);
component["velocityDragFactor"] = velocityDragFactor;
component["angularDragFactor"] = angularDragFactor;
component["gravityFactor"] = gravityFactor;
component["momentOfInertia"] = Json::SaveVec3(momentOfInertia);
Json::Value componentShape;
Json::Value concreteShape;
::Physics::Shape& shape = rigidBody->GetShape();
switch (shape.GetKind()) {
case ::Physics::Shape::Kind::Sphere: {
componentShape["sphere"] = concreteShape;
break;
}
case ::Physics::Shape::Kind::Plane: {
auto planeData = shape.GetPlaneData();
concreteShape["normal"] = Json::SaveVec3(planeData->normal);
concreteShape["planeCoeff"] = planeData->planeCoeff;
componentShape["plane"] = concreteShape;
break;
}
}
component["shape"] = componentShape;
return component;
}
void Physics::Load(const Json::Value& node) {
delete rigidBody;
rigidBody = nullptr;
velocity = Json::LoadVec3(node["velocity"]);
maxVelocity = node.get("maxVelocity", 20.f).asFloat();
angularVelocity = Json::LoadVec3(node["angularVelocity"]);
maxAngularVelocity = node.get("maxAngularVelocity", 2.f).asFloat();
acceleration = Json::LoadVec3(node["acceleration"]);
angularAcceleration = Json::LoadVec3(node["angularAcceleration"]);
velocityDragFactor = node.get("velocityDragFactor", 1.f).asFloat();
angularDragFactor = node.get("angularDragFactor", 1.f).asFloat();
gravityFactor = node.get("gravityFactor", 0.f).asFloat();
momentOfInertia = Json::LoadVec3(node["momentOfInertia"]);
auto shape = node.get("shape", {});
if (shape.isMember("sphere")) {
auto sphere = shape.get("sphere", {});
auto radius = sphere.get("radius", 1.0f).asFloat();
auto shape = new ::Physics::Shape(::Physics::Shape::Sphere(radius));
rigidBody = new ::Physics::RigidBody(shape, 1.0f);
}
else if (shape.isMember("plane")) {
auto plane = shape.get("plane", {});
auto normal = Json::LoadVec3(plane.get("normal", {}));
auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat();
auto shape = new ::Physics::Shape(::Physics::Shape::Plane(normal, planeCoeff));
rigidBody = new ::Physics::RigidBody(shape, 1.0f);
}
assert(rigidBody);
}
::Physics::Shape& Physics::GetShape() {
return rigidBody->GetShape();
}
void Physics::SetShape(::Physics::Shape* shape) {
rigidBody->SetShape(shape);
}
::Physics::RigidBody& Physics::GetRigidBody() {
return *rigidBody;
}
Physics::Physics(Entity* entity) : SuperComponent(entity) {
// Temporary until creation via managers works properly (this is just
// to have some default resources).
auto shape = new ::Physics::Shape(::Physics::Shape::Sphere(2.0f));
rigidBody = new ::Physics::RigidBody(shape, 1.0f);
}
}
<commit_msg>Save sphere data if that's the shape.<commit_after>#include "Physics.hpp"
#include "../Physics/RigidBody.hpp"
#include "../Physics/Shape.hpp"
#include "../Util/Json.hpp"
namespace Component {
Json::Value Physics::Save() const {
Json::Value component;
component["velocity"] = Json::SaveVec3(velocity);
component["maxVelocity"] = maxVelocity;
component["angularVelocity"] = Json::SaveVec3(angularVelocity);
component["maxAngularVelocity"] = maxAngularVelocity;
component["acceleration"] = Json::SaveVec3(acceleration);
component["angularAcceleration"] = Json::SaveVec3(angularAcceleration);
component["velocityDragFactor"] = velocityDragFactor;
component["angularDragFactor"] = angularDragFactor;
component["gravityFactor"] = gravityFactor;
component["momentOfInertia"] = Json::SaveVec3(momentOfInertia);
Json::Value componentShape;
Json::Value concreteShape;
::Physics::Shape& shape = rigidBody->GetShape();
switch (shape.GetKind()) {
case ::Physics::Shape::Kind::Sphere: {
auto sphereData = shape.GetSphereData();
concreteShape["radius"] = sphereData->radius;
componentShape["sphere"] = concreteShape;
break;
}
case ::Physics::Shape::Kind::Plane: {
auto planeData = shape.GetPlaneData();
concreteShape["normal"] = Json::SaveVec3(planeData->normal);
concreteShape["planeCoeff"] = planeData->planeCoeff;
componentShape["plane"] = concreteShape;
break;
}
}
component["shape"] = componentShape;
return component;
}
void Physics::Load(const Json::Value& node) {
delete rigidBody;
rigidBody = nullptr;
velocity = Json::LoadVec3(node["velocity"]);
maxVelocity = node.get("maxVelocity", 20.f).asFloat();
angularVelocity = Json::LoadVec3(node["angularVelocity"]);
maxAngularVelocity = node.get("maxAngularVelocity", 2.f).asFloat();
acceleration = Json::LoadVec3(node["acceleration"]);
angularAcceleration = Json::LoadVec3(node["angularAcceleration"]);
velocityDragFactor = node.get("velocityDragFactor", 1.f).asFloat();
angularDragFactor = node.get("angularDragFactor", 1.f).asFloat();
gravityFactor = node.get("gravityFactor", 0.f).asFloat();
momentOfInertia = Json::LoadVec3(node["momentOfInertia"]);
auto shape = node.get("shape", {});
if (shape.isMember("sphere")) {
auto sphere = shape.get("sphere", {});
auto radius = sphere.get("radius", 1.0f).asFloat();
auto shape = new ::Physics::Shape(::Physics::Shape::Sphere(radius));
rigidBody = new ::Physics::RigidBody(shape, 1.0f);
}
else if (shape.isMember("plane")) {
auto plane = shape.get("plane", {});
auto normal = Json::LoadVec3(plane.get("normal", {}));
auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat();
auto shape = new ::Physics::Shape(::Physics::Shape::Plane(normal, planeCoeff));
rigidBody = new ::Physics::RigidBody(shape, 1.0f);
}
assert(rigidBody);
}
::Physics::Shape& Physics::GetShape() {
return rigidBody->GetShape();
}
void Physics::SetShape(::Physics::Shape* shape) {
rigidBody->SetShape(shape);
}
::Physics::RigidBody& Physics::GetRigidBody() {
return *rigidBody;
}
Physics::Physics(Entity* entity) : SuperComponent(entity) {
// Temporary until creation via managers works properly (this is just
// to have some default resources).
auto shape = new ::Physics::Shape(::Physics::Shape::Sphere(2.0f));
rigidBody = new ::Physics::RigidBody(shape, 1.0f);
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <glm/glm.hpp>
#include <openvr.h>
#include <openvr_capi.h>
/// Handles communication with VR devices using OpenVR.
class VRManager {
friend class Hub;
public:
/// Check if the VRManger is active.
/**
* @return Whether hmd is present or not.
*/
bool Active() const;
/// Sync VR device pose(s).
void Sync();
/// Recommended render target size to minimize pixel stretching.
/**
* @return Recommended size (in pixels).
*/
glm::vec2 GetRecommendedRenderTargetSize() const;
/// Returns the transform for the HMD.
/**
* @return The HMD translation matrix.
*/
glm::mat4 GetHMDPoseMatrix() const;
/// Returns the transform for the controllers
/**
* @param controlID Which controller to get the matrix for (1 = left, 2 = right).
* @return The Controllers translation matrix.
*/
glm::mat4 GetControllerPoseMatrix(int controlID) const;
/// Returns the transform between the view space and eye space.
/**
* @param eye Which eye the function should return the eye matrix for.
* @return The eye matrix.
*/
glm::mat4 GetHMDEyeToHeadMatrix(vr::Hmd_Eye eye) const;
/// Returns the projection matrix to use for the specified eye.
/**
* @param eye Which eye the function should return the eye matrix for.
* @param zNear Distance to the near clip plane in meters.
* @param zFar Distance to the far clip plane in meters.
* @return The projection matrix.
*/
glm::mat4 GetHMDProjectionMatrix(vr::Hmd_Eye eye, float zNear, float zFar) const;
/// Submit a texture to an eye.
/**
* @param eye Which eye to submit texture.
* @param texture Texture to submit.
*/
void Submit(vr::Hmd_Eye eye, vr::Texture_t* texture) const;
/// Get scale of player.
/**
* @return Scale to get.
*/
float GetScale() const;
/// Set scale of player.
/**
* @param scale Scale to set.
*/
void SetScale(float scale);
/// Gets if certain button is pressed (Only trigger for now)
/**
* @param buttonID the button we want to check is pressed.
* @return whether certain button is pressed or not.
*/
bool GetInput(vr::EVRButtonId buttonID);
private:
VRManager();
~VRManager();
VRManager(VRManager const&) = delete;
void operator=(VRManager const&) = delete;
static glm::mat4 ConvertMatrix(const vr::HmdMatrix34_t& mat);
static glm::mat4 ConvertMatrix(const vr::HmdMatrix44_t& mat);
float scale;
vr::IVRSystem* vrSystem;
vr::TrackedDevicePose_t tracedDevicePoseArray[vr::k_unMaxTrackedDeviceCount];
glm::mat4 deviceTransforms[vr::k_unMaxTrackedDeviceCount];
bool pressedTrackedDevice[vr::k_unMaxTrackedDeviceCount];
};
<commit_msg>Fix compilation with MinGW<commit_after>#pragma once
#include <glm/glm.hpp>
#include <openvr.h>
/// Handles communication with VR devices using OpenVR.
class VRManager {
friend class Hub;
public:
/// Check if the VRManger is active.
/**
* @return Whether hmd is present or not.
*/
bool Active() const;
/// Sync VR device pose(s).
void Sync();
/// Recommended render target size to minimize pixel stretching.
/**
* @return Recommended size (in pixels).
*/
glm::vec2 GetRecommendedRenderTargetSize() const;
/// Returns the transform for the HMD.
/**
* @return The HMD translation matrix.
*/
glm::mat4 GetHMDPoseMatrix() const;
/// Returns the transform for the controllers
/**
* @param controlID Which controller to get the matrix for (1 = left, 2 = right).
* @return The Controllers translation matrix.
*/
glm::mat4 GetControllerPoseMatrix(int controlID) const;
/// Returns the transform between the view space and eye space.
/**
* @param eye Which eye the function should return the eye matrix for.
* @return The eye matrix.
*/
glm::mat4 GetHMDEyeToHeadMatrix(vr::Hmd_Eye eye) const;
/// Returns the projection matrix to use for the specified eye.
/**
* @param eye Which eye the function should return the eye matrix for.
* @param zNear Distance to the near clip plane in meters.
* @param zFar Distance to the far clip plane in meters.
* @return The projection matrix.
*/
glm::mat4 GetHMDProjectionMatrix(vr::Hmd_Eye eye, float zNear, float zFar) const;
/// Submit a texture to an eye.
/**
* @param eye Which eye to submit texture.
* @param texture Texture to submit.
*/
void Submit(vr::Hmd_Eye eye, vr::Texture_t* texture) const;
/// Get scale of player.
/**
* @return Scale to get.
*/
float GetScale() const;
/// Set scale of player.
/**
* @param scale Scale to set.
*/
void SetScale(float scale);
/// Gets if certain button is pressed (Only trigger for now)
/**
* @param buttonID the button we want to check is pressed.
* @return whether certain button is pressed or not.
*/
bool GetInput(vr::EVRButtonId buttonID);
private:
VRManager();
~VRManager();
VRManager(VRManager const&) = delete;
void operator=(VRManager const&) = delete;
static glm::mat4 ConvertMatrix(const vr::HmdMatrix34_t& mat);
static glm::mat4 ConvertMatrix(const vr::HmdMatrix44_t& mat);
float scale;
vr::IVRSystem* vrSystem;
vr::TrackedDevicePose_t tracedDevicePoseArray[vr::k_unMaxTrackedDeviceCount];
glm::mat4 deviceTransforms[vr::k_unMaxTrackedDeviceCount];
bool pressedTrackedDevice[vr::k_unMaxTrackedDeviceCount];
};
<|endoftext|>
|
<commit_before>#include "process.h"
#include <iostream>
using namespace std;
int main() {
cout << "Example 1 - simple echo process" << endl;
Process process1("echo \"Hello World\"", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
});
auto exit_code=process1.get_exit_code();
cout << "Example 1 process returned: " << exit_code << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << endl << "Example 2 - cd into nonexistent directory" << endl;
Process process2("cd nonexistent_directory", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, [](const char *bytes, size_t n) {
cout << "Output from stderr: " << std::string(bytes, n);
});
exit_code=process2.get_exit_code();
cout << "Example 2 process returned: " << exit_code << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << endl << "Example 3 - async sleep process" << endl;
std::thread thread3([]() {
Process process3("sleep 5");
auto exit_code=process3.get_exit_code();
cout << "Example 3 process returned (" << (exit_code==0?"success":"failure") << "): " << exit_code << endl;
});
thread3.detach();
std::this_thread::sleep_for(std::chrono::seconds(10));
cout << endl << "Example 4 - killing async sleep process after 5 seconds" << endl;
auto process4=std::make_shared<Process>("sleep 10");
std::thread thread4([process4]() {
auto exit_code=process4->get_exit_code();
cout << "Example 4 process returned (" << (exit_code==0?"success":"failure") << "): " << exit_code << endl;
});
thread4.detach();
std::this_thread::sleep_for(std::chrono::seconds(5));
Process::kill(process4->get_id());
std::this_thread::sleep_for(std::chrono::seconds(5));
#if !defined(_WIN32) || defined(MSYS_PROCESS_USE_SH)
//Example 5 only works when having access to the sh command (for multiple commands)
//On Windows: install MSYS2 (https://msys2.github.io)
cout << endl << "Example 5 - multiple commands, stdout and stderr" << endl;
Process process5("echo Hello && ls an_incorrect_path", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, [](const char *bytes, size_t n) {
cout << "Output from stderr: " << std::string(bytes, n);
});
exit_code=process5.get_exit_code();
cout << "Example 5 process returned: " << exit_code << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
//Example 6 only works when having access to the bash command
//On Windows: install MSYS2 (https://msys2.github.io)
cout << endl << "Example 6 - run bash with input from stdin" << endl;
Process process6("bash", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, nullptr, true);
process6.write("echo Hello from bash\n");
process6.write("exit\n");
exit_code=process6.get_exit_code();
cout << "Example 6 process returned: " << exit_code << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
//Example 7 only works when having access to the cat command
//On Windows: install MSYS2 (https://msys2.github.io)
cout << endl << "Example 7 - send data to cat through stdin" << endl;
Process process7("cat", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, nullptr, true);
process7.write("Hello cat\n");
process7.close_stdin();
exit_code=process7.get_exit_code();
cout << "Example 7 process returned: " << exit_code << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
#endif
return 0;
}
<commit_msg>Improved examples<commit_after>#include "process.h"
#include <iostream>
using namespace std;
int main() {
cout << "Example 1 - the mandatory Hello World" << endl;
Process process1("echo Hello World", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
});
auto exit_code=process1.get_exit_code();
cout << "Example 1 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << endl << "Example 2 - cd into nonexistent directory" << endl;
Process process2("cd nonexistent_directory", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, [](const char *bytes, size_t n) {
cout << "Output from stderr: " << std::string(bytes, n);
});
exit_code=process2.get_exit_code();
cout << "Example 2 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << endl << "Example 3 - async sleep process" << endl;
std::thread thread3([]() {
Process process3("sleep 5");
auto exit_code=process3.get_exit_code();
cout << "Example 3 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
});
thread3.detach();
std::this_thread::sleep_for(std::chrono::seconds(10));
cout << endl << "Example 4 - killing async sleep process after 5 seconds" << endl;
auto process4=std::make_shared<Process>("sleep 10");
std::thread thread4([process4]() {
auto exit_code=process4->get_exit_code();
cout << "Example 4 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
});
thread4.detach();
std::this_thread::sleep_for(std::chrono::seconds(5));
Process::kill(process4->get_id());
std::this_thread::sleep_for(std::chrono::seconds(5));
#if !defined(_WIN32) || defined(MSYS_PROCESS_USE_SH)
//Example 5 only works when having access to the sh command (for multiple commands)
//On Windows: install MSYS2 (https://msys2.github.io)
cout << endl << "Example 5 - multiple commands, stdout and stderr" << endl;
Process process5("echo Hello && ls an_incorrect_path", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, [](const char *bytes, size_t n) {
cout << "Output from stderr: " << std::string(bytes, n);
});
exit_code=process5.get_exit_code();
cout << "Example 5 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
//Example 6 only works when having access to the bash command
//On Windows: install MSYS2 (https://msys2.github.io)
cout << endl << "Example 6 - run bash with input from stdin" << endl;
Process process6("bash", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, nullptr, true);
process6.write("echo Hello from bash\n");
process6.write("exit\n");
exit_code=process6.get_exit_code();
cout << "Example 6 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
//Example 7 only works when having access to the cat command
//On Windows: install MSYS2 (https://msys2.github.io)
cout << endl << "Example 7 - send data to cat through stdin" << endl;
Process process7("cat", "", [](const char *bytes, size_t n) {
cout << "Output from stdout: " << std::string(bytes, n);
}, nullptr, true);
process7.write("Hello cat\n");
process7.close_stdin();
exit_code=process7.get_exit_code();
cout << "Example 7 process returned: " << exit_code << " (" << (exit_code==0?"success":"failure") << ")" << endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
#endif
return 0;
}
<|endoftext|>
|
<commit_before>//===-- ItaniumABILanguageRuntime.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ItaniumABILanguageRuntime.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Core/ValueObjectMemory.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
static const char *pluginName = "ItaniumABILanguageRuntime";
static const char *pluginDesc = "Itanium ABI for the C++ language";
static const char *pluginShort = "language.itanium";
static const char *vtable_demangled_prefix = "vtable for ";
bool
ItaniumABILanguageRuntime::CouldHaveDynamicValue (ValueObject &in_value)
{
return in_value.IsPossibleCPlusPlusDynamicType();
}
bool
ItaniumABILanguageRuntime::GetDynamicTypeAndAddress (ValueObject &in_value,
lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name,
Address &dynamic_address)
{
// For Itanium, if the type has a vtable pointer in the object, it will be at offset 0
// in the object. That will point to the "address point" within the vtable (not the beginning of the
// vtable.) We can then look up the symbol containing this "address point" and that symbol's name
// demangled will contain the full class name.
// The second pointer above the "address point" is the "offset_to_top". We'll use that to get the
// start of the value object which holds the dynamic type.
//
// Only a pointer or reference type can have a different dynamic and static type:
if (CouldHaveDynamicValue (in_value))
{
// First job, pull out the address at 0 offset from the object.
AddressType address_type;
lldb::addr_t original_ptr = in_value.GetPointerValue(&address_type);
if (original_ptr == LLDB_INVALID_ADDRESS)
return false;
ExecutionContext exe_ctx (in_value.GetExecutionContextRef());
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
char memory_buffer[16];
DataExtractor data(memory_buffer, sizeof(memory_buffer),
process->GetByteOrder(),
process->GetAddressByteSize());
size_t address_byte_size = process->GetAddressByteSize();
Error error;
size_t bytes_read = process->ReadMemory (original_ptr,
memory_buffer,
address_byte_size,
error);
if (!error.Success() || (bytes_read != address_byte_size))
{
return false;
}
uint32_t offset_ptr = 0;
lldb::addr_t vtable_address_point = data.GetAddress (&offset_ptr);
if (offset_ptr == 0)
return false;
// Now find the symbol that contains this address:
SymbolContext sc;
Address address_point_address;
if (target && !target->GetSectionLoadList().IsEmpty())
{
if (target->GetSectionLoadList().ResolveLoadAddress (vtable_address_point, address_point_address))
{
target->GetImages().ResolveSymbolContextForAddress (address_point_address, eSymbolContextSymbol, sc);
Symbol *symbol = sc.symbol;
if (symbol != NULL)
{
const char *name = symbol->GetMangled().GetDemangledName().AsCString();
if (strstr(name, vtable_demangled_prefix) == name)
{
/*
printf ("0x%16.16llx: static-type = '%s' has vtable symbol '%s'\n",
original_ptr,
in_value.GetTypeName().GetCString(),
name);
*/
// We are a C++ class, that's good. Get the class name and look it up:
const char *class_name = name + strlen(vtable_demangled_prefix);
class_type_or_name.SetName (class_name);
const bool exact_match = true;
TypeList class_types;
uint32_t num_matches = target->GetImages().FindTypes2 (sc,
ConstString(class_name),
exact_match,
UINT32_MAX,
class_types);
if (num_matches == 0)
{
//printf ("0x%16.16llx: is not dynamic\n", original_ptr);
return false;
}
if (num_matches == 1)
{
lldb::TypeSP type_sp(class_types.GetTypeAtIndex(0));
/*
printf ("0x%16.16llx: static-type = '%s' has single matching dynamic type: uid={0x%llx}, type-name='%s'\n",
original_ptr,
in_value.GetTypeName().AsCString(),
type_sp->GetID(),
type_sp->GetName().GetCString());
*/
class_type_or_name.SetTypeSP(class_types.GetTypeAtIndex(0));
}
else if (num_matches > 1)
{
for (size_t i = 0; i < num_matches; i++)
{
lldb::TypeSP type_sp(class_types.GetTypeAtIndex(i));
if (type_sp)
{
/*
printf ("0x%16.16llx: static-type = '%s' has multiple matching dynamic types: uid={0x%llx}, type-name='%s'\n",
original_ptr,
in_value.GetTypeName().AsCString(),
type_sp->GetID(),
type_sp->GetName().GetCString());
*/
// if (ClangASTContext::IsCXXClassType(type_sp->GetClangFullType()))
// {
// // There can only be one type with a given name,
// // so we've just found duplicate definitions, and this
// // one will do as well as any other.
// // We don't consider something to have a dynamic type if
// // it is the same as the static type. So compare against
// // the value we were handed:
//
// clang::ASTContext *in_ast_ctx = in_value.GetClangAST ();
// clang::ASTContext *this_ast_ctx = type_sp->GetClangAST ();
// if (in_ast_ctx != this_ast_ctx
// || !ClangASTContext::AreTypesSame (in_ast_ctx,
// in_value.GetClangType(),
// type_sp->GetClangFullType()))
// {
// class_type_or_name.SetTypeSP (this_type);
// return true;
// }
// return false;
// }
}
}
return false;
}
// The offset_to_top is two pointers above the address.
Address offset_to_top_address = address_point_address;
int64_t slide = -2 * ((int64_t) target->GetArchitecture().GetAddressByteSize());
offset_to_top_address.Slide (slide);
Error error;
lldb::addr_t offset_to_top_location = offset_to_top_address.GetLoadAddress(target);
size_t bytes_read = process->ReadMemory (offset_to_top_location,
memory_buffer,
address_byte_size,
error);
if (!error.Success() || (bytes_read != address_byte_size))
{
return false;
}
offset_ptr = 0;
int64_t offset_to_top = data.GetMaxS64(&offset_ptr, process->GetAddressByteSize());
// So the dynamic type is a value that starts at offset_to_top
// above the original address.
lldb::addr_t dynamic_addr = original_ptr + offset_to_top;
if (!target->GetSectionLoadList().ResolveLoadAddress (dynamic_addr, dynamic_address))
{
dynamic_address.SetRawAddress(dynamic_addr);
}
return true;
}
}
}
}
}
return false;
}
bool
ItaniumABILanguageRuntime::IsVTableName (const char *name)
{
if (name == NULL)
return false;
// Can we maybe ask Clang about this?
if (strstr (name, "_vptr$") == name)
return true;
else
return false;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
LanguageRuntime *
ItaniumABILanguageRuntime::CreateInstance (Process *process, lldb::LanguageType language)
{
// FIXME: We have to check the process and make sure we actually know that this process supports
// the Itanium ABI.
if (language == eLanguageTypeC_plus_plus)
return new ItaniumABILanguageRuntime (process);
else
return NULL;
}
void
ItaniumABILanguageRuntime::Initialize()
{
PluginManager::RegisterPlugin (pluginName,
pluginDesc,
CreateInstance);
}
void
ItaniumABILanguageRuntime::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
ItaniumABILanguageRuntime::GetPluginName()
{
return pluginName;
}
const char *
ItaniumABILanguageRuntime::GetShortPluginName()
{
return pluginShort;
}
uint32_t
ItaniumABILanguageRuntime::GetPluginVersion()
{
return 1;
}
static const char *exception_names[] = { "__cxa_begin_catch", "__cxa_throw", "__cxa_rethrow", "__cxa_allocate_exception"};
static const int num_throw_names = 3;
static const int num_expression_throw_names = 1;
BreakpointResolverSP
ItaniumABILanguageRuntime::CreateExceptionResolver (Breakpoint *bkpt, bool catch_bp, bool throw_bp)
{
return CreateExceptionResolver (bkpt, catch_bp, throw_bp, false);
}
BreakpointResolverSP
ItaniumABILanguageRuntime::CreateExceptionResolver (Breakpoint *bkpt, bool catch_bp, bool throw_bp, bool for_expressions)
{
BreakpointResolverSP resolver_sp;
static const int total_expressions = sizeof (exception_names)/sizeof (char *);
// One complication here is that most users DON'T want to stop at __cxa_allocate_expression, but until we can do
// anything better with predicting unwinding the expression parser does. So we have two forms of the exception
// breakpoints, one for expressions that leaves out __cxa_allocate_exception, and one that includes it.
// The SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in the runtime the former.
uint32_t num_expressions;
if (catch_bp && throw_bp)
{
if (for_expressions)
num_expressions = total_expressions;
else
num_expressions = total_expressions - num_expression_throw_names;
resolver_sp.reset (new BreakpointResolverName (bkpt,
exception_names,
num_expressions,
eFunctionNameTypeBase,
eLazyBoolNo));
}
else if (throw_bp)
{
if (for_expressions)
num_expressions = num_throw_names - num_expression_throw_names;
else
num_expressions = num_throw_names;
resolver_sp.reset (new BreakpointResolverName (bkpt,
exception_names + 1,
num_expressions,
eFunctionNameTypeBase,
eLazyBoolNo));
}
else if (catch_bp)
resolver_sp.reset (new BreakpointResolverName (bkpt,
exception_names,
total_expressions - num_throw_names,
eFunctionNameTypeBase,
eLazyBoolNo));
return resolver_sp;
}
void
ItaniumABILanguageRuntime::SetExceptionBreakpoints ()
{
if (!m_process)
return;
const bool catch_bp = false;
const bool throw_bp = true;
const bool is_internal = true;
const bool for_expressions = true;
// For the exception breakpoints set by the Expression parser, we'll be a little more aggressive and
// stop at exception allocation as well.
if (!m_cxx_exception_bp_sp)
{
Target &target = m_process->GetTarget();
BreakpointResolverSP exception_resolver_sp = CreateExceptionResolver (NULL, catch_bp, throw_bp, for_expressions);
SearchFilterSP filter_sp = target.GetSearchFilterForModule(NULL);
m_cxx_exception_bp_sp = target.CreateBreakpoint (filter_sp, exception_resolver_sp, is_internal);
}
else
m_cxx_exception_bp_sp->SetEnabled (true);
}
void
ItaniumABILanguageRuntime::ClearExceptionBreakpoints ()
{
if (!m_process)
return;
if (m_cxx_exception_bp_sp.get())
{
m_cxx_exception_bp_sp->SetEnabled (false);
}
}
bool
ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop (lldb::StopInfoSP stop_reason)
{
if (!m_process)
return false;
if (!stop_reason ||
stop_reason->GetStopReason() != eStopReasonBreakpoint)
return false;
uint64_t break_site_id = stop_reason->GetValue();
return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(break_site_id,
m_cxx_exception_bp_sp->GetID());
}
<commit_msg>Converted commented out printf statements for dynamic type logging to use the log for "log enabe lldb types".<commit_after>//===-- ItaniumABILanguageRuntime.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ItaniumABILanguageRuntime.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Core/ValueObjectMemory.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
static const char *pluginName = "ItaniumABILanguageRuntime";
static const char *pluginDesc = "Itanium ABI for the C++ language";
static const char *pluginShort = "language.itanium";
static const char *vtable_demangled_prefix = "vtable for ";
bool
ItaniumABILanguageRuntime::CouldHaveDynamicValue (ValueObject &in_value)
{
return in_value.IsPossibleCPlusPlusDynamicType();
}
bool
ItaniumABILanguageRuntime::GetDynamicTypeAndAddress (ValueObject &in_value,
lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name,
Address &dynamic_address)
{
// For Itanium, if the type has a vtable pointer in the object, it will be at offset 0
// in the object. That will point to the "address point" within the vtable (not the beginning of the
// vtable.) We can then look up the symbol containing this "address point" and that symbol's name
// demangled will contain the full class name.
// The second pointer above the "address point" is the "offset_to_top". We'll use that to get the
// start of the value object which holds the dynamic type.
//
// Only a pointer or reference type can have a different dynamic and static type:
if (CouldHaveDynamicValue (in_value))
{
// First job, pull out the address at 0 offset from the object.
AddressType address_type;
lldb::addr_t original_ptr = in_value.GetPointerValue(&address_type);
if (original_ptr == LLDB_INVALID_ADDRESS)
return false;
ExecutionContext exe_ctx (in_value.GetExecutionContextRef());
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
char memory_buffer[16];
DataExtractor data(memory_buffer, sizeof(memory_buffer),
process->GetByteOrder(),
process->GetAddressByteSize());
size_t address_byte_size = process->GetAddressByteSize();
Error error;
size_t bytes_read = process->ReadMemory (original_ptr,
memory_buffer,
address_byte_size,
error);
if (!error.Success() || (bytes_read != address_byte_size))
{
return false;
}
uint32_t offset_ptr = 0;
lldb::addr_t vtable_address_point = data.GetAddress (&offset_ptr);
if (offset_ptr == 0)
return false;
// Now find the symbol that contains this address:
SymbolContext sc;
Address address_point_address;
if (target && !target->GetSectionLoadList().IsEmpty())
{
if (target->GetSectionLoadList().ResolveLoadAddress (vtable_address_point, address_point_address))
{
target->GetImages().ResolveSymbolContextForAddress (address_point_address, eSymbolContextSymbol, sc);
Symbol *symbol = sc.symbol;
if (symbol != NULL)
{
const char *name = symbol->GetMangled().GetDemangledName().AsCString();
if (strstr(name, vtable_demangled_prefix) == name)
{
LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
if (log)
log->Printf ("0x%16.16llx: static-type = '%s' has vtable symbol '%s'\n",
original_ptr,
in_value.GetTypeName().GetCString(),
name);
// We are a C++ class, that's good. Get the class name and look it up:
const char *class_name = name + strlen(vtable_demangled_prefix);
class_type_or_name.SetName (class_name);
const bool exact_match = true;
TypeList class_types;
uint32_t num_matches = target->GetImages().FindTypes2 (sc,
ConstString(class_name),
exact_match,
UINT32_MAX,
class_types);
if (num_matches == 0)
{
if (log)
log->Printf("0x%16.16llx: is not dynamic\n", original_ptr);
return false;
}
if (num_matches == 1)
{
lldb::TypeSP type_sp(class_types.GetTypeAtIndex(0));
if (log)
log->Printf ("0x%16.16llx: static-type = '%s' has dynamic type: uid={0x%llx}, type-name='%s'\n",
original_ptr,
in_value.GetTypeName().AsCString(),
type_sp->GetID(),
type_sp->GetName().GetCString());
class_type_or_name.SetTypeSP(class_types.GetTypeAtIndex(0));
}
else if (num_matches > 1)
{
for (size_t i = 0; i < num_matches; i++)
{
lldb::TypeSP type_sp(class_types.GetTypeAtIndex(i));
if (type_sp)
{
if (log)
log->Printf ("0x%16.16llx: static-type = '%s' has multiple matching dynamic types: uid={0x%llx}, type-name='%s'\n",
original_ptr,
in_value.GetTypeName().AsCString(),
type_sp->GetID(),
type_sp->GetName().GetCString());
// if (ClangASTContext::IsCXXClassType(type_sp->GetClangFullType()))
// {
// // There can only be one type with a given name,
// // so we've just found duplicate definitions, and this
// // one will do as well as any other.
// // We don't consider something to have a dynamic type if
// // it is the same as the static type. So compare against
// // the value we were handed:
//
// clang::ASTContext *in_ast_ctx = in_value.GetClangAST ();
// clang::ASTContext *this_ast_ctx = type_sp->GetClangAST ();
// if (in_ast_ctx != this_ast_ctx
// || !ClangASTContext::AreTypesSame (in_ast_ctx,
// in_value.GetClangType(),
// type_sp->GetClangFullType()))
// {
// class_type_or_name.SetTypeSP (this_type);
// return true;
// }
// return false;
// }
}
}
return false;
}
// The offset_to_top is two pointers above the address.
Address offset_to_top_address = address_point_address;
int64_t slide = -2 * ((int64_t) target->GetArchitecture().GetAddressByteSize());
offset_to_top_address.Slide (slide);
Error error;
lldb::addr_t offset_to_top_location = offset_to_top_address.GetLoadAddress(target);
size_t bytes_read = process->ReadMemory (offset_to_top_location,
memory_buffer,
address_byte_size,
error);
if (!error.Success() || (bytes_read != address_byte_size))
{
return false;
}
offset_ptr = 0;
int64_t offset_to_top = data.GetMaxS64(&offset_ptr, process->GetAddressByteSize());
// So the dynamic type is a value that starts at offset_to_top
// above the original address.
lldb::addr_t dynamic_addr = original_ptr + offset_to_top;
if (!target->GetSectionLoadList().ResolveLoadAddress (dynamic_addr, dynamic_address))
{
dynamic_address.SetRawAddress(dynamic_addr);
}
return true;
}
}
}
}
}
return false;
}
bool
ItaniumABILanguageRuntime::IsVTableName (const char *name)
{
if (name == NULL)
return false;
// Can we maybe ask Clang about this?
if (strstr (name, "_vptr$") == name)
return true;
else
return false;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
LanguageRuntime *
ItaniumABILanguageRuntime::CreateInstance (Process *process, lldb::LanguageType language)
{
// FIXME: We have to check the process and make sure we actually know that this process supports
// the Itanium ABI.
if (language == eLanguageTypeC_plus_plus)
return new ItaniumABILanguageRuntime (process);
else
return NULL;
}
void
ItaniumABILanguageRuntime::Initialize()
{
PluginManager::RegisterPlugin (pluginName,
pluginDesc,
CreateInstance);
}
void
ItaniumABILanguageRuntime::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
ItaniumABILanguageRuntime::GetPluginName()
{
return pluginName;
}
const char *
ItaniumABILanguageRuntime::GetShortPluginName()
{
return pluginShort;
}
uint32_t
ItaniumABILanguageRuntime::GetPluginVersion()
{
return 1;
}
static const char *exception_names[] = { "__cxa_begin_catch", "__cxa_throw", "__cxa_rethrow", "__cxa_allocate_exception"};
static const int num_throw_names = 3;
static const int num_expression_throw_names = 1;
BreakpointResolverSP
ItaniumABILanguageRuntime::CreateExceptionResolver (Breakpoint *bkpt, bool catch_bp, bool throw_bp)
{
return CreateExceptionResolver (bkpt, catch_bp, throw_bp, false);
}
BreakpointResolverSP
ItaniumABILanguageRuntime::CreateExceptionResolver (Breakpoint *bkpt, bool catch_bp, bool throw_bp, bool for_expressions)
{
BreakpointResolverSP resolver_sp;
static const int total_expressions = sizeof (exception_names)/sizeof (char *);
// One complication here is that most users DON'T want to stop at __cxa_allocate_expression, but until we can do
// anything better with predicting unwinding the expression parser does. So we have two forms of the exception
// breakpoints, one for expressions that leaves out __cxa_allocate_exception, and one that includes it.
// The SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in the runtime the former.
uint32_t num_expressions;
if (catch_bp && throw_bp)
{
if (for_expressions)
num_expressions = total_expressions;
else
num_expressions = total_expressions - num_expression_throw_names;
resolver_sp.reset (new BreakpointResolverName (bkpt,
exception_names,
num_expressions,
eFunctionNameTypeBase,
eLazyBoolNo));
}
else if (throw_bp)
{
if (for_expressions)
num_expressions = num_throw_names - num_expression_throw_names;
else
num_expressions = num_throw_names;
resolver_sp.reset (new BreakpointResolverName (bkpt,
exception_names + 1,
num_expressions,
eFunctionNameTypeBase,
eLazyBoolNo));
}
else if (catch_bp)
resolver_sp.reset (new BreakpointResolverName (bkpt,
exception_names,
total_expressions - num_throw_names,
eFunctionNameTypeBase,
eLazyBoolNo));
return resolver_sp;
}
void
ItaniumABILanguageRuntime::SetExceptionBreakpoints ()
{
if (!m_process)
return;
const bool catch_bp = false;
const bool throw_bp = true;
const bool is_internal = true;
const bool for_expressions = true;
// For the exception breakpoints set by the Expression parser, we'll be a little more aggressive and
// stop at exception allocation as well.
if (!m_cxx_exception_bp_sp)
{
Target &target = m_process->GetTarget();
BreakpointResolverSP exception_resolver_sp = CreateExceptionResolver (NULL, catch_bp, throw_bp, for_expressions);
SearchFilterSP filter_sp = target.GetSearchFilterForModule(NULL);
m_cxx_exception_bp_sp = target.CreateBreakpoint (filter_sp, exception_resolver_sp, is_internal);
}
else
m_cxx_exception_bp_sp->SetEnabled (true);
}
void
ItaniumABILanguageRuntime::ClearExceptionBreakpoints ()
{
if (!m_process)
return;
if (m_cxx_exception_bp_sp.get())
{
m_cxx_exception_bp_sp->SetEnabled (false);
}
}
bool
ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop (lldb::StopInfoSP stop_reason)
{
if (!m_process)
return false;
if (!stop_reason ||
stop_reason->GetStopReason() != eStopReasonBreakpoint)
return false;
uint64_t break_site_id = stop_reason->GetValue();
return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(break_site_id,
m_cxx_exception_bp_sp->GetID());
}
<|endoftext|>
|
<commit_before>/* Copyright 2015 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 <functional>
#include <unordered_map>
#include <utility>
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename T, typename TIndex>
class UniqueOp : public OpKernel {
public:
explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
// TODO(dga): Make unique polymorphic for returning int32 and int64
// vectors to support large tensors.
OP_REQUIRES(context,
input.NumElements() <= std::numeric_limits<int32>::max(),
errors::InvalidArgument(
"unique does not support input tensors larger than ",
std::numeric_limits<int32>::max(), " elements"));
int64 axis = 0;
std::vector<int64> new_sizes{1, input.NumElements(), 1};
if (context->num_inputs() == 1) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
// In case of UniqueV2, the axis is a 1D vector. The purpose is
// to allow specifying either "no axis" or "axis". The `[]` means
// "no axis", while `[x]` means `axis = x`.
const Tensor& axis_tensor = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(axis_tensor.shape()),
errors::InvalidArgument("axis expects a 1D vector."));
OP_REQUIRES(
context, axis_tensor.NumElements() <= 1,
errors::InvalidArgument(
"axis does not support input tensors larger than 1 elements"));
if (axis_tensor.NumElements() == 0) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
OP_REQUIRES(context,
(axis_tensor.dtype() == DT_INT32 ||
axis_tensor.dtype() == DT_INT64),
errors::InvalidArgument(
"axis tensor should be int32 or int64, but got ",
DataTypeString(axis_tensor.dtype())));
if (axis_tensor.dtype() == DT_INT32) {
axis = internal::SubtleMustCopy(axis_tensor.scalar<int32>()());
} else {
axis = internal::SubtleMustCopy(axis_tensor.scalar<int64>()());
}
axis = axis < 0 ? axis + input.dims() : axis;
OP_REQUIRES(context, 0 <= axis && axis < input.dims(),
errors::InvalidArgument("axis has to be between [0, ",
input.dims(), ")"));
if (axis > 0) {
for (int64 i = 0; i < axis; i++) {
new_sizes[0] *= input.dim_size(i);
}
}
new_sizes[1] = input.dim_size(axis);
if (axis + 1 < input.dims()) {
for (int64 i = axis + 1; i < input.dims(); i++) {
new_sizes[2] *= input.dim_size(i);
}
}
}
}
Tensor* idx = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
1, TensorShape({new_sizes[1]}), &idx));
auto idx_vec = idx->template vec<TIndex>();
int64 uniq_size;
if (new_sizes[0] == 1 && new_sizes[2] == 1) {
// Specialized and faster implementation when unique is run over single
// elements. Here we put T directly into the map rather than ints pointing
// to them as in the general case.
auto Tin = input.flat<T>();
const int64 N = static_cast<int64>(Tin.size());
std::unordered_map<T, TIndex> uniq;
uniq.reserve(2 * N);
for (Eigen::Index i = 0, j = 0; i < N; ++i) {
auto it = uniq.insert(std::make_pair(Tin(i), j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
uniq_size = static_cast<int64>(uniq.size());
TensorShape output_shape(input.shape());
output_shape.set_dim(axis, uniq_size);
Tensor* output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, output_shape, &output));
auto Tout = output->flat<T>();
for (auto it : uniq) {
Tout(it.second) = it.first;
}
} else {
// General implementation when unique is run over multiple elements.
auto Tin = input.shaped<T, 3>(new_sizes);
auto hash_fn = [&Tin](const Eigen::Index& key) {
size_t h = 0;
for (Eigen::Index i = 0; i < Tin.dimension(0); i++) {
for (Eigen::Index j = 0; j < Tin.dimension(2); j++) {
h = Hash64Combine(h, hash<T>{}(Tin(i, key, j)));
}
}
return h;
};
auto equal_to_fn = [&Tin](const Eigen::Index& lhs,
const Eigen::Index& rhs) {
for (Eigen::Index i = 0; i < Tin.dimension(0); i++) {
for (Eigen::Index j = 0; j < Tin.dimension(2); j++) {
if (Tin(i, lhs, j) != Tin(i, rhs, j)) {
return false;
}
}
}
return true;
};
std::unordered_map<int64, int64, decltype(hash_fn), decltype(equal_to_fn)>
uniq(0, hash_fn, equal_to_fn);
uniq.reserve(2 * Tin.dimension(1));
for (int64 i = 0, j = 0; i < Tin.dimension(1); ++i) {
auto it = uniq.insert(std::make_pair(i, j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
uniq_size = static_cast<int64>(uniq.size());
new_sizes[1] = uniq_size;
TensorShape output_shape(input.shape());
output_shape.set_dim(axis, uniq_size);
Tensor* output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, output_shape, &output));
auto Tout = output->shaped<T, 3>(new_sizes);
for (auto it : uniq) {
Tout.chip(it.second, 1) = Tin.chip(it.first, 1);
}
}
if (num_outputs() > 2) {
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
2, TensorShape({uniq_size}), &output));
auto count_output_vec = output->template vec<TIndex>();
count_output_vec.setZero();
const int N = idx_vec.size();
for (int64 i = 0; i < N; ++i) {
count_output_vec(idx_vec(i))++;
}
}
}
};
#define REGISTER_UNIQUE(type) \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>) \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCountsV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>) \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCountsV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_UNIQUE);
REGISTER_UNIQUE(string)
#undef REGISTER_UNIQUE
// Fake integer GPU kernels so that the use of Unique in optimizers (to
// de-duplicate sparse gradient indices) does not conflict with gradients being
// located on a GPU. These kernels run on the CPU, their inputs and outputs
// residing in host (not GPU) memory.
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
<commit_msg>Add bool support for unique_with_counts<commit_after>/* Copyright 2015 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 <functional>
#include <unordered_map>
#include <utility>
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename T, typename TIndex>
class UniqueOp : public OpKernel {
public:
explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
// TODO(dga): Make unique polymorphic for returning int32 and int64
// vectors to support large tensors.
OP_REQUIRES(context,
input.NumElements() <= std::numeric_limits<int32>::max(),
errors::InvalidArgument(
"unique does not support input tensors larger than ",
std::numeric_limits<int32>::max(), " elements"));
int64 axis = 0;
std::vector<int64> new_sizes{1, input.NumElements(), 1};
if (context->num_inputs() == 1) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
// In case of UniqueV2, the axis is a 1D vector. The purpose is
// to allow specifying either "no axis" or "axis". The `[]` means
// "no axis", while `[x]` means `axis = x`.
const Tensor& axis_tensor = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(axis_tensor.shape()),
errors::InvalidArgument("axis expects a 1D vector."));
OP_REQUIRES(
context, axis_tensor.NumElements() <= 1,
errors::InvalidArgument(
"axis does not support input tensors larger than 1 elements"));
if (axis_tensor.NumElements() == 0) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
OP_REQUIRES(context,
(axis_tensor.dtype() == DT_INT32 ||
axis_tensor.dtype() == DT_INT64),
errors::InvalidArgument(
"axis tensor should be int32 or int64, but got ",
DataTypeString(axis_tensor.dtype())));
if (axis_tensor.dtype() == DT_INT32) {
axis = internal::SubtleMustCopy(axis_tensor.scalar<int32>()());
} else {
axis = internal::SubtleMustCopy(axis_tensor.scalar<int64>()());
}
axis = axis < 0 ? axis + input.dims() : axis;
OP_REQUIRES(context, 0 <= axis && axis < input.dims(),
errors::InvalidArgument("axis has to be between [0, ",
input.dims(), ")"));
if (axis > 0) {
for (int64 i = 0; i < axis; i++) {
new_sizes[0] *= input.dim_size(i);
}
}
new_sizes[1] = input.dim_size(axis);
if (axis + 1 < input.dims()) {
for (int64 i = axis + 1; i < input.dims(); i++) {
new_sizes[2] *= input.dim_size(i);
}
}
}
}
Tensor* idx = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
1, TensorShape({new_sizes[1]}), &idx));
auto idx_vec = idx->template vec<TIndex>();
int64 uniq_size;
if (new_sizes[0] == 1 && new_sizes[2] == 1) {
// Specialized and faster implementation when unique is run over single
// elements. Here we put T directly into the map rather than ints pointing
// to them as in the general case.
auto Tin = input.flat<T>();
const int64 N = static_cast<int64>(Tin.size());
std::unordered_map<T, TIndex> uniq;
uniq.reserve(2 * N);
for (Eigen::Index i = 0, j = 0; i < N; ++i) {
auto it = uniq.insert(std::make_pair(Tin(i), j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
uniq_size = static_cast<int64>(uniq.size());
TensorShape output_shape(input.shape());
output_shape.set_dim(axis, uniq_size);
Tensor* output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, output_shape, &output));
auto Tout = output->flat<T>();
for (auto it : uniq) {
Tout(it.second) = it.first;
}
} else {
// General implementation when unique is run over multiple elements.
auto Tin = input.shaped<T, 3>(new_sizes);
auto hash_fn = [&Tin](const Eigen::Index& key) {
size_t h = 0;
for (Eigen::Index i = 0; i < Tin.dimension(0); i++) {
for (Eigen::Index j = 0; j < Tin.dimension(2); j++) {
h = Hash64Combine(h, hash<T>{}(Tin(i, key, j)));
}
}
return h;
};
auto equal_to_fn = [&Tin](const Eigen::Index& lhs,
const Eigen::Index& rhs) {
for (Eigen::Index i = 0; i < Tin.dimension(0); i++) {
for (Eigen::Index j = 0; j < Tin.dimension(2); j++) {
if (Tin(i, lhs, j) != Tin(i, rhs, j)) {
return false;
}
}
}
return true;
};
std::unordered_map<int64, int64, decltype(hash_fn), decltype(equal_to_fn)>
uniq(0, hash_fn, equal_to_fn);
uniq.reserve(2 * Tin.dimension(1));
for (int64 i = 0, j = 0; i < Tin.dimension(1); ++i) {
auto it = uniq.insert(std::make_pair(i, j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
uniq_size = static_cast<int64>(uniq.size());
new_sizes[1] = uniq_size;
TensorShape output_shape(input.shape());
output_shape.set_dim(axis, uniq_size);
Tensor* output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, output_shape, &output));
auto Tout = output->shaped<T, 3>(new_sizes);
for (auto it : uniq) {
Tout.chip(it.second, 1) = Tin.chip(it.first, 1);
}
}
if (num_outputs() > 2) {
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
2, TensorShape({uniq_size}), &output));
auto count_output_vec = output->template vec<TIndex>();
count_output_vec.setZero();
const int N = idx_vec.size();
for (int64 i = 0; i < N; ++i) {
count_output_vec(idx_vec(i))++;
}
}
}
};
#define REGISTER_UNIQUE(type) \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>) \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCountsV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>) \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCountsV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_UNIQUE);
REGISTER_UNIQUE(string)
REGISTER_UNIQUE(bool)
#undef REGISTER_UNIQUE
// Fake integer GPU kernels so that the use of Unique in optimizers (to
// de-duplicate sparse gradient indices) does not conflict with gradients being
// located on a GPU. These kernels run on the CPU, their inputs and outputs
// residing in host (not GPU) memory.
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*
OpenDeck MIDI platform firmware
Copyright (C) 2015-2017 Igor Petrovic
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Database.h"
#include "../board/Board.h"
///
/// \brief Creates database layout by defining blocks and sections.
///
void Database::createLayout()
{
DBMS::addBlocks(DB_BLOCKS);
dbSection_t section;
{
section.parameters = MIDI_FEATURES;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_MIDI, section);
section.parameters = MIDI_CHANNELS;
section.defaultValue = 1;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_MIDI, section);
}
{
section.parameters = MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_BUTTON, section);
section.parameters = MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_BUTTON, section);
section.parameters = MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_BUTTON, section);
}
{
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
}
{
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 127;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
}
{
section.parameters = LED_HARDWARE_PARAMETERS;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
section.parameters = MAX_NUMBER_OF_LEDS;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
section.parameters = MAX_NUMBER_OF_LEDS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
section.parameters = MAX_NUMBER_OF_LEDS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
}
{
section.parameters = ID_OFFSET;
section.defaultValue = UNIQUE_ID;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ID, section);
}
}
<commit_msg>add comments<commit_after>/*
OpenDeck MIDI platform firmware
Copyright (C) 2015-2017 Igor Petrovic
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Database.h"
#include "../board/Board.h"
///
/// \brief Creates database layout by defining blocks and sections.
///
void Database::createLayout()
{
DBMS::addBlocks(DB_BLOCKS);
dbSection_t section;
{
//MIDI block
//midi feature section
section.parameters = MIDI_FEATURES;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_MIDI, section);
//midi channel section
section.parameters = MIDI_CHANNELS;
section.defaultValue = 1;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_MIDI, section);
}
{
//button block
//type section
section.parameters = MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_BUTTON, section);
//program change enabled section
section.parameters = MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_BUTTON, section);
//midi id section
section.parameters = MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_BUTTON, section);
}
{
//encoder block
//encoder enabled section
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
//encoder inverted section
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
//encoding mode section
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
//midi id section
section.parameters = MAX_NUMBER_OF_ENCODERS;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ENCODER, section);
}
{
//analog block
//analog enabled section
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
//analog inverted section
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
//analog type section
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
//midi id section
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
//lower cc limit
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
//upper cc limit
section.parameters = MAX_NUMBER_OF_ANALOG;
section.defaultValue = 127;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ANALOG, section);
}
{
//led block
//hardware parameters section
section.parameters = LED_HARDWARE_PARAMETERS;
section.defaultValue = 0;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
//activation id section
section.parameters = MAX_NUMBER_OF_LEDS;
section.defaultValue = AUTO_INCREMENT;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
//rgb enabled section
section.parameters = MAX_NUMBER_OF_LEDS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
//local led control enabled section
section.parameters = MAX_NUMBER_OF_LEDS;
section.defaultValue = 0;
section.parameterType = BIT_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_LED, section);
}
{
//ID block
section.parameters = ID_OFFSET;
section.defaultValue = UNIQUE_ID;
section.parameterType = BYTE_PARAMETER;
section.preserveOnPartialReset = 0;
DBMS::addSection(DB_BLOCK_ID, section);
}
}
<|endoftext|>
|
<commit_before>#include <nds.h>
#include <stdio.h>
#include <fat.h>
#include <vector>
#include <string>
#include "patches.h"
#include "drunkenlogo.h"
unsigned int rawDataOffset=0;
u8 workbuffer[1024] ALIGN(32);
#define SCREEN_COLS 32
#define ITEMS_PER_SCREEN 10
#define ITEMS_START_ROW 12
#define MAX_DATNAME_LEN 26
using namespace std;
struct patchEntry {
string description;
u32 fileoffset;
};
//---------------------------------------------------------------------------------
void halt() {
//---------------------------------------------------------------------------------
int pressed;
iprintf(" Press A to exit\n");
while(1) {
swiWaitForVBlank();
scanKeys();
pressed = keysDown();
if (pressed & KEY_A) break;
}
exit(0);
}
//---------------------------------------------------------------------------------
void userSettingsCRC(void *buffer) {
//---------------------------------------------------------------------------------
u16 *slot = (u16*)buffer;
u16 CRC1 = swiCRC16(0xFFFF, slot, 0x70);
u16 CRC2 = swiCRC16(0xFFFF, &slot[0x3a], 0x8A);
slot[0x39] = CRC1; slot[0x7f] = CRC2;
}
/*
//---------------------------------------------------------------------------------
void saveFile(char *name, void *buffer, int size) {
//---------------------------------------------------------------------------------
FILE *out = fopen(name,"wb");
if (out) {
fwrite(buffer, 1, 1024, out);
fclose(out);
} else {
printf("couldn't open %s for writing\n",name);
}
}
*/
//---------------------------------------------------------------------------------
void showPatchList (const vector<patchEntry>& patchList, const char* datName, int offset) {
//---------------------------------------------------------------------------------
for (unsigned int i = 0; i < patchList.size() && i < ITEMS_PER_SCREEN; i++) {
const patchEntry* patch = &patchList.at(i);
// Set row
iprintf ("\x1b[%d;5H", i + ITEMS_START_ROW + offset);
iprintf ("%s", patch->description.c_str());
iprintf (datName);
}
}
void aread( void * ptr, size_t size, size_t count, int stream ){ // 'array read' drop in substitute for fread
size=0;
stream=0;
memcpy(ptr,&rawData[rawDataOffset],count);
rawDataOffset+=count;
}
int aseek( int stream, int offset, int origin ){ // 'array seek' drop in substitute for fseek
origin=0;
stream=0;
rawDataOffset=offset;
return 0;
}
int aeof(int stream){
stream=0;
int result=0;
if(rawDataOffset >= fSIZE)result=1;
return result;
}
int atell(int stream){
return rawDataOffset;
}
char * agets( char * str, int num, int stream ){
stream=0;
memcpy(str,&rawData[rawDataOffset],num);
return str;
}
//---------------------------------------------------------------------------------
int main(int argc, char **argv) {
//---------------------------------------------------------------------------------
videoSetMode(MODE_5_2D); //shamlessly ripped from the libnds examples :p
videoSetModeSub(MODE_0_2D);
vramSetBankA(VRAM_A_MAIN_BG);
bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
decompress(drunkenlogoBitmap, BG_GFX, LZ77Vram);
consoleDemoInit();
iprintf("\n\n\n\n\n\n");
iprintf(" >> Cakes ROP Installer << \n");
iprintf("\n\n");
int patchfile = 0;
int header;
rawDataOffset=0;
char datName[MAX_DATNAME_LEN]="YS:/" DATNAME;
char custom[6][35];
aread(&header,1,4,patchfile);
if ( header != 'ROPP') {
iprintf(" Invalid patch file!\n");
halt();
}
int index_offset;
aread(&index_offset,1,4,patchfile);
aseek(patchfile,index_offset,SEEK_SET);
vector<patchEntry> patches;
patchEntry patch;
while(1) {
patch.description.clear();
int string_offset;
aread(&string_offset,1,4,patchfile);
if (aeof(patchfile)) break;
aread(&patch.fileoffset,1,4,patchfile);
// save file pointer
int file_ptr = atell(patchfile);
aseek(patchfile,string_offset,SEEK_SET);
char description[21];
char *desc = agets(description, 20, patchfile);
if (desc == NULL ) {
iprintf(" Failed reading description\n");
halt();
}
// terminate string
description[20] = 0;
patch.description = description;
patches.push_back(patch);
// restore file pointer for next offset
aseek(patchfile,file_ptr,SEEK_SET);
}
int pressed,fwSelected=0,screenOffset=0;
// Default Cakes.dat + custom
int patch_count = patches.size() * 2;
showPatchList(patches, DISPNAME, 0);
showPatchList(patches, "ropCustom.txt", patches.size());
while(1) {
// Show cursor
iprintf ("\x1b[%d;3H[>\x1b[21C<]", fwSelected - screenOffset + ITEMS_START_ROW);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;3H \x1b[21C ", fwSelected - screenOffset + ITEMS_START_ROW);
if (pressed & KEY_UP) fwSelected -= 1;
if (pressed & KEY_DOWN) fwSelected += 1;
if (pressed & KEY_A) break;
if (fwSelected < 0) fwSelected = patch_count - 1; // Wrap around to bottom of list
if (fwSelected > (patch_count - 1)) fwSelected = 0; // Wrap around to top of list
}
iprintf ("\x1b[5;0H\x1b[J");
const patchEntry *selectedPatch;
if (fwSelected < (int)patches.size()) {
selectedPatch = &patches.at(fwSelected);
} else {
selectedPatch = &patches.at(fwSelected - (patch_count - patches.size()));
}
iprintf("Patching for %s\n\n",selectedPatch->description.c_str());
// read header
readFirmware(0,workbuffer,42);
u32 userSettingsOffset = (workbuffer[32] + (workbuffer[33] << 8))<<3;
// read User Settings
readFirmware(userSettingsOffset,workbuffer,512);
aseek(patchfile,selectedPatch->fileoffset,SEEK_SET);
aread(&header,1,4,patchfile);
if (header != 'PTCH' ) {
printf(" Patch set invalid\n");
halt();
} else {
int32_t numPatches;
uint32_t patchSize,patchOffset;
aread(&numPatches,1,4,patchfile);
uint32_t patchOffsetList[numPatches];
aread(patchOffsetList,1,sizeof(patchOffsetList),patchfile);
for (int i=0; i<numPatches; i++) {
aseek(patchfile,patchOffsetList[i],SEEK_SET);
aread(&patchSize,1,4,patchfile);
aread(&patchOffset,1,4,patchfile);
aread(&workbuffer[patchOffset],1,patchSize,patchfile);
}
}
if (fwSelected < (int)patches.size()) {
for(int i = 0;i < MAX_DATNAME_LEN * 2;i += 2){
*(workbuffer + 0x11C + i) = datName[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
} else {
// Load filename from ropCustom.txt
int csSelected=0; //custom selected
int customLinesTotal=6;
int i=0;
char pathBegin[]="YS:/";
if(!fatInitDefault()){
iprintf(" fat init error\n");
halt();
}
FILE *text=fopen("ropCustom.txt","r");
if(!text){
iprintf(" ropCustom.txt load error\n Does it exist?\n\n");
halt();
}
for(i=0;i<customLinesTotal;i++){
fgets(custom[i],30,text);
if(!custom[i] || (custom[i][0] < 0x21) )break;
for(int j=0; j < 30 ;j++){ //strip newline junk
if(custom[i][j]==0x0D || custom[i][j]==0x0A)
custom[i][j]=0;
}
custom[i][25]=0; //make damn sure it terminates
}
if(i==0){
iprintf(" ropCustom.txt read error\n");
iprintf(" invalid first line path\n");
halt();
}
customLinesTotal=i;
fclose(text);
iprintf("\x1b[2J"); //clear console
iprintf("Custom filename list:");
for(i=0;i<customLinesTotal;i++){
iprintf ("\x1b[%d;3H", i + ITEMS_START_ROW -8);
iprintf ("%s", custom[i]);
}
while(1) {
// Show cursor
iprintf ("\x1b[%d;0H[>", csSelected - screenOffset + ITEMS_START_ROW -8);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;0H ", csSelected - screenOffset + ITEMS_START_ROW -8);
if (pressed & KEY_UP) csSelected -= 1;
if (pressed & KEY_DOWN) csSelected += 1;
if (pressed & KEY_A) break;
if (csSelected < 0) csSelected = customLinesTotal - 1; // Wrap around to bottom of list
if (csSelected > (customLinesTotal - 1)) csSelected = 0; // Wrap around to top of list
}
for(int i = 0; i < 4 * 2 ;i += 2){
*(workbuffer + 0x11C + i) = pathBegin[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
for(int i = 0; i < (MAX_DATNAME_LEN - 4) * 2;i += 2){
*(workbuffer + 0x124 + i) = custom[csSelected][i / 2];
*(workbuffer + 0x124 + i + 1)=0;
}
*(workbuffer + 0x142)=0; //ensure terminated string (again)
*(workbuffer + 0x143)=0;
}
userSettingsCRC(workbuffer);
userSettingsCRC(workbuffer+256);
iprintf("\n\n\n\n\n Writing ... ");
int ret = writeFirmware(userSettingsOffset,workbuffer,512);
if (ret) {
iprintf("failed\n");
} else {
iprintf("success\n");
}
iprintf(" Verifying ... ");
readFirmware(userSettingsOffset,workbuffer+512,512);
if (memcmp(workbuffer,workbuffer+512,512)){
iprintf("failed\n");
} else {
iprintf("success\n");
}
halt();
return 0;
}
<commit_msg>Fixing string termination and stuff.<commit_after>#include <nds.h>
#include <stdio.h>
#include <fat.h>
#include <vector>
#include <string>
#include "patches.h"
#include "drunkenlogo.h"
unsigned int rawDataOffset=0;
u8 workbuffer[1024] ALIGN(32);
#define SCREEN_COLS 32
#define ITEMS_PER_SCREEN 10
#define ITEMS_START_ROW 12
#define MAX_DATNAME_LEN 26
using namespace std;
struct patchEntry {
string description;
u32 fileoffset;
};
//---------------------------------------------------------------------------------
void halt() {
//---------------------------------------------------------------------------------
int pressed;
iprintf(" Press A to exit\n");
while(1) {
swiWaitForVBlank();
scanKeys();
pressed = keysDown();
if (pressed & KEY_A) break;
}
exit(0);
}
//---------------------------------------------------------------------------------
void userSettingsCRC(void *buffer) {
//---------------------------------------------------------------------------------
u16 *slot = (u16*)buffer;
u16 CRC1 = swiCRC16(0xFFFF, slot, 0x70);
u16 CRC2 = swiCRC16(0xFFFF, &slot[0x3a], 0x8A);
slot[0x39] = CRC1; slot[0x7f] = CRC2;
}
/*
//---------------------------------------------------------------------------------
void saveFile(char *name, void *buffer, int size) {
//---------------------------------------------------------------------------------
FILE *out = fopen(name,"wb");
if (out) {
fwrite(buffer, 1, 1024, out);
fclose(out);
} else {
printf("couldn't open %s for writing\n",name);
}
}
*/
//---------------------------------------------------------------------------------
void showPatchList (const vector<patchEntry>& patchList, const char* datName, int offset) {
//---------------------------------------------------------------------------------
for (unsigned int i = 0; i < patchList.size() && i < ITEMS_PER_SCREEN; i++) {
const patchEntry* patch = &patchList.at(i);
// Set row
iprintf ("\x1b[%d;5H", i + ITEMS_START_ROW + offset);
iprintf ("%s", patch->description.c_str());
iprintf (datName);
}
}
void aread( void * ptr, size_t size, size_t count, int stream ){ // 'array read' drop in substitute for fread
size=0;
stream=0;
memcpy(ptr,&rawData[rawDataOffset],count);
rawDataOffset+=count;
}
int aseek( int stream, int offset, int origin ){ // 'array seek' drop in substitute for fseek
origin=0;
stream=0;
rawDataOffset=offset;
return 0;
}
int aeof(int stream){
stream=0;
int result=0;
if(rawDataOffset >= fSIZE)result=1;
return result;
}
int atell(int stream){
return rawDataOffset;
}
char * agets( char * str, int num, int stream ){
stream=0;
memcpy(str,&rawData[rawDataOffset],num);
return str;
}
//---------------------------------------------------------------------------------
int main(int argc, char **argv) {
//---------------------------------------------------------------------------------
videoSetMode(MODE_5_2D); //shamlessly ripped from the libnds examples :p
videoSetModeSub(MODE_0_2D);
vramSetBankA(VRAM_A_MAIN_BG);
bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
decompress(drunkenlogoBitmap, BG_GFX, LZ77Vram);
consoleDemoInit();
iprintf("\n\n\n\n\n\n");
iprintf(" >> Cakes ROP Installer << \n");
iprintf("\n\n");
int patchfile = 0;
int header;
rawDataOffset=0;
char datName[MAX_DATNAME_LEN]="YS:/" DATNAME;
char custom[6][MAX_DATNAME_LEN-4]={};
aread(&header,1,4,patchfile);
if ( header != 'ROPP') {
iprintf(" Invalid patch file!\n");
halt();
}
int index_offset;
aread(&index_offset,1,4,patchfile);
aseek(patchfile,index_offset,SEEK_SET);
vector<patchEntry> patches;
patchEntry patch;
while(1) {
patch.description.clear();
int string_offset;
aread(&string_offset,1,4,patchfile);
if (aeof(patchfile)) break;
aread(&patch.fileoffset,1,4,patchfile);
// save file pointer
int file_ptr = atell(patchfile);
aseek(patchfile,string_offset,SEEK_SET);
char description[21];
char *desc = agets(description, 20, patchfile);
if (desc == NULL ) {
iprintf(" Failed reading description\n");
halt();
}
// terminate string
description[20] = 0;
patch.description = description;
patches.push_back(patch);
// restore file pointer for next offset
aseek(patchfile,file_ptr,SEEK_SET);
}
int pressed,fwSelected=0,screenOffset=0;
// Default Cakes.dat + custom
int patch_count = patches.size() * 2;
showPatchList(patches, DISPNAME, 0);
showPatchList(patches, "ropCustom.txt", patches.size());
while(1) {
// Show cursor
iprintf ("\x1b[%d;3H[>\x1b[21C<]", fwSelected - screenOffset + ITEMS_START_ROW);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;3H \x1b[21C ", fwSelected - screenOffset + ITEMS_START_ROW);
if (pressed & KEY_UP) fwSelected -= 1;
if (pressed & KEY_DOWN) fwSelected += 1;
if (pressed & KEY_A) break;
if (fwSelected < 0) fwSelected = patch_count - 1; // Wrap around to bottom of list
if (fwSelected > (patch_count - 1)) fwSelected = 0; // Wrap around to top of list
}
iprintf ("\x1b[5;0H\x1b[J");
const patchEntry *selectedPatch;
if (fwSelected < (int)patches.size()) {
selectedPatch = &patches.at(fwSelected);
} else {
selectedPatch = &patches.at(fwSelected - (patch_count - patches.size()));
}
iprintf("Patching for %s\n\n",selectedPatch->description.c_str());
// read header
readFirmware(0,workbuffer,42);
u32 userSettingsOffset = (workbuffer[32] + (workbuffer[33] << 8))<<3;
// read User Settings
readFirmware(userSettingsOffset,workbuffer,512);
aseek(patchfile,selectedPatch->fileoffset,SEEK_SET);
aread(&header,1,4,patchfile);
if (header != 'PTCH' ) {
printf(" Patch set invalid\n");
halt();
} else {
int32_t numPatches;
uint32_t patchSize,patchOffset;
aread(&numPatches,1,4,patchfile);
uint32_t patchOffsetList[numPatches];
aread(patchOffsetList,1,sizeof(patchOffsetList),patchfile);
for (int i=0; i<numPatches; i++) {
aseek(patchfile,patchOffsetList[i],SEEK_SET);
aread(&patchSize,1,4,patchfile);
aread(&patchOffset,1,4,patchfile);
aread(&workbuffer[patchOffset],1,patchSize,patchfile);
}
}
if (fwSelected < (int)patches.size()) {
for(int i = 0;i < MAX_DATNAME_LEN * 2 - 2;i += 2){
*(workbuffer + 0x11C + i) = datName[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
*(workbuffer + 0x11C + MAX_DATNAME_LEN * 2 - 2)=0;
*(workbuffer + 0x11C + MAX_DATNAME_LEN * 2 - 1)=0;
} else {
// Load filename from ropCustom.txt
int csSelected=0; //custom selected
int customLinesTotal=6;
int i=0;
char pathBegin[]="YS:/";
if(!fatInitDefault()){
iprintf(" fat init error\n");
halt();
}
FILE *text=fopen("ropCustom.txt","r");
if(!text){
iprintf(" ropCustom.txt load error\n Does it exist?\n\n");
halt();
}
for(i=0;i<customLinesTotal;i++){
fgets(custom[i],MAX_DATNAME_LEN-4,text);
if(!custom[i] || (custom[i][0] < 0x21) )break;
for(int j=0; j < MAX_DATNAME_LEN-4 ;j++){ //strip newline junk
if(custom[i][j]==0x0D || custom[i][j]==0x0A)
custom[i][j]=0;
}
custom[i][MAX_DATNAME_LEN-5]=0; //make damn sure it terminates
}
if(i==0){
iprintf(" ropCustom.txt read error\n");
iprintf(" invalid first line path\n");
halt();
}
customLinesTotal=i;
fclose(text);
iprintf("\x1b[2J"); //clear console
iprintf("Custom filename list:");
for(i=0;i<customLinesTotal;i++){
iprintf ("\x1b[%d;3H", i + ITEMS_START_ROW -8);
iprintf ("%s", custom[i]);
}
while(1) {
// Show cursor
iprintf ("\x1b[%d;0H[>", csSelected - screenOffset + ITEMS_START_ROW -8);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;0H ", csSelected - screenOffset + ITEMS_START_ROW -8);
if (pressed & KEY_UP) csSelected -= 1;
if (pressed & KEY_DOWN) csSelected += 1;
if (pressed & KEY_A) break;
if (csSelected < 0) csSelected = customLinesTotal - 1; // Wrap around to bottom of list
if (csSelected > (customLinesTotal - 1)) csSelected = 0; // Wrap around to top of list
}
for(int i = 0; i < 4 * 2 ;i += 2){
*(workbuffer + 0x11C + i) = pathBegin[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
for(int i = 0; i < (MAX_DATNAME_LEN - 4) * 2 - 2;i += 2){
*(workbuffer + 0x124 + i) = custom[csSelected][i / 2];
*(workbuffer + 0x124 + i + 1)=0;
}
*(workbuffer + 0x11C + MAX_DATNAME_LEN * 2 - 2)=0; //ensure terminated string (again)
*(workbuffer + 0x11C + MAX_DATNAME_LEN * 2 - 1)=0;
}
userSettingsCRC(workbuffer);
userSettingsCRC(workbuffer+256);
iprintf("\n\n\n\n\n Writing ... ");
int ret = writeFirmware(userSettingsOffset,workbuffer,512);
if (ret) {
iprintf("failed\n");
} else {
iprintf("success\n");
}
iprintf(" Verifying ... ");
readFirmware(userSettingsOffset,workbuffer+512,512);
if (memcmp(workbuffer,workbuffer+512,512)){
iprintf("failed\n");
} else {
iprintf("success\n");
}
halt();
return 0;
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <sstream>
#include <iomanip>
#include <stdio.h>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_SELECT)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
if(ninjhax) {
stream << "SELECT - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string targetInstall;
App targetDelete;
if(mode == INSTALL) {
uiSelectFile(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
return onLoop();
}, [&](std::string path, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Install the selected title?", true)) {
AppResult ret = appInstallFile(destination, path, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE) {
uiSelectApp(&targetDelete, destination, onLoop, [&](App app, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
}
if(netInstall && !exit) {
netInstall = false;
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<commit_msg>Allow deleting CIA files and installing/deleting all CIA files in a directory at once.<commit_after>#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <sys/dirent.h>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
/* if(ninjhax) {
consoleInit(GFX_BOTTOM, NULL);
consoleClear();
AcquireResult result = platformAcquireServices();
if(result != ACQUIRE_SUCCESS) {
//std::stringstream errorStream;
//errorStream << "Failed to acquire services." << "\n";
//errorStream << platformGetAcquireResultString(result) << "\n";
//uiPrompt(TOP_SCREEN, errorStream.str(), false);
while(true) {
inputPoll();
if(inputIsPressed(BUTTON_START)) {
break;
}
}
platformCleanup();
return 0;
}
} */
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_SELECT)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
} else {
mode = INSTALL_CIA;
}
breakLoop = true;
}
if(inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : "Delete Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "Y - Receive an app over the network" << "\n";
if(ninjhax) {
stream << "SELECT - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA) {
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
if(uiPrompt(TOP_SCREEN, "Install all CIAs in the current directory?", true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Install the selected CIA?", true)) {
AppResult ret = appInstallFile(destination, path, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_CIA) {
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
if(uiPrompt(TOP_SCREEN, "Delete all CIAs in the current directory?", true)) {
updateList = true;
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
if(!fsDelete(path)) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << fileName << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Delete succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Delete the selected CIA?", true)) {
updateList = true;
std::stringstream resultMsg;
resultMsg << "Delete ";
if(fsDelete(path)) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE) {
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
}
if(netInstall && !exit) {
netInstall = false;
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<|endoftext|>
|
<commit_before>//
//
// Created by Steven Massey on 4/15/19.
// Copyright © 2019 Steven Massey. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "m3.hpp"
extern "C"
{
# include "m3_core.h"
}
#include "m3_host.h"
void m3Output (const char * i_string)
{
printf ("%s\n", i_string);
}
int main (int i_argc, const char * i_argv [])
{
M3Result result = c_m3Err_none;
if (i_argc >= 2)
{
FILE * f = fopen (i_argv [1], "rb");
if (f)
{
fseek (f, 0, SEEK_END);
size_t fsize = ftell (f);
fseek (f, 0, SEEK_SET);
if (fsize < 100000)
{
u8 * wasm = (u8 *) malloc (fsize);
if (wasm)
{
IM3Runtime env = nullptr;
try
{
fread (wasm, 1, fsize, f);
fclose (f);
IM3Module module;
result = m3_ParseModule (& module, wasm, (u32) fsize); if (result) throw result;
env = m3_NewRuntime (32768);
result = m3_LoadModule (env, module); if (result) throw result;
m3_LinkFunction (module, "_m3TestOut", "v(iFi)", (void *) m3TestOut);
m3_LinkFunction (module, "_m3StdOut", "v(*)", (void *) m3Output);
m3_LinkFunction (module, "_m3Export", "v(*i)", (void *) m3Export);
m3_LinkFunction (module, "_m3Out_f64", "v(F)", (void *) m3Out_f64);
m3_LinkFunction (module, "_m3Out_i32", "v(i)", (void *) m3Out_i32);
m3_LinkFunction (module, "_TestReturn", "F(i)", (void *) TestReturn);
m3_LinkFunction (module, "abortStackOverflow", "v(i)", (void *) m3_abort);
result = m3_LinkCStd (module); if (result) throw result;
m3_PrintRuntimeInfo (env);
IM3Function f;
result = m3_FindFunction (& f, env, "__post_instantiate");
if (not result)
{
result = m3_Call (f); if (result) throw result;
}
IM3Function main;
result = m3_FindFunction (& main, env, i_argv[2]); if (result) throw result;
if (main)
{
printf ("found %s\n", i_argv[2]);
clock_t start = clock ();
// result = m3_Call (main);
if (i_argc)
{
i_argc -= 2;
i_argv += 2;
}
result = m3_CallWithArgs (main, i_argc, i_argv);
clock_t end = clock ();
double elapsed_time = (end - start) / (double) CLOCKS_PER_SEC ;
printf("Time: %.3lf s\n", elapsed_time);
// printf ("call: %s\n", result);
m3_PrintProfilerInfo ();
}
}
catch (const M3Result & r) {}
if (result)
{
printf ("result: %s", result);
if (env)
{
M3ErrorInfo info = m3_GetErrorInfo (env);
printf (" (%s)", info.message);
}
printf ("\n");
return 1;
}
m3_FreeRuntime (env);
}
free (wasm);
}
}
else printf ("couldn't open '%s'\n", i_argv [1]);
} else printf ("not enough arguments\n");
printf ("\n");
return 0;
}
<commit_msg>Allow running exported functions with args<commit_after>//
//
// Created by Steven Massey on 4/15/19.
// Copyright © 2019 Steven Massey. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "m3.hpp"
extern "C"
{
# include "m3_core.h"
}
#include "m3_host.h"
void m3Output (const char * i_string)
{
printf ("%s\n", i_string);
}
int main (int i_argc, const char * i_argv [])
{
M3Result result = c_m3Err_none;
if (i_argc >= 2)
{
FILE * f = fopen (i_argv [1], "rb");
if (f)
{
fseek (f, 0, SEEK_END);
size_t fsize = ftell (f);
fseek (f, 0, SEEK_SET);
if (fsize < 100000)
{
u8 * wasm = (u8 *) malloc (fsize);
if (wasm)
{
IM3Runtime env = nullptr;
try
{
fread (wasm, 1, fsize, f);
fclose (f);
IM3Module module;
result = m3_ParseModule (& module, wasm, (u32) fsize); if (result) throw result;
env = m3_NewRuntime (32768);
result = m3_LoadModule (env, module); if (result) throw result;
m3_LinkFunction (module, "_m3TestOut", "v(iFi)", (void *) m3TestOut);
m3_LinkFunction (module, "_m3StdOut", "v(*)", (void *) m3Output);
m3_LinkFunction (module, "_m3Export", "v(*i)", (void *) m3Export);
m3_LinkFunction (module, "_m3Out_f64", "v(F)", (void *) m3Out_f64);
m3_LinkFunction (module, "_m3Out_i32", "v(i)", (void *) m3Out_i32);
m3_LinkFunction (module, "_TestReturn", "F(i)", (void *) TestReturn);
m3_LinkFunction (module, "abortStackOverflow", "v(i)", (void *) m3_abort);
result = m3_LinkCStd (module); if (result) throw result;
//m3_PrintRuntimeInfo (env);
IM3Function f;
result = m3_FindFunction (& f, env, "__post_instantiate");
if (not result)
{
result = m3_Call (f); if (result) throw result;
}
const char* fname = i_argv[2];
IM3Function main;
result = m3_FindFunction (& main, env, fname); if (result) throw result;
if (main)
{
clock_t start = clock ();
if (!strcmp(fname, "_main") || !strcmp(fname, "main")) {
if (i_argc)
{
i_argc -= 2;
i_argv += 2;
}
result = m3_CallMain (main, i_argc, i_argv);
} else {
if (i_argc)
{
i_argc -= 3;
i_argv += 3;
}
result = m3_CallWithArgs (main, i_argc, i_argv);
}
clock_t end = clock ();
double elapsed_time = (end - start) / (double) CLOCKS_PER_SEC ;
printf("Time: %.3lf s\n", elapsed_time);
// printf ("call: %s\n", result);
//m3_PrintProfilerInfo ();
} else {
printf ("%s not found\n", fname);
}
}
catch (const M3Result & r) {}
if (result)
{
printf ("Error: %s", result);
if (env)
{
M3ErrorInfo info = m3_GetErrorInfo (env);
printf (" (%s)", info.message);
}
printf ("\n");
return 1;
}
m3_FreeRuntime (env);
}
free (wasm);
}
}
else printf ("couldn't open '%s'\n", i_argv [1]);
} else printf ("not enough arguments\n");
printf ("\n");
return 0;
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool netInstall = false;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(input_is_pressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
ui_display_progress("Installing", "Press B to cancel.", true, progress);
input_poll();
return !input_is_pressed(BUTTON_B);
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(netInstall) {
netInstall = false;
// Clear bottom screen on both buffers.
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
RemoteFile file = ui_accept_remote_file();
if(file.socket == -1) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(ui_prompt(confirmStream.str(), true)) {
int ret = app_install(destination, file.socket, true, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == 0) {
resultMsg << "succeeded!";
} else if(ret == -2) {
resultMsg << "cancelled!";
} else {
resultMsg << "failed! Error: 0x" << std::hex << ret;
}
ui_prompt(resultMsg.str(), false);
}
socket_close(file.socket);
continue;
}
if(obtained) {
std::stringstream prompt;
if(mode == INSTALL) {
prompt << "Install ";
} else if(mode == DELETE) {
prompt << "Delete ";
}
prompt << "the selected title?";
if(ui_prompt(prompt.str(), true)) {
int ret = 0;
if(mode == INSTALL) {
ret = app_install_file(destination, targetInstall, onProgress);
} else if(mode == DELETE) {
ui_display_message("Deleting title...");
ret = app_delete(targetDelete);
}
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == 0) {
resultMsg << "succeeded!";
} else if(ret == -2) {
resultMsg << "cancelled!";
} else {
resultMsg << "failed! Error: 0x" << std::hex << ret;
}
ui_prompt(resultMsg.str(), false);
freeSpace = fs_get_free_space(destination);
}
}
}
platform_cleanup();
return 0;
}
<commit_msg>Use app_install_socket.<commit_after>#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool netInstall = false;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(input_is_pressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
ui_display_progress("Installing", "Press B to cancel.", true, progress);
input_poll();
return !input_is_pressed(BUTTON_B);
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(netInstall) {
netInstall = false;
// Clear bottom screen on both buffers.
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
RemoteFile file = ui_accept_remote_file();
if(file.socket == -1) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(ui_prompt(confirmStream.str(), true)) {
int ret = app_install_socket(destination, file.socket, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == 0) {
resultMsg << "succeeded!";
} else if(ret == -2) {
resultMsg << "cancelled!";
} else {
resultMsg << "failed! Error: 0x" << std::hex << ret;
}
ui_prompt(resultMsg.str(), false);
}
socket_close(file.socket);
continue;
}
if(obtained) {
std::stringstream prompt;
if(mode == INSTALL) {
prompt << "Install ";
} else if(mode == DELETE) {
prompt << "Delete ";
}
prompt << "the selected title?";
if(ui_prompt(prompt.str(), true)) {
int ret = 0;
if(mode == INSTALL) {
ret = app_install_file(destination, targetInstall, onProgress);
} else if(mode == DELETE) {
ui_display_message("Deleting title...");
ret = app_delete(targetDelete);
}
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == 0) {
resultMsg << "succeeded!";
} else if(ret == -2) {
resultMsg << "cancelled!";
} else {
resultMsg << "failed! Error: 0x" << std::hex << ret;
}
ui_prompt(resultMsg.str(), false);
freeSpace = fs_get_free_space(destination);
}
}
}
platform_cleanup();
return 0;
}
<|endoftext|>
|
<commit_before>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkPatternIntensityImageToImageMetric_txx
#define __itkPatternIntensityImageToImageMetric_txx
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkNumericTraits.h"
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include "itkSimpleFilterWatcher.h"
//#include "itkImageFileWriter.h"
namespace itk
{
/**
* ********************* Constructor ******************************
*/
template <class TFixedImage, class TMovingImage>
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::PatternIntensityImageToImageMetric()
{
this->m_NormalizationFactor = 1.0;
this->m_Rescalingfactor = 1.0;
this->m_DerivativeDelta = 0.001;
this->m_NoiseConstant = 10000; // = sigma * sigma = 100*100 if not specified
this->m_NeighborhoodRadius = 3;
this->m_FixedMeasure = 0;
this->m_OptimizeNormalizationFactor = false;
this->m_TransformMovingImageFilter = TransformMovingImageFilterType::New();
this->m_CombinationTransform = CombinationTransformType::New();
this->m_RescaleImageFilter = RescaleIntensityImageFilterType::New();
this->m_DifferenceImageFilter = DifferenceImageFilterType::New();
this->m_MultiplyByConstantImageFilter = MultiplyByConstantImageFilterType::New();
} // end Constructor
/**
* ********************* Initialize ******************************
*/
template <class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::Initialize( void ) throw ( ExceptionObject )
{
Superclass::Initialize();
/* resampling for 3D->2D */
this->m_TransformMovingImageFilter->SetTransform(
dynamic_cast<CombinationTransformType *>(
dynamic_cast<RayCastInterpolatorType *>(
const_cast< InterpolatorType *>( ( this->GetInterpolator() ) ) )->GetTransform() ) );
this->m_TransformMovingImageFilter->SetInterpolator( this->m_Interpolator );
this->m_TransformMovingImageFilter->SetInput( this->m_MovingImage );
this->m_TransformMovingImageFilter->SetDefaultPixelValue( 0 );
this->m_TransformMovingImageFilter->SetSize(
this->m_FixedImage->GetLargestPossibleRegion().GetSize() );
this->m_TransformMovingImageFilter->SetOutputOrigin(
this->m_FixedImage->GetOrigin() );
this->m_TransformMovingImageFilter->SetOutputSpacing(
this->m_FixedImage->GetSpacing() );
this->m_TransformMovingImageFilter->SetOutputDirection(
this->m_FixedImage->GetDirection() );
this->m_TransformMovingImageFilter->UpdateLargestPossibleRegion();
this->ComputeFixedImageExtrema(
this->GetFixedImage(), this->GetFixedImageRegion() );
this->ComputeMovingImageExtrema(
this->m_TransformMovingImageFilter->GetOutput(),
this->m_TransformMovingImageFilter->GetOutput()->GetBufferedRegion() );
this->m_NormalizationFactor = this->m_FixedImageTrueMax / this->m_MovingImageTrueMax;
this->m_MultiplyByConstantImageFilter->SetInput(
this->m_TransformMovingImageFilter->GetOutput() );
this->m_MultiplyByConstantImageFilter->SetConstant(
this->m_NormalizationFactor );
this->m_DifferenceImageFilter->SetInput1( this->m_FixedImage );
this->m_DifferenceImageFilter->SetInput2( this->m_MultiplyByConstantImageFilter->GetOutput() );
this->m_DifferenceImageFilter->UpdateLargestPossibleRegion();
this->m_FixedMeasure = this->ComputePIFixed();
/* to rescale the similarity measure between 0-1;*/
MeasureType tmpmeasure = this->GetValue( this->m_CombinationTransform->GetParameters() );
while ( ( vcl_fabs( tmpmeasure ) / this->m_Rescalingfactor ) > 1 )
{
this->m_Rescalingfactor *= 10;
}
} // end Initialize()
/**
* ********************* PrintSelf ******************************
*/
template <class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::PrintSelf( std::ostream& os, Indent indent ) const
{
Superclass::PrintSelf( os, indent );
os << indent << "DerivativeDelta: " << this->m_DerivativeDelta << std::endl;
} // end PrintSelf()
/**
* ********************* ComputePIFixed ******************************
*/
template <class TFixedImage, class TMovingImage>
typename PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>::MeasureType
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::ComputePIFixed( ) const
{
unsigned int iDimension;
MeasureType measure = NumericTraits< MeasureType >::Zero;
MeasureType diff = NumericTraits< MeasureType >::Zero;
typename FixedImageType::SizeType iterationSize =
this->m_FixedImage->GetLargestPossibleRegion().GetSize();
typename FixedImageType::IndexType iterationStartIndex, currentIndex, neighborIndex;
typename FixedImageType::SizeType neighborIterationSize;
typename FixedImageType::PointType point;
for( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
iterationSize[ iDimension ] -= static_cast<int>( 2 * this->m_NeighborhoodRadius );
iterationStartIndex[ iDimension ] = static_cast<int>( this->m_NeighborhoodRadius );
neighborIterationSize[ iDimension ] = static_cast<int>(2 * this->m_NeighborhoodRadius) + 1;
}
/** replace this by checking the size of the 3rd dimension of fixedimage */
iterationSize[ 2 ] = neighborIterationSize[ 2 ] = 1;
iterationStartIndex[ 2 ] = 0;
typename FixedImageType::RegionType iterationRegion, neighboriterationRegion;
iterationRegion.SetIndex( iterationStartIndex );
iterationRegion.SetSize( iterationSize );
typedef itk::ImageRegionConstIteratorWithIndex< FixedImageType > FixedImageTypeIteratorType;
FixedImageTypeIteratorType fixedImageIt( this->m_FixedImage, iterationRegion );
fixedImageIt.GoToBegin();
neighboriterationRegion.SetSize( neighborIterationSize );
bool sampleOK = false;
if ( this->m_FixedImageMask.IsNull() )
{
sampleOK = true;
}
while ( !fixedImageIt.IsAtEnd() )
{
/** Get current index */
currentIndex = fixedImageIt.GetIndex();
this->m_FixedImage->TransformIndexToPhysicalPoint( currentIndex, point );
/** if fixedMask is given */
if ( !this->m_FixedImageMask.IsNull() )
{
if ( this->m_FixedImageMask->IsInside( point ) )
{
sampleOK = true;
}
else
{
sampleOK = false;
}
}
if ( sampleOK )
{
/** setup the neighborhood iterator */
for( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
neighborIndex[ iDimension ] = currentIndex[ iDimension ] - this->m_NeighborhoodRadius;
neighborIndex[ 2 ] = 0; // 2D only
}
neighboriterationRegion.SetIndex( neighborIndex );
FixedImageTypeIteratorType neighborIt( this->m_FixedImage, neighboriterationRegion );
neighborIt.GoToBegin();
while ( ! neighborIt.IsAtEnd() )
{
diff = fixedImageIt.Value() - neighborIt.Value();
measure += ( this->m_NoiseConstant ) / ( this->m_NoiseConstant + ( diff * diff ) );
++neighborIt;
} // end while neighborIt
} // end if sampleOK
++fixedImageIt;
} //end while fixedImageIt
return measure;
} // end ComputePIFixed()
/**
* ********************* ComputePIDiff ******************************
*/
template <class TFixedImage, class TMovingImage>
typename PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>::MeasureType
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::ComputePIDiff( const TransformParametersType & parameters, float scalingfactor ) const
{
unsigned int iDimension;
this->SetTransformParameters( parameters );
this->m_TransformMovingImageFilter->Modified();
this->m_MultiplyByConstantImageFilter->SetConstant( scalingfactor );
this->m_DifferenceImageFilter->UpdateLargestPossibleRegion();
MeasureType measure = NumericTraits< MeasureType >::Zero;
MeasureType diff = NumericTraits< MeasureType >::Zero;
typename FixedImageType::SizeType iterationSize = this->m_FixedImage->GetLargestPossibleRegion().GetSize();
typename FixedImageType::IndexType iterationStartIndex, currentIndex, neighborIndex;
typename FixedImageType::SizeType neighborIterationSize;
typename FixedImageType::PointType point;
for ( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
iterationSize[iDimension] -= static_cast<int>( 2 * this->m_NeighborhoodRadius );
iterationStartIndex[iDimension] = static_cast<int>( this->m_NeighborhoodRadius );
neighborIterationSize[iDimension] = static_cast<int>( 2 * this->m_NeighborhoodRadius + 1 );
}
/** 3rd Dimension is 1 */
iterationSize[ 2 ] = neighborIterationSize[ 2 ] = 1;
iterationStartIndex[ 2 ] = 0;
typename FixedImageType::RegionType iterationRegion, neighboriterationRegion;
iterationRegion.SetIndex( iterationStartIndex );
iterationRegion.SetSize( iterationSize );
typedef itk::ImageRegionConstIteratorWithIndex< TransformedMovingImageType > DifferenceImageIteratorType;
DifferenceImageIteratorType differenceImageIt( this->m_DifferenceImageFilter->GetOutput(), iterationRegion );
differenceImageIt.GoToBegin();
neighboriterationRegion.SetSize( neighborIterationSize );
bool sampleOK = false;
if ( this->m_FixedImageMask.IsNull() )
{
sampleOK = true;
}
while ( !differenceImageIt.IsAtEnd() )
{
/** Get current index */
currentIndex = differenceImageIt.GetIndex();
this->m_FixedImage->TransformIndexToPhysicalPoint( currentIndex, point );
/** if fixedMask is given */
if ( !this->m_FixedImageMask.IsNull() )
{
if ( this->m_FixedImageMask->IsInside( point ) )
{
sampleOK = true;
}
else
{
sampleOK = false;
}
}
if ( sampleOK )
{
/** setup the neighborhood iterator */
for ( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
neighborIndex[ iDimension ] = currentIndex[ iDimension ] - this->m_NeighborhoodRadius;
neighborIndex[ 2 ] = 0; // 2D only
}
neighboriterationRegion.SetIndex( neighborIndex );
DifferenceImageIteratorType neighborIt( this->m_DifferenceImageFilter->GetOutput(), neighboriterationRegion );
neighborIt.GoToBegin();
while ( !neighborIt.IsAtEnd() )
{
diff = differenceImageIt.Value() - neighborIt.Value();
measure += ( this->m_NoiseConstant )/( this->m_NoiseConstant + ( diff * diff ) );
++neighborIt;
} // end while neighborIt
} // end if sampleOK
++differenceImageIt;
} // end while differenceImageIt
return measure;
} // end ComputePIDiff()
/**
* ********************* GetValue ******************************
*/
template <class TFixedImage, class TMovingImage>
typename PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>::MeasureType
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::GetValue( const TransformParametersType & parameters ) const
{
this->SetTransformParameters( parameters );
this->m_TransformMovingImageFilter->Modified();
this->m_DifferenceImageFilter->UpdateLargestPossibleRegion();
MeasureType measure = 1e10;
MeasureType currentMeasure = 1e10;
if ( this->m_OptimizeNormalizationFactor )
{
float tmpfactor = 0.0;
float factorstep = ( this->m_NormalizationFactor * 10 - tmpfactor ) / 100;
float bestfactor = tmpfactor;
MeasureType tmpMeasure = 1e10;
while ( tmpfactor <= this->m_NormalizationFactor * 1.0 )
{
measure = this->ComputePIDiff( parameters, tmpfactor );
tmpMeasure = ( measure - this->m_FixedMeasure ) / - this->m_Rescalingfactor;
if( tmpMeasure < currentMeasure )
{
currentMeasure = tmpMeasure;
bestfactor = tmpfactor;
}
tmpfactor += factorstep;
}
}
else
{
measure = this->ComputePIDiff( parameters, this->m_NormalizationFactor );
currentMeasure = -( measure - this->m_FixedMeasure ) / this->m_Rescalingfactor;
}
return currentMeasure;
} // end GetValue()
/**
* ********************* GetDerivative ******************************
*/
template < class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::GetDerivative( const TransformParametersType & parameters,
DerivativeType & derivative ) const
{
TransformParametersType testPoint;
testPoint = parameters;
const unsigned int numberOfParameters = this->GetNumberOfParameters();
derivative = DerivativeType( numberOfParameters );
for ( unsigned int i = 0; i < numberOfParameters; i++ )
{
testPoint[ i ] -= this->m_DerivativeDelta / vcl_sqrt( this->m_Scales[ i ] );
const MeasureType valuep0 = this->GetValue( testPoint );
testPoint[ i ] += 2 * this->m_DerivativeDelta / vcl_sqrt( this->m_Scales[ i ] );
const MeasureType valuep1 = this->GetValue( testPoint );
derivative[ i ] = ( valuep1 - valuep0 ) / ( 2 * this->m_DerivativeDelta / vcl_sqrt( this->m_Scales[ i ] ) );
testPoint[ i ] = parameters[ i ];
}
} // end GetDerivative()
/**
* ********************* GetValueAndDerivative ******************************
*/
template <class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::GetValueAndDerivative( const TransformParametersType & parameters,
MeasureType & Value, DerivativeType & derivative ) const
{
Value = this->GetValue( parameters );
this->GetDerivative( parameters, derivative );
} // end GetValueAndDerivative()
} // end namespace itk
#endif // end __itkPatternIntensityImageToImageMetric_txx
<commit_msg>Bug fix<commit_after>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkPatternIntensityImageToImageMetric_txx
#define __itkPatternIntensityImageToImageMetric_txx
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkNumericTraits.h"
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include "itkSimpleFilterWatcher.h"
#include "itkImageFileWriter.h"
namespace itk
{
/**
* ********************* Constructor ******************************
*/
template <class TFixedImage, class TMovingImage>
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::PatternIntensityImageToImageMetric()
{
this->m_NormalizationFactor = 1.0;
this->m_Rescalingfactor = 1.0;
this->m_DerivativeDelta = 0.001;
this->m_NoiseConstant = 10000; // = sigma * sigma = 100*100 if not specified
this->m_NeighborhoodRadius = 3;
this->m_FixedMeasure = 0;
this->m_OptimizeNormalizationFactor = false;
this->m_TransformMovingImageFilter = TransformMovingImageFilterType::New();
this->m_CombinationTransform = CombinationTransformType::New();
this->m_RescaleImageFilter = RescaleIntensityImageFilterType::New();
this->m_DifferenceImageFilter = DifferenceImageFilterType::New();
this->m_MultiplyByConstantImageFilter = MultiplyByConstantImageFilterType::New();
} // end Constructor
/**
* ********************* Initialize ******************************
*/
template <class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::Initialize( void ) throw ( ExceptionObject )
{
Superclass::Initialize();
/* resampling for 3D->2D */
this->m_TransformMovingImageFilter->SetTransform(
dynamic_cast<CombinationTransformType *>(
dynamic_cast<RayCastInterpolatorType *>(
const_cast< InterpolatorType *>( ( this->GetInterpolator() ) ) )->GetTransform() ) );
this->m_TransformMovingImageFilter->SetInterpolator( this->m_Interpolator );
this->m_TransformMovingImageFilter->SetInput( this->m_MovingImage );
this->m_TransformMovingImageFilter->SetDefaultPixelValue( 0 );
this->m_TransformMovingImageFilter->SetSize(
this->m_FixedImage->GetLargestPossibleRegion().GetSize() );
this->m_TransformMovingImageFilter->SetOutputOrigin(
this->m_FixedImage->GetOrigin() );
this->m_TransformMovingImageFilter->SetOutputSpacing(
this->m_FixedImage->GetSpacing() );
this->m_TransformMovingImageFilter->SetOutputDirection(
this->m_FixedImage->GetDirection() );
this->m_TransformMovingImageFilter->UpdateLargestPossibleRegion();
this->ComputeFixedImageExtrema(
this->GetFixedImage(), this->GetFixedImageRegion() );
this->ComputeMovingImageExtrema(
this->m_TransformMovingImageFilter->GetOutput(),
this->m_TransformMovingImageFilter->GetOutput()->GetBufferedRegion() );
this->m_NormalizationFactor = this->m_FixedImageTrueMax / this->m_MovingImageTrueMax;
this->m_MultiplyByConstantImageFilter->SetInput(
this->m_TransformMovingImageFilter->GetOutput() );
this->m_MultiplyByConstantImageFilter->SetConstant(
this->m_NormalizationFactor );
this->m_DifferenceImageFilter->SetInput1( this->m_FixedImage );
this->m_DifferenceImageFilter->SetInput2( this->m_MultiplyByConstantImageFilter->GetOutput() );
this->m_DifferenceImageFilter->UpdateLargestPossibleRegion();
this->m_FixedMeasure = this->ComputePIFixed();
/* to rescale the similarity measure between 0-1;*/
MeasureType tmpmeasure = this->GetValue( this->m_Transform->GetParameters() );
while ( ( fabs( tmpmeasure ) / this->m_Rescalingfactor ) > 1 )
{
this->m_Rescalingfactor *= 10;
}
} // end Initialize()
/**
* ********************* Constructor ******************************PrintSelf
*/
template <class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::PrintSelf( std::ostream& os, Indent indent ) const
{
Superclass::PrintSelf( os, indent );
os << indent << "DerivativeDelta: " << this->m_DerivativeDelta << std::endl;
}
/**
* ********************* ComputePIFixed ******************************
*/
template <class TFixedImage, class TMovingImage>
typename PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>::MeasureType
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::ComputePIFixed( ) const
{
unsigned int iDimension;
MeasureType measure = NumericTraits< MeasureType >::Zero;
MeasureType diff = NumericTraits< MeasureType >::Zero;
typename FixedImageType::SizeType iterationSize =
this->m_FixedImage->GetLargestPossibleRegion().GetSize();
typename FixedImageType::IndexType iterationStartIndex, currentIndex, neighborIndex;
typename FixedImageType::SizeType neighborIterationSize;
typename FixedImageType::PointType point;
for( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
iterationSize[ iDimension ] -= static_cast<int>( 2 * this->m_NeighborhoodRadius );
iterationStartIndex[ iDimension ] = static_cast<int>( this->m_NeighborhoodRadius );
neighborIterationSize[ iDimension ] = static_cast<int>(2 * this->m_NeighborhoodRadius) + 1;
}
/** replace this by checking the size of the 3rd dimension of fixedimage */
iterationSize[ 2 ] = neighborIterationSize[ 2 ] = 1;
iterationStartIndex[ 2 ] = 0;
typename FixedImageType::RegionType iterationRegion, neighboriterationRegion;
iterationRegion.SetIndex( iterationStartIndex );
iterationRegion.SetSize( iterationSize );
typedef itk::ImageRegionConstIteratorWithIndex< FixedImageType > FixedImageTypeIteratorType;
FixedImageTypeIteratorType fixedImageIt( this->m_FixedImage, iterationRegion );
fixedImageIt.GoToBegin();
neighboriterationRegion.SetSize( neighborIterationSize );
bool sampleOK = false;
if ( this->m_FixedImageMask.IsNull() )
sampleOK = true;
while ( !fixedImageIt.IsAtEnd() )
{
/** Get current index */
currentIndex = fixedImageIt.GetIndex();
this->m_FixedImage->TransformIndexToPhysicalPoint( currentIndex, point );
/** if fixedMask is given */
if ( !this->m_FixedImageMask.IsNull() )
{
if ( this->m_FixedImageMask->IsInside( point ) )
sampleOK = true;
else
sampleOK = false;
}
if( sampleOK )
{
/** setup the neighborhood iterator */
for( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
neighborIndex[ iDimension ] = currentIndex[ iDimension ] - this->m_NeighborhoodRadius;
neighborIndex[ 2 ] = 0; // 2D only
}
neighboriterationRegion.SetIndex( neighborIndex );
FixedImageTypeIteratorType neighborIt( this->m_FixedImage, neighboriterationRegion );
neighborIt.GoToBegin();
while ( ! neighborIt.IsAtEnd() )
{
diff = fixedImageIt.Value() - neighborIt.Value();
measure += ( this->m_NoiseConstant )/( this->m_NoiseConstant + ( diff ) * ( diff ) );
++neighborIt;
} // end while neighborIt
} // end if sampleOK
++fixedImageIt;
} //end while fixedImageIt
return measure;
}
/**
* ********************* ComputePIDiff ******************************
*/
template <class TFixedImage, class TMovingImage>
typename PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>::MeasureType
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::ComputePIDiff( const TransformParametersType & parameters, float scalingfactor ) const
{
unsigned int iDimension;
this->SetTransformParameters( parameters );
this->m_TransformMovingImageFilter->Modified();
this->m_MultiplyByConstantImageFilter->SetConstant( scalingfactor );
this->m_DifferenceImageFilter->UpdateLargestPossibleRegion();
MeasureType measure = NumericTraits< MeasureType >::Zero;
MeasureType diff = NumericTraits< MeasureType >::Zero;
typename FixedImageType::SizeType iterationSize = this->m_FixedImage->GetLargestPossibleRegion().GetSize();
typename FixedImageType::IndexType iterationStartIndex, currentIndex, neighborIndex;
typename FixedImageType::SizeType neighborIterationSize;
typename FixedImageType::PointType point;
for( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
iterationSize[iDimension] -= static_cast<int>( 2 * this->m_NeighborhoodRadius );
iterationStartIndex[iDimension] = static_cast<int>( this->m_NeighborhoodRadius );
neighborIterationSize[iDimension] = static_cast<int>( 2 * this->m_NeighborhoodRadius + 1 );
}
/** 3rd Dimension is 1 */
iterationSize[ 2 ] = neighborIterationSize[ 2 ] = 1;
iterationStartIndex[ 2 ] = 0;
typename FixedImageType::RegionType iterationRegion, neighboriterationRegion;
iterationRegion.SetIndex( iterationStartIndex );
iterationRegion.SetSize( iterationSize );
typedef itk::ImageRegionConstIteratorWithIndex< TransformedMovingImageType > DifferenceImageIteratorType;
DifferenceImageIteratorType differenceImageIt( this->m_DifferenceImageFilter->GetOutput(), iterationRegion );
differenceImageIt.GoToBegin();
neighboriterationRegion.SetSize( neighborIterationSize );
bool sampleOK = false;
if ( this->m_FixedImageMask.IsNull() )
sampleOK = true;
while ( !differenceImageIt.IsAtEnd() )
{
/** Get current index */
currentIndex = differenceImageIt.GetIndex();
this->m_FixedImage->TransformIndexToPhysicalPoint( currentIndex, point );
/** if fixedMask is given */
if ( !this->m_FixedImageMask.IsNull() )
{
if ( this->m_FixedImageMask->IsInside( point ) )
sampleOK = true;
else
sampleOK = false;
}
if( sampleOK )
{
/** setup the neighborhood iterator */
for ( iDimension = 0; iDimension < this->m_FixedImage->GetImageDimension(); iDimension++ )
{
neighborIndex[ iDimension ] = currentIndex[ iDimension ] - this->m_NeighborhoodRadius;
neighborIndex[ 2] = 0; // 2D only
}
neighboriterationRegion.SetIndex( neighborIndex );
DifferenceImageIteratorType neighborIt( this->m_DifferenceImageFilter->GetOutput(), neighboriterationRegion );
neighborIt.GoToBegin();
while ( !neighborIt.IsAtEnd() )
{
diff = differenceImageIt.Value() - neighborIt.Value();
measure += ( this->m_NoiseConstant )/( this->m_NoiseConstant + ( ( diff ) * ( diff ) ) );
++neighborIt;
} // end while neighborIt
} // end if sampleOK
++differenceImageIt;
} // end while differenceImageIt
return measure;
}
/**
* ********************* GetValue ******************************
*/
template <class TFixedImage, class TMovingImage>
typename PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>::MeasureType
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::GetValue( const TransformParametersType & parameters ) const
{
this->SetTransformParameters( parameters );
this->m_TransformMovingImageFilter->Modified();
this->m_DifferenceImageFilter->UpdateLargestPossibleRegion();
MeasureType measure = 1e10;
MeasureType currentMeasure = 1e10;
if ( this->m_OptimizeNormalizationFactor )
{
float tmpfactor = 0.0;
float factorstep = ( this->m_NormalizationFactor * 10 - tmpfactor ) / 100;
float bestfactor = tmpfactor;
MeasureType tmpMeasure = 1e10;
while ( tmpfactor <= this->m_NormalizationFactor * 1.0 )
{
measure = this->ComputePIDiff( parameters, tmpfactor );
tmpMeasure = ( measure - this->m_FixedMeasure ) / - this->m_Rescalingfactor;
if( tmpMeasure < currentMeasure )
{
currentMeasure = tmpMeasure;
bestfactor = tmpfactor;
}
tmpfactor += factorstep;
}
}
else
{
measure = this->ComputePIDiff( parameters, this->m_NormalizationFactor );
currentMeasure = -( measure - this->m_FixedMeasure ) / this->m_Rescalingfactor;
}
return currentMeasure;
}
/**
* ********************* GetDerivative ******************************
*/
template < class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::GetDerivative( const TransformParametersType & parameters,
DerivativeType & derivative ) const
{
TransformParametersType testPoint;
testPoint = parameters;
const unsigned int numberOfParameters = this->GetNumberOfParameters();
derivative = DerivativeType( numberOfParameters );
for ( unsigned int i = 0; i < numberOfParameters; i++ )
{
testPoint[ i ] -= this->m_DerivativeDelta / sqrt( this->m_Scales[ i ] );
const MeasureType valuep0 = this->GetValue( testPoint );
testPoint[ i ] += 2* this->m_DerivativeDelta / sqrt( this->m_Scales[ i ] );
const MeasureType valuep1 = this->GetValue( testPoint );
derivative[ i ] = ( valuep1 - valuep0 ) / ( 2 * this->m_DerivativeDelta / sqrt( this->m_Scales[ i ] ) );
testPoint[ i ] = parameters[ i ];
}
}
/**
* ********************* GetValueAndDerivative ******************************
*/
template <class TFixedImage, class TMovingImage>
void
PatternIntensityImageToImageMetric<TFixedImage,TMovingImage>
::GetValueAndDerivative( const TransformParametersType & parameters,
MeasureType & Value, DerivativeType & Derivative ) const
{
Value = this->GetValue( parameters );
this->GetDerivative( parameters, Derivative );
}
} // end namespace itk
#endif // end __itkPatternIntensityImageToImageMetric_txx
<|endoftext|>
|
<commit_before>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* 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 */
// <h1>FEMSystem Example 1 - Unsteady Navier-Stokes Equations with
// FEMSystem</h1>
//
// This example shows how the transient nonlinear problem from
// example 13 can be solved using the
// DifferentiableSystem class framework
// C++ includes
#include <iomanip>
// Basic include files
#include "libmesh/equation_systems.h"
#include "libmesh/error_vector.h"
#include "libmesh/getpot.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_refinement.h"
#include "libmesh/uniform_refinement_estimator.h"
// The systems and solvers we may use
#include "naviersystem.h"
#include "libmesh/diff_solver.h"
#include "libmesh/euler_solver.h"
#include "libmesh/steady_solver.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// The main program.
int main (int argc, char** argv)
{
// Initialize libMesh.
LibMeshInit init (argc, argv);
// This example fails without at least double precision FP
#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
libmesh_example_assert(false, "--disable-singleprecision");
#endif
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Trilinos solver NaNs by default on the zero pressure block.
// We'll skip this example for now.
if (libMesh::default_solver_package() == TRILINOS_SOLVERS)
{
std::cout << "We skip example 18 when using the Trilinos solvers.\n"
<< std::endl;
return 0;
}
// Parse the input file
GetPot infile("fem_system_ex1.in");
// Read in parameters from the input file
const Real global_tolerance = infile("global_tolerance", 0.);
const unsigned int nelem_target = infile("n_elements", 400);
const bool transient = infile("transient", true);
const Real deltat = infile("deltat", 0.005);
unsigned int n_timesteps = infile("n_timesteps", 20);
const unsigned int write_interval = infile("write_interval", 5);
const unsigned int coarsegridsize = infile("coarsegridsize", 1);
const unsigned int coarserefinements = infile("coarserefinements", 0);
const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10);
const unsigned int dim = infile("dimension", 2);
// Skip higher-dimensional examples on a lower-dimensional libMesh build
libmesh_example_assert(dim <= LIBMESH_DIM, "2D/3D support");
// We have only defined 2 and 3 dimensional problems
libmesh_assert (dim == 2 || dim == 3);
// Create a mesh.
Mesh mesh;
// And an object to refine it
MeshRefinement mesh_refinement(mesh);
mesh_refinement.coarsen_by_parents() = true;
mesh_refinement.absolute_global_tolerance() = global_tolerance;
mesh_refinement.nelem_target() = nelem_target;
mesh_refinement.refine_fraction() = 0.3;
mesh_refinement.coarsen_fraction() = 0.3;
mesh_refinement.coarsen_threshold() = 0.1;
// Use the MeshTools::Generation mesh generator to create a uniform
// grid on the square [-1,1]^D. We instruct the mesh generator
// to build a mesh of 8x8 \p Quad9 elements in 2D, or \p Hex27
// elements in 3D. Building these higher-order elements allows
// us to use higher-order approximation, as in example 3.
if (dim == 2)
MeshTools::Generation::build_square (mesh,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
QUAD9);
else if (dim == 3)
MeshTools::Generation::build_cube (mesh,
coarsegridsize,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
0., 1.,
HEX27);
mesh_refinement.uniformly_refine(coarserefinements);
// Print information about the mesh to the screen.
mesh.print_info();
// Create an equation systems object.
EquationSystems equation_systems (mesh);
// Declare the system "Navier-Stokes" and its variables.
NavierSystem & system =
equation_systems.add_system<NavierSystem> ("Navier-Stokes");
// Solve this as a time-dependent or steady system
if (transient)
system.time_solver =
AutoPtr<TimeSolver>(new EulerSolver(system));
else
{
system.time_solver =
AutoPtr<TimeSolver>(new SteadySolver(system));
libmesh_assert_equal_to (n_timesteps, 1);
}
// Initialize the system
equation_systems.init ();
// Set the time stepping options
system.deltat = deltat;
// And the nonlinear solver options
DiffSolver &solver = *(system.time_solver->diff_solver().get());
solver.quiet = infile("solver_quiet", true);
solver.verbose = !solver.quiet;
solver.max_nonlinear_iterations =
infile("max_nonlinear_iterations", 15);
solver.relative_step_tolerance =
infile("relative_step_tolerance", 1.e-3);
solver.relative_residual_tolerance =
infile("relative_residual_tolerance", 0.0);
solver.absolute_residual_tolerance =
infile("absolute_residual_tolerance", 0.0);
// And the linear solver options
solver.max_linear_iterations =
infile("max_linear_iterations", 50000);
solver.initial_linear_tolerance =
infile("initial_linear_tolerance", 1.e-3);
// Print information about the system to the screen.
equation_systems.print_info();
// Now we begin the timestep loop to compute the time-accurate
// solution of the equations.
for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
{
// A pretty update message
std::cout << "\n\nSolving time step " << t_step << ", time = "
<< system.time << std::endl;
// Adaptively solve the timestep
unsigned int a_step = 0;
for (; a_step != max_adaptivesteps; ++a_step)
{
system.solve();
system.postprocess();
ErrorVector error;
AutoPtr<ErrorEstimator> error_estimator;
// To solve to a tolerance in this problem we
// need a better estimator than Kelly
if (global_tolerance != 0.)
{
// We can't adapt to both a tolerance and a mesh
// size at once
libmesh_assert_equal_to (nelem_target, 0);
UniformRefinementEstimator *u =
new UniformRefinementEstimator;
// The lid-driven cavity problem isn't in H1, so
// lets estimate L2 error
u->error_norm = L2;
error_estimator.reset(u);
}
else
{
// If we aren't adapting to a tolerance we need a
// target mesh size
libmesh_assert_greater (nelem_target, 0);
// Kelly is a lousy estimator to use for a problem
// not in H1 - if we were doing more than a few
// timesteps we'd need to turn off or limit the
// maximum level of our adaptivity eventually
error_estimator.reset(new KellyErrorEstimator);
}
// Calculate error based on u and v (and w?) but not p
std::vector<Real> weights(2,1.0); // u, v
if (dim == 3)
weights.push_back(1.0); // w
weights.push_back(0.0); // p
// Keep the same default norm type.
std::vector<FEMNormType>
norms(1, error_estimator->error_norm.type(0));
error_estimator->error_norm = SystemNorm(norms, weights);
error_estimator->estimate_error(system, error);
// Print out status at each adaptive step.
Real global_error = error.l2_norm();
std::cout << "Adaptive step " << a_step << ": " << std::endl;
if (global_tolerance != 0.)
std::cout << "Global_error = " << global_error
<< std::endl;
if (global_tolerance != 0.)
std::cout << "Worst element error = " << error.maximum()
<< ", mean = " << error.mean() << std::endl;
if (global_tolerance != 0.)
{
// If we've reached our desired tolerance, we
// don't need any more adaptive steps
if (global_error < global_tolerance)
break;
mesh_refinement.flag_elements_by_error_tolerance(error);
}
else
{
// If flag_elements_by_nelem_target returns true, this
// should be our last adaptive step.
if (mesh_refinement.flag_elements_by_nelem_target(error))
{
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
a_step = max_adaptivesteps;
break;
}
}
// Carry out the adaptive mesh refinement/coarsening
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
std::cout << "Refined mesh to "
<< mesh.n_active_elem()
<< " active elements and "
<< equation_systems.n_active_dofs()
<< " active dofs." << std::endl;
}
// Do one last solve if necessary
if (a_step == max_adaptivesteps)
{
system.solve();
system.postprocess();
}
// Advance to the next timestep in a transient problem
system.time_solver->advance_timestep();
#ifdef LIBMESH_HAVE_EXODUS_API
// Write out this timestep if we're requested to
if ((t_step+1)%write_interval == 0)
{
std::ostringstream file_name;
// We write the file in the ExodusII format.
file_name << "out_"
<< std::setw(3)
<< std::setfill('0')
<< std::right
<< t_step+1
<< ".e";
ExodusII_IO(mesh).write_timestep(file_name.str(),
equation_systems,
1, /* This number indicates how many time steps
are being written to the file */
system.time);
}
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
}
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done.
return 0;
}
<commit_msg>Fix anachronistic example name in message<commit_after>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* 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 */
// <h1>FEMSystem Example 1 - Unsteady Navier-Stokes Equations with
// FEMSystem</h1>
//
// This example shows how the transient nonlinear problem from
// example 13 can be solved using the
// DifferentiableSystem class framework
// C++ includes
#include <iomanip>
// Basic include files
#include "libmesh/equation_systems.h"
#include "libmesh/error_vector.h"
#include "libmesh/getpot.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_refinement.h"
#include "libmesh/uniform_refinement_estimator.h"
// The systems and solvers we may use
#include "naviersystem.h"
#include "libmesh/diff_solver.h"
#include "libmesh/euler_solver.h"
#include "libmesh/steady_solver.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// The main program.
int main (int argc, char** argv)
{
// Initialize libMesh.
LibMeshInit init (argc, argv);
// This example fails without at least double precision FP
#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
libmesh_example_assert(false, "--disable-singleprecision");
#endif
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Trilinos solver NaNs by default on the zero pressure block.
// We'll skip this example for now.
if (libMesh::default_solver_package() == TRILINOS_SOLVERS)
{
std::cout << "We skip fem_system_ex1 when using the Trilinos solvers.\n"
<< std::endl;
return 0;
}
// Parse the input file
GetPot infile("fem_system_ex1.in");
// Read in parameters from the input file
const Real global_tolerance = infile("global_tolerance", 0.);
const unsigned int nelem_target = infile("n_elements", 400);
const bool transient = infile("transient", true);
const Real deltat = infile("deltat", 0.005);
unsigned int n_timesteps = infile("n_timesteps", 20);
const unsigned int write_interval = infile("write_interval", 5);
const unsigned int coarsegridsize = infile("coarsegridsize", 1);
const unsigned int coarserefinements = infile("coarserefinements", 0);
const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10);
const unsigned int dim = infile("dimension", 2);
// Skip higher-dimensional examples on a lower-dimensional libMesh build
libmesh_example_assert(dim <= LIBMESH_DIM, "2D/3D support");
// We have only defined 2 and 3 dimensional problems
libmesh_assert (dim == 2 || dim == 3);
// Create a mesh.
Mesh mesh;
// And an object to refine it
MeshRefinement mesh_refinement(mesh);
mesh_refinement.coarsen_by_parents() = true;
mesh_refinement.absolute_global_tolerance() = global_tolerance;
mesh_refinement.nelem_target() = nelem_target;
mesh_refinement.refine_fraction() = 0.3;
mesh_refinement.coarsen_fraction() = 0.3;
mesh_refinement.coarsen_threshold() = 0.1;
// Use the MeshTools::Generation mesh generator to create a uniform
// grid on the square [-1,1]^D. We instruct the mesh generator
// to build a mesh of 8x8 \p Quad9 elements in 2D, or \p Hex27
// elements in 3D. Building these higher-order elements allows
// us to use higher-order approximation, as in example 3.
if (dim == 2)
MeshTools::Generation::build_square (mesh,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
QUAD9);
else if (dim == 3)
MeshTools::Generation::build_cube (mesh,
coarsegridsize,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
0., 1.,
HEX27);
mesh_refinement.uniformly_refine(coarserefinements);
// Print information about the mesh to the screen.
mesh.print_info();
// Create an equation systems object.
EquationSystems equation_systems (mesh);
// Declare the system "Navier-Stokes" and its variables.
NavierSystem & system =
equation_systems.add_system<NavierSystem> ("Navier-Stokes");
// Solve this as a time-dependent or steady system
if (transient)
system.time_solver =
AutoPtr<TimeSolver>(new EulerSolver(system));
else
{
system.time_solver =
AutoPtr<TimeSolver>(new SteadySolver(system));
libmesh_assert_equal_to (n_timesteps, 1);
}
// Initialize the system
equation_systems.init ();
// Set the time stepping options
system.deltat = deltat;
// And the nonlinear solver options
DiffSolver &solver = *(system.time_solver->diff_solver().get());
solver.quiet = infile("solver_quiet", true);
solver.verbose = !solver.quiet;
solver.max_nonlinear_iterations =
infile("max_nonlinear_iterations", 15);
solver.relative_step_tolerance =
infile("relative_step_tolerance", 1.e-3);
solver.relative_residual_tolerance =
infile("relative_residual_tolerance", 0.0);
solver.absolute_residual_tolerance =
infile("absolute_residual_tolerance", 0.0);
// And the linear solver options
solver.max_linear_iterations =
infile("max_linear_iterations", 50000);
solver.initial_linear_tolerance =
infile("initial_linear_tolerance", 1.e-3);
// Print information about the system to the screen.
equation_systems.print_info();
// Now we begin the timestep loop to compute the time-accurate
// solution of the equations.
for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
{
// A pretty update message
std::cout << "\n\nSolving time step " << t_step << ", time = "
<< system.time << std::endl;
// Adaptively solve the timestep
unsigned int a_step = 0;
for (; a_step != max_adaptivesteps; ++a_step)
{
system.solve();
system.postprocess();
ErrorVector error;
AutoPtr<ErrorEstimator> error_estimator;
// To solve to a tolerance in this problem we
// need a better estimator than Kelly
if (global_tolerance != 0.)
{
// We can't adapt to both a tolerance and a mesh
// size at once
libmesh_assert_equal_to (nelem_target, 0);
UniformRefinementEstimator *u =
new UniformRefinementEstimator;
// The lid-driven cavity problem isn't in H1, so
// lets estimate L2 error
u->error_norm = L2;
error_estimator.reset(u);
}
else
{
// If we aren't adapting to a tolerance we need a
// target mesh size
libmesh_assert_greater (nelem_target, 0);
// Kelly is a lousy estimator to use for a problem
// not in H1 - if we were doing more than a few
// timesteps we'd need to turn off or limit the
// maximum level of our adaptivity eventually
error_estimator.reset(new KellyErrorEstimator);
}
// Calculate error based on u and v (and w?) but not p
std::vector<Real> weights(2,1.0); // u, v
if (dim == 3)
weights.push_back(1.0); // w
weights.push_back(0.0); // p
// Keep the same default norm type.
std::vector<FEMNormType>
norms(1, error_estimator->error_norm.type(0));
error_estimator->error_norm = SystemNorm(norms, weights);
error_estimator->estimate_error(system, error);
// Print out status at each adaptive step.
Real global_error = error.l2_norm();
std::cout << "Adaptive step " << a_step << ": " << std::endl;
if (global_tolerance != 0.)
std::cout << "Global_error = " << global_error
<< std::endl;
if (global_tolerance != 0.)
std::cout << "Worst element error = " << error.maximum()
<< ", mean = " << error.mean() << std::endl;
if (global_tolerance != 0.)
{
// If we've reached our desired tolerance, we
// don't need any more adaptive steps
if (global_error < global_tolerance)
break;
mesh_refinement.flag_elements_by_error_tolerance(error);
}
else
{
// If flag_elements_by_nelem_target returns true, this
// should be our last adaptive step.
if (mesh_refinement.flag_elements_by_nelem_target(error))
{
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
a_step = max_adaptivesteps;
break;
}
}
// Carry out the adaptive mesh refinement/coarsening
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
std::cout << "Refined mesh to "
<< mesh.n_active_elem()
<< " active elements and "
<< equation_systems.n_active_dofs()
<< " active dofs." << std::endl;
}
// Do one last solve if necessary
if (a_step == max_adaptivesteps)
{
system.solve();
system.postprocess();
}
// Advance to the next timestep in a transient problem
system.time_solver->advance_timestep();
#ifdef LIBMESH_HAVE_EXODUS_API
// Write out this timestep if we're requested to
if ((t_step+1)%write_interval == 0)
{
std::ostringstream file_name;
// We write the file in the ExodusII format.
file_name << "out_"
<< std::setw(3)
<< std::setfill('0')
<< std::right
<< t_step+1
<< ".e";
ExodusII_IO(mesh).write_timestep(file_name.str(),
equation_systems,
1, /* This number indicates how many time steps
are being written to the file */
system.time);
}
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
}
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done.
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright DaiMysha (c) 2015, All rights reserved.
DaiMysha@gmail.com
https://github.com/DaiMysha
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <LightSystem/ShadowSystem.hpp>
#include <LightSystem/Light.hpp>
#include <DMUtils/sfml.hpp>
namespace DMGDVT {
namespace LS {
void ShadowSystem::addWall(const sf::ConvexShape& shape) {
_walls.emplace_back(shape);
}
const std::list<sf::ConvexShape> ShadowSystem::getWalls() const {
return _walls;
}
void ShadowSystem::clear() {
_walls.clear();
}
void ShadowSystem::draw(const sf::View& screenView, sf::RenderTarget& target) {
sf::Vertex points[2];
points[0].color = sf::Color(180,180,180);
points[1].color = points[0].color;
for(const sf::ConvexShape& s : _walls) {
for(size_t i = 0;i<s.getPointCount();++i) {
points[0].position = s.getPoint(i);
points[1].position = s.getPoint((i+1)%s.getPointCount());
target.draw(points,2,sf::Lines);
}
}
}
void ShadowSystem::castShadowsFromPoint(const sf::Vector2f& origin, const std::list<sf::ConvexShape>& walls, const sf::FloatRect& screenRect, std::list<sf::ConvexShape>& result) {
sf::ConvexShape screen;
screen.setPointCount(5);
screen.setPoint(0,sf::Vector2f(screenRect.left,screenRect.top));
screen.setPoint(1,sf::Vector2f(screenRect.left + screenRect.width,screenRect.top));
screen.setPoint(2,sf::Vector2f(screenRect.left + screenRect.width,screenRect.top+screenRect.height));
screen.setPoint(3,sf::Vector2f(screenRect.left,screenRect.top+screenRect.height));
screen.setPoint(4,screen.getPoint(0));
for(const sf::ConvexShape& s : walls) {
std::list<int> resultPointsList;
std::vector<bool> visiblePoints;
int size = s.getPointCount();
if(size < 3) continue;
visiblePoints.resize(size,false);
int closest = 0;
float distClosest = dist(origin,s.getPoint(closest));
for(int i=1;i<size;++i) {
float d = dist(origin,s.getPoint(i));
if(d < distClosest) {
distClosest = d;
closest = i;
}
}
resultPointsList.emplace_back(closest);
visiblePoints[closest] = true;
bool visible = true;
sf::Vector2f tmp;
bool goRight = true;
bool goLeft = true;
int id = (closest - 1 + size)%size;
int id2 = (closest + 1) % size;
if(id >= 0) {
visible = isVisibleFrom(origin,s.getPoint(id2),s.getPoint(closest),s.getPoint(id),tmp);
if(visible) {
resultPointsList.emplace_back(id2);
visiblePoints[id2] = true;
}
goRight = visible;
}
if(id2 < size) {
visible = isVisibleFrom(origin,s.getPoint(id),s.getPoint(closest),s.getPoint(id2),tmp);
if(visible) {
resultPointsList.emplace_front(id);
visiblePoints[id] = true;
}
goLeft = visible;
}
if(goLeft) {
id = (closest - 2 + size)%size;
visible = true;
while(visible && id >= 0) {
auto it = resultPointsList.begin();
auto it2 = it++;
while(it != resultPointsList.end() && visible) {
if(id == *it || id == *it2) visible = false;
else visible = isVisibleFrom(origin,s.getPoint(id),s.getPoint(*it),s.getPoint(*it2),tmp);
if(visible) {
it2 = it++;
}
}
if(visible) {
visiblePoints[id] = true;
resultPointsList.emplace_front(id);
} else if(DMUtils::maths::abs(closest-id)<=1) {
visiblePoints[id] = false;
if(id != *it && id != *it2) {
resultPointsList.remove(id);
}
}
--id;
}
}
if(goRight) {
int id = (closest + 2) % size;
visible = true;
while(visible && id < size) {
auto it = resultPointsList.begin();
auto it2 = it++;
while(it != resultPointsList.end() && visible) {
if(id == *it || id == *it2) visible = false;
else visible = isVisibleFrom(origin,s.getPoint(id),s.getPoint(*it),s.getPoint(*it2),tmp);
if(visible) {
it2 = it++;
}
}
if(visible) {
visiblePoints[id] = true;
resultPointsList.emplace_back(id);
} else if(DMUtils::maths::abs(closest-id)<=1) {
visiblePoints[id] = false;
if(id != *it && id != *it2) {
resultPointsList.remove(id);
}
}
++id;
}
}
auto it = resultPointsList.begin();
auto it_prev = resultPointsList.end();
while(it != resultPointsList.end()) {
auto it2 = it;
++it2;
if(it2==resultPointsList.end()) it2 = resultPointsList.begin();
visible = true;
while(visible && it2 != resultPointsList.end()) {
auto it3 = it2++;
if(it2 == resultPointsList.end()) {
it2 = resultPointsList.begin();
}
if(DMUtils::maths::abs(*it2 - *it3) != 1 && !(*it2==0&&*it3==size-1) && !(*it3==0&&*it2==size-1)) {
continue;
}
if(it3 == it || it2 == it) {
break;
}
if(!isVisibleFrom(origin,s.getPoint(*it),s.getPoint(*it2),s.getPoint(*it3),tmp)) {
//found a collision, the thiing isn't visible
visible = false;
visiblePoints[*it] = false;
}
}
if(!visible) {
visiblePoints[*it] = false;
if(it_prev==resultPointsList.end()) {
resultPointsList.pop_front();
it = resultPointsList.begin();
} else {
resultPointsList.erase(it);
it = it_prev;
}
}
it_prev = it++;
}
//pushes edges
it = resultPointsList.begin();
while(it!=resultPointsList.end()) {
if(!visiblePoints[(*it+1)%size]) {
resultPointsList.erase(it);
resultPointsList.emplace_back(*it);
break;
}
++it;
}
it = resultPointsList.begin();
while(it!=resultPointsList.end()) {
if(!visiblePoints[(*it-1+size)%size]) {
resultPointsList.erase(it);
resultPointsList.emplace_front(*it);
break;
}
++it;
}
sf::Vector2f furtherLeft = s.getPoint(*resultPointsList.begin());
sf::Vector2f furtherRight = s.getPoint(*resultPointsList.rbegin());
sf::ConvexShape shapeResult;
//shapeResult.setFillColor(sf::Color(0,0,255,127));
shapeResult.setFillColor(sf::Color::Black);
shapeResult.setPointCount(resultPointsList.size()+2);
int shapeResult_vid = 0;
for(auto vid : resultPointsList) {
shapeResult.setPoint(1+shapeResult_vid++,s.getPoint(vid));
}
int closestToLeft=0;
int closestToRight=0;
//extrapolations
for(int i=0;i<5;++i) {
if(intersect(origin,furtherLeft-origin,screen.getPoint(i),screen.getPoint(i+1),tmp)) {
shapeResult.setPoint(0,tmp);
closestToLeft = i+1;
}
if(intersect(origin,furtherRight-origin,screen.getPoint(i),screen.getPoint(i+1),tmp)) {
shapeResult.setPoint(shapeResult.getPointCount()-1,tmp);
closestToRight = i+1;
}
}
//corners
if(!(furtherLeft.x <= screenRect.left && furtherRight.x <= screenRect.left) || (furtherLeft.x <= screenRect.left + screenRect.width && furtherRight.x <= screenRect.left + screenRect.width) ||
!(furtherLeft.y <= screenRect.top && furtherRight.y <= screenRect.top) || (furtherLeft.y <= screenRect.top + screenRect.height && furtherRight.y <= screenRect.top + screenRect.height)) {
closest = 0;
std::list<int> cornerList;
id = closestToLeft;
int i = 0;
while(i < 4) {
if(intersect(origin,screen.getPoint(id)-origin,furtherLeft,furtherRight,tmp)) {
cornerList.emplace_back(id);
}
id = (id+1)%4;
++i;
}
if(cornerList.size()) {
int ind = shapeResult.getPointCount();
shapeResult.setPointCount(shapeResult.getPointCount()+cornerList.size());
for(auto i : cornerList) {
shapeResult.setPoint(ind++,screen.getPoint(i));
}
}
}
result.emplace_back(shapeResult);
}
}
/*********** PRIVATE ***********/
float ShadowSystem::dist(const sf::Vector2f& a, const sf::Vector2f& b) {
return DMUtils::sfml::norm2(b-a);
}
bool ShadowSystem::isVisibleFrom(const sf::Vector2f& origin, const sf::Vector2f& target, const sf::Vector2f& s1, const sf::Vector2f& s2, sf::Vector2f& tmp) {
float d = intersect(origin,target-origin,s1,s2,tmp);
if(d==0.0f) return true;
d = DMUtils::sfml::norm2(target-origin)*d*d;
float d2 = dist(origin,target);
return d > d2;
}
float ShadowSystem::intersect(const sf::Vector2f& c, const sf::Vector2f& u, const sf::Vector2f& a, const sf::Vector2f& b, sf::Vector2f& result) {
float k1, k2;
if(u.x == 0.0f) {
float med = DMUtils::maths::abs(b.y + a.y) / 2.0f;
if(u.y * (med - c.y) < 0) {
return 0.0f;
}
if(c.x < DMUtils::maths::min(a.x,b.x) || c.x > DMUtils::maths::max(a.x,b.x)) {
return 0.0f;
}
result.x = c.x;
result.y = med;
return c.y - med;
}
k1 = ( u.x * (c.y - a.y) + u.y * (a.x - c.x) ) / ( u.x * (b.y - a.y) + u.y * (a.x - b.x) );
k2 = ( a.x + k1 * (b.x - a.x) - c.x ) / u.x;
if(k1 < 0 || k1 > 1 || k2 <= 0) return 0.0f;
result.x = c.x + k2 * u.x;
result.y = c.y + k2 * u.y;
return k2;
}
}
}
<commit_msg>New shadow algorithm, most efficient so far<commit_after>/*
Copyright DaiMysha (c) 2015, All rights reserved.
DaiMysha@gmail.com
https://github.com/DaiMysha
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <LightSystem/ShadowSystem.hpp>
#include <LightSystem/Light.hpp>
#include <DMUtils/sfml.hpp>
namespace DMGDVT {
namespace LS {
void ShadowSystem::addWall(const sf::ConvexShape& shape) {
_walls.emplace_back(shape);
}
const std::list<sf::ConvexShape> ShadowSystem::getWalls() const {
return _walls;
}
void ShadowSystem::clear() {
_walls.clear();
}
void ShadowSystem::draw(const sf::View& screenView, sf::RenderTarget& target) {
sf::Vertex points[2];
points[0].color = sf::Color(180,180,180);
points[1].color = points[0].color;
for(const sf::ConvexShape& s : _walls) {
for(size_t i = 0;i<s.getPointCount();++i) {
points[0].position = s.getPoint(i);
points[1].position = s.getPoint((i+1)%s.getPointCount());
target.draw(points,2,sf::Lines);
}
}
}
void ShadowSystem::castShadowsFromPoint(const sf::Vector2f& origin, const std::list<sf::ConvexShape>& walls, const sf::FloatRect& screenRect, std::list<sf::ConvexShape>& result) {
sf::ConvexShape screen;
screen.setPointCount(5);
screen.setPoint(0,sf::Vector2f(screenRect.left,screenRect.top));
screen.setPoint(1,sf::Vector2f(screenRect.left + screenRect.width,screenRect.top));
screen.setPoint(2,sf::Vector2f(screenRect.left + screenRect.width,screenRect.top+screenRect.height));
screen.setPoint(3,sf::Vector2f(screenRect.left,screenRect.top+screenRect.height));
screen.setPoint(4,screen.getPoint(0));
sf::Vector2f tmp;
for(const sf::ConvexShape& s : walls) {
const int size = s.getPointCount();
std::vector<bool> backFacing(size);
for (int i = 0; i < size; i++) {
sf::Vector2f firstVertex(s.getPoint(i).x, s.getPoint(i).y);
int secondIndex = (i + 1) % size;
sf::Vector2f secondVertex(s.getPoint(secondIndex).x, s.getPoint(secondIndex).y);
sf::Vector2f middle = (firstVertex + secondVertex);
middle.x /= 2;
middle.y /= 2;
sf::Vector2f u = origin - middle;
sf::Vector2f normal;
normal.x = - (secondVertex.y - firstVertex.y);
normal.y = secondVertex.x - firstVertex.x;
if (DMUtils::sfml::dot(normal,u) > 0)
backFacing[i] = false;
else
backFacing[i] = true;
}
int firstBoundaryIndex = 0;
int secondBoundaryIndex = 0;
for (int i = 0; i < size; i++)
{
int currentEdge = i;
int nextEdge = (i + 1) % size;
if (backFacing[currentEdge] && !backFacing[nextEdge])
firstBoundaryIndex = nextEdge;
if (!backFacing[currentEdge] && backFacing[nextEdge])
secondBoundaryIndex = nextEdge;
}
int shapeSize = 0;
if(secondBoundaryIndex < firstBoundaryIndex) {
shapeSize = DMUtils::maths::abs(secondBoundaryIndex - firstBoundaryIndex) + 1;
} else {
shapeSize = DMUtils::maths::abs(size - secondBoundaryIndex + firstBoundaryIndex) + 1;
}
if(shapeSize) {
sf::ConvexShape resultShape;
resultShape.setFillColor(sf::Color(0,0,255,127));
resultShape.setPointCount(shapeSize+2);
int id = 1;
int i = firstBoundaryIndex;
while(i != secondBoundaryIndex) {
resultShape.setPoint(id++,s.getPoint(i));
--i;
if(i<0) i+=size;
else if(i>size) i-=size;
}
resultShape.setPoint(id++,s.getPoint(secondBoundaryIndex));
int closestToLeft=0;
for(int i=0;i<5;++i) {
if(intersect(origin,s.getPoint(firstBoundaryIndex)-origin,screen.getPoint(i),screen.getPoint(i+1),tmp)) {
resultShape.setPoint(0,tmp);
closestToLeft = i+1;
}
if(intersect(origin,s.getPoint(secondBoundaryIndex)-origin,screen.getPoint(i),screen.getPoint(i+1),tmp)) {
resultShape.setPoint(resultShape.getPointCount()-1,tmp);
}
}
std::list<int> cornerList;
id = closestToLeft;
i = 0;
sf::Vector2f furtherLeft = resultShape.getPoint(0);
sf::Vector2f furtherRight = resultShape.getPoint(resultShape.getPointCount()-1);
while(i < 4) {
if(intersect(origin,screen.getPoint(id)-origin,furtherLeft,furtherRight,tmp)) {
cornerList.emplace_front(id);
}
id = (id+1)%4;
++i;
}
if(cornerList.size()) {
int ind = resultShape.getPointCount();
resultShape.setPointCount(resultShape.getPointCount()+cornerList.size());
for(auto i : cornerList) {
resultShape.setPoint(ind++,screen.getPoint(i));
}
}
result.emplace_back(resultShape);
} else {
std::cout << "Step = 0" << std::endl;
}
}
}
/*********** PRIVATE ***********/
float ShadowSystem::dist(const sf::Vector2f& a, const sf::Vector2f& b) {
return DMUtils::sfml::norm2(b-a);
}
bool ShadowSystem::isVisibleFrom(const sf::Vector2f& origin, const sf::Vector2f& target, const sf::Vector2f& s1, const sf::Vector2f& s2, sf::Vector2f& tmp) {
float d = intersect(origin,target-origin,s1,s2,tmp);
if(d==0.0f) return true;
d = DMUtils::sfml::norm2(target-origin)*d*d;
float d2 = dist(origin,target);
return d > d2;
}
float ShadowSystem::intersect(const sf::Vector2f& c, const sf::Vector2f& u, const sf::Vector2f& a, const sf::Vector2f& b, sf::Vector2f& result) {
float k1, k2;
if(u.x == 0.0f) {
float med = DMUtils::maths::abs(b.y + a.y) / 2.0f;
if(u.y * (med - c.y) < 0) {
return 0.0f;
}
if(c.x < DMUtils::maths::min(a.x,b.x) || c.x > DMUtils::maths::max(a.x,b.x)) {
return 0.0f;
}
result.x = c.x;
result.y = med;
return c.y - med;
}
k1 = ( u.x * (c.y - a.y) + u.y * (a.x - c.x) ) / ( u.x * (b.y - a.y) + u.y * (a.x - b.x) );
k2 = ( a.x + k1 * (b.x - a.x) - c.x ) / u.x;
if(k1 < 0 || k1 > 1 || k2 <= 0) return 0.0f;
result.x = c.x + k2 * u.x;
result.y = c.y + k2 * u.y;
return k2;
}
}
}
<|endoftext|>
|
<commit_before>#include <armadillo>
#include <iostream>
#include <string>
#include <fastlib/fx/io.h>
#include "svm.h"
#define BOOST_TEST_MODULE SVM test
#include <boost/test/unit_test.hpp>
PROGRAM_INFO("SVM Unit Test",
"This program tests various methods in the SVM implementation.", "svm");
using std::string;
using namespace mlpack;
// Create test data
arma::mat matrix(20,3);
bool first = true;
/***
*
*/
/*
BOOST_AUTO_TEST_CASE(test_test) {
double x = 1.0, y = 1.0, z = 2.0;
// We need to make sure someValue is 1.
BOOST_REQUIRE_CLOSE(x, y, 1e-5);
BOOST_REQUIRE_CLOSE(z, y, 1e-5);
}
*/
//IO::GetParam<>() = ;
/**
* Creates the data to train and test with and prints it to stdout.
* Should only have any effect once.
*/
void setup() {
if(!first)
return;
first = false;
IO::GetParam<bool>("svm/shrink") = true;
IO::GetParam<double>("svm/epsilon") = .1;
IO::GetParam<double>("svm/sigma") = 1;
// Protect the test from taking forever
//IO::GetParam<index_t>("svm/n_iter") = 10000;
matrix <<
7.19906628001437787e-01 << 1.83250823399634477e+00 << 0 << arma::endr <<
1.37899419263889733e+01 << 1.78198235122579263e+00 << 1 << arma::endr <<
6.68859485848275703e-01 << 2.14083320956715983e+00 << 0 << arma::endr <<
1.84729928795588165e+01 << 2.25024702760868101e+00 << 1 << arma::endr <<
9.22802773268335819e-01 << 1.61469358350834513e+00 << 0 << arma::endr <<
2.06209849662245204e-01 << 6.34699695340683490e-01 << 1 << arma::endr <<
4.01062068250524817e-01 << 1.65802752932441777e+00 << 0 << arma::endr <<
5.02985607135568635e+00 << 1.39976642741810831e+00 << 1 << arma::endr <<
3.66471199955079319e-01 << 1.62780588172739638e+00 << 0 << arma::endr <<
1.56912570240400999e+01 << 2.16941541650770953e+00 << 1 << arma::endr <<
9.98909584711729304e-01 << 2.00337906391517206e+00 << 0 << arma::endr <<
1.31430438780891912e+01 << 1.34410346059319719e+00 << 1 << arma::endr <<
3.41572957272442523e-01 << 1.16758463655951639e+00 << 0 << arma::endr <<
9.53941410851637528e-01 << 6.30271704462483373e-01 << 1 << arma::endr <<
7.07135529120981432e-01 << 2.17763537339756041e+00 << 0 << arma::endr <<
9.68899714280338742e+00 << 1.26922579378319256e+00 << 1 << arma::endr <<
9.82393905512240706e-01 << 2.36790583090293483e+00 << 0 << arma::endr <<
1.31583349281727973e+01 << 1.45115094722767868e+00 << 1 << arma::endr <<
3.80991188521027202e-01 << 9.05379134419085019e-01 << 0 << arma::endr <<
1.86057436180327755e+01 << 2.26941891469499968e+00 << 1 << arma::endr;
matrix = trans(matrix);
std::cout << matrix << std::endl;
}
/**
* Compares predicted values with known values to see if the prediction/training works.
*
* @param: learner_typeid Magic number for selecting between classification and
* regression.
* @param: data The dataset with the data to predict with.
* @param: svm The SVM class instance that has been trained for this data, et al.
*/
template<typename T>
void verify(index_t learner_typeid, Dataset& data, SVM<T>& svm) {
for(index_t i = 0; i < data.n_points(); i++) {
arma::vec testvec = data.matrix().col(i);
double predictedvalue = svm.Predict(learner_typeid, testvec);
BOOST_REQUIRE_CLOSE(predictedvalue,
data.matrix()(data.n_features()-1,i),1e-6);
}
}
/**
* Trains a classifier with a linear kernel and checks predictions against
* classes.
*/
BOOST_AUTO_TEST_CASE(svm_classification_linear_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMLinearKernel> svm;
svm.InitTrain(0,trainingdata); // 0 for classification
verify(0,trainingdata,svm);
}
/**
* Trains a classifier with a gaussian kernel and checks predictions against
* classes.
*/
BOOST_AUTO_TEST_CASE(svm_classification_gaussian_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMRBFKernel> svm;
svm.InitTrain(0,trainingdata); // 0 for classification
verify(0,trainingdata,svm);
}
/**
* Trains a classifier with a linear kernel and checks predictions against
* classes, using regression. TODO: BROKEN
*/
BOOST_AUTO_TEST_CASE(svm_regression_linear_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMLinearKernel> svm;
svm.InitTrain(1,trainingdata); // 0 for classification
//verify(1,trainingdata,svm);
}
/**
* Trains a classifier with a gaussian kernel and checks predictions against
* classes, using regression. TODO: BROKEN
*/
BOOST_AUTO_TEST_CASE(svm_regression_gaussian_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMRBFKernel> svm;
svm.InitTrain(1,trainingdata); // 0 for classification
//verify(1,trainingdata,svm);
}
<commit_msg>Limit to 10k iterations as opposed to 10M for the test.<commit_after>#include <armadillo>
#include <iostream>
#include <string>
#include <fastlib/fx/io.h>
#include "svm.h"
#define BOOST_TEST_MODULE SVM test
#include <boost/test/unit_test.hpp>
PROGRAM_INFO("SVM Unit Test",
"This program tests various methods in the SVM implementation.", "svm");
using std::string;
using namespace mlpack;
// Create test data
arma::mat matrix(20,3);
bool first = true;
/***
*
*/
/*
BOOST_AUTO_TEST_CASE(test_test) {
double x = 1.0, y = 1.0, z = 2.0;
// We need to make sure someValue is 1.
BOOST_REQUIRE_CLOSE(x, y, 1e-5);
BOOST_REQUIRE_CLOSE(z, y, 1e-5);
}
*/
//IO::GetParam<>() = ;
/**
* Creates the data to train and test with and prints it to stdout.
* Should only have any effect once.
*/
void setup() {
if(!first)
return;
first = false;
IO::GetParam<bool>("svm/shrink") = true;
IO::GetParam<double>("svm/epsilon") = .1;
IO::GetParam<double>("svm/sigma") = 1;
// Protect the test from taking forever
IO::GetParam<index_t>("svm/n_iter") = 10000;
matrix <<
7.19906628001437787e-01 << 1.83250823399634477e+00 << 0 << arma::endr <<
1.37899419263889733e+01 << 1.78198235122579263e+00 << 1 << arma::endr <<
6.68859485848275703e-01 << 2.14083320956715983e+00 << 0 << arma::endr <<
1.84729928795588165e+01 << 2.25024702760868101e+00 << 1 << arma::endr <<
9.22802773268335819e-01 << 1.61469358350834513e+00 << 0 << arma::endr <<
2.06209849662245204e-01 << 6.34699695340683490e-01 << 1 << arma::endr <<
4.01062068250524817e-01 << 1.65802752932441777e+00 << 0 << arma::endr <<
5.02985607135568635e+00 << 1.39976642741810831e+00 << 1 << arma::endr <<
3.66471199955079319e-01 << 1.62780588172739638e+00 << 0 << arma::endr <<
1.56912570240400999e+01 << 2.16941541650770953e+00 << 1 << arma::endr <<
9.98909584711729304e-01 << 2.00337906391517206e+00 << 0 << arma::endr <<
1.31430438780891912e+01 << 1.34410346059319719e+00 << 1 << arma::endr <<
3.41572957272442523e-01 << 1.16758463655951639e+00 << 0 << arma::endr <<
9.53941410851637528e-01 << 6.30271704462483373e-01 << 1 << arma::endr <<
7.07135529120981432e-01 << 2.17763537339756041e+00 << 0 << arma::endr <<
9.68899714280338742e+00 << 1.26922579378319256e+00 << 1 << arma::endr <<
9.82393905512240706e-01 << 2.36790583090293483e+00 << 0 << arma::endr <<
1.31583349281727973e+01 << 1.45115094722767868e+00 << 1 << arma::endr <<
3.80991188521027202e-01 << 9.05379134419085019e-01 << 0 << arma::endr <<
1.86057436180327755e+01 << 2.26941891469499968e+00 << 1 << arma::endr;
matrix = trans(matrix);
std::cout << matrix << std::endl;
}
/**
* Compares predicted values with known values to see if the prediction/training works.
*
* @param: learner_typeid Magic number for selecting between classification and
* regression.
* @param: data The dataset with the data to predict with.
* @param: svm The SVM class instance that has been trained for this data, et al.
*/
template<typename T>
void verify(index_t learner_typeid, Dataset& data, SVM<T>& svm) {
for(index_t i = 0; i < data.n_points(); i++) {
arma::vec testvec = data.matrix().col(i);
double predictedvalue = svm.Predict(learner_typeid, testvec);
BOOST_REQUIRE_CLOSE(predictedvalue,
data.matrix()(data.n_features()-1,i),1e-6);
}
}
/**
* Trains a classifier with a linear kernel and checks predictions against
* classes.
*/
BOOST_AUTO_TEST_CASE(svm_classification_linear_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMLinearKernel> svm;
svm.InitTrain(0,trainingdata); // 0 for classification
verify(0,trainingdata,svm);
}
/**
* Trains a classifier with a gaussian kernel and checks predictions against
* classes.
*/
BOOST_AUTO_TEST_CASE(svm_classification_gaussian_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMRBFKernel> svm;
svm.InitTrain(0,trainingdata); // 0 for classification
verify(0,trainingdata,svm);
}
/**
* Trains a classifier with a linear kernel and checks predictions against
* classes, using regression. TODO: BROKEN
*/
BOOST_AUTO_TEST_CASE(svm_regression_linear_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMLinearKernel> svm;
svm.InitTrain(1,trainingdata); // 0 for classification
//verify(1,trainingdata,svm);
}
/**
* Trains a classifier with a gaussian kernel and checks predictions against
* classes, using regression. TODO: BROKEN
*/
BOOST_AUTO_TEST_CASE(svm_regression_gaussian_kernel_test) {
setup();
Dataset trainingdata;
trainingdata.matrix() = matrix;
SVM<SVMRBFKernel> svm;
svm.InitTrain(1,trainingdata); // 0 for classification
//verify(1,trainingdata,svm);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/nacl/nacl_thread.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/nacl_messages.h"
// This is ugly. We need an interface header file for the exported
// sel_ldr interfaces.
// TODO(gregoryd,sehr): Add an interface header.
#if defined(OS_WIN)
typedef HANDLE NaClHandle;
#else
typedef int NaClHandle;
#endif // NaClHandle
// This is currently necessary because we have a conflict between
// NaCl's "struct NaClThread" and Chromium's "class NaClThread".
extern "C" int NaClMainForChromium(int handle_count, const NaClHandle* handles);
NaClThread::NaClThread() {
}
NaClThread::~NaClThread() {
}
NaClThread* NaClThread::current() {
return static_cast<NaClThread*>(ChildThread::current());
}
void NaClThread::OnControlMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(NaClThread, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr)
IPC_END_MESSAGE_MAP()
}
void NaClThread::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) {
NaClHandle* array = new NaClHandle[handles.size()];
for (size_t i = 0; i < handles.size(); i++) {
array[i] = nacl::ToNativeHandle(handles[i]);
}
NaClMainForChromium(static_cast<int>(handles.size()), array);
delete array;
}
<commit_msg>nacl: Use a scoped_array rather than a bare pointer.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/nacl/nacl_thread.h"
#include "base/scoped_ptr.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/nacl_messages.h"
// This is ugly. We need an interface header file for the exported
// sel_ldr interfaces.
// TODO(gregoryd,sehr): Add an interface header.
#if defined(OS_WIN)
typedef HANDLE NaClHandle;
#else
typedef int NaClHandle;
#endif // NaClHandle
// This is currently necessary because we have a conflict between
// NaCl's "struct NaClThread" and Chromium's "class NaClThread".
extern "C" int NaClMainForChromium(int handle_count, const NaClHandle* handles);
NaClThread::NaClThread() {
}
NaClThread::~NaClThread() {
}
NaClThread* NaClThread::current() {
return static_cast<NaClThread*>(ChildThread::current());
}
void NaClThread::OnControlMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(NaClThread, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr)
IPC_END_MESSAGE_MAP()
}
void NaClThread::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) {
scoped_array<NaClHandle> array(new NaClHandle[handles.size()]);
for (size_t i = 0; i < handles.size(); i++) {
array[i] = nacl::ToNativeHandle(handles[i]);
}
NaClMainForChromium(static_cast<int>(handles.size()), array.get());
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.