text
stringlengths 54
60.6k
|
---|
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
// This file is auto-generated by CMake at build time
#include "nomlib/version.hpp"
const std::string NOMLIB_INSTALL_PREFIX = "/Users/jeff/Library/Frameworks";
const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";
<commit_msg>Add conditional preprocessor for nomlib's install prefix under Windows<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
// This file is auto-generated by CMake at build time
#include "nomlib/version.hpp"
#if defined (NOM_PLATFORM_WINDOWS)
const std::string NOMLIB_INSTALL_PREFIX = "C:/";
#endif
const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-geo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define STRINGIFY(s) #s
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>changes<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-foo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define STRINGIFY(s) #s
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "05f29b5"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>baseline, sirius<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "9d5939c"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
#include <sstream>
#include "BasicTypes.h"
#include "GraphicsTypes.h"
#include "Shader.h"
#include "RefCountedObjectImpl.hpp"
#include "Errors.hpp"
namespace Diligent
{
String BuildHLSLSourceString(const ShaderCreateInfo& ShaderCI,
const char* ExtraDefinitions = nullptr);
String GetHLSLProfileString(SHADER_TYPE ShaderType, ShaderVersion ShaderModel);
template <typename BlobType>
void HandleHLSLCompilerResult(bool CompilationSucceeded,
BlobType* pCompilerMsgBlob,
const std::string& ShaderSource,
const char* ShaderName,
IDataBlob** ppOutputLog) noexcept(false)
{
const char* CompilerMsg = pCompilerMsgBlob ? static_cast<const char*>(pCompilerMsgBlob->GetBufferPointer()) : nullptr;
const size_t CompilerMsgLen = CompilerMsg ? pCompilerMsgBlob->GetBufferSize() : 0;
if (ppOutputLog != nullptr)
{
const auto ShaderSourceLen = ShaderSource.length();
auto* pOutputLogBlob = MakeNewRCObj<DataBlobImpl>{}(ShaderSourceLen + 1 + CompilerMsgLen + 1);
auto* log = static_cast<char*>(pOutputLogBlob->GetDataPtr());
if (CompilerMsg != nullptr)
memcpy(log, CompilerMsg, CompilerMsgLen);
log[CompilerMsgLen] = 0; // Explicitly set null terminator
log += CompilerMsgLen + 1;
memcpy(log, ShaderSource.data(), ShaderSourceLen);
log[ShaderSourceLen] = 0;
pOutputLogBlob->QueryInterface(IID_DataBlob, reinterpret_cast<IObject**>(ppOutputLog));
}
if (!CompilationSucceeded || CompilerMsgLen != 0)
{
std::stringstream ss;
ss << (CompilationSucceeded ? "Compiler output for shader '" : "Failed to compile shader '")
<< (ShaderName != nullptr ? ShaderName : "<unknown>")
<< "'";
if (CompilerMsg != nullptr && CompilerMsgLen != 0)
{
ss << ":" << std::endl
<< CompilerMsg;
}
else if (!CompilationSucceeded)
{
ss << " (no shader log available).";
}
if (CompilationSucceeded)
LOG_INFO_MESSAGE(ss.str());
else
LOG_ERROR_AND_THROW(ss.str());
}
}
} // namespace Diligent
<commit_msg>Fixe Linux/Mac build - part II<commit_after>/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
#include <sstream>
#include "BasicTypes.h"
#include "GraphicsTypes.h"
#include "Shader.h"
#include "RefCountedObjectImpl.hpp"
#include "Errors.hpp"
#include "DataBlobImpl.hpp"
namespace Diligent
{
String BuildHLSLSourceString(const ShaderCreateInfo& ShaderCI,
const char* ExtraDefinitions = nullptr);
String GetHLSLProfileString(SHADER_TYPE ShaderType, ShaderVersion ShaderModel);
template <typename BlobType>
void HandleHLSLCompilerResult(bool CompilationSucceeded,
BlobType* pCompilerMsgBlob,
const std::string& ShaderSource,
const char* ShaderName,
IDataBlob** ppOutputLog) noexcept(false)
{
const char* CompilerMsg = pCompilerMsgBlob ? static_cast<const char*>(pCompilerMsgBlob->GetBufferPointer()) : nullptr;
const size_t CompilerMsgLen = CompilerMsg ? pCompilerMsgBlob->GetBufferSize() : 0;
if (ppOutputLog != nullptr)
{
const auto ShaderSourceLen = ShaderSource.length();
auto* pOutputLogBlob = MakeNewRCObj<DataBlobImpl>{}(ShaderSourceLen + 1 + CompilerMsgLen + 1);
auto* log = static_cast<char*>(pOutputLogBlob->GetDataPtr());
if (CompilerMsg != nullptr)
memcpy(log, CompilerMsg, CompilerMsgLen);
log[CompilerMsgLen] = 0; // Explicitly set null terminator
log += CompilerMsgLen + 1;
memcpy(log, ShaderSource.data(), ShaderSourceLen);
log[ShaderSourceLen] = 0;
pOutputLogBlob->QueryInterface(IID_DataBlob, reinterpret_cast<IObject**>(ppOutputLog));
}
if (!CompilationSucceeded || CompilerMsgLen != 0)
{
std::stringstream ss;
ss << (CompilationSucceeded ? "Compiler output for shader '" : "Failed to compile shader '")
<< (ShaderName != nullptr ? ShaderName : "<unknown>")
<< "'";
if (CompilerMsg != nullptr && CompilerMsgLen != 0)
{
ss << ":" << std::endl
<< CompilerMsg;
}
else if (!CompilationSucceeded)
{
ss << " (no shader log available).";
}
if (CompilationSucceeded)
LOG_INFO_MESSAGE(ss.str());
else
LOG_ERROR_AND_THROW(ss.str());
}
}
} // namespace Diligent
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template <
typename fn_output,
typename char_type = char,
char_type opening = '(',
char_type closing = ')'
>
class generate_balanced_parenthesis {
fn_output out;
string buffer;
size_t pairs;
void generate(size_t open, size_t position) {
if(position == buffer.size()) {
out(buffer, 0);
return;
}
if(position < buffer.size() - 1) {
buffer[position] = opening;
generate(open + 1, position + 1);
}
else {
assert(open == buffer.size() / 2);
}
if(open > 0) {
buffer[position] = closing;
generate(open - 1, position + 1);
}
}
public:
generate_balanced_parenthesis(fn_output out, size_t pairs):
out(out),
buffer(pairs * 2),
pairs(pairs)
{
assert(pairs > 0);
}
void operator () {
generate(0, 0, 0);
}
};
void generate_balanced_parenthesis() {
vector<char> buffer(pairs * 2);
}
template <typename fn_output>
void {
vector<char> buffer(pairs * 2);
}
int main(int argc, char **argv) {
generate_balanced_parenthesis(
[](string const &s, size_t depth) {
cout << s << ", depth = " << depth << endl;
},
argc > 1 ? atoi(argv[1]) : 3
);
return 0;
}
<commit_msg>[30]: - removing depth information - fixing main<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template <
typename fn_output,
typename char_type = char,
char_type opening = '(',
char_type closing = ')'
>
class generate_balanced_parenthesis {
fn_output out;
string buffer;
size_t pairs;
void generate(size_t open, size_t position) {
if(position == buffer.size()) {
out(buffer);
return;
}
if(position < buffer.size() - 1) {
buffer[position] = opening;
generate(open + 1, position + 1);
}
else {
assert(open == buffer.size() / 2);
}
if(open > 0) {
buffer[position] = closing;
generate(open - 1, position + 1);
}
}
public:
generate_balanced_parenthesis(fn_output out, size_t pairs):
out(out),
buffer(pairs * 2),
pairs(pairs)
{
assert(pairs > 0);
}
void operator () {
generate(0, 0);
}
};
void generate_balanced_parenthesis() {
vector<char> buffer(pairs * 2);
}
template <typename fn_output>
void {
vector<char> buffer(pairs * 2);
}
int main(int argc, char **argv) {
auto out = [](string const &s) { cout << s << endl; };
generate_balanced_parenthesis<decltype(out)>(
out, argc > 1 ? atoi(argv[1]) : 3
)();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 The Orbit 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 "OrbitUserSpaceInstrumentation.h"
#include <sys/types.h>
#include <cstdint>
#include <stack>
#include <variant>
#include "CaptureEventProducer/LockFreeBufferCaptureEventProducer.h"
#include "OrbitBase/Profiling.h"
#include "OrbitBase/ThreadUtils.h"
#include "ProducerSideChannel/ProducerSideChannel.h"
using orbit_base::CaptureTimestampNs;
namespace {
struct OpenFunctionCall {
OpenFunctionCall(uint64_t return_address, uint64_t timestamp_on_entry_ns)
: return_address(return_address), timestamp_on_entry_ns(timestamp_on_entry_ns) {}
uint64_t return_address;
uint64_t timestamp_on_entry_ns;
};
// The amount of data we store for each call is relevant for the overall performance. The assert is
// here for awareness and to avoid packing issues in the struct.
static_assert(sizeof(OpenFunctionCall) == 16, "OpenFunctionCall should be 16 bytes.");
std::stack<OpenFunctionCall>& GetOpenFunctionCallStack() {
thread_local std::stack<OpenFunctionCall> open_function_calls;
return open_function_calls;
}
uint64_t current_capture_start_timestamp_ns = 0;
// We can use the protos directly: since their fields are all integer fields, they are basically
// plain structs.
using FunctionEntryExitVariant =
std::variant<orbit_grpc_protos::FunctionEntry, orbit_grpc_protos::FunctionExit>;
// This class is used to enqueue FunctionEntry and FunctionExit events from multiple threads and
// relay them to OrbitService.
class LockFreeUserSpaceInstrumentationEventProducer
: public orbit_capture_event_producer::LockFreeBufferCaptureEventProducer<
FunctionEntryExitVariant> {
public:
LockFreeUserSpaceInstrumentationEventProducer() {
BuildAndStart(orbit_producer_side_channel::CreateProducerSideChannel());
}
~LockFreeUserSpaceInstrumentationEventProducer() override { ShutdownAndWait(); }
protected:
[[nodiscard]] orbit_grpc_protos::ProducerCaptureEvent* TranslateIntermediateEvent(
FunctionEntryExitVariant&& raw_event, google::protobuf::Arena* arena) override {
auto* capture_event =
google::protobuf::Arena::CreateMessage<orbit_grpc_protos::ProducerCaptureEvent>(arena);
std::visit(
[capture_event](auto&& raw_event) {
using DecayedEventType = std::decay_t<decltype(raw_event)>;
if constexpr (std::is_same_v<DecayedEventType, orbit_grpc_protos::FunctionEntry>) {
orbit_grpc_protos::FunctionEntry* function_entry =
capture_event->mutable_function_entry();
*function_entry = std::forward<decltype(raw_event)>(raw_event);
} else if constexpr (std::is_same_v<DecayedEventType, orbit_grpc_protos::FunctionExit>) {
orbit_grpc_protos::FunctionExit* function_exit = capture_event->mutable_function_exit();
*function_exit = std::forward<decltype(raw_event)>(raw_event);
} else {
static_assert(always_false_v<DecayedEventType>, "Non-exhaustive visitor");
}
},
std::move(raw_event));
return capture_event;
}
private:
template <class>
[[maybe_unused]] static constexpr bool always_false_v = false;
};
LockFreeUserSpaceInstrumentationEventProducer& GetCaptureEventProducer() {
static LockFreeUserSpaceInstrumentationEventProducer producer;
return producer;
}
// Provide a thread local bool to keep track of whether the current thread is inside the payload we
// injected. If that is the case we avoid further instrumentation.
bool& GetIsInPayload() {
thread_local bool is_in_payload = false;
return is_in_payload;
}
} // namespace
void StartNewCapture() {
current_capture_start_timestamp_ns = CaptureTimestampNs();
// If the library has just been injected, initialize the
// LockFreeUserSpaceInstrumentationEventProducer and establish the connection to OrbitService now
// instead of waiting for the first call to EntryPayload. As it takes a bit to
// establish the connection, GetCaptureEventProducer().IsCapturing() would otherwise always be
// false in the first call to EntryPayload, which would cause the first function call to be missed
// even if the time between StartNewCapture() and the first function call is large.
// TODO(b/205939288): The fix involving calling GetCaptureEventProducer() here was removed because
// of b/209560448 (we could have interrupted a malloc, which is not re-entrant, so we need to
// avoid any memory allocation). Re-add the call once we have a solution to allow re-entrancy.
}
void EntryPayload(uint64_t return_address, uint64_t function_id, uint64_t stack_pointer,
uint64_t return_trampoline_address) {
bool& is_in_payload = GetIsInPayload();
// If something in the callgraph below `EntryPayload` or `ExitPayload` was instrumented we need to
// break the cycle here otherwise we would crash in an infinite recursion.
if (is_in_payload) {
return;
}
is_in_payload = true;
const uint64_t timestamp_on_entry_ns = CaptureTimestampNs();
std::stack<OpenFunctionCall>& open_function_call_stack = GetOpenFunctionCallStack();
open_function_call_stack.emplace(return_address, timestamp_on_entry_ns);
if (GetCaptureEventProducer().IsCapturing()) {
static uint32_t pid = orbit_base::GetCurrentProcessId();
thread_local uint32_t tid = orbit_base::GetCurrentThreadId();
orbit_grpc_protos::FunctionEntry function_entry;
function_entry.set_pid(pid);
function_entry.set_tid(tid);
function_entry.set_function_id(function_id);
function_entry.set_stack_pointer(stack_pointer);
function_entry.set_return_address(return_address);
function_entry.set_timestamp_ns(timestamp_on_entry_ns);
GetCaptureEventProducer().EnqueueIntermediateEvent(std::move(function_entry));
}
// Overwrite return address so that we end up returning to the exit trampoline.
*reinterpret_cast<uint64_t*>(stack_pointer) = return_trampoline_address;
is_in_payload = false;
}
uint64_t ExitPayload() {
bool& is_in_payload = GetIsInPayload();
is_in_payload = true;
const uint64_t timestamp_on_exit_ns = CaptureTimestampNs();
std::stack<OpenFunctionCall>& open_function_call_stack = GetOpenFunctionCallStack();
OpenFunctionCall current_function_call = open_function_call_stack.top();
open_function_call_stack.pop();
// Skip emitting an event if we are not capturing or if the function call doesn't fully belong to
// this capture.
if (GetCaptureEventProducer().IsCapturing() &&
current_capture_start_timestamp_ns < current_function_call.timestamp_on_entry_ns) {
static uint32_t pid = orbit_base::GetCurrentProcessId();
thread_local uint32_t tid = orbit_base::GetCurrentThreadId();
orbit_grpc_protos::FunctionExit function_exit;
function_exit.set_pid(pid);
function_exit.set_tid(tid);
function_exit.set_timestamp_ns(timestamp_on_exit_ns);
GetCaptureEventProducer().EnqueueIntermediateEvent(std::move(function_exit));
}
is_in_payload = false;
return current_function_call.return_address;
}
<commit_msg>Optimize EntryPayload & ExitPayload by not using protos directly (#3390)<commit_after>// Copyright (c) 2021 The Orbit 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 "OrbitUserSpaceInstrumentation.h"
#include <sys/types.h>
#include <cstdint>
#include <stack>
#include <variant>
#include "CaptureEventProducer/LockFreeBufferCaptureEventProducer.h"
#include "OrbitBase/Profiling.h"
#include "OrbitBase/ThreadUtils.h"
#include "ProducerSideChannel/ProducerSideChannel.h"
using orbit_base::CaptureTimestampNs;
namespace {
struct OpenFunctionCall {
OpenFunctionCall(uint64_t return_address, uint64_t timestamp_on_entry_ns)
: return_address(return_address), timestamp_on_entry_ns(timestamp_on_entry_ns) {}
uint64_t return_address;
uint64_t timestamp_on_entry_ns;
};
// The amount of data we store for each call is relevant for the overall performance. The assert is
// here for awareness and to avoid packing issues in the struct.
static_assert(sizeof(OpenFunctionCall) == 16, "OpenFunctionCall should be 16 bytes.");
std::stack<OpenFunctionCall>& GetOpenFunctionCallStack() {
thread_local std::stack<OpenFunctionCall> open_function_calls;
return open_function_calls;
}
uint64_t current_capture_start_timestamp_ns = 0;
// Don't use the orbit_grpc_protos::FunctionEntry and orbit_grpc_protos::FunctionExit protos
// directly. While in memory those protos are basically plain structs as their fields are all
// integer fields, their constructors and assignment operators are more complicated, and spend a lot
// of time in InternalSwap.
struct FunctionEntry {
FunctionEntry() = default;
FunctionEntry(uint32_t pid, uint32_t tid, uint64_t function_id, uint64_t stack_pointer,
uint64_t return_address, uint64_t timestamp_ns)
: pid{pid},
tid{tid},
function_id{function_id},
stack_pointer{stack_pointer},
return_address{return_address},
timestamp_ns{timestamp_ns} {}
uint32_t pid;
uint32_t tid;
uint64_t function_id;
uint64_t stack_pointer;
uint64_t return_address;
uint64_t timestamp_ns;
};
struct FunctionExit {
FunctionExit() = default;
FunctionExit(uint32_t pid, uint32_t tid, uint64_t timestamp_ns)
: pid{pid}, tid{tid}, timestamp_ns{timestamp_ns} {}
uint32_t pid;
uint32_t tid;
uint64_t timestamp_ns;
};
using FunctionEntryExitVariant = std::variant<FunctionEntry, FunctionExit>;
// This class is used to enqueue FunctionEntry and FunctionExit events from multiple threads,
// transform them into orbit_grpc_protos::FunctionEntry and orbit_grpc_protos::FunctionExit protos,
// and relay them to OrbitService.
class LockFreeUserSpaceInstrumentationEventProducer
: public orbit_capture_event_producer::LockFreeBufferCaptureEventProducer<
FunctionEntryExitVariant> {
public:
LockFreeUserSpaceInstrumentationEventProducer() {
BuildAndStart(orbit_producer_side_channel::CreateProducerSideChannel());
}
~LockFreeUserSpaceInstrumentationEventProducer() override { ShutdownAndWait(); }
protected:
[[nodiscard]] orbit_grpc_protos::ProducerCaptureEvent* TranslateIntermediateEvent(
FunctionEntryExitVariant&& raw_event, google::protobuf::Arena* arena) override {
auto* capture_event =
google::protobuf::Arena::CreateMessage<orbit_grpc_protos::ProducerCaptureEvent>(arena);
std::visit(
[capture_event](auto&& raw_event) {
using DecayedEventType = std::decay_t<decltype(raw_event)>;
if constexpr (std::is_same_v<DecayedEventType, FunctionEntry>) {
orbit_grpc_protos::FunctionEntry* function_entry =
capture_event->mutable_function_entry();
function_entry->set_pid(raw_event.pid);
function_entry->set_tid(raw_event.tid);
function_entry->set_function_id(raw_event.function_id);
function_entry->set_stack_pointer(raw_event.stack_pointer);
function_entry->set_return_address(raw_event.return_address);
function_entry->set_timestamp_ns(raw_event.timestamp_ns);
} else if constexpr (std::is_same_v<DecayedEventType, FunctionExit>) {
orbit_grpc_protos::FunctionExit* function_exit = capture_event->mutable_function_exit();
function_exit->set_pid(raw_event.pid);
function_exit->set_tid(raw_event.tid);
function_exit->set_timestamp_ns(raw_event.timestamp_ns);
} else {
static_assert(always_false_v<DecayedEventType>, "Non-exhaustive visitor");
}
},
raw_event);
return capture_event;
}
private:
template <class>
[[maybe_unused]] static constexpr bool always_false_v = false;
};
LockFreeUserSpaceInstrumentationEventProducer& GetCaptureEventProducer() {
static LockFreeUserSpaceInstrumentationEventProducer producer;
return producer;
}
// Provide a thread local bool to keep track of whether the current thread is inside the payload we
// injected. If that is the case we avoid further instrumentation.
bool& GetIsInPayload() {
thread_local bool is_in_payload = false;
return is_in_payload;
}
} // namespace
void StartNewCapture() {
current_capture_start_timestamp_ns = CaptureTimestampNs();
// If the library has just been injected, initialize the
// LockFreeUserSpaceInstrumentationEventProducer and establish the connection to OrbitService now
// instead of waiting for the first call to EntryPayload. As it takes a bit to
// establish the connection, GetCaptureEventProducer().IsCapturing() would otherwise always be
// false in the first call to EntryPayload, which would cause the first function call to be missed
// even if the time between StartNewCapture() and the first function call is large.
// TODO(b/205939288): The fix involving calling GetCaptureEventProducer() here was removed because
// of b/209560448 (we could have interrupted a malloc, which is not re-entrant, so we need to
// avoid any memory allocation). Re-add the call once we have a solution to allow re-entrancy.
}
void EntryPayload(uint64_t return_address, uint64_t function_id, uint64_t stack_pointer,
uint64_t return_trampoline_address) {
bool& is_in_payload = GetIsInPayload();
// If something in the callgraph below `EntryPayload` or `ExitPayload` was instrumented we need to
// break the cycle here otherwise we would crash in an infinite recursion.
if (is_in_payload) {
return;
}
is_in_payload = true;
const uint64_t timestamp_on_entry_ns = CaptureTimestampNs();
std::stack<OpenFunctionCall>& open_function_call_stack = GetOpenFunctionCallStack();
open_function_call_stack.emplace(return_address, timestamp_on_entry_ns);
if (GetCaptureEventProducer().IsCapturing()) {
static uint32_t pid = orbit_base::GetCurrentProcessId();
thread_local uint32_t tid = orbit_base::GetCurrentThreadId();
GetCaptureEventProducer().EnqueueIntermediateEvent(
FunctionEntry{pid, tid, function_id, stack_pointer, return_address, timestamp_on_entry_ns});
}
// Overwrite return address so that we end up returning to the exit trampoline.
*reinterpret_cast<uint64_t*>(stack_pointer) = return_trampoline_address;
is_in_payload = false;
}
uint64_t ExitPayload() {
bool& is_in_payload = GetIsInPayload();
is_in_payload = true;
const uint64_t timestamp_on_exit_ns = CaptureTimestampNs();
std::stack<OpenFunctionCall>& open_function_call_stack = GetOpenFunctionCallStack();
OpenFunctionCall current_function_call = open_function_call_stack.top();
open_function_call_stack.pop();
// Skip emitting an event if we are not capturing or if the function call doesn't fully belong to
// this capture.
if (GetCaptureEventProducer().IsCapturing() &&
current_capture_start_timestamp_ns < current_function_call.timestamp_on_entry_ns) {
static uint32_t pid = orbit_base::GetCurrentProcessId();
thread_local uint32_t tid = orbit_base::GetCurrentThreadId();
GetCaptureEventProducer().EnqueueIntermediateEvent(
FunctionExit{pid, tid, timestamp_on_exit_ns});
}
is_in_payload = false;
return current_function_call.return_address;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: salinst.cxx,v $
*
* $Revision: 1.28 $
*
* last change: $Author: pluby $ $Date: 2001-02-28 03:15:14 $
*
* 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_SALINST_CXX
#include <stdio.h>
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#ifndef _SV_SALSYS_HXX
#include <salsys.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
#ifndef _SV_DIALOG_HXX
#include <dialog.hxx>
#endif
#ifndef _SV_VCLAPPLICATION_H
#include <VCLApplication.h>
#endif
#ifndef _SV_VCLAUTORELEASEPOOL_H
#include <VCLAutoreleasePool.h>
#endif
#ifndef _FSYS_HXX
#include <tools/fsys.hxx>
#endif
static VCLAUTORELEASEPOOL hMainAutoreleasePool = NULL;
// =======================================================================
void SalAbort( const XubString& rErrorText )
{
if( !rErrorText.Len() )
fprintf( stderr, "Application Error " );
else
fprintf( stderr, "%s ",
ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() );
abort();
}
// -----------------------------------------------------------------------
void InitSalData()
{
SalData *pSalData = new SalData;
memset( pSalData, 0, sizeof( SalData ) );
SetSalData( pSalData );
}
// -----------------------------------------------------------------------
void DeInitSalData()
{
SalData *pSalData = GetSalData();
delete pSalData;
SetSalData( NULL );
}
// -----------------------------------------------------------------------
void InitSalMain()
{
// Need to include the absolute path for this executable in the PATH
// and STAR_RESOURCEPATH environment variables so that the resource manager
// can find resource files and in the DYLD_LIBRARY_PATH environment
// variable so that the dynamic library loader can find shared libraries
extern const char *__progname;
ByteString aPath( getenv( "PATH" ) );
ByteString aCmdPath( __progname );
// Get absolute path of command's directory
if ( aCmdPath.Len() ) {
DirEntry aCmdDirEntry( aCmdPath );
aCmdDirEntry.ToAbs();
aCmdPath = ByteString( aCmdDirEntry.GetPath().GetFull(), RTL_TEXTENCODING_ASCII_US );
}
if ( aPath.Len() ) {
if ( aCmdPath.Len() )
aCmdPath += ByteString( DirEntry::GetSearchDelimiter(), RTL_TEXTENCODING_ASCII_US );
aCmdPath += aPath;
}
// Assign to PATH environment variable
if ( aCmdPath.Len() ) {
aPath = ByteString( "PATH=" );
aPath += aCmdPath;
putenv( aPath.GetBuffer() );
}
// Assign to STAR_RESOURCEPATH environment variable
if ( aCmdPath.Len() ) {
aPath = ByteString( "STAR_RESOURCEPATH=" );
aPath += aCmdPath;
putenv( aPath.GetBuffer() );
}
// Assign to DYLD_LIBRARY_PATH environment variable
if ( aCmdPath.Len() ) {
aPath = ByteString( "DYLD_LIBRARY_PATH=" );
aPath += aCmdPath;
putenv( aPath.GetBuffer() );
}
// Setup up autorelease pool for Objective-C objects
hMainAutoreleasePool = VCLAutoreleasePool_Init();
// Initialize application's connection to the window server
VCLApplication_SharedApplication();
}
// -----------------------------------------------------------------------
void DeInitSalMain()
{
// Release autorelease pool
VCLAutoreleasePool_Release( hMainAutoreleasePool );
}
// -----------------------------------------------------------------------
void SetFilterCallback( void* pCallback, void* pInst )
{
SalData *pSalData = GetSalData();
pSalData->mpFirstInstance->maInstData.mpFilterCallback = pCallback;
pSalData->mpFirstInstance->maInstData.mpFilterInst = pInst;
}
// =======================================================================
SalYieldMutex::SalYieldMutex()
{
mnCount = 0;
mnThreadId = 0;
}
void SalYieldMutex::acquire()
{
OMutex::acquire();
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
}
void SalYieldMutex::release()
{
if ( mnThreadId == NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
if ( mnCount == 1 )
mnThreadId = 0;
mnCount--;
}
OMutex::release();
}
sal_Bool SalYieldMutex::tryToAcquire()
{
if ( OMutex::tryToAcquire() )
{
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
return True;
}
else
return False;
}
// =======================================================================
SalInstance* CreateSalInstance()
{
SalData* pSalData = GetSalData();
SalInstance* pInst = new SalInstance;
// init instance (only one instance in this version !!!)
pSalData->mpFirstInstance = pInst;
return pInst;
}
// -----------------------------------------------------------------------
void DestroySalInstance( SalInstance* pInst )
{
delete pInst;
}
// -----------------------------------------------------------------------
SalInstance::SalInstance()
{
maInstData.mpFilterCallback = NULL;
maInstData.mpFilterInst = NULL;
maInstData.mpSalYieldMutex = new SalYieldMutex;
maInstData.mpSalYieldMutex->acquire();
}
// -----------------------------------------------------------------------
SalInstance::~SalInstance()
{
maInstData.mpSalYieldMutex->release();
delete maInstData.mpSalYieldMutex;
}
// -----------------------------------------------------------------------
#ifdef _VOS_NO_NAMESPACE
IMutex* SalInstance::GetYieldMutex()
#else
vos::IMutex* SalInstance::GetYieldMutex()
#endif
{
return maInstData.mpSalYieldMutex;
}
// -----------------------------------------------------------------------
ULONG SalInstance::ReleaseYieldMutex()
{
SalYieldMutex* pYieldMutex = maInstData.mpSalYieldMutex;
if ( pYieldMutex->GetThreadId() ==
NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
ULONG nCount = pYieldMutex->GetAcquireCount();
ULONG n = nCount;
while ( n )
{
pYieldMutex->release();
n--;
}
return nCount;
}
else
return 0;
}
// -----------------------------------------------------------------------
void SalInstance::AcquireYieldMutex( ULONG nCount )
{
SalYieldMutex* pYieldMutex = maInstData.mpSalYieldMutex;
while ( nCount )
{
pYieldMutex->acquire();
nCount--;
}
}
// -----------------------------------------------------------------------
void SalInstance::Yield( BOOL bWait )
{
ULONG nCount = 0;
// Release all locks so that we don't deadlock when we pull pending
// events from the event queue
nCount = ReleaseYieldMutex();
// Pull pending events from the event queue and dispatch them.
VCLApplication_Run( bWait );
// Reset all locks
AcquireYieldMutex( nCount );
}
// -----------------------------------------------------------------------
BOOL SalInstance::AnyInput( USHORT nType )
{
return FALSE;
}
// -----------------------------------------------------------------------
SalFrame* SalInstance::CreateChildFrame( SystemParentData* pSystemParentData, ULONG nSalFrameStyle )
{
return NULL;
}
// -----------------------------------------------------------------------
SalFrame* SalInstance::CreateFrame( SalFrame* pParent, ULONG nSalFrameStyle )
{
SalFrame *pFrame = new SalFrame;
pFrame->maFrameData.mpParent = pParent;
// Create the native window
pFrame->maFrameData.mhWnd = VCLWindow_New( nSalFrameStyle, NULL,
pFrame, &(pFrame->maFrameData) );
return pFrame;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyFrame( SalFrame* pFrame )
{
delete pFrame;
}
// -----------------------------------------------------------------------
SalObject* SalInstance::CreateObject( SalFrame* pParent )
{
SalObject *pObject = NULL;
if ( pParent )
{
pObject = new SalObject;
pObject->maObjectData.mpFrame = pParent;
}
return pObject;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyObject( SalObject* pObject )
{
delete ( pObject );
}
// -----------------------------------------------------------------------
SalVirtualDevice* SalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
long nDX, long nDY, USHORT nBitCount )
{
SalVirtualDevice *pVirDev = new SalVirtualDevice;
// Cache values for when SalVirtualDevice::GetGraphics() is invoked
pVirDev->maVirDevData.mnBitCount = nBitCount;
pVirDev->maVirDevData.mnWidth = nDX;
pVirDev->maVirDevData.mnHeight = nDY;
return pVirDev;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
delete pDevice;
}
// -----------------------------------------------------------------------
SalPrinter* SalInstance::CreatePrinter( SalInfoPrinter* pInfoPrinter )
{
return NULL;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyPrinter( SalPrinter* pPrinter )
{
}
// -----------------------------------------------------------------------
void SalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )
{
}
// -----------------------------------------------------------------------
void SalInstance::GetPrinterQueueState( SalPrinterQueueInfo* pInfo )
{
}
// -----------------------------------------------------------------------
void SalInstance::DeletePrinterQueueInfo( SalPrinterQueueInfo* pInfo )
{
}
// -----------------------------------------------------------------------
XubString SalInstance::GetDefaultPrinter()
{
return XubString();
}
// -----------------------------------------------------------------------
SalInfoPrinter* SalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,
ImplJobSetup* pSetupData )
{
return NULL;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )
{
}
// -----------------------------------------------------------------------
SalSystem* SalInstance::CreateSystem()
{
return new SalSystem();
}
// -----------------------------------------------------------------------
void SalInstance::DestroySystem( SalSystem* pSystem )
{
delete pSystem;
}
// -----------------------------------------------------------------------
#if SUPD > 618
void SalInstance::SetEventCallback( void* pInstance, bool(*pCallback)(void*,void*,int) )
{
}
// -----------------------------------------------------------------------
void SalInstance::SetErrorEventCallback( void* pInstance, bool(*pCallback)(void*,void*,int) )
{
}
// -----------------------------------------------------------------------
void* SalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
{
rReturnedBytes = 1;
rReturnedType = AsciiCString;
return "";
}
#endif // SUPD > 618
<commit_msg>Corrections to InitSalMain<commit_after>/*************************************************************************
*
* $RCSfile: salinst.cxx,v $
*
* $Revision: 1.29 $
*
* last change: $Author: pluby $ $Date: 2001-03-05 02:01:42 $
*
* 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_SALINST_CXX
#include <stdio.h>
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#ifndef _SV_SALSYS_HXX
#include <salsys.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
#ifndef _SV_DIALOG_HXX
#include <dialog.hxx>
#endif
#ifndef _SV_VCLAPPLICATION_H
#include <VCLApplication.h>
#endif
#ifndef _SV_VCLAUTORELEASEPOOL_H
#include <VCLAutoreleasePool.h>
#endif
#ifndef _FSYS_HXX
#include <tools/fsys.hxx>
#endif
static VCLAUTORELEASEPOOL hMainAutoreleasePool = NULL;
// =======================================================================
void SalAbort( const XubString& rErrorText )
{
if( !rErrorText.Len() )
fprintf( stderr, "Application Error " );
else
fprintf( stderr, "%s ",
ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() );
abort();
}
// -----------------------------------------------------------------------
void InitSalData()
{
SalData *pSalData = new SalData;
memset( pSalData, 0, sizeof( SalData ) );
SetSalData( pSalData );
}
// -----------------------------------------------------------------------
void DeInitSalData()
{
SalData *pSalData = GetSalData();
delete pSalData;
SetSalData( NULL );
}
// -----------------------------------------------------------------------
void InitSalMain()
{
extern char **environ;
char **pEnviron;
// Get full executable path. We cna't use __progname as that only holds
// the name of the executable and not the path. The full executable path
// is listed after the first NULL in *environ.
pEnviron = environ;
while ( *pEnviron++ )
;
// Need to include the absolute path for this executable in the PATH
// and STAR_RESOURCEPATH environment variables so that the resource manager
// can find resource files and in the DYLD_LIBRARY_PATH environment
// variable so that the dynamic library loader can find shared libraries
ByteString aPath( getenv( "PATH" ) );
ByteString aCmdPath( *pEnviron );
// Get absolute path of command's directory
if ( aCmdPath.Len() ) {
DirEntry aCmdDirEntry( aCmdPath );
aCmdDirEntry.ToAbs();
aCmdPath = ByteString( aCmdDirEntry.GetPath().GetFull(), RTL_TEXTENCODING_ASCII_US );
}
if ( aPath.Len() ) {
if ( aCmdPath.Len() )
aCmdPath += ByteString( DirEntry::GetSearchDelimiter(), RTL_TEXTENCODING_ASCII_US );
aCmdPath += aPath;
}
// Assign to PATH environment variable
if ( aCmdPath.Len() ) {
aPath = ByteString( "PATH=" );
aPath += aCmdPath;
putenv( aPath.GetBuffer() );
}
// Assign to STAR_RESOURCEPATH environment variable
if ( aCmdPath.Len() ) {
aPath = ByteString( "STAR_RESOURCEPATH=" );
aPath += aCmdPath;
putenv( aPath.GetBuffer() );
}
// Assign to DYLD_LIBRARY_PATH environment variable
if ( aCmdPath.Len() ) {
aPath = ByteString( "DYLD_LIBRARY_PATH=" );
aPath += aCmdPath;
putenv( aPath.GetBuffer() );
}
// Setup up autorelease pool for Objective-C objects
hMainAutoreleasePool = VCLAutoreleasePool_Init();
// Initialize application's connection to the window server
VCLApplication_SharedApplication();
}
// -----------------------------------------------------------------------
void DeInitSalMain()
{
// Release autorelease pool
VCLAutoreleasePool_Release( hMainAutoreleasePool );
}
// -----------------------------------------------------------------------
void SetFilterCallback( void* pCallback, void* pInst )
{
SalData *pSalData = GetSalData();
pSalData->mpFirstInstance->maInstData.mpFilterCallback = pCallback;
pSalData->mpFirstInstance->maInstData.mpFilterInst = pInst;
}
// =======================================================================
SalYieldMutex::SalYieldMutex()
{
mnCount = 0;
mnThreadId = 0;
}
void SalYieldMutex::acquire()
{
OMutex::acquire();
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
}
void SalYieldMutex::release()
{
if ( mnThreadId == NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
if ( mnCount == 1 )
mnThreadId = 0;
mnCount--;
}
OMutex::release();
}
sal_Bool SalYieldMutex::tryToAcquire()
{
if ( OMutex::tryToAcquire() )
{
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
return True;
}
else
return False;
}
// =======================================================================
SalInstance* CreateSalInstance()
{
SalData* pSalData = GetSalData();
SalInstance* pInst = new SalInstance;
// init instance (only one instance in this version !!!)
pSalData->mpFirstInstance = pInst;
return pInst;
}
// -----------------------------------------------------------------------
void DestroySalInstance( SalInstance* pInst )
{
delete pInst;
}
// -----------------------------------------------------------------------
SalInstance::SalInstance()
{
maInstData.mpFilterCallback = NULL;
maInstData.mpFilterInst = NULL;
maInstData.mpSalYieldMutex = new SalYieldMutex;
maInstData.mpSalYieldMutex->acquire();
}
// -----------------------------------------------------------------------
SalInstance::~SalInstance()
{
maInstData.mpSalYieldMutex->release();
delete maInstData.mpSalYieldMutex;
}
// -----------------------------------------------------------------------
#ifdef _VOS_NO_NAMESPACE
IMutex* SalInstance::GetYieldMutex()
#else
vos::IMutex* SalInstance::GetYieldMutex()
#endif
{
return maInstData.mpSalYieldMutex;
}
// -----------------------------------------------------------------------
ULONG SalInstance::ReleaseYieldMutex()
{
SalYieldMutex* pYieldMutex = maInstData.mpSalYieldMutex;
if ( pYieldMutex->GetThreadId() ==
NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
ULONG nCount = pYieldMutex->GetAcquireCount();
ULONG n = nCount;
while ( n )
{
pYieldMutex->release();
n--;
}
return nCount;
}
else
return 0;
}
// -----------------------------------------------------------------------
void SalInstance::AcquireYieldMutex( ULONG nCount )
{
SalYieldMutex* pYieldMutex = maInstData.mpSalYieldMutex;
while ( nCount )
{
pYieldMutex->acquire();
nCount--;
}
}
// -----------------------------------------------------------------------
void SalInstance::Yield( BOOL bWait )
{
ULONG nCount = 0;
// Release all locks so that we don't deadlock when we pull pending
// events from the event queue
nCount = ReleaseYieldMutex();
// Pull pending events from the event queue and dispatch them.
VCLApplication_Run( bWait );
// Reset all locks
AcquireYieldMutex( nCount );
}
// -----------------------------------------------------------------------
BOOL SalInstance::AnyInput( USHORT nType )
{
return FALSE;
}
// -----------------------------------------------------------------------
SalFrame* SalInstance::CreateChildFrame( SystemParentData* pSystemParentData, ULONG nSalFrameStyle )
{
return NULL;
}
// -----------------------------------------------------------------------
SalFrame* SalInstance::CreateFrame( SalFrame* pParent, ULONG nSalFrameStyle )
{
SalFrame *pFrame = new SalFrame;
pFrame->maFrameData.mpParent = pParent;
// Create the native window
pFrame->maFrameData.mhWnd = VCLWindow_New( nSalFrameStyle, NULL,
pFrame, &(pFrame->maFrameData) );
return pFrame;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyFrame( SalFrame* pFrame )
{
delete pFrame;
}
// -----------------------------------------------------------------------
SalObject* SalInstance::CreateObject( SalFrame* pParent )
{
SalObject *pObject = NULL;
if ( pParent )
{
pObject = new SalObject;
pObject->maObjectData.mpFrame = pParent;
}
return pObject;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyObject( SalObject* pObject )
{
delete ( pObject );
}
// -----------------------------------------------------------------------
SalVirtualDevice* SalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
long nDX, long nDY, USHORT nBitCount )
{
SalVirtualDevice *pVirDev = new SalVirtualDevice;
// Cache values for when SalVirtualDevice::GetGraphics() is invoked
pVirDev->maVirDevData.mnBitCount = nBitCount;
pVirDev->maVirDevData.mnWidth = nDX;
pVirDev->maVirDevData.mnHeight = nDY;
return pVirDev;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
delete pDevice;
}
// -----------------------------------------------------------------------
SalPrinter* SalInstance::CreatePrinter( SalInfoPrinter* pInfoPrinter )
{
return NULL;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyPrinter( SalPrinter* pPrinter )
{
}
// -----------------------------------------------------------------------
void SalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )
{
}
// -----------------------------------------------------------------------
void SalInstance::GetPrinterQueueState( SalPrinterQueueInfo* pInfo )
{
}
// -----------------------------------------------------------------------
void SalInstance::DeletePrinterQueueInfo( SalPrinterQueueInfo* pInfo )
{
}
// -----------------------------------------------------------------------
XubString SalInstance::GetDefaultPrinter()
{
return XubString();
}
// -----------------------------------------------------------------------
SalInfoPrinter* SalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,
ImplJobSetup* pSetupData )
{
return NULL;
}
// -----------------------------------------------------------------------
void SalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )
{
}
// -----------------------------------------------------------------------
SalSystem* SalInstance::CreateSystem()
{
return new SalSystem();
}
// -----------------------------------------------------------------------
void SalInstance::DestroySystem( SalSystem* pSystem )
{
delete pSystem;
}
// -----------------------------------------------------------------------
#if SUPD > 618
void SalInstance::SetEventCallback( void* pInstance, bool(*pCallback)(void*,void*,int) )
{
}
// -----------------------------------------------------------------------
void SalInstance::SetErrorEventCallback( void* pInstance, bool(*pCallback)(void*,void*,int) )
{
}
// -----------------------------------------------------------------------
void* SalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
{
rReturnedBytes = 1;
rReturnedType = AsciiCString;
return "";
}
#endif // SUPD > 618
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: liImageRegistrationConsole.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <liImageRegistrationConsole.h>
#include <FL/fl_file_chooser.H>
#include <itkFileIOMetaImage.h>
// This macro helps to connect observers for events
#define AddObserverMacro( filter, event, widget ) \
filter->AddObserver( itk::event(), widget->GetRedrawCommand().GetPointer() );
/************************************
*
* Constructor
*
***********************************/
liImageRegistrationConsole
::liImageRegistrationConsole()
{
FileIOMetaImageFactory * factory = new FileIOMetaImageFactory;
ObjectFactoryBase * factoryBase = static_cast<ObjectFactoryBase *>( factory );
ObjectFactoryBase::RegisterFactory( factoryBase );
m_MovingImageViewer.SetLabel( "Moving Image" );
m_FixedImageViewer.SetLabel( "Fixed Image" );
m_InputMovingImageViewer.SetLabel( "Input Moving Image" );
m_MappedMovingImageViewer.SetLabel( "Mapped Moving Image" );
AddObserverMacro( m_FixedImageReader, StartEvent, fixedImageButton );
AddObserverMacro( m_FixedImageReader, EndEvent, fixedImageButton );
AddObserverMacro( m_FixedImageReader, ModifiedEvent, fixedImageButton );
AddObserverMacro( m_MovingImageReader, StartEvent, inputMovingImageButton );
AddObserverMacro( m_MovingImageReader, EndEvent, inputMovingImageButton );
AddObserverMacro( m_MovingImageReader, ModifiedEvent, inputMovingImageButton );
AddObserverMacro( m_FixedImageReader, StartEvent, loadFixedImageButton );
AddObserverMacro( m_FixedImageReader, EndEvent, loadFixedImageButton );
AddObserverMacro( m_FixedImageReader, ModifiedEvent, loadFixedImageButton );
AddObserverMacro( m_MovingImageReader, StartEvent, loadMovingImageButton );
AddObserverMacro( m_MovingImageReader, EndEvent, loadMovingImageButton );
AddObserverMacro( m_MovingImageReader, ModifiedEvent, loadMovingImageButton );
this->ShowStatus("Let's start by loading an image...");
}
/************************************
*
* Destructor
*
***********************************/
liImageRegistrationConsole
::~liImageRegistrationConsole()
{
}
/************************************
*
* Load Moving Image
*
***********************************/
void
liImageRegistrationConsole
::LoadMovingImage( void )
{
const char * filename = fl_file_chooser("Moving Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadMovingImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Moving Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Load Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::LoadFixedImage( void )
{
const char * filename = fl_file_chooser("Fixed Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadFixedImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Fixed Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Show
*
***********************************/
void
liImageRegistrationConsole
::Show( void )
{
consoleWindow->show();
}
/************************************
*
* Hide
*
***********************************/
void
liImageRegistrationConsole
::Hide( void )
{
consoleWindow->hide();
m_FixedImageViewer.Hide();
m_MovingImageViewer.Hide();
m_InputMovingImageViewer.Hide();
m_MappedMovingImageViewer.Hide();
}
/************************************
*
* Quit
*
***********************************/
void
liImageRegistrationConsole
::Quit( void )
{
this->Hide();
}
/************************************
*
* Show Progress
*
***********************************/
void
liImageRegistrationConsole
::ShowProgress( float fraction )
{
liImageRegistrationConsoleBase::ShowProgress( fraction );
progressSlider->value( fraction );
Fl::check();
}
/************************************
*
* Show Status
*
***********************************/
void
liImageRegistrationConsole
::ShowStatus( const char * message )
{
liImageRegistrationConsoleBase::ShowStatus( message );
statusTextOutput->value( message );
Fl::check();
}
/************************************
*
* Show Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::ShowFixedImage( void )
{
if( !m_FixedImageIsLoaded )
{
return;
}
m_FixedImageViewer.SetImage( m_FixedImageReader->GetOutput() );
m_FixedImageViewer.Show();
}
/************************************
*
* Show Input Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowInputMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_InputMovingImageViewer.SetImage( m_MovingImageReader->GetOutput() );
m_InputMovingImageViewer.Show();
}
/************************************
*
* Show Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
this->GenerateMovingImage();
m_MovingImageViewer.SetImage( m_ResampleInputMovingImageFilter->GetOutput() );
m_MovingImageViewer.Show();
}
/************************************
*
* Show Mapped Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_MappedMovingImageViewer.SetImage( m_ResampleMovingImageFilter->GetOutput() );
m_MappedMovingImageViewer.Show();
}
/************************************
*
* Execute
*
***********************************/
void
liImageRegistrationConsole
::Execute( void )
{
this->ShowStatus("Registering Moving Image against Fixed Image ...");
liImageRegistrationConsoleBase::Execute();
this->ShowStatus("Registration done ");
}
/************************************
*
* Update the parameters of the
* Transform
*
***********************************/
void
liImageRegistrationConsole
::UpdateTransformParameters( void )
{
typedef itk::AffineTransform<double,3> TransformType;
TransformType::Pointer affineTransform = TransformType::New();
TransformType::OffsetType offset;
TransformType::OutputVectorType axis;
const double angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
affineTransform->Rotate3D( axis, angle );
affineTransform->SetOffset( offset );
TransformType::MatrixType matrix;
matrix = affineTransform->GetMatrix();
offset = affineTransform->GetOffset();
std::cout << "Matrix = " << matrix << std::endl;
std::cout << "Offset = " << offset << std::endl;
const unsigned long numberOfParamenters =
affineTransform->GetNumberOfParameters();
TransformParametersType transformationParameters( numberOfParamenters );
unsigned int counter = 0;
for(unsigned int i=0; i<ImageDimension; i++)
{
for(unsigned int j=0; j<ImageDimension; j++)
{
transformationParameters[counter++] = matrix[i][j];
}
}
for(unsigned int k=0; k<ImageDimension; k++)
{
transformationParameters[counter++] = offset[k];
}
}
/************************************
*
* Generate Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
movingImageButton->selection_color( FL_RED );
movingImageButton->value( 1 );
movingImageButton->redraw();
AffineTransformType::OffsetType offset;
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
AffineTransformType::OutputVectorType axis;
AffineTransformType::ScalarType angle;
angle = angleRotation->value();
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
m_InputTransform->SetIdentity();
m_InputTransform->SetOffset( offset );
m_InputTransform->Rotate3D( axis, angle );
liImageRegistrationConsoleBase::GenerateMovingImage();
movingImageButton->selection_color( FL_GREEN );
movingImageButton->value( 1 );
movingImageButton->redraw();
}
/************************************
*
* Generate Mapped Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
mappedMovingImageButton->selection_color( FL_RED );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
liImageRegistrationConsoleBase::GenerateMappedMovingImage();
mappedMovingImageButton->selection_color( FL_GREEN );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
}
<commit_msg>FIX: Angle converted from degrees (from the GUI) to radians for the transform.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: liImageRegistrationConsole.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <liImageRegistrationConsole.h>
#include <FL/fl_file_chooser.H>
#include <itkFileIOMetaImage.h>
// This macro helps to connect observers for events
#define AddObserverMacro( filter, event, widget ) \
filter->AddObserver( itk::event(), widget->GetRedrawCommand().GetPointer() );
/************************************
*
* Constructor
*
***********************************/
liImageRegistrationConsole
::liImageRegistrationConsole()
{
FileIOMetaImageFactory * factory = new FileIOMetaImageFactory;
ObjectFactoryBase * factoryBase = static_cast<ObjectFactoryBase *>( factory );
ObjectFactoryBase::RegisterFactory( factoryBase );
m_MovingImageViewer.SetLabel( "Moving Image" );
m_FixedImageViewer.SetLabel( "Fixed Image" );
m_InputMovingImageViewer.SetLabel( "Input Moving Image" );
m_MappedMovingImageViewer.SetLabel( "Mapped Moving Image" );
AddObserverMacro( m_FixedImageReader, StartEvent, fixedImageButton );
AddObserverMacro( m_FixedImageReader, EndEvent, fixedImageButton );
AddObserverMacro( m_FixedImageReader, ModifiedEvent, fixedImageButton );
AddObserverMacro( m_MovingImageReader, StartEvent, inputMovingImageButton );
AddObserverMacro( m_MovingImageReader, EndEvent, inputMovingImageButton );
AddObserverMacro( m_MovingImageReader, ModifiedEvent, inputMovingImageButton );
AddObserverMacro( m_FixedImageReader, StartEvent, loadFixedImageButton );
AddObserverMacro( m_FixedImageReader, EndEvent, loadFixedImageButton );
AddObserverMacro( m_FixedImageReader, ModifiedEvent, loadFixedImageButton );
AddObserverMacro( m_MovingImageReader, StartEvent, loadMovingImageButton );
AddObserverMacro( m_MovingImageReader, EndEvent, loadMovingImageButton );
AddObserverMacro( m_MovingImageReader, ModifiedEvent, loadMovingImageButton );
this->ShowStatus("Let's start by loading an image...");
}
/************************************
*
* Destructor
*
***********************************/
liImageRegistrationConsole
::~liImageRegistrationConsole()
{
}
/************************************
*
* Load Moving Image
*
***********************************/
void
liImageRegistrationConsole
::LoadMovingImage( void )
{
const char * filename = fl_file_chooser("Moving Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadMovingImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Moving Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Load Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::LoadFixedImage( void )
{
const char * filename = fl_file_chooser("Fixed Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadFixedImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Fixed Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Show
*
***********************************/
void
liImageRegistrationConsole
::Show( void )
{
consoleWindow->show();
}
/************************************
*
* Hide
*
***********************************/
void
liImageRegistrationConsole
::Hide( void )
{
consoleWindow->hide();
m_FixedImageViewer.Hide();
m_MovingImageViewer.Hide();
m_InputMovingImageViewer.Hide();
m_MappedMovingImageViewer.Hide();
}
/************************************
*
* Quit
*
***********************************/
void
liImageRegistrationConsole
::Quit( void )
{
this->Hide();
}
/************************************
*
* Show Progress
*
***********************************/
void
liImageRegistrationConsole
::ShowProgress( float fraction )
{
liImageRegistrationConsoleBase::ShowProgress( fraction );
progressSlider->value( fraction );
Fl::check();
}
/************************************
*
* Show Status
*
***********************************/
void
liImageRegistrationConsole
::ShowStatus( const char * message )
{
liImageRegistrationConsoleBase::ShowStatus( message );
statusTextOutput->value( message );
Fl::check();
}
/************************************
*
* Show Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::ShowFixedImage( void )
{
if( !m_FixedImageIsLoaded )
{
return;
}
m_FixedImageViewer.SetImage( m_FixedImageReader->GetOutput() );
m_FixedImageViewer.Show();
}
/************************************
*
* Show Input Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowInputMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_InputMovingImageViewer.SetImage( m_MovingImageReader->GetOutput() );
m_InputMovingImageViewer.Show();
}
/************************************
*
* Show Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
this->GenerateMovingImage();
m_MovingImageViewer.SetImage( m_ResampleInputMovingImageFilter->GetOutput() );
m_MovingImageViewer.Show();
}
/************************************
*
* Show Mapped Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_MappedMovingImageViewer.SetImage( m_ResampleMovingImageFilter->GetOutput() );
m_MappedMovingImageViewer.Show();
}
/************************************
*
* Execute
*
***********************************/
void
liImageRegistrationConsole
::Execute( void )
{
this->ShowStatus("Registering Moving Image against Fixed Image ...");
liImageRegistrationConsoleBase::Execute();
this->ShowStatus("Registration done ");
}
/************************************
*
* Update the parameters of the
* Transform
*
***********************************/
void
liImageRegistrationConsole
::UpdateTransformParameters( void )
{
typedef itk::AffineTransform<double,3> TransformType;
TransformType::Pointer affineTransform = TransformType::New();
TransformType::OffsetType offset;
TransformType::OutputVectorType axis;
const double angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
affineTransform->Rotate3D( axis, angle );
affineTransform->SetOffset( offset );
TransformType::MatrixType matrix;
matrix = affineTransform->GetMatrix();
offset = affineTransform->GetOffset();
std::cout << "Matrix = " << matrix << std::endl;
std::cout << "Offset = " << offset << std::endl;
const unsigned long numberOfParamenters =
affineTransform->GetNumberOfParameters();
TransformParametersType transformationParameters( numberOfParamenters );
unsigned int counter = 0;
for(unsigned int i=0; i<ImageDimension; i++)
{
for(unsigned int j=0; j<ImageDimension; j++)
{
transformationParameters[counter++] = matrix[i][j];
}
}
for(unsigned int k=0; k<ImageDimension; k++)
{
transformationParameters[counter++] = offset[k];
}
}
/************************************
*
* Generate Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
movingImageButton->selection_color( FL_RED );
movingImageButton->value( 1 );
movingImageButton->redraw();
AffineTransformType::OffsetType offset;
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
AffineTransformType::OutputVectorType axis;
AffineTransformType::ScalarType angle;
angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
m_InputTransform->SetIdentity();
m_InputTransform->SetOffset( offset );
m_InputTransform->Rotate3D( axis, angle );
liImageRegistrationConsoleBase::GenerateMovingImage();
movingImageButton->selection_color( FL_GREEN );
movingImageButton->value( 1 );
movingImageButton->redraw();
}
/************************************
*
* Generate Mapped Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
mappedMovingImageButton->selection_color( FL_RED );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
liImageRegistrationConsoleBase::GenerateMappedMovingImage();
mappedMovingImageButton->selection_color( FL_GREEN );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "sal/config.h"
#include <list>
#include <memory>
#include <utility>
#include <vector>
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
#include "com/sun/star/container/XNameAccess.hpp"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/lang/Locale.hpp"
#include "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "comphelper/processfactory.hxx"
#include "osl/file.hxx"
#include "osl/diagnose.h"
#include "rtl/bootstrap.hxx"
#include "rtl/string.h"
#include "rtl/textenc.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "tools/stream.hxx"
#include "tools/urlobj.hxx"
#include "vcl/bitmapex.hxx"
#include "vcl/pngread.hxx"
#include "vcl/settings.hxx"
#include "vcl/svapp.hxx"
#include "impimagetree.hxx"
namespace {
OUString createPath(
OUString const & name, sal_Int32 pos, OUString const & locale)
{
OUStringBuffer b(name.copy(0, pos + 1));
b.append(locale);
b.append(name.copy(pos));
return b.makeStringAndClear();
}
boost::shared_ptr< SvStream > wrapFile(osl::File & file)
{
// This could use SvInputStream instead if that did not have a broken
// SeekPos implementation for an XInputStream that is not also XSeekable
// (cf. "@@@" at tags/DEV300_m37/svtools/source/misc1/strmadpt.cxx@264807
// l. 593):
boost::shared_ptr< SvStream > s(new SvMemoryStream);
for (;;) {
void *data[2048];
sal_uInt64 n;
file.read(data, 2048, n);
s->Write(data, n);
if (n < 2048) {
break;
}
}
s->Seek(0);
return s;
}
void loadFromFile(
osl::File & file,
OUString const & path, BitmapEx & bitmap)
{
boost::shared_ptr< SvStream > s(wrapFile(file));
if (path.endsWith(".png"))
{
vcl::PNGReader aPNGReader( *s );
aPNGReader.SetIgnoreGammaChunk( sal_True );
bitmap = aPNGReader.Read();
} else {
*s >> bitmap;
}
}
boost::shared_ptr< SvStream > wrapStream(
css::uno::Reference< css::io::XInputStream > const & stream)
{
// This could use SvInputStream instead if that did not have a broken
// SeekPos implementation for an XInputStream that is not also XSeekable
// (cf. "@@@" at tags/DEV300_m37/svtools/source/misc1/strmadpt.cxx@264807
// l. 593):
OSL_ASSERT(stream.is());
boost::shared_ptr< SvStream > s(new SvMemoryStream);
for (;;) {
sal_Int32 const size = 2048;
css::uno::Sequence< sal_Int8 > data(size);
sal_Int32 n = stream->readBytes(data, size);
s->Write(data.getConstArray(), n);
if (n < size) {
break;
}
}
s->Seek(0);
return s;
}
void loadFromStream(
css::uno::Reference< css::io::XInputStream > const & stream,
OUString const & path, BitmapEx & bitmap)
{
boost::shared_ptr< SvStream > s(wrapStream(stream));
if (path.endsWith(".png"))
{
vcl::PNGReader aPNGReader( *s );
aPNGReader.SetIgnoreGammaChunk( sal_True );
bitmap = aPNGReader.Read();
} else {
*s >> bitmap;
}
}
}
ImplImageTree::ImplImageTree() { m_cacheIcons = true; }
ImplImageTree::~ImplImageTree() {}
bool ImplImageTree::checkStyle(OUString const & style)
{
bool exists;
// using cache because setStyle is an expensive operation
// setStyle calls resetPaths => closes any opened zip files with icons, cleans the icon cache, ...
if (checkStyleCacheLookup(style, exists)) {
return exists;
}
setStyle(style);
exists = false;
const OUString sBrandURLSuffix("_brand");
for (Paths::iterator i(m_paths.begin()); i != m_paths.end() && !exists; ++i) {
OUString aURL = i->first;
sal_Int32 nFromIndex = aURL.getLength() - sBrandURLSuffix.getLength();
// skip brand-specific icon themes; they are incomplete and thus not useful for this check
if (nFromIndex < 0 || !aURL.match(sBrandURLSuffix, nFromIndex)) {
osl::File aZip(aURL + ".zip");
if (aZip.open(osl_File_OpenFlag_Read) == ::osl::FileBase::E_None) {
aZip.close();
exists = true;
}
osl::Directory aLookaside(aURL);
if (aLookaside.open() == ::osl::FileBase::E_None) {
aLookaside.close();
exists = true;
m_cacheIcons = false;
} else {
m_cacheIcons = true;
}
}
}
m_checkStyleCache[style] = exists;
return exists;
}
bool ImplImageTree::loadImage(
OUString const & name, OUString const & style, BitmapEx & bitmap,
bool localized, bool loadMissing )
{
bool found = false;
try {
found = doLoadImage(name, style, bitmap, localized);
} catch (css::uno::RuntimeException &) {
if (!loadMissing)
throw;
}
if (found || !loadMissing)
return found;
SAL_INFO("vcl", "ImplImageTree::loadImage exception couldn't load \""
<< name << "\", fetching default image");
return loadDefaultImage(style, bitmap);
}
bool ImplImageTree::loadDefaultImage(
OUString const & style,
BitmapEx& bitmap)
{
return doLoadImage(
OUString("res/grafikde.png"),
style, bitmap, false);
}
bool ImplImageTree::doLoadImage(
OUString const & name, OUString const & style, BitmapEx & bitmap,
bool localized)
{
setStyle(style);
if (m_cacheIcons && iconCacheLookup(name, localized, bitmap)) {
return true;
}
if (!bitmap.IsEmpty()) {
bitmap.SetEmpty();
}
std::vector< OUString > paths;
paths.push_back(name);
if (localized) {
sal_Int32 pos = name.lastIndexOf('/');
if (pos != -1) {
/* FIXME-BCP47: this needs to be changed for language tags! */
css::lang::Locale const & loc =
Application::GetSettings().GetUILanguageTag().getLocale();
paths.push_back(createPath(name, pos, loc.Language));
if (!loc.Country.isEmpty()) {
OUStringBuffer b(loc.Language);
b.append(sal_Unicode('-'));
b.append(loc.Country);
OUString p(createPath(name, pos, b.makeStringAndClear()));
paths.push_back(p);
if (!loc.Variant.isEmpty()) {
b.append(p);
b.append(sal_Unicode('-'));
b.append(loc.Variant);
paths.push_back(
createPath(name, pos, b.makeStringAndClear()));
}
}
}
}
bool found = false;
try {
found = find(paths, bitmap);
} catch (css::uno::RuntimeException &) {
throw;
} catch (const css::uno::Exception & e) {
SAL_INFO("vcl", "ImplImageTree::doLoadImage exception " << e.Message);
}
if (m_cacheIcons && found) {
m_iconCache[name.intern()] = std::make_pair(localized, bitmap);
}
return found;
}
void ImplImageTree::shutDown() {
m_style = OUString();
// for safety; empty m_style means "not initialized"
m_paths.clear();
m_iconCache.clear();
m_checkStyleCache.clear();
}
void ImplImageTree::setStyle(OUString const & style) {
OSL_ASSERT(!style.isEmpty()); // empty m_style means "not initialized"
if (style != m_style) {
m_style = style;
resetPaths();
m_iconCache.clear();
}
}
void ImplImageTree::resetPaths() {
m_paths.clear();
{
OUString url(
"$BRAND_BASE_DIR/program/edition/images");
rtl::Bootstrap::expandMacros(url);
INetURLObject u(url);
OSL_ASSERT(!u.HasError());
m_paths.push_back(
std::make_pair(
u.GetMainURL(INetURLObject::NO_DECODE),
css::uno::Reference< css::container::XNameAccess >()));
}
{
OUString url(
"$BRAND_BASE_DIR/share/config");
rtl::Bootstrap::expandMacros(url);
INetURLObject u(url);
OSL_ASSERT(!u.HasError());
OUStringBuffer b;
b.appendAscii("images_");
b.append(m_style);
b.appendAscii("_brand");
bool ok = u.Append(b.makeStringAndClear(), INetURLObject::ENCODE_ALL);
OSL_ASSERT(ok); (void) ok;
m_paths.push_back(
std::make_pair(
u.GetMainURL(INetURLObject::NO_DECODE),
css::uno::Reference< css::container::XNameAccess >()));
}
{
OUString url( "$BRAND_BASE_DIR/share/config/images_brand");
rtl::Bootstrap::expandMacros(url);
m_paths.push_back(
std::make_pair(
url, css::uno::Reference< css::container::XNameAccess >()));
}
{
OUString url(
"$BRAND_BASE_DIR/share/config");
rtl::Bootstrap::expandMacros(url);
INetURLObject u(url);
OSL_ASSERT(!u.HasError());
OUStringBuffer b;
b.appendAscii("images_");
b.append(m_style);
bool ok = u.Append(b.makeStringAndClear(), INetURLObject::ENCODE_ALL);
OSL_ASSERT(ok); (void) ok;
m_paths.push_back(
std::make_pair(
u.GetMainURL(INetURLObject::NO_DECODE),
css::uno::Reference< css::container::XNameAccess >()));
}
if ( m_style == "default" )
{
OUString url( "$BRAND_BASE_DIR/share/config/images");
rtl::Bootstrap::expandMacros(url);
m_paths.push_back(
std::make_pair(
url, css::uno::Reference< css::container::XNameAccess >()));
}
}
bool ImplImageTree::checkStyleCacheLookup(
OUString const & style, bool &exists)
{
CheckStyleCache::iterator i(m_checkStyleCache.find(style));
if (i != m_checkStyleCache.end()) {
exists = i->second;
return true;
} else {
return false;
}
}
bool ImplImageTree::iconCacheLookup(
OUString const & name, bool localized, BitmapEx & bitmap)
{
IconCache::iterator i(m_iconCache.find(name));
if (i != m_iconCache.end() && i->second.first == localized) {
bitmap = i->second.second;
return true;
} else {
return false;
}
}
bool ImplImageTree::find(
std::vector< OUString > const & paths, BitmapEx & bitmap)
{
if (!m_cacheIcons) {
for (Paths::iterator i(m_paths.begin()); i != m_paths.end(); ++i) {
for (std::vector< OUString >::const_reverse_iterator j(
paths.rbegin());
j != paths.rend(); ++j)
{
osl::File file(i->first + "/" + *j);
if (file.open(osl_File_OpenFlag_Read) == ::osl::FileBase::E_None) {
loadFromFile(file, *j, bitmap);
file.close();
return true;
}
}
}
}
for (Paths::iterator i(m_paths.begin()); i != m_paths.end();) {
if (!i->second.is()) {
css::uno::Sequence< css::uno::Any > args(1);
args[0] <<= i->first + ".zip";
try {
i->second.set(
comphelper::getProcessServiceFactory()->createInstanceWithArguments(
OUString( "com.sun.star.packages.zip.ZipFileAccess"),
args),
css::uno::UNO_QUERY_THROW);
} catch (css::uno::RuntimeException &) {
throw;
} catch (const css::uno::Exception & e) {
SAL_INFO("vcl", "ImplImageTree::find exception "
<< e.Message << " for " << i->first);
i = m_paths.erase(i);
continue;
}
}
for (std::vector< OUString >::const_reverse_iterator j(
paths.rbegin());
j != paths.rend(); ++j)
{
if (i->second->hasByName(*j)) {
css::uno::Reference< css::io::XInputStream > s;
bool ok = i->second->getByName(*j) >>= s;
OSL_ASSERT(ok); (void) ok;
loadFromStream(s, *j, bitmap);
return true;
}
}
++i;
}
return false;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>use LanguageTag fallback<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "sal/config.h"
#include <list>
#include <memory>
#include <utility>
#include <vector>
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
#include "com/sun/star/container/XNameAccess.hpp"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/lang/Locale.hpp"
#include "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "comphelper/processfactory.hxx"
#include "osl/file.hxx"
#include "osl/diagnose.h"
#include "rtl/bootstrap.hxx"
#include "rtl/string.h"
#include "rtl/textenc.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "tools/stream.hxx"
#include "tools/urlobj.hxx"
#include "vcl/bitmapex.hxx"
#include "vcl/pngread.hxx"
#include "vcl/settings.hxx"
#include "vcl/svapp.hxx"
#include "impimagetree.hxx"
namespace {
OUString createPath(
OUString const & name, sal_Int32 pos, OUString const & locale)
{
OUStringBuffer b(name.copy(0, pos + 1));
b.append(locale);
b.append(name.copy(pos));
return b.makeStringAndClear();
}
boost::shared_ptr< SvStream > wrapFile(osl::File & file)
{
// This could use SvInputStream instead if that did not have a broken
// SeekPos implementation for an XInputStream that is not also XSeekable
// (cf. "@@@" at tags/DEV300_m37/svtools/source/misc1/strmadpt.cxx@264807
// l. 593):
boost::shared_ptr< SvStream > s(new SvMemoryStream);
for (;;) {
void *data[2048];
sal_uInt64 n;
file.read(data, 2048, n);
s->Write(data, n);
if (n < 2048) {
break;
}
}
s->Seek(0);
return s;
}
void loadFromFile(
osl::File & file,
OUString const & path, BitmapEx & bitmap)
{
boost::shared_ptr< SvStream > s(wrapFile(file));
if (path.endsWith(".png"))
{
vcl::PNGReader aPNGReader( *s );
aPNGReader.SetIgnoreGammaChunk( sal_True );
bitmap = aPNGReader.Read();
} else {
*s >> bitmap;
}
}
boost::shared_ptr< SvStream > wrapStream(
css::uno::Reference< css::io::XInputStream > const & stream)
{
// This could use SvInputStream instead if that did not have a broken
// SeekPos implementation for an XInputStream that is not also XSeekable
// (cf. "@@@" at tags/DEV300_m37/svtools/source/misc1/strmadpt.cxx@264807
// l. 593):
OSL_ASSERT(stream.is());
boost::shared_ptr< SvStream > s(new SvMemoryStream);
for (;;) {
sal_Int32 const size = 2048;
css::uno::Sequence< sal_Int8 > data(size);
sal_Int32 n = stream->readBytes(data, size);
s->Write(data.getConstArray(), n);
if (n < size) {
break;
}
}
s->Seek(0);
return s;
}
void loadFromStream(
css::uno::Reference< css::io::XInputStream > const & stream,
OUString const & path, BitmapEx & bitmap)
{
boost::shared_ptr< SvStream > s(wrapStream(stream));
if (path.endsWith(".png"))
{
vcl::PNGReader aPNGReader( *s );
aPNGReader.SetIgnoreGammaChunk( sal_True );
bitmap = aPNGReader.Read();
} else {
*s >> bitmap;
}
}
}
ImplImageTree::ImplImageTree() { m_cacheIcons = true; }
ImplImageTree::~ImplImageTree() {}
bool ImplImageTree::checkStyle(OUString const & style)
{
bool exists;
// using cache because setStyle is an expensive operation
// setStyle calls resetPaths => closes any opened zip files with icons, cleans the icon cache, ...
if (checkStyleCacheLookup(style, exists)) {
return exists;
}
setStyle(style);
exists = false;
const OUString sBrandURLSuffix("_brand");
for (Paths::iterator i(m_paths.begin()); i != m_paths.end() && !exists; ++i) {
OUString aURL = i->first;
sal_Int32 nFromIndex = aURL.getLength() - sBrandURLSuffix.getLength();
// skip brand-specific icon themes; they are incomplete and thus not useful for this check
if (nFromIndex < 0 || !aURL.match(sBrandURLSuffix, nFromIndex)) {
osl::File aZip(aURL + ".zip");
if (aZip.open(osl_File_OpenFlag_Read) == ::osl::FileBase::E_None) {
aZip.close();
exists = true;
}
osl::Directory aLookaside(aURL);
if (aLookaside.open() == ::osl::FileBase::E_None) {
aLookaside.close();
exists = true;
m_cacheIcons = false;
} else {
m_cacheIcons = true;
}
}
}
m_checkStyleCache[style] = exists;
return exists;
}
bool ImplImageTree::loadImage(
OUString const & name, OUString const & style, BitmapEx & bitmap,
bool localized, bool loadMissing )
{
bool found = false;
try {
found = doLoadImage(name, style, bitmap, localized);
} catch (css::uno::RuntimeException &) {
if (!loadMissing)
throw;
}
if (found || !loadMissing)
return found;
SAL_INFO("vcl", "ImplImageTree::loadImage exception couldn't load \""
<< name << "\", fetching default image");
return loadDefaultImage(style, bitmap);
}
bool ImplImageTree::loadDefaultImage(
OUString const & style,
BitmapEx& bitmap)
{
return doLoadImage(
OUString("res/grafikde.png"),
style, bitmap, false);
}
bool ImplImageTree::doLoadImage(
OUString const & name, OUString const & style, BitmapEx & bitmap,
bool localized)
{
setStyle(style);
if (m_cacheIcons && iconCacheLookup(name, localized, bitmap)) {
return true;
}
if (!bitmap.IsEmpty()) {
bitmap.SetEmpty();
}
std::vector< OUString > paths;
paths.push_back(name);
if (localized) {
sal_Int32 pos = name.lastIndexOf('/');
if (pos != -1) {
// find() uses a reverse iterator, so push in reverse order.
std::vector< OUString > aFallbacks( Application::GetSettings().GetUILanguageTag().getFallbackStrings());
for (std::vector< OUString >::const_reverse_iterator it( aFallbacks.rbegin());
it != aFallbacks.rend(); ++it)
{
paths.push_back(createPath(name, pos, *it));
}
}
}
bool found = false;
try {
found = find(paths, bitmap);
} catch (css::uno::RuntimeException &) {
throw;
} catch (const css::uno::Exception & e) {
SAL_INFO("vcl", "ImplImageTree::doLoadImage exception " << e.Message);
}
if (m_cacheIcons && found) {
m_iconCache[name.intern()] = std::make_pair(localized, bitmap);
}
return found;
}
void ImplImageTree::shutDown() {
m_style = OUString();
// for safety; empty m_style means "not initialized"
m_paths.clear();
m_iconCache.clear();
m_checkStyleCache.clear();
}
void ImplImageTree::setStyle(OUString const & style) {
OSL_ASSERT(!style.isEmpty()); // empty m_style means "not initialized"
if (style != m_style) {
m_style = style;
resetPaths();
m_iconCache.clear();
}
}
void ImplImageTree::resetPaths() {
m_paths.clear();
{
OUString url(
"$BRAND_BASE_DIR/program/edition/images");
rtl::Bootstrap::expandMacros(url);
INetURLObject u(url);
OSL_ASSERT(!u.HasError());
m_paths.push_back(
std::make_pair(
u.GetMainURL(INetURLObject::NO_DECODE),
css::uno::Reference< css::container::XNameAccess >()));
}
{
OUString url(
"$BRAND_BASE_DIR/share/config");
rtl::Bootstrap::expandMacros(url);
INetURLObject u(url);
OSL_ASSERT(!u.HasError());
OUStringBuffer b;
b.appendAscii("images_");
b.append(m_style);
b.appendAscii("_brand");
bool ok = u.Append(b.makeStringAndClear(), INetURLObject::ENCODE_ALL);
OSL_ASSERT(ok); (void) ok;
m_paths.push_back(
std::make_pair(
u.GetMainURL(INetURLObject::NO_DECODE),
css::uno::Reference< css::container::XNameAccess >()));
}
{
OUString url( "$BRAND_BASE_DIR/share/config/images_brand");
rtl::Bootstrap::expandMacros(url);
m_paths.push_back(
std::make_pair(
url, css::uno::Reference< css::container::XNameAccess >()));
}
{
OUString url(
"$BRAND_BASE_DIR/share/config");
rtl::Bootstrap::expandMacros(url);
INetURLObject u(url);
OSL_ASSERT(!u.HasError());
OUStringBuffer b;
b.appendAscii("images_");
b.append(m_style);
bool ok = u.Append(b.makeStringAndClear(), INetURLObject::ENCODE_ALL);
OSL_ASSERT(ok); (void) ok;
m_paths.push_back(
std::make_pair(
u.GetMainURL(INetURLObject::NO_DECODE),
css::uno::Reference< css::container::XNameAccess >()));
}
if ( m_style == "default" )
{
OUString url( "$BRAND_BASE_DIR/share/config/images");
rtl::Bootstrap::expandMacros(url);
m_paths.push_back(
std::make_pair(
url, css::uno::Reference< css::container::XNameAccess >()));
}
}
bool ImplImageTree::checkStyleCacheLookup(
OUString const & style, bool &exists)
{
CheckStyleCache::iterator i(m_checkStyleCache.find(style));
if (i != m_checkStyleCache.end()) {
exists = i->second;
return true;
} else {
return false;
}
}
bool ImplImageTree::iconCacheLookup(
OUString const & name, bool localized, BitmapEx & bitmap)
{
IconCache::iterator i(m_iconCache.find(name));
if (i != m_iconCache.end() && i->second.first == localized) {
bitmap = i->second.second;
return true;
} else {
return false;
}
}
bool ImplImageTree::find(
std::vector< OUString > const & paths, BitmapEx & bitmap)
{
if (!m_cacheIcons) {
for (Paths::iterator i(m_paths.begin()); i != m_paths.end(); ++i) {
for (std::vector< OUString >::const_reverse_iterator j(
paths.rbegin());
j != paths.rend(); ++j)
{
osl::File file(i->first + "/" + *j);
if (file.open(osl_File_OpenFlag_Read) == ::osl::FileBase::E_None) {
loadFromFile(file, *j, bitmap);
file.close();
return true;
}
}
}
}
for (Paths::iterator i(m_paths.begin()); i != m_paths.end();) {
if (!i->second.is()) {
css::uno::Sequence< css::uno::Any > args(1);
args[0] <<= i->first + ".zip";
try {
i->second.set(
comphelper::getProcessServiceFactory()->createInstanceWithArguments(
OUString( "com.sun.star.packages.zip.ZipFileAccess"),
args),
css::uno::UNO_QUERY_THROW);
} catch (css::uno::RuntimeException &) {
throw;
} catch (const css::uno::Exception & e) {
SAL_INFO("vcl", "ImplImageTree::find exception "
<< e.Message << " for " << i->first);
i = m_paths.erase(i);
continue;
}
}
for (std::vector< OUString >::const_reverse_iterator j(
paths.rbegin());
j != paths.rend(); ++j)
{
if (i->second->hasByName(*j)) {
css::uno::Reference< css::io::XInputStream > s;
bool ok = i->second->getByName(*j) >>= s;
OSL_ASSERT(ok); (void) ok;
loadFromStream(s, *j, bitmap);
return true;
}
}
++i;
}
return false;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich 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 "handlers/HPositionLayout.h"
#include "VisualizationBase/src/layouts/PositionLayout.h"
#include "VisualizationBase/src/Scene.h"
#include "ModelBase/src/model/Model.h"
namespace Interaction {
HPositionLayout::HPositionLayout() : originalX(0), originalY(0), currentItem(nullptr), currentItemPosition(nullptr)
{
}
HPositionLayout* HPositionLayout::instance()
{
static HPositionLayout h;
return &h;
}
void HPositionLayout::mousePressEvent(Visualization::Item *target, QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier)
{
Visualization::PositionLayout* layout = static_cast<Visualization::PositionLayout*> (target);
// Find out which of the children has the cursor.
// If there is only child or there is no child selected do not allow movement and ignore this event.
Visualization::Item* itemToMove = nullptr;
if (layout->length() >=2)
{
for(int i = 0; i<layout->length(); ++i)
{
itemToMove = layout->at<Visualization::Item>(i);
if (itemToMove->contains(itemToMove->mapFromParent(event->pos()))) break;
else itemToMove = nullptr;
}
}
if (itemToMove)
{
Model::CompositeNode* composite = static_cast<Model::CompositeNode*> (itemToMove->node());
Visualization::Position* pos = composite->extension<Visualization::Position>();
target->scene()->clearSelection();
target->scene()->clearFocus();
itemToMove->setSelected(true);
originalX = pos->xNode() ? pos->x() : 0;
originalY = pos->yNode() ? pos->y() : 0;
currentItem = itemToMove;
currentItemPosition = pos;
}
else event->ignore();
}
else event->ignore();//GenericHandler::mousePressEvent(target, event);
}
void HPositionLayout::mouseMoveEvent(Visualization::Item *target, QGraphicsSceneMouseEvent *event)
{
if (event->modifiers() == Qt::ControlModifier && !event->buttonDownPos( Qt::LeftButton).isNull() )
{
if (currentItem)
{
Visualization::PositionLayout* layout = static_cast<Visualization::PositionLayout*> (target);
int newX = layout->toGrid( originalX + event->pos().x() - event->buttonDownPos(Qt::LeftButton).x() );
int newY = layout->toGrid( originalY + event->pos().y() - event->buttonDownPos(Qt::LeftButton).y() );;
int currentItemPositionX = currentItemPosition->xNode() ? currentItemPosition->x() : 0;
int currentItemPositionY = currentItemPosition->yNode() ? currentItemPosition->y() : 0;
if (newX != currentItemPositionX || newY != currentItemPositionY)
{
currentItem->node()->model()->beginModification(currentItem->node(),"Change position");
currentItemPosition->setX( newX );
currentItemPosition->setY( newY );
currentItem->node()->model()->endModification();
currentItem->setUpdateNeeded(Visualization::Item::StandardUpdate);
target->scene()->scheduleUpdate();
}
}
}
else GenericHandler::mouseMoveEvent(target, event);
}
void HPositionLayout::mouseReleaseEvent(Visualization::Item *target, QGraphicsSceneMouseEvent *event)
{
if (event->modifiers() == Qt::ControlModifier && !event->button() == Qt::LeftButton)
{
currentItem = nullptr;
currentItemPosition = nullptr;
}
else GenericHandler::mouseReleaseEvent(target, event);
}
}
<commit_msg>Move items by holding Shift, not CTRL as before<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich 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 "handlers/HPositionLayout.h"
#include "VisualizationBase/src/layouts/PositionLayout.h"
#include "VisualizationBase/src/Scene.h"
#include "ModelBase/src/model/Model.h"
namespace Interaction {
HPositionLayout::HPositionLayout() : originalX(0), originalY(0), currentItem(nullptr), currentItemPosition(nullptr)
{
}
HPositionLayout* HPositionLayout::instance()
{
static HPositionLayout h;
return &h;
}
void HPositionLayout::mousePressEvent(Visualization::Item *target, QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && event->modifiers() == Qt::ShiftModifier)
{
Visualization::PositionLayout* layout = static_cast<Visualization::PositionLayout*> (target);
// Find out which of the children has the cursor.
// If there is only child or there is no child selected do not allow movement and ignore this event.
Visualization::Item* itemToMove = nullptr;
if (layout->length() >=2)
{
for(int i = 0; i<layout->length(); ++i)
{
itemToMove = layout->at<Visualization::Item>(i);
if (itemToMove->contains(itemToMove->mapFromParent(event->pos()))) break;
else itemToMove = nullptr;
}
}
if (itemToMove)
{
Model::CompositeNode* composite = static_cast<Model::CompositeNode*> (itemToMove->node());
Visualization::Position* pos = composite->extension<Visualization::Position>();
target->scene()->clearSelection();
target->scene()->clearFocus();
itemToMove->setSelected(true);
originalX = pos->xNode() ? pos->x() : 0;
originalY = pos->yNode() ? pos->y() : 0;
currentItem = itemToMove;
currentItemPosition = pos;
}
else event->ignore();
}
else event->ignore();//GenericHandler::mousePressEvent(target, event);
}
void HPositionLayout::mouseMoveEvent(Visualization::Item *target, QGraphicsSceneMouseEvent *event)
{
if (currentItem)
{
Visualization::PositionLayout* layout = static_cast<Visualization::PositionLayout*> (target);
int newX = layout->toGrid( originalX + event->pos().x() - event->buttonDownPos(Qt::LeftButton).x() );
int newY = layout->toGrid( originalY + event->pos().y() - event->buttonDownPos(Qt::LeftButton).y() );;
int currentItemPositionX = currentItemPosition->xNode() ? currentItemPosition->x() : 0;
int currentItemPositionY = currentItemPosition->yNode() ? currentItemPosition->y() : 0;
if (newX != currentItemPositionX || newY != currentItemPositionY)
{
currentItem->node()->model()->beginModification(currentItem->node(),"Change position");
currentItemPosition->setX( newX );
currentItemPosition->setY( newY );
currentItem->node()->model()->endModification();
currentItem->setUpdateNeeded(Visualization::Item::StandardUpdate);
target->scene()->scheduleUpdate();
}
}
}
void HPositionLayout::mouseReleaseEvent(Visualization::Item *, QGraphicsSceneMouseEvent *)
{
currentItem = nullptr;
currentItemPosition = nullptr;
}
}
<|endoftext|>
|
<commit_before>
/*==================================================================
Program: Visualization Toolkit
Module: TestHyperTreeGridTernary3DClip.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
===================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware 2013
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)
#include "vtkHyperTreeGrid.h"
#include "vtkHyperTreeGridToUnstructuredGrid.h"
#include "vtkHyperTreeGridSource.h"
#include "vtkCamera.h"
#include "vtkPointData.h"
#include "vtkClipDataSet.h"
#include "vtkDataSetMapper.h"
#include "vtkNew.h"
#include "vtkPlane.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkShrinkFilter.h"
#include "vtkUnstructuredGrid.h"
int TestHyperTreeGridTernary3DClip( int argc, char* argv[] )
{
// Hyper tree grid
vtkNew<vtkHyperTreeGridSource> htGrid;
htGrid->SetMaximumLevel( 5 );
htGrid->SetGridSize( 3, 3, 2 );
htGrid->SetGridScale( 1.5, 1., .7 );
htGrid->SetDimension( 3 );
htGrid->SetBranchFactor( 3 );
htGrid->SetDescriptor( "RRR .R. .RR ..R ..R .R.|R.......................... ........................... ........................... .............R............. ....RR.RR........R......... .....RRRR.....R.RR......... ........................... ........................... ...........................|........................... ........................... ........................... ...RR.RR.......RR.......... ........................... RR......................... ........................... ........................... ........................... ........................... ........................... ........................... ........................... ............RRR............|........................... ........................... .......RR.................. ........................... ........................... ........................... ........................... ........................... ........................... ........................... ...........................|........................... ..........................." );
// Hyper tree grid to unstructured grid filter
vtkNew<vtkHyperTreeGridToUnstructuredGrid> htg2ug;
htg2ug->SetInputConnection( htGrid->GetOutputPort() );
// Cuts
vtkNew<vtkPlane> plane;
plane->SetOrigin( 0., .5, .4 );
plane->SetNormal( -.2, -.6, 1. );
vtkNew<vtkClipDataSet> clip;
clip->SetInputConnection( htGrid->GetOutputPort() );
clip->SetClipFunction( plane.GetPointer() );
// Shrink
vtkNew<vtkShrinkFilter> shrink;
shrink->SetInputConnection( clip->GetOutputPort() );
shrink->SetShrinkFactor( .8 );
// Mappers
clip->Update();
double* range = clip->GetOutput()->GetPointData()->GetScalars()->GetRange();
vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 );
vtkNew<vtkDataSetMapper> mapper1;
mapper1->SetInputConnection( clip->GetOutputPort() );
mapper1->SetScalarRange( range );
vtkNew<vtkDataSetMapper> mapper2;
mapper2->SetInputConnection( htg2ug->GetOutputPort() );
mapper2->ScalarVisibilityOff();
vtkNew<vtkDataSetMapper> mapper3;
mapper3->SetInputConnection( shrink->GetOutputPort() );
mapper3->SetScalarRange( range );
// Actors
vtkNew<vtkActor> actor1;
actor1->SetMapper( mapper1.GetPointer() );
vtkNew<vtkActor> actor2;
actor2->SetMapper( mapper2.GetPointer() );
actor2->GetProperty()->SetRepresentationToWireframe();
actor2->GetProperty()->SetColor( .8, .8, .8 );
vtkNew<vtkActor> actor3;
actor3->SetMapper( mapper3.GetPointer() );
// Camera
vtkHyperTreeGrid* ht = htGrid->GetOutput();
double bd[6];
ht->GetBounds( bd );
vtkNew<vtkCamera> camera;
camera->SetClippingRange( 1., 100. );
camera->SetFocalPoint( ht->GetCenter() );
camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] );
// Renderer
vtkNew<vtkRenderer> renderer;
renderer->SetActiveCamera( camera.GetPointer() );
renderer->SetBackground( 1., 1., 1. );
//renderer->AddActor( actor1.GetPointer() );
renderer->AddActor( actor2.GetPointer() );
renderer->AddActor( actor3.GetPointer() );
// Render window
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer( renderer.GetPointer() );
renWin->SetSize( 400, 400 );
renWin->SetMultiSamples( 0 );
// Interactor
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow( renWin.GetPointer() );
// Render and test
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR )
{
iren->Start();
}
return !retVal;
}
<commit_msg>Whitespace cleanup<commit_after>/*==================================================================
Program: Visualization Toolkit
Module: TestHyperTreeGridTernary3DClip.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
===================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware 2013
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)
#include "vtkHyperTreeGrid.h"
#include "vtkHyperTreeGridToUnstructuredGrid.h"
#include "vtkHyperTreeGridSource.h"
#include "vtkCamera.h"
#include "vtkPointData.h"
#include "vtkClipDataSet.h"
#include "vtkDataSetMapper.h"
#include "vtkNew.h"
#include "vtkPlane.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkShrinkFilter.h"
#include "vtkUnstructuredGrid.h"
int TestHyperTreeGridTernary3DClip( int argc, char* argv[] )
{
// Hyper tree grid
vtkNew<vtkHyperTreeGridSource> htGrid;
htGrid->SetMaximumLevel( 5 );
htGrid->SetGridSize( 3, 3, 2 );
htGrid->SetGridScale( 1.5, 1., .7 );
htGrid->SetDimension( 3 );
htGrid->SetBranchFactor( 3 );
htGrid->SetDescriptor( "RRR .R. .RR ..R ..R .R.|R.......................... ........................... ........................... .............R............. ....RR.RR........R......... .....RRRR.....R.RR......... ........................... ........................... ...........................|........................... ........................... ........................... ...RR.RR.......RR.......... ........................... RR......................... ........................... ........................... ........................... ........................... ........................... ........................... ........................... ............RRR............|........................... ........................... .......RR.................. ........................... ........................... ........................... ........................... ........................... ........................... ........................... ...........................|........................... ..........................." );
// Hyper tree grid to unstructured grid filter
vtkNew<vtkHyperTreeGridToUnstructuredGrid> htg2ug;
htg2ug->SetInputConnection( htGrid->GetOutputPort() );
// Cuts
vtkNew<vtkPlane> plane;
plane->SetOrigin( 0., .5, .4 );
plane->SetNormal( -.2, -.6, 1. );
vtkNew<vtkClipDataSet> clip;
clip->SetInputConnection( htGrid->GetOutputPort() );
clip->SetClipFunction( plane.GetPointer() );
// Shrink
vtkNew<vtkShrinkFilter> shrink;
shrink->SetInputConnection( clip->GetOutputPort() );
shrink->SetShrinkFactor( .8 );
// Mappers
clip->Update();
double* range = clip->GetOutput()->GetPointData()->GetScalars()->GetRange();
vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 );
vtkNew<vtkDataSetMapper> mapper1;
mapper1->SetInputConnection( clip->GetOutputPort() );
mapper1->SetScalarRange( range );
vtkNew<vtkDataSetMapper> mapper2;
mapper2->SetInputConnection( htg2ug->GetOutputPort() );
mapper2->ScalarVisibilityOff();
vtkNew<vtkDataSetMapper> mapper3;
mapper3->SetInputConnection( shrink->GetOutputPort() );
mapper3->SetScalarRange( range );
// Actors
vtkNew<vtkActor> actor1;
actor1->SetMapper( mapper1.GetPointer() );
vtkNew<vtkActor> actor2;
actor2->SetMapper( mapper2.GetPointer() );
actor2->GetProperty()->SetRepresentationToWireframe();
actor2->GetProperty()->SetColor( .8, .8, .8 );
vtkNew<vtkActor> actor3;
actor3->SetMapper( mapper3.GetPointer() );
// Camera
vtkHyperTreeGrid* ht = htGrid->GetOutput();
double bd[6];
ht->GetBounds( bd );
vtkNew<vtkCamera> camera;
camera->SetClippingRange( 1., 100. );
camera->SetFocalPoint( ht->GetCenter() );
camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] );
// Renderer
vtkNew<vtkRenderer> renderer;
renderer->SetActiveCamera( camera.GetPointer() );
renderer->SetBackground( 1., 1., 1. );
//renderer->AddActor( actor1.GetPointer() );
renderer->AddActor( actor2.GetPointer() );
renderer->AddActor( actor3.GetPointer() );
// Render window
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer( renderer.GetPointer() );
renWin->SetSize( 400, 400 );
renWin->SetMultiSamples( 0 );
// Interactor
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow( renWin.GetPointer() );
// Render and test
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR )
{
iren->Start();
}
return !retVal;
}
<|endoftext|>
|
<commit_before>#include "alias_registry.hh"
#include "command_manager.hh"
#include "containers.hh"
namespace Kakoune
{
void AliasRegistry::add_alias(String alias, String command)
{
kak_assert(not alias.empty());
kak_assert(CommandManager::instance().command_defined(command));
auto it = m_aliases.find(alias);
if (it == m_aliases.end())
m_aliases.append({std::move(alias), std::move(command) });
else
it->value = std::move(command);
}
void AliasRegistry::remove_alias(StringView alias)
{
auto it = m_aliases.find(alias);
if (it != m_aliases.end())
m_aliases.erase(it);
}
StringView AliasRegistry::operator[](StringView alias) const
{
auto it = m_aliases.find(alias);
if (it != m_aliases.end())
return it->value;
else if (m_parent)
return (*m_parent)[alias];
else
return StringView{};
}
Vector<StringView> AliasRegistry::aliases_for(StringView command) const
{
Vector<StringView> res;
if (m_parent)
res = m_parent->aliases_for(command);
for (auto& alias : m_aliases)
{
if (alias.value == command)
res.emplace_back(alias.key);
}
return res;
}
}
<commit_msg>Simplify AliasRegistry::remove_alias<commit_after>#include "alias_registry.hh"
#include "command_manager.hh"
#include "containers.hh"
namespace Kakoune
{
void AliasRegistry::add_alias(String alias, String command)
{
kak_assert(not alias.empty());
kak_assert(CommandManager::instance().command_defined(command));
auto it = m_aliases.find(alias);
if (it == m_aliases.end())
m_aliases.append({std::move(alias), std::move(command) });
else
it->value = std::move(command);
}
void AliasRegistry::remove_alias(StringView alias)
{
m_aliases.remove(alias);
}
StringView AliasRegistry::operator[](StringView alias) const
{
auto it = m_aliases.find(alias);
if (it != m_aliases.end())
return it->value;
else if (m_parent)
return (*m_parent)[alias];
else
return StringView{};
}
Vector<StringView> AliasRegistry::aliases_for(StringView command) const
{
Vector<StringView> res;
if (m_parent)
res = m_parent->aliases_for(command);
for (auto& alias : m_aliases)
{
if (alias.value == command)
res.emplace_back(alias.key);
}
return res;
}
}
<|endoftext|>
|
<commit_before>// The MIT License(MIT)
//
// Copyright 2017 Huldra
//
// 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.
//t800
//
// Copyright 2017 Bogdan Kozyrev [email protected]
// Desert Engine project
#include <cstring>
// Примечание: контрибут от Андрея Коновода и Владимира Победина от 4.07.2017
//
//t800
#include "engine/byte_array.h"
#include <memory>
#include "engine/arctic_platform.h"
namespace arctic {
ByteArray::ByteArray() {
allocated_size_ = 128;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::ByteArray(Ui64 size) {
allocated_size_ = size;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::~ByteArray() {
allocated_size_ = 0;
size_ = 0;
free(data_);
data_ = nullptr;
}
void* ByteArray::GetVoidData() const {
return static_cast<void*>(data_);
}
Ui8* ByteArray::data() const {
return data_;
}
Ui64 ByteArray::size() const {
return size_;
}
void ByteArray::Resize(Ui64 size) {
if (size <= allocated_size_) {
size_ = size;
} else {
Ui8 *data = static_cast<Ui8*>(malloc(static_cast<size_t>(size)));
Check(data != nullptr, "Allocaton error.");
memcpy(data, data_, static_cast<size_t>(size_));
free(data_);
allocated_size_ = size;
size_ = size;
data_ = data;
}
}
void ByteArray::Reserve(Ui64 size) {
if (size > size_) {
Ui64 oldSize = size_;
Resize(size);
Resize(oldSize);
}
}
} // namespace arctic
<commit_msg>Update byte_array.cpp<commit_after>// The MIT License(MIT)
//
// Copyright 2017 Huldra
//
// 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.
//t800
//
// Copyright 2017 Bogdan Kozyrev [email protected]
// Desert Engine project
//
#if defined(LINUX)
#include <cstring>
#endif
// Примечание: контрибут от Андрея Коновода и Владимира Победина от 4.07.2017
//
//t800
#include "engine/byte_array.h"
#include <memory>
#include "engine/arctic_platform.h"
namespace arctic {
ByteArray::ByteArray() {
allocated_size_ = 128;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::ByteArray(Ui64 size) {
allocated_size_ = size;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::~ByteArray() {
allocated_size_ = 0;
size_ = 0;
free(data_);
data_ = nullptr;
}
void* ByteArray::GetVoidData() const {
return static_cast<void*>(data_);
}
Ui8* ByteArray::data() const {
return data_;
}
Ui64 ByteArray::size() const {
return size_;
}
void ByteArray::Resize(Ui64 size) {
if (size <= allocated_size_) {
size_ = size;
} else {
Ui8 *data = static_cast<Ui8*>(malloc(static_cast<size_t>(size)));
Check(data != nullptr, "Allocaton error.");
memcpy(data, data_, static_cast<size_t>(size_));
free(data_);
allocated_size_ = size;
size_ = size;
data_ = data;
}
}
void ByteArray::Reserve(Ui64 size) {
if (size > size_) {
Ui64 oldSize = size_;
Resize(size);
Resize(oldSize);
}
}
} // namespace arctic
<|endoftext|>
|
<commit_before>#include "sampling.h"
#include "config.h"
#include <sys_config.h>
#include <arch/MGSystem.h>
#include <algorithm>
#include <map>
#include <vector>
#include <ctime>
#include <fnmatch.h>
#include <unistd.h>
using namespace std;
struct VarInfo
{
void * var;
size_t width;
SampleVariableDataType type;
SampleVariableCategory cat;
vector<char> max;
VarInfo() : var(0), width(0), type(SV_INTEGER), cat(SVC_LEVEL), max() {};
VarInfo(const VarInfo&) = default;
VarInfo& operator=(const VarInfo&) = default;
};
typedef map<string, VarInfo> var_registry_t;
static var_registry_t& GetRegistry()
{
static var_registry_t registry;
return registry;
}
void _RegisterSampleVariable(void *var, size_t width, const string& name, SampleVariableDataType type, SampleVariableCategory cat, void *maxval)
{
auto ®istry = GetRegistry();
assert (registry.find(name) == registry.end()); // no duplicates allowed.
VarInfo vinfo;
vinfo.var = var;
vinfo.width = width;
vinfo.type = type;
vinfo.cat = cat;
const char *maxdata = (const char*)maxval;
for (size_t i = 0; i < width; ++i)
vinfo.max.push_back(maxdata[i]);
registry[name] = vinfo;
}
static
void ListSampleVariables_header(ostream& os)
{
os << "# size\ttype\tdtype\tmax\taddress\tname" << endl;
}
static
void ListSampleVariables_onevar(ostream& os, const string& name, const VarInfo& vinfo)
{
os << vinfo.width << "\t";
switch(vinfo.cat)
{
case SVC_LEVEL: os << "level"; break;
case SVC_STATE: os << "state"; break;
case SVC_WATERMARK: os << "wmark"; break;
case SVC_CUMULATIVE: os << "cumul"; break;
default: os << "unknown"; break;
}
os << (const char*)((vinfo.type == SV_INTEGER) ? "\tint\t" : "\tfloat\t");
if (vinfo.cat == SVC_LEVEL || vinfo.cat == SVC_WATERMARK)
{
const void *p = &vinfo.max[0];
switch(vinfo.type) {
case SV_INTEGER:
switch(vinfo.width) {
case 1: os << dec << (unsigned)*(uint8_t*)p; break;
case 2: os << dec << *(uint16_t*)p; break;
case 4: os << dec << *(uint32_t*)p; break;
case 8: os << dec << *(uint64_t*)p; break;
default: os << "<invsize>"; break;
}
break;
case SV_FLOAT:
if (vinfo.width == sizeof(float))
os << *(float*)p;
else
os << *(double*)p;
break;
}
}
else
os << "N/A";
os << '\t' << vinfo.var << '\t'
<< name
<< endl;
}
void ListSampleVariables(ostream& os, const string& pat)
{
ListSampleVariables_header(os);
for (auto& i : GetRegistry())
{
if (FNM_NOMATCH == fnmatch(pat.c_str(), i.first.c_str(), 0))
continue;
ListSampleVariables_onevar(os, i.first, i.second);
}
}
bool ReadSampleVariables(ostream& os, const string& pat)
{
bool some = false;
for (auto& i : GetRegistry())
{
if (FNM_NOMATCH == fnmatch(pat.c_str(), i.first.c_str(), 0))
continue;
os << i.first << " = ";
const VarInfo& vinfo = i.second;
void *p = vinfo.var;
switch(vinfo.type) {
case SV_INTEGER:
switch(vinfo.width) {
case 1: os << dec << (unsigned)*(uint8_t*)p; break;
case 2: os << dec << *(uint16_t*)p; break;
case 4: os << dec << *(uint32_t*)p; break;
case 8: os << dec << *(uint64_t*)p; break;
default: os << "<invsize>"; break;
}
break;
case SV_FLOAT:
if (vinfo.width == sizeof(float))
os << *(float*)p;
else
os << *(double*)p;
break;
}
os << endl;
some = true;
}
return some;
}
typedef pair<const string*, const VarInfo*> varsel_t;
typedef vector<varsel_t> varvec_t;
static
bool comparevars(const varsel_t& left, const varsel_t& right)
{
return left.second->var < right.second->var;
}
BinarySampler::BinarySampler(ostream& os, const Config& config,
const vector<string>& pats)
: m_datasize(0), m_vars()
{
varvec_t vars;
//
// Select variables to sample
//
auto& registry = GetRegistry();
for (auto& i : pats)
for (auto& j : registry)
{
if (FNM_NOMATCH == fnmatch(i.c_str(), j.first.c_str(), 0))
continue;
vars.push_back(make_pair(&j.first, &j.second));
}
if (vars.size() >= 2)
// we sort everything but the first and last variables,
// which should be the cycle counters. The cycle counters
// must be sampled once before and after everything else,
// to evaluate how imprecise the measurement is.
sort(vars.begin()+1, vars.end()-1, comparevars);
//
// Generate header for output file
//
time_t cl = time(0);
string timestr = asctime(gmtime(&cl));
os << "# date: " << timestr // asctime already embeds a newline character
<< "# generator: " << PACKAGE_STRING << endl;
char hn[255];
if (gethostname(hn, 255) == 0)
os << "# host: " << hn << endl;
vector<pair<string, string> > rawconf = config.getRawConfiguration();
os << "# configuration: " << rawconf.size() << endl;
for (auto& i : rawconf)
os << i.first << " = " << i.second << endl;
os << "# varinfo: " << vars.size() << endl;
// ListSampleVariables_header(os);
for (auto& i : vars)
{
m_datasize += i.second->width;
m_vars.push_back(make_pair((const char*)i.second->var, i.second->width));
ListSampleVariables_onevar(os, *i.first, *i.second);
}
os << "# recwidth: " << m_datasize << endl;
}
<commit_msg>Throw an informative exception on duplicate variable registration.<commit_after>#include "sampling.h"
#include "config.h"
#include "except.h"
#include <sys_config.h>
#include <arch/MGSystem.h>
#include <algorithm>
#include <map>
#include <vector>
#include <ctime>
#include <fnmatch.h>
#include <unistd.h>
using namespace std;
struct VarInfo
{
void * var;
size_t width;
SampleVariableDataType type;
SampleVariableCategory cat;
vector<char> max;
VarInfo() : var(0), width(0), type(SV_INTEGER), cat(SVC_LEVEL), max() {};
VarInfo(const VarInfo&) = default;
VarInfo& operator=(const VarInfo&) = default;
};
typedef map<string, VarInfo> var_registry_t;
static var_registry_t& GetRegistry()
{
static var_registry_t registry;
return registry;
}
void _RegisterSampleVariable(void *var, size_t width, const string& name, SampleVariableDataType type, SampleVariableCategory cat, void *maxval)
{
auto ®istry = GetRegistry();
if (registry.find(name) != registry.end())
throw Simulator::exceptf<>("Duplicate variable registration: %s", name.c_str());
VarInfo vinfo;
vinfo.var = var;
vinfo.width = width;
vinfo.type = type;
vinfo.cat = cat;
const char *maxdata = (const char*)maxval;
for (size_t i = 0; i < width; ++i)
vinfo.max.push_back(maxdata[i]);
registry[name] = vinfo;
}
static
void ListSampleVariables_header(ostream& os)
{
os << "# size\ttype\tdtype\tmax\taddress\tname" << endl;
}
static
void ListSampleVariables_onevar(ostream& os, const string& name, const VarInfo& vinfo)
{
os << vinfo.width << "\t";
switch(vinfo.cat)
{
case SVC_LEVEL: os << "level"; break;
case SVC_STATE: os << "state"; break;
case SVC_WATERMARK: os << "wmark"; break;
case SVC_CUMULATIVE: os << "cumul"; break;
default: os << "unknown"; break;
}
os << (const char*)((vinfo.type == SV_INTEGER) ? "\tint\t" : "\tfloat\t");
if (vinfo.cat == SVC_LEVEL || vinfo.cat == SVC_WATERMARK)
{
const void *p = &vinfo.max[0];
switch(vinfo.type) {
case SV_INTEGER:
switch(vinfo.width) {
case 1: os << dec << (unsigned)*(uint8_t*)p; break;
case 2: os << dec << *(uint16_t*)p; break;
case 4: os << dec << *(uint32_t*)p; break;
case 8: os << dec << *(uint64_t*)p; break;
default: os << "<invsize>"; break;
}
break;
case SV_FLOAT:
if (vinfo.width == sizeof(float))
os << *(float*)p;
else
os << *(double*)p;
break;
}
}
else
os << "N/A";
os << '\t' << vinfo.var << '\t'
<< name
<< endl;
}
void ListSampleVariables(ostream& os, const string& pat)
{
ListSampleVariables_header(os);
for (auto& i : GetRegistry())
{
if (FNM_NOMATCH == fnmatch(pat.c_str(), i.first.c_str(), 0))
continue;
ListSampleVariables_onevar(os, i.first, i.second);
}
}
bool ReadSampleVariables(ostream& os, const string& pat)
{
bool some = false;
for (auto& i : GetRegistry())
{
if (FNM_NOMATCH == fnmatch(pat.c_str(), i.first.c_str(), 0))
continue;
os << i.first << " = ";
const VarInfo& vinfo = i.second;
void *p = vinfo.var;
switch(vinfo.type) {
case SV_INTEGER:
switch(vinfo.width) {
case 1: os << dec << (unsigned)*(uint8_t*)p; break;
case 2: os << dec << *(uint16_t*)p; break;
case 4: os << dec << *(uint32_t*)p; break;
case 8: os << dec << *(uint64_t*)p; break;
default: os << "<invsize>"; break;
}
break;
case SV_FLOAT:
if (vinfo.width == sizeof(float))
os << *(float*)p;
else
os << *(double*)p;
break;
}
os << endl;
some = true;
}
return some;
}
typedef pair<const string*, const VarInfo*> varsel_t;
typedef vector<varsel_t> varvec_t;
static
bool comparevars(const varsel_t& left, const varsel_t& right)
{
return left.second->var < right.second->var;
}
BinarySampler::BinarySampler(ostream& os, const Config& config,
const vector<string>& pats)
: m_datasize(0), m_vars()
{
varvec_t vars;
//
// Select variables to sample
//
auto& registry = GetRegistry();
for (auto& i : pats)
for (auto& j : registry)
{
if (FNM_NOMATCH == fnmatch(i.c_str(), j.first.c_str(), 0))
continue;
vars.push_back(make_pair(&j.first, &j.second));
}
if (vars.size() >= 2)
// we sort everything but the first and last variables,
// which should be the cycle counters. The cycle counters
// must be sampled once before and after everything else,
// to evaluate how imprecise the measurement is.
sort(vars.begin()+1, vars.end()-1, comparevars);
//
// Generate header for output file
//
time_t cl = time(0);
string timestr = asctime(gmtime(&cl));
os << "# date: " << timestr // asctime already embeds a newline character
<< "# generator: " << PACKAGE_STRING << endl;
char hn[255];
if (gethostname(hn, 255) == 0)
os << "# host: " << hn << endl;
vector<pair<string, string> > rawconf = config.getRawConfiguration();
os << "# configuration: " << rawconf.size() << endl;
for (auto& i : rawconf)
os << i.first << " = " << i.second << endl;
os << "# varinfo: " << vars.size() << endl;
// ListSampleVariables_header(os);
for (auto& i : vars)
{
m_datasize += i.second->width;
m_vars.push_back(make_pair((const char*)i.second->var, i.second->width));
ListSampleVariables_onevar(os, *i.first, *i.second);
}
os << "# recwidth: " << m_datasize << endl;
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "zqrpc/ZSocket.hpp"
namespace zqrpc {
struct Worker {
typedef std::vector<std::string> FramesT;
zmq::context_t* context_;
Worker(zmq::context_t* context) : context_(context) {}
~Worker() {}
void operator() () {
zqrpc::ZSocket socket(context_,ZMQ_DEALER,boost::lexical_cast<std::string>(boost::this_thread::get_id()));
socket.connect(ZQRPC_INPROC_WORKER);
socket.SetLinger(0);
typedef std::deque<std::string> FramesT;
FramesT frames;
while (1) {
frames.clear();
frames = socket.BlockingRecv<FramesT>();
socket.Send<FramesT>(frames);
}
}
};
}
int main(int argc, char *argv[])
{
google::InitGoogleLogging(argv[0]);
zmq::context_t context;
zqrpc::ZSocket rpc_frontend_(&context,ZMQ_ROUTER,"ROUTER");
zqrpc::ZSocket rpc_backend_(&context,ZMQ_DEALER,"DEALER");
boost::thread_group threads;
rpc_frontend_.bind("tcp://127.0.0.1:9089");
rpc_backend_.bind(ZQRPC_INPROC_WORKER);
std::size_t noof_threads=2;
for(std::size_t i = 0; i < noof_threads; ++i) {
zqrpc::Worker w(&context);
threads.create_thread<zqrpc::Worker>(w);
}
rpc_frontend_.ProxyTo( rpc_backend_);
try {
} catch (zqrpc::ZError& e) {
DLOG(INFO) << "ZError THROWN" << std::endl;
} catch (zqrpc::RetryException& e) {
DLOG(INFO) << "Retry Exception THROWN" << std::endl;
} catch (zmq::error_t& e) {
DLOG(INFO) << "ZMQ ZERROR THROWN : " << e.what() << std::endl;
}
threads.join_all();
}
<commit_msg>Wed Jul 23 10:07:10 IST 2014<commit_after>#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include "zqrpc/ZSocket.hpp"
namespace zqrpc {
struct Worker {
typedef std::vector<std::string> FramesT;
zmq::context_t* context_;
Worker(zmq::context_t* context) : context_(context) {}
~Worker() {}
void operator() () {
zqrpc::ZSocket socket(context_,ZMQ_DEALER,boost::lexical_cast<std::string>(boost::this_thread::get_id()));
socket.connect(ZQRPC_INPROC_WORKER);
socket.SetLinger(0);
typedef std::deque<std::string> FramesT;
FramesT frames;
while (1) {
frames.clear();
frames = socket.BlockingRecv<FramesT>();
BOOST_FOREACH(std::string s, frames) { std::cerr << "## " << s << std::endl; }
socket.Send<FramesT>(frames);
}
}
};
}
int main(int argc, char *argv[])
{
google::InitGoogleLogging(argv[0]);
zmq::context_t context;
zqrpc::ZSocket rpc_frontend_(&context,ZMQ_ROUTER,"ROUTER");
zqrpc::ZSocket rpc_backend_(&context,ZMQ_DEALER,"DEALER");
boost::thread_group threads;
rpc_frontend_.bind("tcp://127.0.0.1:9089");
rpc_backend_.bind(ZQRPC_INPROC_WORKER);
std::size_t noof_threads=2;
for(std::size_t i = 0; i < noof_threads; ++i) {
zqrpc::Worker w(&context);
threads.create_thread<zqrpc::Worker>(w);
}
rpc_frontend_.ProxyTo( rpc_backend_);
try {
} catch (zqrpc::ZError& e) {
DLOG(INFO) << "ZError THROWN" << std::endl;
} catch (zqrpc::RetryException& e) {
DLOG(INFO) << "Retry Exception THROWN" << std::endl;
} catch (zmq::error_t& e) {
DLOG(INFO) << "ZMQ ZERROR THROWN : " << e.what() << std::endl;
}
threads.join_all();
}
<|endoftext|>
|
<commit_before>//===- LinkerScript.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the parser/evaluator of the linker script.
// It does not construct an AST but consume linker script directives directly.
// Results are written to Driver or Config object.
//
//===----------------------------------------------------------------------===//
#include "Config.h"
#include "Driver.h"
#include "SymbolTable.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/StringSaver.h"
using namespace llvm;
using namespace lld;
using namespace lld::elf2;
namespace {
class LinkerScript {
public:
LinkerScript(BumpPtrAllocator *A, StringRef S, bool B)
: Saver(*A), Tokens(tokenize(S)), IsUnderSysroot(B) {}
void run();
private:
static std::vector<StringRef> tokenize(StringRef S);
static StringRef skipSpace(StringRef S);
StringRef next();
bool skip(StringRef Tok);
bool atEOF() { return Tokens.size() == Pos; }
void expect(StringRef Expect);
void addFile(StringRef Path);
void readAsNeeded();
void readEntry();
void readExtern();
void readGroup();
void readInclude();
void readOutput();
void readOutputArch();
void readOutputFormat();
void readSearchDir();
void readSections();
void readOutputSectionDescription();
StringSaver Saver;
std::vector<StringRef> Tokens;
size_t Pos = 0;
bool IsUnderSysroot;
};
}
void LinkerScript::run() {
while (!atEOF()) {
StringRef Tok = next();
if (Tok == ";")
continue;
if (Tok == "ENTRY") {
readEntry();
} else if (Tok == "EXTERN") {
readExtern();
} else if (Tok == "GROUP" || Tok == "INPUT") {
readGroup();
} else if (Tok == "INCLUDE") {
readInclude();
} else if (Tok == "OUTPUT") {
readOutput();
} else if (Tok == "OUTPUT_ARCH") {
readOutputArch();
} else if (Tok == "OUTPUT_FORMAT") {
readOutputFormat();
} else if (Tok == "SEARCH_DIR") {
readSearchDir();
} else if (Tok == "SECTIONS") {
readSections();
} else {
error("unknown directive: " + Tok);
}
}
}
// Split S into linker script tokens.
std::vector<StringRef> LinkerScript::tokenize(StringRef S) {
std::vector<StringRef> Ret;
for (;;) {
S = skipSpace(S);
if (S.empty())
return Ret;
// Quoted token
if (S.startswith("\"")) {
size_t E = S.find("\"", 1);
if (E == StringRef::npos)
error("unclosed quote");
Ret.push_back(S.substr(1, E));
S = S.substr(E + 1);
continue;
}
// Unquoted token
size_t Pos = S.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
"0123456789_.$/\\~=+[]*?-:");
// A character that cannot start a word (which is usually a
// punctuation) forms a single character token.
if (Pos == 0)
Pos = 1;
Ret.push_back(S.substr(0, Pos));
S = S.substr(Pos);
}
}
// Skip leading whitespace characters or /**/-style comments.
StringRef LinkerScript::skipSpace(StringRef S) {
for (;;) {
if (S.startswith("/*")) {
size_t E = S.find("*/", 2);
if (E == StringRef::npos)
error("unclosed comment in a linker script");
S = S.substr(E + 2);
continue;
}
size_t Size = S.size();
S = S.ltrim();
if (S.size() == Size)
return S;
}
}
StringRef LinkerScript::next() {
if (atEOF())
error("unexpected EOF");
return Tokens[Pos++];
}
bool LinkerScript::skip(StringRef Tok) {
if (atEOF())
error("unexpected EOF");
if (Tok != Tokens[Pos])
return false;
++Pos;
return true;
}
void LinkerScript::expect(StringRef Expect) {
StringRef Tok = next();
if (Tok != Expect)
error(Expect + " expected, but got " + Tok);
}
void LinkerScript::addFile(StringRef S) {
if (IsUnderSysroot && S.startswith("/")) {
SmallString<128> Path;
(Config->Sysroot + S).toStringRef(Path);
if (sys::fs::exists(Path)) {
Driver->addFile(Saver.save(Path.str()));
return;
}
}
if (sys::path::is_absolute(S)) {
Driver->addFile(S);
} else if (S.startswith("=")) {
if (Config->Sysroot.empty())
Driver->addFile(S.substr(1));
else
Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
} else if (S.startswith("-l")) {
Driver->addFile(searchLibrary(S.substr(2)));
} else {
std::string Path = findFromSearchPaths(S);
if (Path.empty())
error("Unable to find " + S);
Driver->addFile(Saver.save(Path));
}
}
void LinkerScript::readAsNeeded() {
expect("(");
bool Orig = Config->AsNeeded;
Config->AsNeeded = true;
for (;;) {
StringRef Tok = next();
if (Tok == ")")
break;
addFile(Tok);
}
Config->AsNeeded = Orig;
}
void LinkerScript::readEntry() {
// -e <symbol> takes predecence over ENTRY(<symbol>).
expect("(");
StringRef Tok = next();
if (Config->Entry.empty())
Config->Entry = Tok;
expect(")");
}
void LinkerScript::readExtern() {
expect("(");
for (;;) {
StringRef Tok = next();
if (Tok == ")")
return;
Config->Undefined.push_back(Tok);
}
}
void LinkerScript::readGroup() {
expect("(");
for (;;) {
StringRef Tok = next();
if (Tok == ")")
return;
if (Tok == "AS_NEEDED") {
readAsNeeded();
continue;
}
addFile(Tok);
}
}
void LinkerScript::readInclude() {
StringRef Tok = next();
auto MBOrErr = MemoryBuffer::getFile(Tok);
error(MBOrErr, "cannot open " + Tok);
std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
std::vector<StringRef> V = tokenize(S);
Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
}
void LinkerScript::readOutput() {
// -o <file> takes predecence over OUTPUT(<file>).
expect("(");
StringRef Tok = next();
if (Config->OutputFile.empty())
Config->OutputFile = Tok;
expect(")");
}
void LinkerScript::readOutputArch() {
// Error checking only for now.
expect("(");
next();
expect(")");
}
void LinkerScript::readOutputFormat() {
// Error checking only for now.
expect("(");
next();
StringRef Tok = next();
if (Tok == ")")
return;
if (Tok != ",")
error("unexpected token: " + Tok);
next();
expect(",");
next();
expect(")");
}
void LinkerScript::readSearchDir() {
expect("(");
Config->SearchPaths.push_back(next());
expect(")");
}
void LinkerScript::readSections() {
expect("{");
while (!skip("}"))
readOutputSectionDescription();
}
void LinkerScript::readOutputSectionDescription() {
StringRef Name = next();
std::vector<StringRef> &InputSections = Config->OutputSections[Name];
expect(":");
expect("{");
while (!skip("}")) {
next(); // Skip input file name.
expect("(");
while (!skip(")"))
InputSections.push_back(next());
}
}
static bool isUnderSysroot(StringRef Path) {
if (Config->Sysroot == "")
return false;
for (; !Path.empty(); Path = sys::path::parent_path(Path))
if (sys::fs::equivalent(Config->Sysroot, Path))
return true;
return false;
}
// Entry point. The other functions or classes are private to this file.
void lld::elf2::readLinkerScript(BumpPtrAllocator *A, MemoryBufferRef MB) {
StringRef Path = MB.getBufferIdentifier();
LinkerScript(A, MB.getBuffer(), isUnderSysroot(Path)).run();
}
<commit_msg>[ELF] Lookup INPUT argument in the current directory<commit_after>//===- LinkerScript.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the parser/evaluator of the linker script.
// It does not construct an AST but consume linker script directives directly.
// Results are written to Driver or Config object.
//
//===----------------------------------------------------------------------===//
#include "Config.h"
#include "Driver.h"
#include "SymbolTable.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/StringSaver.h"
using namespace llvm;
using namespace lld;
using namespace lld::elf2;
namespace {
class LinkerScript {
public:
LinkerScript(BumpPtrAllocator *A, StringRef S, bool B)
: Saver(*A), Tokens(tokenize(S)), IsUnderSysroot(B) {}
void run();
private:
static std::vector<StringRef> tokenize(StringRef S);
static StringRef skipSpace(StringRef S);
StringRef next();
bool skip(StringRef Tok);
bool atEOF() { return Tokens.size() == Pos; }
void expect(StringRef Expect);
void addFile(StringRef Path);
void readAsNeeded();
void readEntry();
void readExtern();
void readGroup();
void readInclude();
void readOutput();
void readOutputArch();
void readOutputFormat();
void readSearchDir();
void readSections();
void readOutputSectionDescription();
StringSaver Saver;
std::vector<StringRef> Tokens;
size_t Pos = 0;
bool IsUnderSysroot;
};
}
void LinkerScript::run() {
while (!atEOF()) {
StringRef Tok = next();
if (Tok == ";")
continue;
if (Tok == "ENTRY") {
readEntry();
} else if (Tok == "EXTERN") {
readExtern();
} else if (Tok == "GROUP" || Tok == "INPUT") {
readGroup();
} else if (Tok == "INCLUDE") {
readInclude();
} else if (Tok == "OUTPUT") {
readOutput();
} else if (Tok == "OUTPUT_ARCH") {
readOutputArch();
} else if (Tok == "OUTPUT_FORMAT") {
readOutputFormat();
} else if (Tok == "SEARCH_DIR") {
readSearchDir();
} else if (Tok == "SECTIONS") {
readSections();
} else {
error("unknown directive: " + Tok);
}
}
}
// Split S into linker script tokens.
std::vector<StringRef> LinkerScript::tokenize(StringRef S) {
std::vector<StringRef> Ret;
for (;;) {
S = skipSpace(S);
if (S.empty())
return Ret;
// Quoted token
if (S.startswith("\"")) {
size_t E = S.find("\"", 1);
if (E == StringRef::npos)
error("unclosed quote");
Ret.push_back(S.substr(1, E));
S = S.substr(E + 1);
continue;
}
// Unquoted token
size_t Pos = S.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
"0123456789_.$/\\~=+[]*?-:");
// A character that cannot start a word (which is usually a
// punctuation) forms a single character token.
if (Pos == 0)
Pos = 1;
Ret.push_back(S.substr(0, Pos));
S = S.substr(Pos);
}
}
// Skip leading whitespace characters or /**/-style comments.
StringRef LinkerScript::skipSpace(StringRef S) {
for (;;) {
if (S.startswith("/*")) {
size_t E = S.find("*/", 2);
if (E == StringRef::npos)
error("unclosed comment in a linker script");
S = S.substr(E + 2);
continue;
}
size_t Size = S.size();
S = S.ltrim();
if (S.size() == Size)
return S;
}
}
StringRef LinkerScript::next() {
if (atEOF())
error("unexpected EOF");
return Tokens[Pos++];
}
bool LinkerScript::skip(StringRef Tok) {
if (atEOF())
error("unexpected EOF");
if (Tok != Tokens[Pos])
return false;
++Pos;
return true;
}
void LinkerScript::expect(StringRef Expect) {
StringRef Tok = next();
if (Tok != Expect)
error(Expect + " expected, but got " + Tok);
}
void LinkerScript::addFile(StringRef S) {
if (IsUnderSysroot && S.startswith("/")) {
SmallString<128> Path;
(Config->Sysroot + S).toStringRef(Path);
if (sys::fs::exists(Path)) {
Driver->addFile(Saver.save(Path.str()));
return;
}
}
if (sys::path::is_absolute(S)) {
Driver->addFile(S);
} else if (S.startswith("=")) {
if (Config->Sysroot.empty())
Driver->addFile(S.substr(1));
else
Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
} else if (S.startswith("-l")) {
Driver->addFile(searchLibrary(S.substr(2)));
} else if (sys::fs::exists(S)) {
Driver->addFile(S);
} else {
std::string Path = findFromSearchPaths(S);
if (Path.empty())
error("Unable to find " + S);
Driver->addFile(Saver.save(Path));
}
}
void LinkerScript::readAsNeeded() {
expect("(");
bool Orig = Config->AsNeeded;
Config->AsNeeded = true;
for (;;) {
StringRef Tok = next();
if (Tok == ")")
break;
addFile(Tok);
}
Config->AsNeeded = Orig;
}
void LinkerScript::readEntry() {
// -e <symbol> takes predecence over ENTRY(<symbol>).
expect("(");
StringRef Tok = next();
if (Config->Entry.empty())
Config->Entry = Tok;
expect(")");
}
void LinkerScript::readExtern() {
expect("(");
for (;;) {
StringRef Tok = next();
if (Tok == ")")
return;
Config->Undefined.push_back(Tok);
}
}
void LinkerScript::readGroup() {
expect("(");
for (;;) {
StringRef Tok = next();
if (Tok == ")")
return;
if (Tok == "AS_NEEDED") {
readAsNeeded();
continue;
}
addFile(Tok);
}
}
void LinkerScript::readInclude() {
StringRef Tok = next();
auto MBOrErr = MemoryBuffer::getFile(Tok);
error(MBOrErr, "cannot open " + Tok);
std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
std::vector<StringRef> V = tokenize(S);
Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
}
void LinkerScript::readOutput() {
// -o <file> takes predecence over OUTPUT(<file>).
expect("(");
StringRef Tok = next();
if (Config->OutputFile.empty())
Config->OutputFile = Tok;
expect(")");
}
void LinkerScript::readOutputArch() {
// Error checking only for now.
expect("(");
next();
expect(")");
}
void LinkerScript::readOutputFormat() {
// Error checking only for now.
expect("(");
next();
StringRef Tok = next();
if (Tok == ")")
return;
if (Tok != ",")
error("unexpected token: " + Tok);
next();
expect(",");
next();
expect(")");
}
void LinkerScript::readSearchDir() {
expect("(");
Config->SearchPaths.push_back(next());
expect(")");
}
void LinkerScript::readSections() {
expect("{");
while (!skip("}"))
readOutputSectionDescription();
}
void LinkerScript::readOutputSectionDescription() {
StringRef Name = next();
std::vector<StringRef> &InputSections = Config->OutputSections[Name];
expect(":");
expect("{");
while (!skip("}")) {
next(); // Skip input file name.
expect("(");
while (!skip(")"))
InputSections.push_back(next());
}
}
static bool isUnderSysroot(StringRef Path) {
if (Config->Sysroot == "")
return false;
for (; !Path.empty(); Path = sys::path::parent_path(Path))
if (sys::fs::equivalent(Config->Sysroot, Path))
return true;
return false;
}
// Entry point. The other functions or classes are private to this file.
void lld::elf2::readLinkerScript(BumpPtrAllocator *A, MemoryBufferRef MB) {
StringRef Path = MB.getBufferIdentifier();
LinkerScript(A, MB.getBuffer(), isUnderSysroot(Path)).run();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 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 "chrome/browser/extensions/suspicious_extension_bubble_controller.h"
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_message_bubble.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_system.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
base::LazyInstance<std::set<Profile*> > g_shown_for_profiles =
LAZY_INSTANCE_INITIALIZER;
////////////////////////////////////////////////////////////////////////////////
// SuspiciousExtensionBubbleDelegate
SuspiciousExtensionBubbleDelegate::SuspiciousExtensionBubbleDelegate(
Profile* profile)
: profile_(profile) {}
SuspiciousExtensionBubbleDelegate::~SuspiciousExtensionBubbleDelegate() {
}
bool SuspiciousExtensionBubbleDelegate::ShouldIncludeExtension(
const std::string& extension_id) {
extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
if (!prefs->IsExtensionDisabled(extension_id))
return false;
int disble_reasons = prefs->GetDisableReasons(extension_id);
if (disble_reasons & extensions::Extension::DISABLE_NOT_VERIFIED)
return !prefs->HasWipeoutBeenAcknowledged(extension_id);
return false;
}
void SuspiciousExtensionBubbleDelegate::AcknowledgeExtension(
const std::string& extension_id,
ExtensionMessageBubbleController::BubbleAction user_action) {
extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
prefs->SetWipeoutAcknowledged(extension_id, true);
}
void SuspiciousExtensionBubbleDelegate::PerformAction(
const extensions::ExtensionIdList& list) {
// This bubble solicits no action from the user. Or as Nimoy would have it:
// "Well, my work here is done".
}
base::string16 SuspiciousExtensionBubbleDelegate::GetTitle() const {
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_SUSPICIOUS_DISABLED_TITLE);
}
base::string16 SuspiciousExtensionBubbleDelegate::GetMessageBody() const {
return l10n_util::GetStringFUTF16(IDS_EXTENSIONS_SUSPICIOUS_DISABLED_BODY,
l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE));
}
base::string16 SuspiciousExtensionBubbleDelegate::GetOverflowText(
const base::string16& overflow_count) const {
base::string16 overflow_string = l10n_util::GetStringUTF16(
IDS_EXTENSIONS_SUSPICIOUS_DISABLED_AND_N_MORE);
base::string16 new_string;
// Just before string freeze, we checked in # as a substitution value for
// this string, whereas we should have used $1. It was discovered too late,
// so we do the substitution by hand in that case.
if (overflow_string.find(base::ASCIIToUTF16("#")) != base::string16::npos) {
base::ReplaceChars(overflow_string, base::ASCIIToUTF16("#").c_str(),
overflow_count, &new_string);
} else {
new_string = l10n_util::GetStringFUTF16(
IDS_EXTENSIONS_SUSPICIOUS_DISABLED_AND_N_MORE,
overflow_count);
}
return new_string;
}
base::string16
SuspiciousExtensionBubbleDelegate::GetLearnMoreLabel() const {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
GURL SuspiciousExtensionBubbleDelegate::GetLearnMoreUrl() const {
return GURL(chrome::kRemoveNonCWSExtensionURL);
}
base::string16
SuspiciousExtensionBubbleDelegate::GetActionButtonLabel() const {
return base::string16();
}
base::string16
SuspiciousExtensionBubbleDelegate::GetDismissButtonLabel() const {
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_SUSPICIOUS_DISABLED_BUTTON);
}
bool
SuspiciousExtensionBubbleDelegate::ShouldShowExtensionList() const {
return true;
}
void SuspiciousExtensionBubbleDelegate::LogExtensionCount(
size_t count) {
UMA_HISTOGRAM_COUNTS_100(
"ExtensionWipeoutBubble.ExtensionWipeoutCount", count);
}
void SuspiciousExtensionBubbleDelegate::LogAction(
ExtensionMessageBubbleController::BubbleAction action) {
UMA_HISTOGRAM_ENUMERATION(
"ExtensionWipeoutBubble.UserSelection",
action, ExtensionMessageBubbleController::ACTION_BOUNDARY);
}
} // namespace
namespace extensions {
////////////////////////////////////////////////////////////////////////////////
// SuspiciousExtensionBubbleController
// static
void SuspiciousExtensionBubbleController::ClearProfileListForTesting() {
g_shown_for_profiles.Get().clear();
}
SuspiciousExtensionBubbleController::SuspiciousExtensionBubbleController(
Profile* profile)
: ExtensionMessageBubbleController(
new SuspiciousExtensionBubbleDelegate(profile),
profile),
profile_(profile) {}
SuspiciousExtensionBubbleController::~SuspiciousExtensionBubbleController() {
}
bool SuspiciousExtensionBubbleController::ShouldShow() {
return !g_shown_for_profiles.Get().count(profile_->GetOriginalProfile()) &&
!GetExtensionList().empty();
}
void SuspiciousExtensionBubbleController::Show(ExtensionMessageBubble* bubble) {
g_shown_for_profiles.Get().insert(profile_->GetOriginalProfile());
ExtensionMessageBubbleController::Show(bubble);
}
} // namespace extensions
<commit_msg>Change the title of the suspicious extensions bubble dialog<commit_after>// Copyright (c) 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 "chrome/browser/extensions/suspicious_extension_bubble_controller.h"
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_message_bubble.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_system.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
base::LazyInstance<std::set<Profile*> > g_shown_for_profiles =
LAZY_INSTANCE_INITIALIZER;
////////////////////////////////////////////////////////////////////////////////
// SuspiciousExtensionBubbleDelegate
SuspiciousExtensionBubbleDelegate::SuspiciousExtensionBubbleDelegate(
Profile* profile)
: profile_(profile) {}
SuspiciousExtensionBubbleDelegate::~SuspiciousExtensionBubbleDelegate() {
}
bool SuspiciousExtensionBubbleDelegate::ShouldIncludeExtension(
const std::string& extension_id) {
extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
if (!prefs->IsExtensionDisabled(extension_id))
return false;
int disble_reasons = prefs->GetDisableReasons(extension_id);
if (disble_reasons & extensions::Extension::DISABLE_NOT_VERIFIED)
return !prefs->HasWipeoutBeenAcknowledged(extension_id);
return false;
}
void SuspiciousExtensionBubbleDelegate::AcknowledgeExtension(
const std::string& extension_id,
ExtensionMessageBubbleController::BubbleAction user_action) {
extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
prefs->SetWipeoutAcknowledged(extension_id, true);
}
void SuspiciousExtensionBubbleDelegate::PerformAction(
const extensions::ExtensionIdList& list) {
// This bubble solicits no action from the user. Or as Nimoy would have it:
// "Well, my work here is done".
}
base::string16 SuspiciousExtensionBubbleDelegate::GetTitle() const {
// TODO(asargent/finnur) - we've temporarily borrowed an already translated
// string that has another purpose so we could change this on a release
// branch. crbug.com/370517
return l10n_util::GetStringUTF16(
IDS_PERFORMANCE_MONITOR_EXTENSION_DISABLE_EVENT_MOUSEOVER);
}
base::string16 SuspiciousExtensionBubbleDelegate::GetMessageBody() const {
return l10n_util::GetStringFUTF16(IDS_EXTENSIONS_SUSPICIOUS_DISABLED_BODY,
l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE));
}
base::string16 SuspiciousExtensionBubbleDelegate::GetOverflowText(
const base::string16& overflow_count) const {
base::string16 overflow_string = l10n_util::GetStringUTF16(
IDS_EXTENSIONS_SUSPICIOUS_DISABLED_AND_N_MORE);
base::string16 new_string;
// Just before string freeze, we checked in # as a substitution value for
// this string, whereas we should have used $1. It was discovered too late,
// so we do the substitution by hand in that case.
if (overflow_string.find(base::ASCIIToUTF16("#")) != base::string16::npos) {
base::ReplaceChars(overflow_string, base::ASCIIToUTF16("#").c_str(),
overflow_count, &new_string);
} else {
new_string = l10n_util::GetStringFUTF16(
IDS_EXTENSIONS_SUSPICIOUS_DISABLED_AND_N_MORE,
overflow_count);
}
return new_string;
}
base::string16
SuspiciousExtensionBubbleDelegate::GetLearnMoreLabel() const {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
GURL SuspiciousExtensionBubbleDelegate::GetLearnMoreUrl() const {
return GURL(chrome::kRemoveNonCWSExtensionURL);
}
base::string16
SuspiciousExtensionBubbleDelegate::GetActionButtonLabel() const {
return base::string16();
}
base::string16
SuspiciousExtensionBubbleDelegate::GetDismissButtonLabel() const {
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_SUSPICIOUS_DISABLED_BUTTON);
}
bool
SuspiciousExtensionBubbleDelegate::ShouldShowExtensionList() const {
return true;
}
void SuspiciousExtensionBubbleDelegate::LogExtensionCount(
size_t count) {
UMA_HISTOGRAM_COUNTS_100(
"ExtensionWipeoutBubble.ExtensionWipeoutCount", count);
}
void SuspiciousExtensionBubbleDelegate::LogAction(
ExtensionMessageBubbleController::BubbleAction action) {
UMA_HISTOGRAM_ENUMERATION(
"ExtensionWipeoutBubble.UserSelection",
action, ExtensionMessageBubbleController::ACTION_BOUNDARY);
}
} // namespace
namespace extensions {
////////////////////////////////////////////////////////////////////////////////
// SuspiciousExtensionBubbleController
// static
void SuspiciousExtensionBubbleController::ClearProfileListForTesting() {
g_shown_for_profiles.Get().clear();
}
SuspiciousExtensionBubbleController::SuspiciousExtensionBubbleController(
Profile* profile)
: ExtensionMessageBubbleController(
new SuspiciousExtensionBubbleDelegate(profile),
profile),
profile_(profile) {}
SuspiciousExtensionBubbleController::~SuspiciousExtensionBubbleController() {
}
bool SuspiciousExtensionBubbleController::ShouldShow() {
return !g_shown_for_profiles.Get().count(profile_->GetOriginalProfile()) &&
!GetExtensionList().empty();
}
void SuspiciousExtensionBubbleController::Show(ExtensionMessageBubble* bubble) {
g_shown_for_profiles.Get().insert(profile_->GetOriginalProfile());
ExtensionMessageBubbleController::Show(bubble);
}
} // namespace extensions
<|endoftext|>
|
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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. */
/*
* This file contains demo of mobilenet for tensorrt.
*/
#include <gflags/gflags.h>
#include <glog/logging.h> // use glog instead of CHECK to avoid importing other paddle header files.
#include <fstream>
#include <iostream>
// #include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/inference/demo_ci/utils.h"
#ifdef PADDLE_WITH_CUDA
DECLARE_double(fraction_of_gpu_memory_to_use);
#endif
DEFINE_string(modeldir, "", "Directory of the inference model.");
DEFINE_string(refer, "", "path to reference result for comparison.");
DEFINE_string(
data, "",
"path of data; each line is a record, format is "
"'<space splitted floats as data>\t<space splitted ints as shape'");
namespace paddle {
namespace demo {
/*
* Use the native fluid engine to inference the demo.
*/
void Main() {
std::unique_ptr<PaddlePredictor> predictor;
paddle::contrib::MixedRTConfig config;
config.param_file = FLAGS_modeldir + "/__params__";
config.prog_file = FLAGS_modeldir + "/__model__";
config.use_gpu = true;
config.device = 0;
config.max_batch_size = 1;
config.fraction_of_gpu_memory = 0.1; // set by yourself
predictor = CreatePaddlePredictor<paddle::contrib::MixedRTConfig>(config);
VLOG(3) << "begin to process data";
// Just a single batch of data.
std::string line;
std::ifstream file(FLAGS_data);
std::getline(file, line);
auto record = ProcessALine(line);
file.close();
// Inference.
PaddleTensor input;
input.shape = record.shape;
input.data =
PaddleBuf(record.data.data(), record.data.size() * sizeof(float));
input.dtype = PaddleDType::FLOAT32;
VLOG(3) << "run executor";
std::vector<PaddleTensor> output;
predictor->Run({input}, &output, 1);
VLOG(3) << "output.size " << output.size();
auto& tensor = output.front();
VLOG(3) << "output: " << SummaryTensor(tensor);
// compare with reference result
CheckOutput(FLAGS_refer, tensor);
}
} // namespace demo
} // namespace paddle
int main(int argc, char** argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
paddle::demo::Main();
return 0;
}
<commit_msg>fix commets<commit_after>/* Copyright (c) 2018 PaddlePaddle 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. */
/*
* This file contains demo of mobilenet for tensorrt.
*/
#include <gflags/gflags.h>
#include <glog/logging.h> // use glog instead of CHECK to avoid importing other paddle header files.
#include "paddle/fluid/inference/demo_ci/utils.h"
DECLARE_double(fraction_of_gpu_memory_to_use);
DEFINE_string(modeldir, "", "Directory of the inference model.");
DEFINE_string(refer, "", "path to reference result for comparison.");
DEFINE_string(
data, "",
"path of data; each line is a record, format is "
"'<space splitted floats as data>\t<space splitted ints as shape'");
namespace paddle {
namespace demo {
/*
* Use the tensorrt fluid engine to inference the demo.
*/
void Main() {
std::unique_ptr<PaddlePredictor> predictor;
paddle::contrib::MixedRTConfig config;
config.param_file = FLAGS_modeldir + "/__params__";
config.prog_file = FLAGS_modeldir + "/__model__";
config.use_gpu = true;
config.device = 0;
config.max_batch_size = 1;
config.fraction_of_gpu_memory = 0.1; // set by yourself
predictor = CreatePaddlePredictor<paddle::contrib::MixedRTConfig>(config);
VLOG(3) << "begin to process data";
// Just a single batch of data.
std::string line;
std::ifstream file(FLAGS_data);
std::getline(file, line);
auto record = ProcessALine(line);
file.close();
// Inference.
PaddleTensor input;
input.shape = record.shape;
input.data =
PaddleBuf(record.data.data(), record.data.size() * sizeof(float));
input.dtype = PaddleDType::FLOAT32;
VLOG(3) << "run executor";
std::vector<PaddleTensor> output;
predictor->Run({input}, &output, 1);
VLOG(3) << "output.size " << output.size();
auto& tensor = output.front();
VLOG(3) << "output: " << SummaryTensor(tensor);
// compare with reference result
CheckOutput(FLAGS_refer, tensor);
}
} // namespace demo
} // namespace paddle
int main(int argc, char** argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
paddle::demo::Main();
return 0;
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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 "OgreShaderFunctionAtom.h"
#include "OgreRoot.h"
namespace Ogre {
namespace RTShader {
//-----------------------------------------------------------------------------
Operand::Operand(ParameterPtr parameter, Operand::OpSemantic opSemantic, int opMask, ushort indirectionLevel)
{
mParameter = parameter;
mSemantic = opSemantic;
mMask = opMask;
mIndirectionLevel = indirectionLevel;
}
//-----------------------------------------------------------------------------
Operand::Operand(const Operand& other)
{
*this = other;
}
//-----------------------------------------------------------------------------
Operand& Operand::operator= (const Operand & other)
{
if (this != &other)
{
mParameter = other.mParameter;
mSemantic = other.mSemantic;
mMask = other.mMask;
mIndirectionLevel = other.mIndirectionLevel;
}
return *this;
}
//-----------------------------------------------------------------------------
Operand::~Operand()
{
// nothing todo
}
//-----------------------------------------------------------------------------
String Operand::getMaskAsString(int mask)
{
String retVal = "";
if (mask & ~OPM_ALL)
{
if (mask & OPM_X)
{
retVal += "x";
}
if (mask & OPM_Y)
{
retVal += "y";
}
if (mask & OPM_Z)
{
retVal += "z";
}
if (mask & OPM_W)
{
retVal += "w";
}
}
return retVal;
}
//-----------------------------------------------------------------------------
int Operand::getFloatCount(int mask)
{
int floatCount = 0;
while (mask != 0)
{
if ((mask & Operand::OPM_X) != 0)
{
floatCount++;
}
mask = mask >> 1;
}
return floatCount;
}
//-----------------------------------------------------------------------------
GpuConstantType Operand::getGpuConstantType(int mask)
{
int floatCount = getFloatCount(mask);
GpuConstantType type;
switch (floatCount)
{
case 1:
type = GCT_FLOAT1;
break;
case 2:
type = GCT_FLOAT2;
break;
case 3:
type = GCT_FLOAT3;
break;
case 4:
type = GCT_FLOAT4;
break;
default:
type = GCT_UNKNOWN;
break;
}
return type;
}
//-----------------------------------------------------------------------------
String Operand::toString() const
{
String retVal = mParameter->toString();
if ((mMask & OPM_ALL) || ((mMask & OPM_X) && (mMask & OPM_Y) && (mMask & OPM_Z) && (mMask & OPM_W)))
{
return retVal;
}
retVal += "." + getMaskAsString(mMask);
return retVal;
}
//-----------------------------------------------------------------------------
FunctionAtom::FunctionAtom()
{
mGroupExecutionOrder = -1;
mInternalExecutionOrder = -1;
}
//-----------------------------------------------------------------------------
int FunctionAtom::getGroupExecutionOrder() const
{
return mGroupExecutionOrder;
}
//-----------------------------------------------------------------------------
int FunctionAtom::getInternalExecutionOrder() const
{
return mInternalExecutionOrder;
}
String FunctionInvocation::Type = "FunctionInvocation";
//-----------------------------------------------------------------------
FunctionInvocation::FunctionInvocation(const String& functionName,
int groupOrder, int internalOrder, String returnType)
{
mFunctionName = functionName;
mGroupExecutionOrder = groupOrder;
mInternalExecutionOrder = internalOrder;
mReturnType = returnType;
}
//-----------------------------------------------------------------------------
FunctionInvocation::FunctionInvocation(const FunctionInvocation& other)
{
mFunctionName = other.mFunctionName;
mGroupExecutionOrder = other.mGroupExecutionOrder;
mInternalExecutionOrder = other.mInternalExecutionOrder;
mReturnType = other.mReturnType;
for ( OperandVector::const_iterator it = other.mOperands.begin(); it != other.mOperands.end(); ++it)
mOperands.push_back(Operand(*it));
}
//-----------------------------------------------------------------------
void FunctionInvocation::writeSourceCode(std::ostream& os, const String& targetLanguage) const
{
// Write function name.
os << mFunctionName << "(";
// Write parameters.
ushort curIndLevel = 0;
for (OperandVector::const_iterator it = mOperands.begin(); it != mOperands.end(); )
{
os << (*it).toString();
++it;
ushort opIndLevel = 0;
if (it != mOperands.end())
{
opIndLevel = (*it).getIndirectionLevel();
}
if (curIndLevel < opIndLevel)
{
while (curIndLevel < opIndLevel)
{
++curIndLevel;
os << "[";
}
}
else //if (curIndLevel >= opIndLevel)
{
while (curIndLevel > opIndLevel)
{
--curIndLevel;
os << "]";
}
if (opIndLevel != 0)
{
os << "][";
}
else if (it != mOperands.end())
{
os << ", ";
}
}
}
// Write function call closer.
os << ");";
}
//-----------------------------------------------------------------------
void FunctionInvocation::pushOperand(ParameterPtr parameter, Operand::OpSemantic opSemantic, int opMask, int indirectionLevel)
{
mOperands.push_back(Operand(parameter, opSemantic, opMask, indirectionLevel));
}
//-----------------------------------------------------------------------
bool FunctionInvocation::operator == ( const FunctionInvocation& rhs ) const
{
return FunctionInvocationCompare()(*this, rhs);
}
//-----------------------------------------------------------------------
bool FunctionInvocation::operator != ( const FunctionInvocation& rhs ) const
{
return !(*this == rhs);
}
//-----------------------------------------------------------------------
bool FunctionInvocation::operator < ( const FunctionInvocation& rhs ) const
{
return FunctionInvocationLessThan()(*this, rhs);
}
bool FunctionInvocation::FunctionInvocationLessThan::operator ()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const
{
// Check the function names first
// Adding an exception to std::string sorting. I feel that functions beginning with an underscore should be placed before
// functions beginning with an alphanumeric character. By default strings are sorted based on the ASCII value of each character.
// Underscores have an ASCII value in between capital and lowercase characters. This is why the exception is needed.
if (lhs.getFunctionName() < rhs.getFunctionName())
{
if(rhs.getFunctionName().at(0) == '_')
return false;
else
return true;
}
if (lhs.getFunctionName() > rhs.getFunctionName())
{
if(lhs.getFunctionName().at(0) == '_')
return true;
else
return false;
}
// Next check the return type
if (lhs.getReturnType() < rhs.getReturnType())
return true;
if (lhs.getReturnType() > rhs.getReturnType())
return false;
// Check the number of operands
if (lhs.mOperands.size() < rhs.mOperands.size())
return true;
if (lhs.mOperands.size() > rhs.mOperands.size())
return false;
// Now that we've gotten past the two quick tests, iterate over operands
// Check the semantic and type. The operands must be in the same order as well.
OperandVector::const_iterator itLHSOps = lhs.mOperands.begin();
OperandVector::const_iterator itRHSOps = rhs.mOperands.begin();
for ( ; itLHSOps != lhs.mOperands.end(), itRHSOps != rhs.mOperands.end(); ++itLHSOps, ++itRHSOps)
{
if (itLHSOps->getSemantic() < itRHSOps->getSemantic())
return true;
if (itLHSOps->getSemantic() > itRHSOps->getSemantic())
return false;
if (itLHSOps->getParameter()->getType() < itRHSOps->getParameter()->getType())
return true;
if (itLHSOps->getParameter()->getType() > itRHSOps->getParameter()->getType())
return false;
}
return false;
}
bool FunctionInvocation::FunctionInvocationCompare::operator ()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const
{
// Check the function names first
if (lhs.getFunctionName() != rhs.getFunctionName())
return false;
// Next check the return type
if (lhs.getReturnType() != rhs.getReturnType())
return false;
// Check the number of operands
if (lhs.mOperands.size() != rhs.mOperands.size())
return false;
// Now that we've gotten past the two quick tests, iterate over operands
// Check the semantic and type. The operands must be in the same order as well.
OperandVector::const_iterator itLHSOps = lhs.mOperands.begin();
OperandVector::const_iterator itRHSOps = rhs.mOperands.begin();
for ( ; itLHSOps != lhs.mOperands.end(), itRHSOps != rhs.mOperands.end(); ++itLHSOps, ++itRHSOps)
{
if (itLHSOps->getSemantic() != itRHSOps->getSemantic())
return false;
GpuConstantType leftType = itLHSOps->getParameter()->getType();
GpuConstantType rightType = itRHSOps->getParameter()->getType();
if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL ES 2") != String::npos)
{
if (leftType == GCT_SAMPLER1D)
leftType = GCT_SAMPLER2D;
if (rightType == GCT_SAMPLER1D)
rightType = GCT_SAMPLER2D;
}
// If a swizzle mask is being applied to the parameter, generate the GpuConstantType to
// perform the parameter type comparison the way that the compiler will see it.
if ((itLHSOps->getFloatCount(itLHSOps->getMask()) > 0) ||
(itRHSOps->getFloatCount(itRHSOps->getMask()) > 0))
{
if (itLHSOps->getFloatCount(itLHSOps->getMask()) > 0)
{
leftType = (GpuConstantType)((itLHSOps->getParameter()->getType() - itLHSOps->getParameter()->getType()) +
itLHSOps->getFloatCount(itLHSOps->getMask()));
}
if (itRHSOps->getFloatCount(itRHSOps->getMask()) > 0)
{
rightType = (GpuConstantType)((itRHSOps->getParameter()->getType() - itRHSOps->getParameter()->getType()) +
itRHSOps->getFloatCount(itRHSOps->getMask()));
}
}
if (leftType != rightType)
return false;
}
// Passed all tests, they are the same
return true;
}
}
}
<commit_msg>RTSS: When comparing function invocations. Assume that the left side is to be ordered first if all other tests fail. Resolves some GL ES 2 issues.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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 "OgreShaderFunctionAtom.h"
#include "OgreRoot.h"
namespace Ogre {
namespace RTShader {
//-----------------------------------------------------------------------------
Operand::Operand(ParameterPtr parameter, Operand::OpSemantic opSemantic, int opMask, ushort indirectionLevel)
{
mParameter = parameter;
mSemantic = opSemantic;
mMask = opMask;
mIndirectionLevel = indirectionLevel;
}
//-----------------------------------------------------------------------------
Operand::Operand(const Operand& other)
{
*this = other;
}
//-----------------------------------------------------------------------------
Operand& Operand::operator= (const Operand & other)
{
if (this != &other)
{
mParameter = other.mParameter;
mSemantic = other.mSemantic;
mMask = other.mMask;
mIndirectionLevel = other.mIndirectionLevel;
}
return *this;
}
//-----------------------------------------------------------------------------
Operand::~Operand()
{
// nothing todo
}
//-----------------------------------------------------------------------------
String Operand::getMaskAsString(int mask)
{
String retVal = "";
if (mask & ~OPM_ALL)
{
if (mask & OPM_X)
{
retVal += "x";
}
if (mask & OPM_Y)
{
retVal += "y";
}
if (mask & OPM_Z)
{
retVal += "z";
}
if (mask & OPM_W)
{
retVal += "w";
}
}
return retVal;
}
//-----------------------------------------------------------------------------
int Operand::getFloatCount(int mask)
{
int floatCount = 0;
while (mask != 0)
{
if ((mask & Operand::OPM_X) != 0)
{
floatCount++;
}
mask = mask >> 1;
}
return floatCount;
}
//-----------------------------------------------------------------------------
GpuConstantType Operand::getGpuConstantType(int mask)
{
int floatCount = getFloatCount(mask);
GpuConstantType type;
switch (floatCount)
{
case 1:
type = GCT_FLOAT1;
break;
case 2:
type = GCT_FLOAT2;
break;
case 3:
type = GCT_FLOAT3;
break;
case 4:
type = GCT_FLOAT4;
break;
default:
type = GCT_UNKNOWN;
break;
}
return type;
}
//-----------------------------------------------------------------------------
String Operand::toString() const
{
String retVal = mParameter->toString();
if ((mMask & OPM_ALL) || ((mMask & OPM_X) && (mMask & OPM_Y) && (mMask & OPM_Z) && (mMask & OPM_W)))
{
return retVal;
}
retVal += "." + getMaskAsString(mMask);
return retVal;
}
//-----------------------------------------------------------------------------
FunctionAtom::FunctionAtom()
{
mGroupExecutionOrder = -1;
mInternalExecutionOrder = -1;
}
//-----------------------------------------------------------------------------
int FunctionAtom::getGroupExecutionOrder() const
{
return mGroupExecutionOrder;
}
//-----------------------------------------------------------------------------
int FunctionAtom::getInternalExecutionOrder() const
{
return mInternalExecutionOrder;
}
String FunctionInvocation::Type = "FunctionInvocation";
//-----------------------------------------------------------------------
FunctionInvocation::FunctionInvocation(const String& functionName,
int groupOrder, int internalOrder, String returnType)
{
mFunctionName = functionName;
mGroupExecutionOrder = groupOrder;
mInternalExecutionOrder = internalOrder;
mReturnType = returnType;
}
//-----------------------------------------------------------------------------
FunctionInvocation::FunctionInvocation(const FunctionInvocation& other)
{
mFunctionName = other.mFunctionName;
mGroupExecutionOrder = other.mGroupExecutionOrder;
mInternalExecutionOrder = other.mInternalExecutionOrder;
mReturnType = other.mReturnType;
for ( OperandVector::const_iterator it = other.mOperands.begin(); it != other.mOperands.end(); ++it)
mOperands.push_back(Operand(*it));
}
//-----------------------------------------------------------------------
void FunctionInvocation::writeSourceCode(std::ostream& os, const String& targetLanguage) const
{
// Write function name.
os << mFunctionName << "(";
// Write parameters.
ushort curIndLevel = 0;
for (OperandVector::const_iterator it = mOperands.begin(); it != mOperands.end(); )
{
os << (*it).toString();
++it;
ushort opIndLevel = 0;
if (it != mOperands.end())
{
opIndLevel = (*it).getIndirectionLevel();
}
if (curIndLevel < opIndLevel)
{
while (curIndLevel < opIndLevel)
{
++curIndLevel;
os << "[";
}
}
else //if (curIndLevel >= opIndLevel)
{
while (curIndLevel > opIndLevel)
{
--curIndLevel;
os << "]";
}
if (opIndLevel != 0)
{
os << "][";
}
else if (it != mOperands.end())
{
os << ", ";
}
}
}
// Write function call closer.
os << ");";
}
//-----------------------------------------------------------------------
void FunctionInvocation::pushOperand(ParameterPtr parameter, Operand::OpSemantic opSemantic, int opMask, int indirectionLevel)
{
mOperands.push_back(Operand(parameter, opSemantic, opMask, indirectionLevel));
}
//-----------------------------------------------------------------------
bool FunctionInvocation::operator == ( const FunctionInvocation& rhs ) const
{
return FunctionInvocationCompare()(*this, rhs);
}
//-----------------------------------------------------------------------
bool FunctionInvocation::operator != ( const FunctionInvocation& rhs ) const
{
return !(*this == rhs);
}
//-----------------------------------------------------------------------
bool FunctionInvocation::operator < ( const FunctionInvocation& rhs ) const
{
return FunctionInvocationLessThan()(*this, rhs);
}
bool FunctionInvocation::FunctionInvocationLessThan::operator ()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const
{
// Check the function names first
// Adding an exception to std::string sorting. I feel that functions beginning with an underscore should be placed before
// functions beginning with an alphanumeric character. By default strings are sorted based on the ASCII value of each character.
// Underscores have an ASCII value in between capital and lowercase characters. This is why the exception is needed.
if (lhs.getFunctionName() < rhs.getFunctionName())
{
if(rhs.getFunctionName().at(0) == '_')
return false;
else
return true;
}
if (lhs.getFunctionName() > rhs.getFunctionName())
{
if(lhs.getFunctionName().at(0) == '_')
return true;
else
return false;
}
// Next check the return type
if (lhs.getReturnType() < rhs.getReturnType())
return true;
if (lhs.getReturnType() > rhs.getReturnType())
return false;
// Check the number of operands
if (lhs.mOperands.size() < rhs.mOperands.size())
return true;
if (lhs.mOperands.size() > rhs.mOperands.size())
return false;
// Now that we've gotten past the two quick tests, iterate over operands
// Check the semantic and type. The operands must be in the same order as well.
OperandVector::const_iterator itLHSOps = lhs.mOperands.begin();
OperandVector::const_iterator itRHSOps = rhs.mOperands.begin();
for ( ; itLHSOps != lhs.mOperands.end(), itRHSOps != rhs.mOperands.end(); ++itLHSOps, ++itRHSOps)
{
if (itLHSOps->getSemantic() < itRHSOps->getSemantic())
return true;
if (itLHSOps->getSemantic() > itRHSOps->getSemantic())
return false;
if (itLHSOps->getParameter()->getType() < itRHSOps->getParameter()->getType())
return true;
if (itLHSOps->getParameter()->getType() > itRHSOps->getParameter()->getType())
return false;
}
return true;
}
bool FunctionInvocation::FunctionInvocationCompare::operator ()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const
{
// Check the function names first
if (lhs.getFunctionName() != rhs.getFunctionName())
return false;
// Next check the return type
if (lhs.getReturnType() != rhs.getReturnType())
return false;
// Check the number of operands
if (lhs.mOperands.size() != rhs.mOperands.size())
return false;
// Now that we've gotten past the two quick tests, iterate over operands
// Check the semantic and type. The operands must be in the same order as well.
OperandVector::const_iterator itLHSOps = lhs.mOperands.begin();
OperandVector::const_iterator itRHSOps = rhs.mOperands.begin();
for ( ; itLHSOps != lhs.mOperands.end(), itRHSOps != rhs.mOperands.end(); ++itLHSOps, ++itRHSOps)
{
if (itLHSOps->getSemantic() != itRHSOps->getSemantic())
return false;
GpuConstantType leftType = itLHSOps->getParameter()->getType();
GpuConstantType rightType = itRHSOps->getParameter()->getType();
if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL ES 2") != String::npos)
{
if (leftType == GCT_SAMPLER1D)
leftType = GCT_SAMPLER2D;
if (rightType == GCT_SAMPLER1D)
rightType = GCT_SAMPLER2D;
}
// If a swizzle mask is being applied to the parameter, generate the GpuConstantType to
// perform the parameter type comparison the way that the compiler will see it.
if ((itLHSOps->getFloatCount(itLHSOps->getMask()) > 0) ||
(itRHSOps->getFloatCount(itRHSOps->getMask()) > 0))
{
if (itLHSOps->getFloatCount(itLHSOps->getMask()) > 0)
{
leftType = (GpuConstantType)((itLHSOps->getParameter()->getType() - itLHSOps->getParameter()->getType()) +
itLHSOps->getFloatCount(itLHSOps->getMask()));
}
if (itRHSOps->getFloatCount(itRHSOps->getMask()) > 0)
{
rightType = (GpuConstantType)((itRHSOps->getParameter()->getType() - itRHSOps->getParameter()->getType()) +
itRHSOps->getFloatCount(itRHSOps->getMask()));
}
}
if (leftType != rightType)
return false;
}
// Passed all tests, they are the same
return true;
}
}
}
<|endoftext|>
|
<commit_before>#include "convergence.hpp"
#include "dofs.hpp"
#include "fem_solve.hpp"
#include "writer.hpp"
#include <Eigen/Core>
#include <igl/readMESH.h>
#include <igl/readSTL.h>
#include <igl/slice.h>
#include <igl/slice_into.h>
#include <sstream>
typedef Eigen::VectorXd Vector;
double f_square(double x, double y) {
return 2 * M_PI * M_PI * sin(M_PI * x) * sin(M_PI * y);
}
double uex_square(double x, double y) {
return sin(M_PI * x) * sin(M_PI * y);
}
Eigen::Vector2d uex_grad_square(double x, double y) {
Eigen::Vector2d grad;
grad << M_PI * cos(M_PI * x) * sin(M_PI * y),
M_PI * sin(M_PI * x) * cos(M_PI * y);
return grad;
}
int main(int, char **) {
try {
Vector u;
Eigen::MatrixXd vertices;
Eigen::MatrixXi triangles;
Eigen::MatrixXi tetrahedra;
igl::readMESH(NPDE_DATA_PATH "square_5.mesh", vertices, tetrahedra, triangles);
QDofs quadraticDofs(vertices, triangles);
solveFiniteElement(u, quadraticDofs, f_square);
writeToFile("square_5_values.txt", u.segment(0, vertices.rows()));
writeMatrixToFile("square_5_vertices.txt", vertices);
writeMatrixToFile("square_5_triangles.txt", triangles);
convergenceAnalysis("square", 7, f_square, uex_square, uex_grad_square);
} catch (std::runtime_error &e) {
std::cerr << "An error occurred. Error message: " << std::endl;
std::cerr << " \"" << e.what() << "\"" << std::endl;
return EXIT_FAILURE;
} catch (...) {
std::cerr << "An unknown error occurred." << std::endl;
throw;
}
return EXIT_SUCCESS;
}
<commit_msg>Don't overwrite files during convergence study<commit_after>#include "convergence.hpp"
#include "dofs.hpp"
#include "fem_solve.hpp"
#include "writer.hpp"
#include <Eigen/Core>
#include <igl/readMESH.h>
#include <igl/readSTL.h>
#include <igl/slice.h>
#include <igl/slice_into.h>
#include <sstream>
typedef Eigen::VectorXd Vector;
double f_square(double x, double y) {
return 2 * M_PI * M_PI * sin(M_PI * x) * sin(M_PI * y);
}
double uex_square(double x, double y) {
return sin(M_PI * x) * sin(M_PI * y);
}
Eigen::Vector2d uex_grad_square(double x, double y) {
Eigen::Vector2d grad;
grad << M_PI * cos(M_PI * x) * sin(M_PI * y),
M_PI * sin(M_PI * x) * cos(M_PI * y);
return grad;
}
int main(int, char **) {
try {
Vector u;
Eigen::MatrixXd vertices;
Eigen::MatrixXi triangles;
Eigen::MatrixXi tetrahedra;
igl::readMESH(NPDE_DATA_PATH "square_5.mesh", vertices, tetrahedra, triangles);
QDofs quadraticDofs(vertices, triangles);
solveFiniteElement(u, quadraticDofs, f_square);
writeToFile("square_values.txt", u.segment(0, vertices.rows()));
writeMatrixToFile("square_vertices.txt", vertices);
writeMatrixToFile("square_triangles.txt", triangles);
convergenceAnalysis("square", 7, f_square, uex_square, uex_grad_square);
} catch (std::runtime_error &e) {
std::cerr << "An error occurred. Error message: " << std::endl;
std::cerr << " \"" << e.what() << "\"" << std::endl;
return EXIT_FAILURE;
} catch (...) {
std::cerr << "An unknown error occurred." << std::endl;
throw;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <leveldb/db.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
namespace caffe {
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::Message;
bool ReadProtoFromTextFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
FileInputStream* input = new FileInputStream(fd);
bool success = google::protobuf::TextFormat::Parse(input, proto);
delete input;
close(fd);
return success;
}
void WriteProtoToTextFile(const Message& proto, const char* filename) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
FileOutputStream* output = new FileOutputStream(fd);
CHECK(google::protobuf::TextFormat::Print(proto, output));
delete output;
close(fd);
}
bool ReadProtoFromBinaryFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
ZeroCopyInputStream* raw_input = new FileInputStream(fd);
CodedInputStream* coded_input = new CodedInputStream(raw_input);
coded_input->SetTotalBytesLimit(1073741824, 536870912);
bool success = proto->ParseFromCodedStream(coded_input);
delete coded_input;
delete raw_input;
close(fd);
return success;
}
void WriteProtoToBinaryFile(const Message& proto, const char* filename) {
fstream output(filename, ios::out | ios::trunc | ios::binary);
CHECK(proto.SerializeToOstream(&output));
}
bool ReadImageToDatum(const string& filename, const int label,
const int height, const int width, const bool is_color, Datum* datum) {
cv::Mat cv_img;
int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag);
if (!cv_img_origin.data) {
LOG(ERROR) << "Could not open or find file " << filename;
return false;
}
if (height > 0 && width > 0) {
cv::resize(cv_img_origin, cv_img, cv::Size(height, width));
} else {
cv_img = cv_img_origin;
}
int num_channels = (is_color ? 3 : 1);
datum->set_channels(num_channels);
datum->set_height(cv_img.rows);
datum->set_width(cv_img.cols);
datum->set_label(label);
datum->clear_data();
datum->clear_float_data();
string* datum_string = datum->mutable_data();
if (is_color) {
for (int c = 0; c < num_channels; ++c) {
for (int h = 0; h < cv_img.rows; ++h) {
for (int w = 0; w < cv_img.cols; ++w) {
datum_string->push_back(
static_cast<char>(cv_img.at<cv::Vec3b>(h, w)[c]));
}
}
}
} else { // Faster than repeatedly testing is_color for each pixel w/i loop
for (int h = 0; h < cv_img.rows; ++h) {
for (int w = 0; w < cv_img.cols; ++w) {
datum_string->push_back(
static_cast<char>(cv_img.at<uchar>(h, w)));
}
}
}
return true;
}
leveldb::Options GetLevelDBOptions() {
// In default, we will return the leveldb option and set the max open files
// in order to avoid using up the operating system's limit.
leveldb::Options options;
options.max_open_files = 100;
return options;
}
// Verifies format of data stored in HDF5 file and reshapes blob accordingly.
template <typename Dtype>
void hdf5_load_nd_dataset_helper(
hid_t file_id, const char* dataset_name_, int min_dim, int max_dim,
Blob<Dtype>* blob) {
// Verify that the number of dimensions is in the accepted range.
herr_t status;
int ndims;
status = H5LTget_dataset_ndims(file_id, dataset_name_, &ndims);
CHECK_GE(status, 0) << "Failed to get dataset ndims for " << dataset_name_;
CHECK_GE(ndims, min_dim);
CHECK_LE(ndims, max_dim);
// Verify that the data format is what we expect: float or double.
std::vector<hsize_t> dims(ndims);
H5T_class_t class_;
status = H5LTget_dataset_info(
file_id, dataset_name_, dims.data(), &class_, NULL);
CHECK_GE(status, 0) << "Failed to get dataset info for " << dataset_name_;
CHECK_EQ(class_, H5T_FLOAT) << "Expected float or double data";
blob->Reshape(
dims[0],
(dims.size() > 1) ? dims[1] : 1,
(dims.size() > 2) ? dims[2] : 1,
(dims.size() > 3) ? dims[3] : 1);
}
template <>
void hdf5_load_nd_dataset<float>(hid_t file_id, const char* dataset_name_,
int min_dim, int max_dim, Blob<float>* blob) {
hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob);
herr_t status = H5LTread_dataset_float(
file_id, dataset_name_, blob->mutable_cpu_data());
CHECK_GE(status, 0) << "Failed to read float dataset " << dataset_name_;
}
template <>
void hdf5_load_nd_dataset<double>(hid_t file_id, const char* dataset_name_,
int min_dim, int max_dim, Blob<double>* blob) {
hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob);
herr_t status = H5LTread_dataset_double(
file_id, dataset_name_, blob->mutable_cpu_data());
CHECK_GE(status, 0) << "Failed to read double dataset " << dataset_name_;
}
template <>
void hdf5_save_nd_dataset<float>(
const hid_t file_id, const string dataset_name, const Blob<float>& blob) {
hsize_t dims[HDF5_NUM_DIMS];
dims[0] = blob.num();
dims[1] = blob.channels();
dims[2] = blob.height();
dims[3] = blob.width();
herr_t status = H5LTmake_dataset_float(
file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data());
CHECK_GE(status, 0) << "Failed to make float dataset " << dataset_name;
}
template <>
void hdf5_save_nd_dataset<double>(
const hid_t file_id, const string dataset_name, const Blob<double>& blob) {
hsize_t dims[HDF5_NUM_DIMS];
dims[0] = blob.num();
dims[1] = blob.channels();
dims[2] = blob.height();
dims[3] = blob.width();
herr_t status = H5LTmake_dataset_double(
file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data());
CHECK_GE(status, 0) << "Failed to make double dataset " << dataset_name;
}
} // namespace caffe
<commit_msg>Fixed param order of cv::Size in cv::resize<commit_after>#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <leveldb/db.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
namespace caffe {
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::Message;
bool ReadProtoFromTextFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
FileInputStream* input = new FileInputStream(fd);
bool success = google::protobuf::TextFormat::Parse(input, proto);
delete input;
close(fd);
return success;
}
void WriteProtoToTextFile(const Message& proto, const char* filename) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
FileOutputStream* output = new FileOutputStream(fd);
CHECK(google::protobuf::TextFormat::Print(proto, output));
delete output;
close(fd);
}
bool ReadProtoFromBinaryFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
ZeroCopyInputStream* raw_input = new FileInputStream(fd);
CodedInputStream* coded_input = new CodedInputStream(raw_input);
coded_input->SetTotalBytesLimit(1073741824, 536870912);
bool success = proto->ParseFromCodedStream(coded_input);
delete coded_input;
delete raw_input;
close(fd);
return success;
}
void WriteProtoToBinaryFile(const Message& proto, const char* filename) {
fstream output(filename, ios::out | ios::trunc | ios::binary);
CHECK(proto.SerializeToOstream(&output));
}
bool ReadImageToDatum(const string& filename, const int label,
const int height, const int width, const bool is_color, Datum* datum) {
cv::Mat cv_img;
int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag);
if (!cv_img_origin.data) {
LOG(ERROR) << "Could not open or find file " << filename;
return false;
}
if (height > 0 && width > 0) {
cv::resize(cv_img_origin, cv_img, cv::Size(width, height));
} else {
cv_img = cv_img_origin;
}
int num_channels = (is_color ? 3 : 1);
datum->set_channels(num_channels);
datum->set_height(cv_img.rows);
datum->set_width(cv_img.cols);
datum->set_label(label);
datum->clear_data();
datum->clear_float_data();
string* datum_string = datum->mutable_data();
if (is_color) {
for (int c = 0; c < num_channels; ++c) {
for (int h = 0; h < cv_img.rows; ++h) {
for (int w = 0; w < cv_img.cols; ++w) {
datum_string->push_back(
static_cast<char>(cv_img.at<cv::Vec3b>(h, w)[c]));
}
}
}
} else { // Faster than repeatedly testing is_color for each pixel w/i loop
for (int h = 0; h < cv_img.rows; ++h) {
for (int w = 0; w < cv_img.cols; ++w) {
datum_string->push_back(
static_cast<char>(cv_img.at<uchar>(h, w)));
}
}
}
return true;
}
leveldb::Options GetLevelDBOptions() {
// In default, we will return the leveldb option and set the max open files
// in order to avoid using up the operating system's limit.
leveldb::Options options;
options.max_open_files = 100;
return options;
}
// Verifies format of data stored in HDF5 file and reshapes blob accordingly.
template <typename Dtype>
void hdf5_load_nd_dataset_helper(
hid_t file_id, const char* dataset_name_, int min_dim, int max_dim,
Blob<Dtype>* blob) {
// Verify that the number of dimensions is in the accepted range.
herr_t status;
int ndims;
status = H5LTget_dataset_ndims(file_id, dataset_name_, &ndims);
CHECK_GE(status, 0) << "Failed to get dataset ndims for " << dataset_name_;
CHECK_GE(ndims, min_dim);
CHECK_LE(ndims, max_dim);
// Verify that the data format is what we expect: float or double.
std::vector<hsize_t> dims(ndims);
H5T_class_t class_;
status = H5LTget_dataset_info(
file_id, dataset_name_, dims.data(), &class_, NULL);
CHECK_GE(status, 0) << "Failed to get dataset info for " << dataset_name_;
CHECK_EQ(class_, H5T_FLOAT) << "Expected float or double data";
blob->Reshape(
dims[0],
(dims.size() > 1) ? dims[1] : 1,
(dims.size() > 2) ? dims[2] : 1,
(dims.size() > 3) ? dims[3] : 1);
}
template <>
void hdf5_load_nd_dataset<float>(hid_t file_id, const char* dataset_name_,
int min_dim, int max_dim, Blob<float>* blob) {
hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob);
herr_t status = H5LTread_dataset_float(
file_id, dataset_name_, blob->mutable_cpu_data());
CHECK_GE(status, 0) << "Failed to read float dataset " << dataset_name_;
}
template <>
void hdf5_load_nd_dataset<double>(hid_t file_id, const char* dataset_name_,
int min_dim, int max_dim, Blob<double>* blob) {
hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob);
herr_t status = H5LTread_dataset_double(
file_id, dataset_name_, blob->mutable_cpu_data());
CHECK_GE(status, 0) << "Failed to read double dataset " << dataset_name_;
}
template <>
void hdf5_save_nd_dataset<float>(
const hid_t file_id, const string dataset_name, const Blob<float>& blob) {
hsize_t dims[HDF5_NUM_DIMS];
dims[0] = blob.num();
dims[1] = blob.channels();
dims[2] = blob.height();
dims[3] = blob.width();
herr_t status = H5LTmake_dataset_float(
file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data());
CHECK_GE(status, 0) << "Failed to make float dataset " << dataset_name;
}
template <>
void hdf5_save_nd_dataset<double>(
const hid_t file_id, const string dataset_name, const Blob<double>& blob) {
hsize_t dims[HDF5_NUM_DIMS];
dims[0] = blob.num();
dims[1] = blob.channels();
dims[2] = blob.height();
dims[3] = blob.width();
herr_t status = H5LTmake_dataset_double(
file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data());
CHECK_GE(status, 0) << "Failed to make double dataset " << dataset_name;
}
} // namespace caffe
<|endoftext|>
|
<commit_before>// MenuTheme.cc for FbTk
// Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// 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.
// $Id: MenuTheme.cc,v 1.6 2003/02/23 01:00:48 fluxgen Exp $
#include "MenuTheme.hh"
#include "Color.hh"
#include "Texture.hh"
#include "Font.hh"
#include "App.hh"
//TODO change this
#include "../StringUtil.hh"
#include <cstdio>
namespace FbTk {
MenuTheme::MenuTheme(int screen_num):
FbTk::Theme(screen_num),
t_text(*this, "menu.title.textColor", "Menu.Title.TextColor"),
f_text(*this, "menu.frame.textColor", "Menu.Frame.TextColor"),
h_text(*this, "menu.hilite.textColor", "Menu.Hilite.TextColor"),
d_text(*this, "menu.frame.disableColor", "Menu.Frame.DisableColor"),
title(*this, "menu.title", "Menu.Title"),
frame(*this, "menu.frame", "Menu.Frame"),
hilite(*this, "menu.hilite", "Menu.Hilite"),
titlefont(*this, "menu.title.font", "Menu.Title.Font"),
framefont(*this, "menu.frame.font", "Menu.Frame.Font"),
framefont_justify(*this, "menu.frame.justify", "Menu.Frame.Justify"),
titlefont_justify(*this, "menu.title.justify", "Menu.Title.Justify"),
bullet_pos(*this, "menu.bullet.position", "Menu.Bullet.Position"),
m_bullet(*this, "menu.bullet", "Menu.Bullet"),
m_border_width(*this, "borderWidth", "BorderWidth"),
m_bevel_width(*this, "bevelWidth", "BevelWidth"),
m_border_color(*this, "borderColor", "BorderColor"),
m_display(FbTk::App::instance()->display()) {
Window rootwindow = RootWindow(m_display, screen_num);
XGCValues gcv;
unsigned long gc_value_mask = GCForeground;
gcv.foreground = t_text->pixel();
t_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = f_text->pixel();
f_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = h_text->pixel();
h_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = d_text->pixel();
d_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = hilite->color().pixel();
hilite_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
}
MenuTheme::~MenuTheme() {
XFreeGC(m_display, t_text_gc);
XFreeGC(m_display, f_text_gc);
XFreeGC(m_display, h_text_gc);
XFreeGC(m_display, d_text_gc);
XFreeGC(m_display, hilite_gc);
}
void MenuTheme::reconfigTheme() {
XGCValues gcv;
unsigned long gc_value_mask = GCForeground;
gcv.foreground = t_text->pixel();
XChangeGC(m_display, t_text_gc,
gc_value_mask, &gcv);
gcv.foreground = f_text->pixel();
XChangeGC(m_display, f_text_gc,
gc_value_mask, &gcv);
gcv.foreground = h_text->pixel();
XChangeGC(m_display, h_text_gc,
gc_value_mask, &gcv);
gcv.foreground = d_text->pixel();
XChangeGC(m_display, d_text_gc,
gc_value_mask, &gcv);
gcv.foreground = hilite->color().pixel();
XChangeGC(m_display, hilite_gc,
gc_value_mask, &gcv);
// notify any listeners
m_theme_change_sig.notify();
}
template <>
void ThemeItem<MenuTheme::BulletType>::setDefaultValue() {
m_value = MenuTheme::EMPTY;
}
template <>
void ThemeItem<MenuTheme::BulletType>::setFromString(const char *str) {
// do nothing
if (StringUtil::strcasestr(str, "empty") != 0)
m_value = MenuTheme::EMPTY;
else if (StringUtil::strcasestr(str, "square") != 0)
m_value = MenuTheme::SQUARE;
else if (StringUtil::strcasestr(str, "triangle") != 0)
m_value = MenuTheme::TRIANGLE;
else if (StringUtil::strcasestr(str, "diamond") != 0)
m_value = MenuTheme::DIAMOND;
else
setDefaultValue();
}
template <>
void ThemeItem<MenuTheme::BulletType>::load() {
// do nothing, we don't have anything extra to load
}
template <>
void ThemeItem<unsigned int>::setDefaultValue() {
m_value = 0;
}
template <>
void ThemeItem<unsigned int>::setFromString(const char *str) {
sscanf(str, "%d", &m_value);
}
template <>
void ThemeItem<unsigned int>::load() {
}
}; // end namespace FbTk
<commit_msg>moved StringUtil to FbTk<commit_after>// MenuTheme.cc for FbTk
// Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// 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.
// $Id: MenuTheme.cc,v 1.7 2003/04/26 22:10:53 fluxgen Exp $
#include "MenuTheme.hh"
#include "Color.hh"
#include "Texture.hh"
#include "Font.hh"
#include "App.hh"
#include "StringUtil.hh"
#include <cstdio>
namespace FbTk {
MenuTheme::MenuTheme(int screen_num):
FbTk::Theme(screen_num),
t_text(*this, "menu.title.textColor", "Menu.Title.TextColor"),
f_text(*this, "menu.frame.textColor", "Menu.Frame.TextColor"),
h_text(*this, "menu.hilite.textColor", "Menu.Hilite.TextColor"),
d_text(*this, "menu.frame.disableColor", "Menu.Frame.DisableColor"),
title(*this, "menu.title", "Menu.Title"),
frame(*this, "menu.frame", "Menu.Frame"),
hilite(*this, "menu.hilite", "Menu.Hilite"),
titlefont(*this, "menu.title.font", "Menu.Title.Font"),
framefont(*this, "menu.frame.font", "Menu.Frame.Font"),
framefont_justify(*this, "menu.frame.justify", "Menu.Frame.Justify"),
titlefont_justify(*this, "menu.title.justify", "Menu.Title.Justify"),
bullet_pos(*this, "menu.bullet.position", "Menu.Bullet.Position"),
m_bullet(*this, "menu.bullet", "Menu.Bullet"),
m_border_width(*this, "borderWidth", "BorderWidth"),
m_bevel_width(*this, "bevelWidth", "BevelWidth"),
m_border_color(*this, "borderColor", "BorderColor"),
m_display(FbTk::App::instance()->display()) {
Window rootwindow = RootWindow(m_display, screen_num);
XGCValues gcv;
unsigned long gc_value_mask = GCForeground;
gcv.foreground = t_text->pixel();
t_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = f_text->pixel();
f_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = h_text->pixel();
h_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = d_text->pixel();
d_text_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
gcv.foreground = hilite->color().pixel();
hilite_gc = XCreateGC(m_display, rootwindow, gc_value_mask, &gcv);
}
MenuTheme::~MenuTheme() {
XFreeGC(m_display, t_text_gc);
XFreeGC(m_display, f_text_gc);
XFreeGC(m_display, h_text_gc);
XFreeGC(m_display, d_text_gc);
XFreeGC(m_display, hilite_gc);
}
void MenuTheme::reconfigTheme() {
XGCValues gcv;
unsigned long gc_value_mask = GCForeground;
gcv.foreground = t_text->pixel();
XChangeGC(m_display, t_text_gc,
gc_value_mask, &gcv);
gcv.foreground = f_text->pixel();
XChangeGC(m_display, f_text_gc,
gc_value_mask, &gcv);
gcv.foreground = h_text->pixel();
XChangeGC(m_display, h_text_gc,
gc_value_mask, &gcv);
gcv.foreground = d_text->pixel();
XChangeGC(m_display, d_text_gc,
gc_value_mask, &gcv);
gcv.foreground = hilite->color().pixel();
XChangeGC(m_display, hilite_gc,
gc_value_mask, &gcv);
// notify any listeners
m_theme_change_sig.notify();
}
template <>
void ThemeItem<MenuTheme::BulletType>::setDefaultValue() {
m_value = MenuTheme::EMPTY;
}
template <>
void ThemeItem<MenuTheme::BulletType>::setFromString(const char *str) {
// do nothing
if (StringUtil::strcasestr(str, "empty") != 0)
m_value = MenuTheme::EMPTY;
else if (StringUtil::strcasestr(str, "square") != 0)
m_value = MenuTheme::SQUARE;
else if (StringUtil::strcasestr(str, "triangle") != 0)
m_value = MenuTheme::TRIANGLE;
else if (StringUtil::strcasestr(str, "diamond") != 0)
m_value = MenuTheme::DIAMOND;
else
setDefaultValue();
}
template <>
void ThemeItem<MenuTheme::BulletType>::load() {
// do nothing, we don't have anything extra to load
}
template <>
void ThemeItem<unsigned int>::setDefaultValue() {
m_value = 0;
}
template <>
void ThemeItem<unsigned int>::setFromString(const char *str) {
sscanf(str, "%d", &m_value);
}
template <>
void ThemeItem<unsigned int>::load() {
}
}; // end namespace FbTk
<|endoftext|>
|
<commit_before>// LatchCube.cpp
#include "LatchCube.h"
wxIMPLEMENT_DYNAMIC_CLASS( LatchCube, Rubiks3x3x3 );
LatchCube::LatchCube( void )
{
}
/*virtual*/ LatchCube::~LatchCube( void )
{
}
/*virtual*/ void LatchCube::Reset( void )
{
Rubiks3x3x3::Reset();
constraintList.clear();
Constraint constraint;
// -X -> cw
constraint.direction = Rotation::DIR_CW;
constraint.location.Set( -2.0, 1.0, 0.0 );
constraintList.push_back( constraint );
constraint.location.Set( -2.0, -1.0, 0.0 );
constraintList.push_back( constraint );
// +X -> ccw
constraint.direction = Rotation::DIR_CCW;
constraint.location.Set( 2.0, 1.0, 0.0 );
constraintList.push_back( constraint );
constraint.location.Set( 2.0, -1.0, 0.0 );
constraintList.push_back( constraint );
// -Y -> ccw
constraint.direction = Rotation::DIR_CCW;
constraint.location.Set( 0.0, -2.0, -1.0 );
constraintList.push_back( constraint );
constraint.location.Set( 0.0, -2.0, 1.0 );
constraintList.push_back( constraint );
// +Y -> ccw
constraint.direction = Rotation::DIR_CCW;
constraint.location.Set( 0.0, 2.0, -1.0 );
constraintList.push_back( constraint );
constraint.location.Set( 0.0, 2.0, 1.0 );
constraintList.push_back( constraint );
// -Z -> cw
constraint.direction = Rotation::DIR_CW;
constraint.location.Set( -1.0, 0.0, -2.0 );
constraintList.push_back( constraint );
constraint.location.Set( 1.0, 0.0, -2.0 );
constraintList.push_back( constraint );
// +Z -> cw
constraint.direction = Rotation::DIR_CW;
constraint.location.Set( -1.0, 0.0, 2.0 );
constraintList.push_back( constraint );
constraint.location.Set( 1.0, 0.0, 2.0 );
constraintList.push_back( constraint );
}
/*virtual*/ void LatchCube::Render( _3DMath::Renderer& renderer, const _3DMath::AffineTransform& transform, GLenum renderMode, int selectedObjectHandle, int renderFlags )
{
Rubiks3x3x3::Render( renderer, transform, renderMode, selectedObjectHandle, renderFlags );
for( ConstraintList::iterator iter = constraintList.begin(); iter != constraintList.end(); iter++ )
{
Constraint& constraint = *iter;
_3DMath::Vector axis;
if( constraint.location.x == -2.0 )
axis.Set( -1.0, 0.0, 0.0 );
else if( constraint.location.x == 2.0 )
axis.Set( 1.0, 0.0, 0.0 );
else if( constraint.location.y == -2.0 )
axis.Set( 0.0, -1.0, 0.0 );
else if( constraint.location.y == 2.0 )
axis.Set( 0.0, 1.0, 0.0 );
else if( constraint.location.z == -2.0 )
axis.Set( 0.0, 0.0, -1.0 );
else if( constraint.location.z == 2.0 )
axis.Set( 0.0, 0.0, 1.0 );
else
continue;
_3DMath::Vector vector;
if( constraint.direction == Rotation::DIR_CCW )
vector.Cross( axis, constraint.location );
else if( constraint.direction == Rotation::DIR_CW )
vector.Cross( constraint.location, axis );
else
continue;
double length = 10.0 / 3.0;
vector.Scale( length / vector.Length() );
_3DMath::Vector position( constraint.location );
position.Scale( 10.0 / 3.0 );
position.AddScale( vector, -0.5 );
_3DMath::Vector color( 0.5, 0.5, 0.5 );
_3DMath::LinearTransform normalTransform;
transform.linearTransform.GetNormalTransform( normalTransform );
transform.Transform( position );
normalTransform.Transform( vector );
renderer.DrawVector( vector, position, color );
}
}
/*virtual*/ bool LatchCube::ApplyCutShapeWithRotation( CutShape* cutShape, const Rotation* rotation )
{
if( rotation && !CanRotate( rotation ) )
return false;
return Rubiks3x3x3::ApplyCutShapeWithRotation( cutShape, rotation );
}
/*virtual*/ void LatchCube::ApplyingTransformWithRotation( const _3DMath::AffineTransform& transform, const Rotation* rotation )
{
CutShape* cutShape = ( CutShape* )CutShape::Dereference( rotation->cutShapeHandle );
_3DMath::Vector center( cutShape->axisOfRotation.normal );
center.Scale( 0.5 );
_3DMath::Plane plane;
plane.SetCenterAndNormal( center, cutShape->axisOfRotation.normal );
for( ConstraintList::iterator iter = constraintList.begin(); iter != constraintList.end(); iter++ )
{
Constraint& constraint = *iter;
if( plane.GetSide( constraint.location ) == _3DMath::Plane::SIDE_FRONT )
{
transform.Transform( constraint.location );
constraint.location.x = round( constraint.location.x );
constraint.location.y = round( constraint.location.y );
constraint.location.z = round( constraint.location.z );
}
}
}
bool LatchCube::CanRotate( const Rotation* rotation ) const
{
CutShape* cutShape = ( CutShape* )CutShape::Dereference( rotation->cutShapeHandle );
if( !cutShape )
return false;
double eps = 1e-4;
int offset = 0;
double target = 0.0;
if( _3DMath::Vector( -1.0, 0.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 0;
target = -2.0;
}
else if( _3DMath::Vector( 1.0, 0.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 0;
target = 2.0;
}
else if( _3DMath::Vector( 0.0, -1.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 1;
target = -2.0;
}
else if( _3DMath::Vector( 0.0, 1.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 1;
target = 2.0;
}
else if( _3DMath::Vector( 0.0, 0.0, -1.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 2;
target = -2.0;
}
else if( _3DMath::Vector( 0.0, 0.0, 1.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 2;
target = 2.0;
}
else
return false;
int ccwCount = 0;
int cwCount = 0;
for( ConstraintList::const_iterator iter = constraintList.cbegin(); iter != constraintList.cend(); iter++ )
{
const Constraint& constraint = *iter;
double* component = ( double* )&constraint.location.x;
if( fabs( component[ offset ] - target ) < eps )
{
if( constraint.direction == Rotation::DIR_CCW )
ccwCount++;
else if( constraint.direction == Rotation::DIR_CW )
cwCount++;
}
}
if( ccwCount > 0 && cwCount > 0 )
return false;
return true;
}
// LatchCube.cpp<commit_msg>looks a bit better<commit_after>// LatchCube.cpp
#include "LatchCube.h"
wxIMPLEMENT_DYNAMIC_CLASS( LatchCube, Rubiks3x3x3 );
LatchCube::LatchCube( void )
{
}
/*virtual*/ LatchCube::~LatchCube( void )
{
}
/*virtual*/ void LatchCube::Reset( void )
{
Rubiks3x3x3::Reset();
constraintList.clear();
Constraint constraint;
// -X -> cw
constraint.direction = Rotation::DIR_CW;
constraint.location.Set( -2.0, 1.0, 0.0 );
constraintList.push_back( constraint );
constraint.location.Set( -2.0, -1.0, 0.0 );
constraintList.push_back( constraint );
// +X -> ccw
constraint.direction = Rotation::DIR_CCW;
constraint.location.Set( 2.0, 1.0, 0.0 );
constraintList.push_back( constraint );
constraint.location.Set( 2.0, -1.0, 0.0 );
constraintList.push_back( constraint );
// -Y -> ccw
constraint.direction = Rotation::DIR_CCW;
constraint.location.Set( 0.0, -2.0, -1.0 );
constraintList.push_back( constraint );
constraint.location.Set( 0.0, -2.0, 1.0 );
constraintList.push_back( constraint );
// +Y -> ccw
constraint.direction = Rotation::DIR_CCW;
constraint.location.Set( 0.0, 2.0, -1.0 );
constraintList.push_back( constraint );
constraint.location.Set( 0.0, 2.0, 1.0 );
constraintList.push_back( constraint );
// -Z -> cw
constraint.direction = Rotation::DIR_CW;
constraint.location.Set( -1.0, 0.0, -2.0 );
constraintList.push_back( constraint );
constraint.location.Set( 1.0, 0.0, -2.0 );
constraintList.push_back( constraint );
// +Z -> cw
constraint.direction = Rotation::DIR_CW;
constraint.location.Set( -1.0, 0.0, 2.0 );
constraintList.push_back( constraint );
constraint.location.Set( 1.0, 0.0, 2.0 );
constraintList.push_back( constraint );
}
/*virtual*/ void LatchCube::Render( _3DMath::Renderer& renderer, const _3DMath::AffineTransform& transform, GLenum renderMode, int selectedObjectHandle, int renderFlags )
{
Rubiks3x3x3::Render( renderer, transform, renderMode, selectedObjectHandle, renderFlags );
for( ConstraintList::iterator iter = constraintList.begin(); iter != constraintList.end(); iter++ )
{
Constraint& constraint = *iter;
_3DMath::Vector axis;
if( constraint.location.x == -2.0 )
axis.Set( -1.0, 0.0, 0.0 );
else if( constraint.location.x == 2.0 )
axis.Set( 1.0, 0.0, 0.0 );
else if( constraint.location.y == -2.0 )
axis.Set( 0.0, -1.0, 0.0 );
else if( constraint.location.y == 2.0 )
axis.Set( 0.0, 1.0, 0.0 );
else if( constraint.location.z == -2.0 )
axis.Set( 0.0, 0.0, -1.0 );
else if( constraint.location.z == 2.0 )
axis.Set( 0.0, 0.0, 1.0 );
else
continue;
_3DMath::Vector vector;
if( constraint.direction == Rotation::DIR_CCW )
vector.Cross( axis, constraint.location );
else if( constraint.direction == Rotation::DIR_CW )
vector.Cross( constraint.location, axis );
else
continue;
double length = 10.0 / 3.0;
vector.Scale( length / vector.Length() );
_3DMath::Vector position( constraint.location );
position.Scale( 10.0 / 3.0 );
position.AddScale( vector, -0.5 );
position.AddScale( axis, -10.0 / 6.5 );
_3DMath::Vector color( 0.5, 0.5, 0.5 );
_3DMath::LinearTransform normalTransform;
transform.linearTransform.GetNormalTransform( normalTransform );
transform.Transform( position );
normalTransform.Transform( vector );
renderer.DrawVector( vector, position, color, 1.0, 0.5 );
}
}
/*virtual*/ bool LatchCube::ApplyCutShapeWithRotation( CutShape* cutShape, const Rotation* rotation )
{
if( rotation && !CanRotate( rotation ) )
return false;
return Rubiks3x3x3::ApplyCutShapeWithRotation( cutShape, rotation );
}
/*virtual*/ void LatchCube::ApplyingTransformWithRotation( const _3DMath::AffineTransform& transform, const Rotation* rotation )
{
CutShape* cutShape = ( CutShape* )CutShape::Dereference( rotation->cutShapeHandle );
_3DMath::Vector center( cutShape->axisOfRotation.normal );
center.Scale( 0.5 );
_3DMath::Plane plane;
plane.SetCenterAndNormal( center, cutShape->axisOfRotation.normal );
for( ConstraintList::iterator iter = constraintList.begin(); iter != constraintList.end(); iter++ )
{
Constraint& constraint = *iter;
if( plane.GetSide( constraint.location ) == _3DMath::Plane::SIDE_FRONT )
{
transform.Transform( constraint.location );
constraint.location.x = round( constraint.location.x );
constraint.location.y = round( constraint.location.y );
constraint.location.z = round( constraint.location.z );
}
}
}
bool LatchCube::CanRotate( const Rotation* rotation ) const
{
CutShape* cutShape = ( CutShape* )CutShape::Dereference( rotation->cutShapeHandle );
if( !cutShape )
return false;
double eps = 1e-4;
int offset = 0;
double target = 0.0;
if( _3DMath::Vector( -1.0, 0.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 0;
target = -2.0;
}
else if( _3DMath::Vector( 1.0, 0.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 0;
target = 2.0;
}
else if( _3DMath::Vector( 0.0, -1.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 1;
target = -2.0;
}
else if( _3DMath::Vector( 0.0, 1.0, 0.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 1;
target = 2.0;
}
else if( _3DMath::Vector( 0.0, 0.0, -1.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 2;
target = -2.0;
}
else if( _3DMath::Vector( 0.0, 0.0, 1.0 ).IsEqualTo( cutShape->axisOfRotation.normal, eps ) )
{
offset = 2;
target = 2.0;
}
else
return false;
int ccwCount = 0;
int cwCount = 0;
for( ConstraintList::const_iterator iter = constraintList.cbegin(); iter != constraintList.cend(); iter++ )
{
const Constraint& constraint = *iter;
double* component = ( double* )&constraint.location.x;
if( fabs( component[ offset ] - target ) < eps )
{
if( constraint.direction == Rotation::DIR_CCW )
ccwCount++;
else if( constraint.direction == Rotation::DIR_CW )
cwCount++;
}
}
if( ccwCount > 0 && cwCount > 0 )
return false;
return true;
}
// LatchCube.cpp<|endoftext|>
|
<commit_before>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "filemenu.h"
#include <QFileInfo>
#include "utilities/settings.h"
#include "gui/messageforwarder.h"
#include "log.h"
#include "data/datasetpackage.h"
#include "mainwindow.h"
FileMenu::FileMenu(QObject *parent, DataSetPackage* package) : QObject(parent), _package(package)
{
_mainWindow = dynamic_cast<MainWindow*>(parent);
_recentFiles = new RecentFiles(parent);
_currentDataFile = new CurrentDataFile(parent);
_computer = new Computer(parent);
_OSF = new OSF(parent);
_dataLibrary = new DataLibrary(parent);
_actionButtons = new ActionButtons(this);
_resourceButtons = new ResourceButtons(this);
_resourceButtonsVisible = new ResourceButtonsVisible(this, _resourceButtons);
connect(_recentFiles, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_currentDataFile, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_computer, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_OSF, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_dataLibrary, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(&_watcher, &QFileSystemWatcher::fileChanged, this, &FileMenu::dataFileModifiedHandler);
connect(_actionButtons, &ActionButtons::buttonClicked, this, &FileMenu::actionButtonClicked );
connect(_actionButtons, &ActionButtons::selectedActionChanged, this, &FileMenu::setFileoperation );
connect(_resourceButtons, &ResourceButtons::selectedButtonChanged, this, &FileMenu::resourceButtonClicked );
connect(_currentDataFile, &CurrentDataFile::setCheckAutomaticSync, _mainWindow, &MainWindow::setCheckAutomaticSync );
_actionButtons->setEnabled(ActionButtons::Open, true);
_actionButtons->setEnabled(ActionButtons::Save, false);
_actionButtons->setEnabled(ActionButtons::SaveAs, false);
_actionButtons->setEnabled(ActionButtons::ExportResults, false);
_actionButtons->setEnabled(ActionButtons::ExportData, false);
_actionButtons->setEnabled(ActionButtons::SyncData, false);
_actionButtons->setEnabled(ActionButtons::Close, false);
_actionButtons->setEnabled(ActionButtons::Preferences, true);
_actionButtons->setEnabled(ActionButtons::About, true);
setResourceButtonsVisibleFor(_fileoperation);
}
void FileMenu::setFileoperation(ActionButtons::FileOperation fo)
{
if(_fileoperation == fo)
return;
_fileoperation = fo;
emit fileoperationChanged();
setResourceButtonsVisibleFor(fo);
}
void FileMenu::setResourceButtonsVisibleFor(ActionButtons::FileOperation fo)
{
_resourceButtons->setOnlyTheseButtonsVisible(_actionButtons->resourceButtonsForButton(fo));
}
void FileMenu::setSaveMode(FileEvent::FileMode mode)
{
_mode = mode;
_computer->setMode(_mode);
_OSF->setMode(_mode);
_OSF->setCurrentFileName(getDefaultOutFileName());
}
void FileMenu::setOnlineDataManager(OnlineDataManager *odm)
{
_odm = odm;
_OSF->setOnlineDataManager(odm);
}
FileEvent *FileMenu::open(const QString &path)
{
FileEvent *event = new FileEvent(this, FileEvent::FileOpen);
event->setPath(path);
dataSetIORequestHandler(event);
return event;
}
FileEvent *FileMenu::save()
{
FileEvent *event = nullptr;
if (_currentFileType != Utils::FileType::jasp || _currentFileReadOnly)
{
event = _computer->browseSave();
if (event->isCompleted())
return event;
}
else
{
event = new FileEvent(this, FileEvent::FileSave);
if (!event->setPath(_currentFilePath))
{
MessageForwarder::showWarning("File Types", event->getLastError());
event->setComplete(false, "Failed to open file from OSF");
return event;
}
}
dataSetIORequestHandler(event);
return event;
}
void FileMenu::sync()
{
QString path = _currentDataFile->getCurrentFilePath();
if (path.isEmpty())
{
if(!MessageForwarder::showYesNo("No associated data file",
"JASP has no associated data file to be synchronized with. "
"Do you want to search for such a data file on your computer?\nNB: You can also set this data file via menu File/Sync Data."))
return;
path = MessageForwarder::browseOpenFile("Find Data File", "", "Data File (*.csv *.txt *.sav *.ods *.dta *.por *.sas7bdat *.sas7bcat *.xpt");
}
_mainWindow->setCheckAutomaticSync(false);
setSyncRequest(path);
}
FileEvent *FileMenu::close()
{
FileEvent *event = new FileEvent(this, FileEvent::FileClose);
dataSetIORequestHandler(event);
return event;
}
void FileMenu::setCurrentDataFile(const QString &path)
{
QString currentPath = _currentDataFile->getCurrentFilePath();
if (!currentPath.isEmpty())
_watcher.removePath(currentPath);
bool setCurrentPath = true;
if (!path.isEmpty())
{
if (checkSyncFileExists(path))
{
int sync = Settings::value(Settings::DATA_AUTO_SYNCHRONIZATION).toInt();
if (sync > 0)
_watcher.addPath(path);
}
else
setCurrentPath = false;
}
if (setCurrentPath)
_currentDataFile->setCurrentFilePath(path);
}
void FileMenu::setDataFileWatcher(bool watch)
{
QString path = _currentDataFile->getCurrentFilePath();
if (!path.isEmpty())
{
if (watch && !_currentDataFile->isOnlineFile(path))
_watcher.addPath(path);
else
_watcher.removePath(path);
}
}
QString FileMenu::getDefaultOutFileName()
{
QString path = getCurrentFilePath(),
DefaultOutFileName = "";
if (path != "")
{
QString name = QFileInfo(path).completeBaseName(),
ext = QFileInfo(path).suffix();
switch (_mode)
{
case FileEvent::FileSave: ext = "jasp"; break;
case FileEvent::FileExportResults: ext = "html"; break;
case FileEvent::FileExportData:
case FileEvent::FileGenerateData: ext = "csv"; break;
default: break;
}
DefaultOutFileName = name + "." + ext;
}
return DefaultOutFileName;
}
void FileMenu::dataSetIOCompleted(FileEvent *event)
{
if (event->operation() == FileEvent::FileSave || event->operation() == FileEvent::FileOpen)
{
if (event->isSuccessful())
{
// don't add examples to the recent list
if (!event->isReadOnly())
{
_recentFiles->pushRecentFilePath(event->path());
_computer->addRecentFolder(event->path());
}
if(event->operation() == FileEvent::FileSave || (event->operation() == FileEvent::FileOpen && !event->isReadOnly()))
{
QString datafile = event->dataFilePath();
if (datafile.isEmpty())
datafile = QString::fromStdString(_package->dataFilePath());
setCurrentDataFile(datafile);
}
// all this stuff is a hack
QFileInfo info(event->path());
_computer->setFileName(info.completeBaseName());
_currentFilePath = event->path();
_currentFileType = event->type();
_currentFileReadOnly = event->isReadOnly();
_OSF->setProcessing(false);
}
}
else if (event->operation() == FileEvent::FileSyncData)
{
if (event->isSuccessful()) setCurrentDataFile(event->dataFilePath());
else
Log::log() << "Sync failed: " << event->getLastError().toStdString() << std::endl;
}
else if (event->operation() == FileEvent::FileClose)
{
_computer->clearFileName();
_currentFilePath = "";
_currentFileType = Utils::FileType::unknown;
_currentFileReadOnly = false;
clearSyncData();
}
_resourceButtons->setButtonEnabled(ResourceButtons::CurrentFile, !_currentDataFile->getCurrentFilePath().isEmpty());
if (event->isSuccessful())
{
switch(event->operation())
{
case FileEvent::FileOpen:
case FileEvent::FileSave:
_actionButtons->setEnabled(ActionButtons::Save, event->type() == Utils::FileType::jasp || event->operation() == FileEvent::FileSave);
_actionButtons->setEnabled(ActionButtons::SaveAs, true);
_actionButtons->setEnabled(ActionButtons::ExportResults, true);
_actionButtons->setEnabled(ActionButtons::ExportData, true);
_actionButtons->setEnabled(ActionButtons::SyncData, true);
_actionButtons->setEnabled(ActionButtons::Close, true);
break;
case FileEvent::FileClose:
_actionButtons->setEnabled(ActionButtons::Save, false);
_actionButtons->setEnabled(ActionButtons::SaveAs, false);
_actionButtons->setEnabled(ActionButtons::ExportResults, false);
_actionButtons->setEnabled(ActionButtons::ExportData, false);
_actionButtons->setEnabled(ActionButtons::SyncData, false);
_actionButtons->setEnabled(ActionButtons::Close, false);
_computer->setMode(FileEvent::FileOpen);
break;
default:
//Do nothing?
break;
}
}
}
void FileMenu::syncDataFile(const QString& path)
{
int autoSync = Settings::value(Settings::DATA_AUTO_SYNCHRONIZATION).toInt();
if (autoSync > 0)
setSyncRequest(path);
}
void FileMenu::dataFileModifiedHandler(QString path)
{
_mainWindow->setCheckAutomaticSync(false);
syncDataFile(path);
}
void FileMenu::dataSetIORequestHandler(FileEvent *event)
{
connect(event, &FileEvent::completed, this, &FileMenu::dataSetIOCompleted );
emit dataSetIORequest(event);
}
void FileMenu::analysisAdded(Analysis *analysis)
{
_actionButtons->setEnabled(ActionButtons::Close, true);
_actionButtons->setEnabled(ActionButtons::SaveAs, true);
_actionButtons->setEnabled(ActionButtons::ExportResults, true);
}
void FileMenu::setSyncFile(FileEvent *event)
{
if (event->isSuccessful())
setCurrentDataFile(event->path());
}
void FileMenu::dataColumnAdded(QString columnName)
{
if(_currentDataFile->getCurrentFilePath() != "" && checkSyncFileExists(_currentDataFile->getCurrentFilePath()))
{
//Ok a column was added to the data but we already have a sync file so we should re-generate the data!
FileEvent * event = new FileEvent(this, FileEvent::FileGenerateData);
connect(event, &FileEvent::completed, this, &FileMenu::setSyncFile);
event->setPath(_currentDataFile->getCurrentFilePath());
dataSetIORequestHandler(event);
}
}
void FileMenu::analysesExportResults()
{
_computer->analysesExportResults();
}
void FileMenu::actionButtonClicked(const ActionButtons::FileOperation action)
{
switch (action)
{
case ActionButtons::FileOperation::Open: setSaveMode(FileEvent::FileOpen); break;
case ActionButtons::FileOperation::SaveAs: setSaveMode(FileEvent::FileSave); break;
case ActionButtons::FileOperation::ExportResults: setSaveMode(FileEvent::FileExportResults); break;
case ActionButtons::FileOperation::ExportData: setSaveMode(FileEvent::FileExportData); break;
case ActionButtons::FileOperation::SyncData: setSaveMode(FileEvent::FileSyncData); break;
case ActionButtons::FileOperation::Save:
if (getCurrentFileType() == Utils::FileType::jasp && ! isCurrentFileReadOnly())
save();
else
setSaveMode(FileEvent::FileSave);
break;
case ActionButtons::FileOperation::Close:
close();
_actionButtons->setSelectedAction(ActionButtons::FileOperation::Open);
break;
case ActionButtons::FileOperation::About:
setVisible(false);
showAboutRequest();
break;
default:
break;
}
}
void FileMenu::resourceButtonClicked(const int buttonType)
{
if (buttonType == ResourceButtons::OSF)
_OSF->attemptToConnect();
}
void FileMenu::showAboutRequest()
{
emit showAbout();
}
void FileMenu::setSyncRequest(const QString& path)
{
if (path.isEmpty())
return;
if (checkSyncFileExists(path))
{
FileEvent *event = new FileEvent(this, FileEvent::FileSyncData);
event->setPath(path);
dataSetIORequestHandler(event);
}
}
bool FileMenu::checkSyncFileExists(const QString &path)
{
bool exists = path.startsWith("http") ? true : (QFileInfo::exists(path) && Utils::getFileSize(path.toStdString()) > 0);
if (!exists)
{
int attempts = 1;
while (!exists && attempts < 20)
{
Utils::sleep(100);
attempts++;
exists = QFileInfo::exists(path) && Utils::getFileSize(path.toStdString()) > 0;
}
}
if (!exists)
{
Log::log() << "Sync file does not exist: " << path.toStdString() << std::endl;
clearSyncData();
}
return exists;
}
void FileMenu::clearSyncData()
{
setDataFileWatcher(false); // must be done before setting the current to empty.
_currentDataFile->setCurrentFilePath(QString());
}
bool FileMenu::clearOSFFromRecentList(QString path)
{
return OnlineDataManager::determineProvider(path) != OnlineDataManager::OSF;
}
void FileMenu::setVisible(bool visible)
{
if (_visible == visible)
return;
_visible = visible;
emit visibleChanged(_visible);
if(!_visible)
{
_resourceButtons->setSelectedButton(ResourceButtons::None);
_actionButtons->setSelectedAction(ActionButtons::None);
}
}
void FileMenu::showFileOpenMenu()
{
setVisible(true);
_actionButtons->setSelectedAction(ActionButtons::Open);
}
void FileMenu::showPreferences()
{
setVisible(true);
_actionButtons->setSelectedAction(ActionButtons::Preferences);
}
<commit_msg>Save OSF sometimes fails<commit_after>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "filemenu.h"
#include <QFileInfo>
#include "utilities/settings.h"
#include "gui/messageforwarder.h"
#include "log.h"
#include "data/datasetpackage.h"
#include "mainwindow.h"
FileMenu::FileMenu(QObject *parent, DataSetPackage* package) : QObject(parent), _package(package)
{
_mainWindow = dynamic_cast<MainWindow*>(parent);
_recentFiles = new RecentFiles(parent);
_currentDataFile = new CurrentDataFile(parent);
_computer = new Computer(parent);
_OSF = new OSF(parent);
_dataLibrary = new DataLibrary(parent);
_actionButtons = new ActionButtons(this);
_resourceButtons = new ResourceButtons(this);
_resourceButtonsVisible = new ResourceButtonsVisible(this, _resourceButtons);
connect(_recentFiles, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_currentDataFile, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_computer, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_OSF, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(_dataLibrary, &FileMenuObject::dataSetIORequest, this, &FileMenu::dataSetIORequestHandler);
connect(&_watcher, &QFileSystemWatcher::fileChanged, this, &FileMenu::dataFileModifiedHandler);
connect(_actionButtons, &ActionButtons::buttonClicked, this, &FileMenu::actionButtonClicked );
connect(_actionButtons, &ActionButtons::selectedActionChanged, this, &FileMenu::setFileoperation );
connect(_resourceButtons, &ResourceButtons::selectedButtonChanged, this, &FileMenu::resourceButtonClicked );
connect(_currentDataFile, &CurrentDataFile::setCheckAutomaticSync, _mainWindow, &MainWindow::setCheckAutomaticSync );
_actionButtons->setEnabled(ActionButtons::Open, true);
_actionButtons->setEnabled(ActionButtons::Save, false);
_actionButtons->setEnabled(ActionButtons::SaveAs, false);
_actionButtons->setEnabled(ActionButtons::ExportResults, false);
_actionButtons->setEnabled(ActionButtons::ExportData, false);
_actionButtons->setEnabled(ActionButtons::SyncData, false);
_actionButtons->setEnabled(ActionButtons::Close, false);
_actionButtons->setEnabled(ActionButtons::Preferences, true);
_actionButtons->setEnabled(ActionButtons::About, true);
setResourceButtonsVisibleFor(_fileoperation);
}
void FileMenu::setFileoperation(ActionButtons::FileOperation fo)
{
if(_fileoperation == fo)
return;
_fileoperation = fo;
emit fileoperationChanged();
setResourceButtonsVisibleFor(fo);
}
void FileMenu::setResourceButtonsVisibleFor(ActionButtons::FileOperation fo)
{
_resourceButtons->setOnlyTheseButtonsVisible(_actionButtons->resourceButtonsForButton(fo));
}
void FileMenu::setSaveMode(FileEvent::FileMode mode)
{
_mode = mode;
_computer->setMode(_mode);
_OSF->setMode(_mode);
_OSF->setCurrentFileName(getDefaultOutFileName());
}
void FileMenu::setOnlineDataManager(OnlineDataManager *odm)
{
_odm = odm;
_OSF->setOnlineDataManager(odm);
}
FileEvent *FileMenu::open(const QString &path)
{
FileEvent *event = new FileEvent(this, FileEvent::FileOpen);
event->setPath(path);
dataSetIORequestHandler(event);
return event;
}
FileEvent *FileMenu::save()
{
FileEvent *event = nullptr;
if (_currentFileType != Utils::FileType::jasp || _currentFileReadOnly)
{
event = _computer->browseSave();
if (event->isCompleted())
return event;
}
else
{
event = new FileEvent(this, FileEvent::FileSave);
if (!event->setPath(_currentFilePath))
{
MessageForwarder::showWarning("File Types", event->getLastError());
event->setComplete(false, "Failed to open file from OSF");
return event;
}
}
dataSetIORequestHandler(event);
return event;
}
void FileMenu::sync()
{
QString path = _currentDataFile->getCurrentFilePath();
if (path.isEmpty())
{
if(!MessageForwarder::showYesNo("No associated data file",
"JASP has no associated data file to be synchronized with. "
"Do you want to search for such a data file on your computer?\nNB: You can also set this data file via menu File/Sync Data."))
return;
path = MessageForwarder::browseOpenFile("Find Data File", "", "Data File (*.csv *.txt *.sav *.ods *.dta *.por *.sas7bdat *.sas7bcat *.xpt");
}
_mainWindow->setCheckAutomaticSync(false);
setSyncRequest(path);
}
FileEvent *FileMenu::close()
{
FileEvent *event = new FileEvent(this, FileEvent::FileClose);
dataSetIORequestHandler(event);
return event;
}
void FileMenu::setCurrentDataFile(const QString &path)
{
QString currentPath = _currentDataFile->getCurrentFilePath();
if (!currentPath.isEmpty())
_watcher.removePath(currentPath);
bool setCurrentPath = true;
if (!path.isEmpty())
{
if (checkSyncFileExists(path))
{
int sync = Settings::value(Settings::DATA_AUTO_SYNCHRONIZATION).toInt();
if (sync > 0)
_watcher.addPath(path);
}
else
setCurrentPath = false;
}
if (setCurrentPath)
_currentDataFile->setCurrentFilePath(path);
}
void FileMenu::setDataFileWatcher(bool watch)
{
QString path = _currentDataFile->getCurrentFilePath();
if (!path.isEmpty())
{
if (watch && !_currentDataFile->isOnlineFile(path))
_watcher.addPath(path);
else
_watcher.removePath(path);
}
}
QString FileMenu::getDefaultOutFileName()
{
QString path = getCurrentFilePath(),
DefaultOutFileName = "";
if (path != "")
{
QString name = QFileInfo(path).completeBaseName(),
ext = QFileInfo(path).suffix();
switch (_mode)
{
case FileEvent::FileSave: ext = "jasp"; break;
case FileEvent::FileExportResults: ext = "html"; break;
case FileEvent::FileExportData:
case FileEvent::FileGenerateData: ext = "csv"; break;
default: break;
}
DefaultOutFileName = name + "." + ext;
}
return DefaultOutFileName;
}
void FileMenu::dataSetIOCompleted(FileEvent *event)
{
if (event->operation() == FileEvent::FileSave || event->operation() == FileEvent::FileOpen)
{
if (event->isSuccessful())
{
// don't add examples to the recent list
if (!event->isReadOnly())
{
_recentFiles->pushRecentFilePath(event->path());
_computer->addRecentFolder(event->path());
}
if(event->operation() == FileEvent::FileSave || (event->operation() == FileEvent::FileOpen && !event->isReadOnly()))
{
QString datafile = event->dataFilePath();
if (datafile.isEmpty())
datafile = QString::fromStdString(_package->dataFilePath());
setCurrentDataFile(datafile);
}
// all this stuff is a hack
QFileInfo info(event->path());
_computer->setFileName(info.completeBaseName());
_currentFilePath = event->path();
_currentFileType = event->type();
_currentFileReadOnly = event->isReadOnly();
_OSF->setProcessing(false);
}
}
else if (event->operation() == FileEvent::FileSyncData)
{
if (event->isSuccessful()) setCurrentDataFile(event->dataFilePath());
else
Log::log() << "Sync failed: " << event->getLastError().toStdString() << std::endl;
}
else if (event->operation() == FileEvent::FileClose)
{
_computer->clearFileName();
_currentFilePath = "";
_currentFileType = Utils::FileType::unknown;
_currentFileReadOnly = false;
clearSyncData();
}
_resourceButtons->setButtonEnabled(ResourceButtons::CurrentFile, !_currentDataFile->getCurrentFilePath().isEmpty());
if (event->isSuccessful())
{
switch(event->operation())
{
case FileEvent::FileOpen:
case FileEvent::FileSave:
_actionButtons->setEnabled(ActionButtons::Save, event->type() == Utils::FileType::jasp || event->operation() == FileEvent::FileSave);
_actionButtons->setEnabled(ActionButtons::SaveAs, true);
_actionButtons->setEnabled(ActionButtons::ExportResults, true);
_actionButtons->setEnabled(ActionButtons::ExportData, true);
_actionButtons->setEnabled(ActionButtons::SyncData, true);
_actionButtons->setEnabled(ActionButtons::Close, true);
break;
case FileEvent::FileClose:
_actionButtons->setEnabled(ActionButtons::Save, false);
_actionButtons->setEnabled(ActionButtons::SaveAs, false);
_actionButtons->setEnabled(ActionButtons::ExportResults, false);
_actionButtons->setEnabled(ActionButtons::ExportData, false);
_actionButtons->setEnabled(ActionButtons::SyncData, false);
_actionButtons->setEnabled(ActionButtons::Close, false);
_computer->setMode(FileEvent::FileOpen);
break;
default:
//Do nothing?
break;
}
}
}
void FileMenu::syncDataFile(const QString& path)
{
int autoSync = Settings::value(Settings::DATA_AUTO_SYNCHRONIZATION).toInt();
if (autoSync > 0)
setSyncRequest(path);
}
void FileMenu::dataFileModifiedHandler(QString path)
{
_mainWindow->setCheckAutomaticSync(false);
syncDataFile(path);
}
void FileMenu::dataSetIORequestHandler(FileEvent *event)
{
connect(event, &FileEvent::completed, this, &FileMenu::dataSetIOCompleted );
emit dataSetIORequest(event);
}
void FileMenu::analysisAdded(Analysis *analysis)
{
_actionButtons->setEnabled(ActionButtons::Close, true);
_actionButtons->setEnabled(ActionButtons::SaveAs, true);
_actionButtons->setEnabled(ActionButtons::ExportResults, true);
}
void FileMenu::setSyncFile(FileEvent *event)
{
if (event->isSuccessful())
setCurrentDataFile(event->path());
}
void FileMenu::dataColumnAdded(QString columnName)
{
if(_currentDataFile->getCurrentFilePath() != "" && checkSyncFileExists(_currentDataFile->getCurrentFilePath()))
{
//Ok a column was added to the data but we already have a sync file so we should re-generate the data!
FileEvent * event = new FileEvent(this, FileEvent::FileGenerateData);
connect(event, &FileEvent::completed, this, &FileMenu::setSyncFile);
event->setPath(_currentDataFile->getCurrentFilePath());
dataSetIORequestHandler(event);
}
}
void FileMenu::analysesExportResults()
{
_computer->analysesExportResults();
}
void FileMenu::actionButtonClicked(const ActionButtons::FileOperation action)
{
switch (action)
{
case ActionButtons::FileOperation::Open: setSaveMode(FileEvent::FileOpen); break;
case ActionButtons::FileOperation::SaveAs: setSaveMode(FileEvent::FileSave); break;
case ActionButtons::FileOperation::ExportResults: setSaveMode(FileEvent::FileExportResults); break;
case ActionButtons::FileOperation::ExportData: setSaveMode(FileEvent::FileExportData); break;
case ActionButtons::FileOperation::SyncData: setSaveMode(FileEvent::FileSyncData); break;
case ActionButtons::FileOperation::Save:
if (getCurrentFileType() == Utils::FileType::jasp && ! isCurrentFileReadOnly())
save();
else
setSaveMode(FileEvent::FileSave);
break;
case ActionButtons::FileOperation::Close:
close();
setSaveMode(FileEvent::FileOpen);
_actionButtons->setSelectedAction(ActionButtons::FileOperation::Open);
break;
case ActionButtons::FileOperation::About:
setVisible(false);
showAboutRequest();
break;
default:
break;
}
}
void FileMenu::resourceButtonClicked(const int buttonType)
{
if (buttonType == ResourceButtons::OSF)
_OSF->attemptToConnect();
}
void FileMenu::showAboutRequest()
{
emit showAbout();
}
void FileMenu::setSyncRequest(const QString& path)
{
if (path.isEmpty())
return;
if (checkSyncFileExists(path))
{
FileEvent *event = new FileEvent(this, FileEvent::FileSyncData);
event->setPath(path);
dataSetIORequestHandler(event);
}
}
bool FileMenu::checkSyncFileExists(const QString &path)
{
bool exists = path.startsWith("http") ? true : (QFileInfo::exists(path) && Utils::getFileSize(path.toStdString()) > 0);
if (!exists)
{
int attempts = 1;
while (!exists && attempts < 20)
{
Utils::sleep(100);
attempts++;
exists = QFileInfo::exists(path) && Utils::getFileSize(path.toStdString()) > 0;
}
}
if (!exists)
{
Log::log() << "Sync file does not exist: " << path.toStdString() << std::endl;
clearSyncData();
}
return exists;
}
void FileMenu::clearSyncData()
{
setDataFileWatcher(false); // must be done before setting the current to empty.
_currentDataFile->setCurrentFilePath(QString());
}
bool FileMenu::clearOSFFromRecentList(QString path)
{
return OnlineDataManager::determineProvider(path) != OnlineDataManager::OSF;
}
void FileMenu::setVisible(bool visible)
{
if (_visible == visible)
return;
_visible = visible;
emit visibleChanged(_visible);
if(!_visible)
{
_resourceButtons->setSelectedButton(ResourceButtons::None);
_actionButtons->setSelectedAction(ActionButtons::None);
}
}
void FileMenu::showFileOpenMenu()
{
setVisible(true);
_actionButtons->setSelectedAction(ActionButtons::Open);
}
void FileMenu::showPreferences()
{
setVisible(true);
_actionButtons->setSelectedAction(ActionButtons::Preferences);
}
<|endoftext|>
|
<commit_before>#ifndef __LUAMANAGER_HPP__
#define __LUAMANAGER_HPP__
#include <string>
#include "server/modules/common/AbstractManager.hpp"
#include "Lua.hpp"
class LuaManager : public zhttpd::mod::StatefullManager<Lua>
{
private:
std::string _name;
public:
LuaManager() :
zhttpd::mod::StatefullManager<Lua>("mod_lua", zhttpd::api::category::PROCESSING)
{
}
bool isRequired(zhttpd::api::IRequest const& request) const
{
std::string ext;
std::string::const_reverse_iterator it = request.getFilePath().rbegin();
std::string::const_reverse_iterator itEnd = request.getFilePath().rend();
for (; it != itEnd; ++it)
if (*it == '.')
{
if (ext == "lua")
return true;
return false;
}
else
ext.insert(ext.begin(), *it);
return false;
}
};
#endif
<commit_msg>improve perf of isRequired<commit_after>#ifndef __LUAMANAGER_HPP__
#define __LUAMANAGER_HPP__
#include <string>
#include "server/modules/common/AbstractManager.hpp"
#include "Lua.hpp"
class LuaManager : public zhttpd::mod::StatefullManager<Lua>
{
private:
std::string _name;
public:
LuaManager() :
zhttpd::mod::StatefullManager<Lua>("mod_lua", zhttpd::api::category::PROCESSING)
{
}
bool isRequired(zhttpd::api::IRequest const& request) const
{
char const* f = request.getFilePath().c_str();
zhttpd::api::size_t s = request.getFilePath().size();
if (s < 4 || f[s - 1] != 'a' || f[s - 2] != 'u' || f[s -3] != 'l' || f[s - 4] != '.')
return false;
return true;
}
};
#endif
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "limitboxcontroller.hxx"
#include <com/sun/star/frame/XDispatchProvider.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <vcl/svapp.hxx>
#include <vcl/window.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <osl/mutex.hxx>
#include <rtl/ustring.hxx>
#include "dbu_reghelper.hxx"
#include "dbu_qry.hrc"
#include "moduledbu.hxx"
#define ALL_STRING ModuleRes(STR_QUERY_LIMIT_ALL).toString()
#define ALL_INT -1
using namespace ::com::sun::star;
////////////////
///LimitBox
////////////////
namespace dbaui
{
namespace global{
/// Default values
sal_Int64 aDefLimitAry[] =
{
5,
10,
20,
50
};
}
LimitBox::LimitBox( Window* pParent, LimitBoxController* pCtrl )
: NumericBox( pParent, WinBits( WB_DROPDOWN | WB_VSCROLL) )
, m_pControl( pCtrl )
{
SetShowTrailingZeros( sal_False );
SetDecimalDigits( 0 );
SetMin( -1 );
SetMax( 9999 );
LoadDefaultLimits();
Size aSize(
CalcMinimumSize().Width() + 20 ,
CalcWindowSizePixel(GetEntryCount() + 1) );
SetSizePixel(aSize);
}
LimitBox::~LimitBox()
{
}
void LimitBox::Reformat()
{
if( GetText() == ALL_STRING )
{
SetValue( -1 );
}
///Reformat only when text is not All
else
{
///Not allow user to type -1
if( GetText() == "-1" )
{
Undo();
}
else
NumericBox::Reformat();
}
}
void LimitBox::ReformatAll()
{
///First entry is All, which do not need numeric reformat
if ( GetEntryCount() > 0 )
{
RemoveEntry( 0 );
NumericBox::ReformatAll();
InsertEntry( ALL_STRING, 0);
}
else
{
NumericBox::ReformatAll();
}
}
OUString LimitBox::CreateFieldText( sal_Int64 nValue ) const
{
if( nValue == ALL_INT )
return ALL_STRING;
else
return NumericBox::CreateFieldText( nValue );
}
long LimitBox::Notify( NotifyEvent& rNEvt )
{
long nReturn = NumericBox::Notify( rNEvt );
switch ( rNEvt.GetType() )
{
case EVENT_LOSEFOCUS:
{
uno::Sequence< beans::PropertyValue > aArgs( 1 );
aArgs[0].Name = OUString( "DBLimit.Value" );
aArgs[0].Value = uno::makeAny( GetValue() );
m_pControl->dispatchCommand( aArgs );
break;
}
case EVENT_KEYINPUT:
{
const sal_uInt16 nCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();
if( nCode == KEY_RETURN )
{
GrabFocusToDocument();
}
break;
}
}
return nReturn;
}
///Initialize entries
void LimitBox::LoadDefaultLimits()
{
SetValue( ALL_INT );
InsertEntry( ALL_STRING );
const unsigned nSize =
sizeof(global::aDefLimitAry)/sizeof(global::aDefLimitAry[0]);
for( unsigned nIndex = 0; nIndex< nSize; ++nIndex)
{
InsertValue( global::aDefLimitAry[nIndex] );
}
}
/////////////////////////
///LimitBoxController
/////////////////////////
LimitBoxController::LimitBoxController(
const uno::Reference< lang::XMultiServiceFactory >& rServiceManager ) :
svt::ToolboxController( rServiceManager,
uno::Reference< frame::XFrame >(),
OUString( ".uno:DBLimit" ) ),
m_pLimitBox( NULL )
{
}
LimitBoxController::~LimitBoxController()
{
}
/// XInterface
uno::Any SAL_CALL LimitBoxController::queryInterface( const uno::Type& aType )
throw (uno::RuntimeException)
{
uno::Any a = ToolboxController::queryInterface( aType );
if ( a.hasValue() )
return a;
return ::cppu::queryInterface( aType, static_cast< lang::XServiceInfo* >( this ));
}
void SAL_CALL LimitBoxController::acquire() throw ()
{
ToolboxController::acquire();
}
void SAL_CALL LimitBoxController::release() throw ()
{
ToolboxController::release();
}
/// XServiceInfo
IMPLEMENT_SERVICE_INFO1_STATIC(LimitBoxController,"org.libreoffice.comp.dbu.LimitBoxController","com.sun.star.frame.ToolboxController")
/// XComponent
void SAL_CALL LimitBoxController::dispose()
throw (uno::RuntimeException)
{
svt::ToolboxController::dispose();
SolarMutexGuard aSolarMutexGuard;
delete m_pLimitBox;
m_pLimitBox = 0;
}
/// XStatusListener
void SAL_CALL LimitBoxController::statusChanged(
const frame::FeatureStateEvent& rEvent )
throw ( uno::RuntimeException )
{
if ( m_pLimitBox )
{
SolarMutexGuard aSolarMutexGuard;
if ( rEvent.FeatureURL.Path == "DBLimit" )
{
if ( rEvent.IsEnabled )
{
m_pLimitBox->Enable();
sal_Int64 nLimit;
if ( (rEvent.State >>= nLimit) )
{
m_pLimitBox->SetValue( nLimit );
}
}
else
m_pLimitBox->Disable();
}
}
}
/// XToolbarController
void SAL_CALL LimitBoxController::execute( sal_Int16 /*KeyModifier*/ )
throw (uno::RuntimeException)
{
}
void SAL_CALL LimitBoxController::click()
throw (uno::RuntimeException)
{
}
void SAL_CALL LimitBoxController::doubleClick()
throw (uno::RuntimeException)
{
}
uno::Reference< awt::XWindow > SAL_CALL LimitBoxController::createPopupWindow()
throw (uno::RuntimeException)
{
return uno::Reference< awt::XWindow >();
}
uno::Reference< awt::XWindow > SAL_CALL LimitBoxController::createItemWindow(
const uno::Reference< awt::XWindow >& Parent )
throw (uno::RuntimeException)
{
uno::Reference< awt::XWindow > xItemWindow;
uno::Reference< awt::XWindow > xParent( Parent );
Window* pParent = VCLUnoHelper::GetWindow( xParent );
if ( pParent )
{
SolarMutexGuard aSolarMutexGuard;
m_pLimitBox = new LimitBox(pParent, this);
xItemWindow = VCLUnoHelper::GetInterface( m_pLimitBox );
}
return xItemWindow;
}
void LimitBoxController::dispatchCommand(
const uno::Sequence< beans::PropertyValue >& rArgs )
{
uno::Reference< frame::XDispatchProvider > xDispatchProvider( m_xFrame, uno::UNO_QUERY );
if ( xDispatchProvider.is() )
{
util::URL aURL;
uno::Reference< frame::XDispatch > xDispatch;
uno::Reference< util::XURLTransformer > xURLTransformer = getURLTransformer();
aURL.Complete = OUString( ".uno:DBLimit" );
xURLTransformer->parseStrict( aURL );
xDispatch = xDispatchProvider->queryDispatch( aURL, OUString(), 0 );
if ( xDispatch.is() )
xDispatch->dispatch( aURL, rArgs );
}
}
} ///dbaui namespace
extern "C" void SAL_CALL createRegistryInfo_LimitBoxController()
{
static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::LimitBoxController > aAutoRegistration;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix WaE<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "limitboxcontroller.hxx"
#include <com/sun/star/frame/XDispatchProvider.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <vcl/svapp.hxx>
#include <vcl/window.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <osl/mutex.hxx>
#include <rtl/ustring.hxx>
#include "dbu_reghelper.hxx"
#include "dbu_qry.hrc"
#include "moduledbu.hxx"
#define ALL_STRING ModuleRes(STR_QUERY_LIMIT_ALL).toString()
#define ALL_INT -1
using namespace ::com::sun::star;
////////////////
///LimitBox
////////////////
namespace dbaui
{
namespace global{
/// Default values
sal_Int64 aDefLimitAry[] =
{
5,
10,
20,
50
};
}
LimitBox::LimitBox( Window* pParent, LimitBoxController* pCtrl )
: NumericBox( pParent, WinBits( WB_DROPDOWN | WB_VSCROLL) )
, m_pControl( pCtrl )
{
SetShowTrailingZeros( sal_False );
SetDecimalDigits( 0 );
SetMin( -1 );
SetMax( 9999 );
LoadDefaultLimits();
Size aSize(
CalcMinimumSize().Width() + 20 ,
CalcWindowSizePixel(GetEntryCount() + 1) );
SetSizePixel(aSize);
}
LimitBox::~LimitBox()
{
}
void LimitBox::Reformat()
{
if( GetText() == ALL_STRING )
{
SetValue( -1 );
}
///Reformat only when text is not All
else
{
///Not allow user to type -1
if( GetText() == "-1" )
{
Undo();
}
else
NumericBox::Reformat();
}
}
void LimitBox::ReformatAll()
{
///First entry is All, which do not need numeric reformat
if ( GetEntryCount() > 0 )
{
RemoveEntry( 0 );
NumericBox::ReformatAll();
InsertEntry( ALL_STRING, 0);
}
else
{
NumericBox::ReformatAll();
}
}
OUString LimitBox::CreateFieldText( sal_Int64 nValue ) const
{
if( nValue == ALL_INT )
return ALL_STRING;
else
return NumericBox::CreateFieldText( nValue );
}
long LimitBox::Notify( NotifyEvent& rNEvt )
{
long nReturn = NumericBox::Notify( rNEvt );
switch ( rNEvt.GetType() )
{
case EVENT_LOSEFOCUS:
{
uno::Sequence< beans::PropertyValue > aArgs( 1 );
aArgs[0].Name = OUString( "DBLimit.Value" );
aArgs[0].Value = uno::makeAny( GetValue() );
m_pControl->dispatchCommand( aArgs );
break;
}
case EVENT_KEYINPUT:
{
const sal_uInt16 nCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();
if( nCode == KEY_RETURN )
{
GrabFocusToDocument();
}
break;
}
}
return nReturn;
}
///Initialize entries
void LimitBox::LoadDefaultLimits()
{
SetValue( ALL_INT );
InsertEntry( ALL_STRING );
const unsigned nSize =
sizeof(global::aDefLimitAry)/sizeof(global::aDefLimitAry[0]);
for( unsigned nIndex = 0; nIndex< nSize; ++nIndex)
{
InsertValue( global::aDefLimitAry[nIndex] );
}
}
/////////////////////////
///LimitBoxController
/////////////////////////
LimitBoxController::LimitBoxController(
const uno::Reference< lang::XMultiServiceFactory >& rServiceManager ) :
svt::ToolboxController( rServiceManager,
uno::Reference< frame::XFrame >(),
OUString( ".uno:DBLimit" ) ),
m_pLimitBox( NULL )
{
}
LimitBoxController::~LimitBoxController()
{
}
/// XInterface
uno::Any SAL_CALL LimitBoxController::queryInterface( const uno::Type& aType )
throw (uno::RuntimeException)
{
uno::Any a = ToolboxController::queryInterface( aType );
if ( a.hasValue() )
return a;
return ::cppu::queryInterface( aType, static_cast< lang::XServiceInfo* >( this ));
}
void SAL_CALL LimitBoxController::acquire() throw ()
{
ToolboxController::acquire();
}
void SAL_CALL LimitBoxController::release() throw ()
{
ToolboxController::release();
}
/// XServiceInfo
IMPLEMENT_SERVICE_INFO1_STATIC(LimitBoxController,"org.libreoffice.comp.dbu.LimitBoxController","com.sun.star.frame.ToolboxController")
/// XComponent
void SAL_CALL LimitBoxController::dispose()
throw (uno::RuntimeException)
{
svt::ToolboxController::dispose();
SolarMutexGuard aSolarMutexGuard;
delete m_pLimitBox;
m_pLimitBox = 0;
}
/// XStatusListener
void SAL_CALL LimitBoxController::statusChanged(
const frame::FeatureStateEvent& rEvent )
throw ( uno::RuntimeException )
{
if ( m_pLimitBox )
{
SolarMutexGuard aSolarMutexGuard;
if ( rEvent.FeatureURL.Path == "DBLimit" )
{
if ( rEvent.IsEnabled )
{
m_pLimitBox->Enable();
sal_Int64 nLimit = 0;
if ( (rEvent.State >>= nLimit) )
{
m_pLimitBox->SetValue( nLimit );
}
}
else
m_pLimitBox->Disable();
}
}
}
/// XToolbarController
void SAL_CALL LimitBoxController::execute( sal_Int16 /*KeyModifier*/ )
throw (uno::RuntimeException)
{
}
void SAL_CALL LimitBoxController::click()
throw (uno::RuntimeException)
{
}
void SAL_CALL LimitBoxController::doubleClick()
throw (uno::RuntimeException)
{
}
uno::Reference< awt::XWindow > SAL_CALL LimitBoxController::createPopupWindow()
throw (uno::RuntimeException)
{
return uno::Reference< awt::XWindow >();
}
uno::Reference< awt::XWindow > SAL_CALL LimitBoxController::createItemWindow(
const uno::Reference< awt::XWindow >& Parent )
throw (uno::RuntimeException)
{
uno::Reference< awt::XWindow > xItemWindow;
uno::Reference< awt::XWindow > xParent( Parent );
Window* pParent = VCLUnoHelper::GetWindow( xParent );
if ( pParent )
{
SolarMutexGuard aSolarMutexGuard;
m_pLimitBox = new LimitBox(pParent, this);
xItemWindow = VCLUnoHelper::GetInterface( m_pLimitBox );
}
return xItemWindow;
}
void LimitBoxController::dispatchCommand(
const uno::Sequence< beans::PropertyValue >& rArgs )
{
uno::Reference< frame::XDispatchProvider > xDispatchProvider( m_xFrame, uno::UNO_QUERY );
if ( xDispatchProvider.is() )
{
util::URL aURL;
uno::Reference< frame::XDispatch > xDispatch;
uno::Reference< util::XURLTransformer > xURLTransformer = getURLTransformer();
aURL.Complete = OUString( ".uno:DBLimit" );
xURLTransformer->parseStrict( aURL );
xDispatch = xDispatchProvider->queryDispatch( aURL, OUString(), 0 );
if ( xDispatch.is() )
xDispatch->dispatch( aURL, rArgs );
}
}
} ///dbaui namespace
extern "C" void SAL_CALL createRegistryInfo_LimitBoxController()
{
static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::LimitBoxController > aAutoRegistration;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* 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 "loader-png.h"
#include <cstring>
#include <cstdlib>
#include <zlib.h>
#include <png.h>
#include <dali/integration-api/bitmap.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/images/image.h>
#include "dali/public-api/math/math-utils.h"
#include "dali/public-api/math/vector2.h"
#include "platform-capabilities.h"
namespace Dali
{
using Integration::Bitmap;
using Dali::Integration::PixelBuffer;
namespace TizenPlatform
{
namespace
{
// simple class to enforce clean-up of PNG structures
struct auto_png
{
auto_png(png_structp& _png, png_infop& _info)
: png(_png),
info(_info)
{
}
~auto_png()
{
if(NULL != png)
{
png_destroy_read_struct(&png, &info, NULL);
}
}
png_structp& png;
png_infop& info;
}; // struct auto_png;
bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info)
{
png_byte header[8] = { 0 };
// Check header to see if it is a PNG file
size_t size = fread(header, 1, 8, fp);
if(size != 8)
{
return false;
}
if(png_sig_cmp(header, 0, 8))
{
return false;
}
png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png)
{
DALI_LOG_WARNING("Can't create PNG read structure\n");
return false;
}
info = png_create_info_struct(png);
if(!info)
{
DALI_LOG_WARNING("png_create_info_struct failed\n");
return false;
}
png_set_expand(png);
if(setjmp(png_jmpbuf(png)))
{
DALI_LOG_WARNING("error during png_init_io\n");
return false;
}
png_init_io(png, fp);
png_set_sig_bytes(png, 8);
// read image info
png_read_info(png, info);
// dimensions
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
return true;
}
} // namespace - anonymous
bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
{
png_structp png = NULL;
png_infop info = NULL;
auto_png autoPng(png, info);
bool success = LoadPngHeader( input.file, width, height, png, info );
return success;
}
bool LoadBitmapFromPng( const ImageLoader::Input& input, Integration::Bitmap& bitmap )
{
png_structp png = NULL;
png_infop info = NULL;
auto_png autoPng(png, info);
/// @todo: consider parameters
unsigned int y;
unsigned int width, height;
unsigned char *pixels;
png_bytep *rows;
unsigned int bpp = 0; // bytes per pixel
bool valid = false;
// Load info from the header
if( !LoadPngHeader( input.file, width, height, png, info ) )
{
return false;
}
Pixel::Format pixelFormat = Pixel::RGBA8888;
// decide pixel format
unsigned int colordepth = png_get_bit_depth(png, info);
// Ask PNGLib to convert high precision images into something we can use:
if (colordepth == 16)
{
png_set_strip_16(png);
colordepth = 8;
}
png_byte colortype = png_get_color_type(png, info);
if(colortype == PNG_COLOR_TYPE_GRAY)
{
switch( colordepth )
{
case 8:
{
pixelFormat = Pixel::L8;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_GRAY_ALPHA)
{
switch(colordepth)
{
case 8:
{
pixelFormat = Pixel::LA88;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_RGB )
{
switch(colordepth)
{
case 8:
{
pixelFormat = Pixel::RGB888;
valid = true;
break;
}
case 5: /// @todo is this correct for RGB16 5-6-5 ?
{
pixelFormat = Pixel::RGB565;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_RGBA)
{
switch(colordepth)
{
case 8:
{
pixelFormat = Pixel::RGBA8888;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_PALETTE)
{
switch(colordepth)
{
case 1:
{
pixelFormat = Pixel::LA88;
valid = true;
break;
}
case 2:
case 4:
case 8:
{
/* Expand paletted or RGB images with transparency to full alpha channels
* so the data will be available as RGBA quartets. PNG_INFO_tRNS = 0x10
*/
if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
{
pixelFormat = Pixel::RGBA8888;
valid = true;
}
else
{
pixelFormat = Pixel::RGB888;
png_set_packing(png);
png_set_packswap(png);
png_set_palette_to_rgb(png);
valid = true;
}
break;
}
default:
{
break;
}
}
}
if( !valid )
{
DALI_LOG_WARNING( "Unsupported png format\n" );
return false;
}
// bytes per pixel
bpp = Pixel::GetBytesPerPixel(pixelFormat);
png_read_update_info(png, info);
if(setjmp(png_jmpbuf(png)))
{
DALI_LOG_WARNING("error during png_read_image\n");
return false;
}
unsigned int rowBytes = png_get_rowbytes(png, info);
unsigned int bufferWidth = GetTextureDimension(width);
unsigned int bufferHeight = GetTextureDimension(height);
unsigned int stride = bufferWidth*bpp;
// not sure if this ever happens
if( rowBytes > stride )
{
stride = GetTextureDimension(rowBytes);
bufferWidth = stride / bpp;
}
// decode the whole image into bitmap buffer
pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer(pixelFormat, width, height, bufferWidth, bufferHeight);
DALI_ASSERT_DEBUG(pixels);
rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) );
for(y=0; y<height; y++)
{
rows[y] = pixels + y * stride;
}
// decode image
png_read_image(png, rows);
free(rows);
return true;
}
// simple class to enforce clean-up of PNG structures
struct AutoPngWrite
{
AutoPngWrite(png_structp& _png, png_infop& _info)
: png(_png),
info(_info)
{
}
~AutoPngWrite()
{
if(NULL != png)
{
png_destroy_write_struct(&png, &info);
}
}
png_structp& png;
png_infop& info;
}; // struct AutoPngWrite;
namespace
{
// Custom libpng write callbacks that buffer to a vector instead of a file:
/**
* extern "C" linkage is used because this is a callback that we pass to a C
* library which is part of the underlying platform and so potentially compiled
* as C rather than C++.
* @see http://stackoverflow.com/a/2594222
* */
extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
{
DALI_ASSERT_DEBUG(png_ptr && data);
if(!png_ptr || !data)
{
return;
}
// Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
try
{
// Recover our buffer for writing into:
Vector<unsigned char>* const encoded_img = static_cast< Vector<unsigned char>* >( png_get_io_ptr(png_ptr) );
if(encoded_img)
{
const Vector<unsigned char>::SizeType bufferSize = encoded_img->Count();
encoded_img->Resize( bufferSize + length ); //< Can throw OOM.
unsigned char* const bufferBack = encoded_img->Begin() + bufferSize;
memcpy(bufferBack, data, length);
}
else
{
DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n");
}
}
catch(...)
{
DALI_LOG_ERROR("C++ Exception caught\n");
}
}
/** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
extern "C" void FlushData(png_structp png_ptr)
{
#ifdef DEBUG_ENABLED
Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
#endif // DEBUG_ENABLED
}
}
/**
* Potential improvements:
* 1. Detect <= 256 colours and write in palette mode.
* 2. Detect grayscale (will early-out quickly for colour images).
* 3. Store colour space / gamma correction info related to the device screen?
* http://www.libpng.org/pub/png/book/chapter10.html
* 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
* 5. Prealloc buffer (reserve) to input size / <A number greater than 2 (expexcted few realloc but without using lots of memory) | 1 (expected zero reallocs but using a lot of memory)>.
* 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
* 7. If caller asks for no compression, bypass libpng and blat raw data to
* disk, topped and tailed with header/tail blocks.
*/
bool EncodeToPng( const unsigned char* const pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
{
// Translate pixel format enum:
int pngPixelFormat = -1;
unsigned pixelBytes = 0;
bool rgbaOrder = true;
// Account for RGB versus BGR and presence of alpha in input pixels:
switch( pixelFormat )
{
case Pixel::RGB888:
{
pngPixelFormat = PNG_COLOR_TYPE_RGB;
pixelBytes = 3;
break;
}
case Pixel::BGRA8888:
{
rgbaOrder = false;
///! No break: fall through:
}
case Pixel::RGBA8888:
{
pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
pixelBytes = 4;
break;
}
default:
{
DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" );
return false;
}
}
const int interlace = PNG_INTERLACE_NONE;
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr)
{
return false;
}
/* Allocate/initialize the image information data. REQUIRED */
png_infop info_ptr = png_create_info_struct( png_ptr );
if(!info_ptr)
{
png_destroy_write_struct(&png_ptr, NULL);
return false;
}
/* Set error handling. REQUIRED if you aren't supplying your own
* error handling functions in the png_create_write_struct() call.
*/
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
return false;
}
// Since we are going to write to memory instead of a file, lets provide
// libpng with a custom write function and ask it to pass back our
// Vector buffer each time it calls back to flush data to "file":
png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
// png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
png_set_compression_level(png_ptr, Z_BEST_SPEED);
// png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
// Explicitly limit the number of filters used per scanline to speed us up:
// png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
// PNG_FILTER_SUB |
// PNG_FILTER_UP |
// PNG_FILTER_AVE |
// PNG_FILTER_PAETH |
// PNG_ALL_FILTERS);
// Play with Zlib parameters in optimisation phase:
// png_set_compression_mem_level(png_ptr, 8);
// png_set_compression_strategy(png_ptr,
// Z_DEFAULT_STRATEGY);
// png_set_compression_window_bits(png_ptr, 15);
// png_set_compression_method(png_ptr, 8);
// png_set_compression_buffer_size(png_ptr, 8192)
// Let lib_png know if the pixel bytes are in BGR(A) order:
if(!rgbaOrder)
{
png_set_bgr( png_ptr );
}
// Set the image information:
png_set_IHDR(png_ptr, info_ptr, width, height, 8,
pngPixelFormat, interlace,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
// Start to output the PNG data to our buffer:
png_write_info(png_ptr, info_ptr);
// Walk the rows:
const unsigned row_step = width * pixelBytes;
png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
const png_bytep row_end = row_ptr + height * row_step;
for(; row_ptr < row_end; row_ptr += row_step)
{
png_write_row(png_ptr, row_ptr);
}
/* It is REQUIRED to call this to finish writing the rest of the file */
png_write_end(png_ptr, info_ptr);
/* Clean up after the write, and free any memory allocated */
png_destroy_write_struct(&png_ptr, &info_ptr);
return true;
}
} // namespace TizenPlatform
} // namespace Dali
<commit_msg>Try to fix png crash issue<commit_after>/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* 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 "loader-png.h"
#include <cstring>
#include <cstdlib>
#include <zlib.h>
#include <png.h>
#include <dali/integration-api/bitmap.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/images/image.h>
#include "dali/public-api/math/math-utils.h"
#include "dali/public-api/math/vector2.h"
#include "platform-capabilities.h"
namespace Dali
{
using Integration::Bitmap;
using Dali::Integration::PixelBuffer;
namespace TizenPlatform
{
namespace
{
// simple class to enforce clean-up of PNG structures
struct auto_png
{
auto_png(png_structp& _png, png_infop& _info)
: png(_png),
info(_info)
{
}
~auto_png()
{
if(NULL != png)
{
png_destroy_read_struct(&png, &info, NULL);
}
}
png_structp& png;
png_infop& info;
}; // struct auto_png;
bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info)
{
png_byte header[8] = { 0 };
// Check header to see if it is a PNG file
size_t size = fread(header, 1, 8, fp);
if(size != 8)
{
return false;
}
if(png_sig_cmp(header, 0, 8))
{
return false;
}
png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png)
{
DALI_LOG_WARNING("Can't create PNG read structure\n");
return false;
}
info = png_create_info_struct(png);
if(!info)
{
DALI_LOG_WARNING("png_create_info_struct failed\n");
return false;
}
png_set_expand(png);
if(setjmp(png_jmpbuf(png)))
{
DALI_LOG_WARNING("error during png_init_io\n");
return false;
}
png_init_io(png, fp);
png_set_sig_bytes(png, 8);
// read image info
png_read_info(png, info);
// dimensions
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
return true;
}
} // namespace - anonymous
bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
{
png_structp png = NULL;
png_infop info = NULL;
auto_png autoPng(png, info);
bool success = LoadPngHeader( input.file, width, height, png, info );
return success;
}
bool LoadBitmapFromPng( const ImageLoader::Input& input, Integration::Bitmap& bitmap )
{
png_structp png = NULL;
png_infop info = NULL;
auto_png autoPng(png, info);
/// @todo: consider parameters
unsigned int y;
unsigned int width, height;
unsigned char *pixels;
png_bytep *rows;
unsigned int bpp = 0; // bytes per pixel
bool valid = false;
// Load info from the header
if( !LoadPngHeader( input.file, width, height, png, info ) )
{
return false;
}
Pixel::Format pixelFormat = Pixel::RGBA8888;
// decide pixel format
unsigned int colordepth = png_get_bit_depth(png, info);
// Ask PNGLib to convert high precision images into something we can use:
if (colordepth == 16)
{
png_set_strip_16(png);
colordepth = 8;
}
png_byte colortype = png_get_color_type(png, info);
if(colortype == PNG_COLOR_TYPE_GRAY)
{
switch( colordepth )
{
case 8:
{
pixelFormat = Pixel::L8;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_GRAY_ALPHA)
{
switch(colordepth)
{
case 8:
{
pixelFormat = Pixel::LA88;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_RGB )
{
switch(colordepth)
{
case 8:
{
pixelFormat = Pixel::RGB888;
valid = true;
break;
}
case 5: /// @todo is this correct for RGB16 5-6-5 ?
{
pixelFormat = Pixel::RGB565;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_RGBA)
{
switch(colordepth)
{
case 8:
{
pixelFormat = Pixel::RGBA8888;
valid = true;
break;
}
default:
{
break;
}
}
}
else if(colortype == PNG_COLOR_TYPE_PALETTE)
{
switch(colordepth)
{
case 1:
{
pixelFormat = Pixel::LA88;
valid = true;
break;
}
case 2:
case 4:
case 8:
{
/* Expand paletted or RGB images with transparency to full alpha channels
* so the data will be available as RGBA quartets. PNG_INFO_tRNS = 0x10
*/
if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
{
pixelFormat = Pixel::RGBA8888;
valid = true;
}
else
{
pixelFormat = Pixel::RGB888;
png_set_packing(png);
png_set_packswap(png);
png_set_palette_to_rgb(png);
valid = true;
}
break;
}
default:
{
break;
}
}
}
if( !valid )
{
DALI_LOG_WARNING( "Unsupported png format\n" );
return false;
}
// bytes per pixel
bpp = Pixel::GetBytesPerPixel(pixelFormat);
png_read_update_info(png, info);
if(setjmp(png_jmpbuf(png)))
{
DALI_LOG_WARNING("error during png_read_image\n");
return false;
}
unsigned int rowBytes = png_get_rowbytes(png, info);
unsigned int bufferWidth = GetTextureDimension(width);
unsigned int bufferHeight = GetTextureDimension(height);
unsigned int stride = bufferWidth*bpp;
// not sure if this ever happens
if( rowBytes > stride )
{
stride = GetTextureDimension(rowBytes);
bpp = stride / bufferWidth;
switch(bpp)
{
case 3:
pixelFormat = Pixel::RGB888;
break;
case 4:
pixelFormat = Pixel::RGBA8888;
break;
default:
break;
}
}
// decode the whole image into bitmap buffer
pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer(pixelFormat, width, height, bufferWidth, bufferHeight);
DALI_ASSERT_DEBUG(pixels);
rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) );
for(y=0; y<height; y++)
{
rows[y] = pixels + y * stride;
}
// decode image
png_read_image(png, rows);
free(rows);
return true;
}
// simple class to enforce clean-up of PNG structures
struct AutoPngWrite
{
AutoPngWrite(png_structp& _png, png_infop& _info)
: png(_png),
info(_info)
{
}
~AutoPngWrite()
{
if(NULL != png)
{
png_destroy_write_struct(&png, &info);
}
}
png_structp& png;
png_infop& info;
}; // struct AutoPngWrite;
namespace
{
// Custom libpng write callbacks that buffer to a vector instead of a file:
/**
* extern "C" linkage is used because this is a callback that we pass to a C
* library which is part of the underlying platform and so potentially compiled
* as C rather than C++.
* @see http://stackoverflow.com/a/2594222
* */
extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
{
DALI_ASSERT_DEBUG(png_ptr && data);
if(!png_ptr || !data)
{
return;
}
// Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
try
{
// Recover our buffer for writing into:
Vector<unsigned char>* const encoded_img = static_cast< Vector<unsigned char>* >( png_get_io_ptr(png_ptr) );
if(encoded_img)
{
const Vector<unsigned char>::SizeType bufferSize = encoded_img->Count();
encoded_img->Resize( bufferSize + length ); //< Can throw OOM.
unsigned char* const bufferBack = encoded_img->Begin() + bufferSize;
memcpy(bufferBack, data, length);
}
else
{
DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n");
}
}
catch(...)
{
DALI_LOG_ERROR("C++ Exception caught\n");
}
}
/** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
extern "C" void FlushData(png_structp png_ptr)
{
#ifdef DEBUG_ENABLED
Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
#endif // DEBUG_ENABLED
}
}
/**
* Potential improvements:
* 1. Detect <= 256 colours and write in palette mode.
* 2. Detect grayscale (will early-out quickly for colour images).
* 3. Store colour space / gamma correction info related to the device screen?
* http://www.libpng.org/pub/png/book/chapter10.html
* 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
* 5. Prealloc buffer (reserve) to input size / <A number greater than 2 (expexcted few realloc but without using lots of memory) | 1 (expected zero reallocs but using a lot of memory)>.
* 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
* 7. If caller asks for no compression, bypass libpng and blat raw data to
* disk, topped and tailed with header/tail blocks.
*/
bool EncodeToPng( const unsigned char* const pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
{
// Translate pixel format enum:
int pngPixelFormat = -1;
unsigned pixelBytes = 0;
bool rgbaOrder = true;
// Account for RGB versus BGR and presence of alpha in input pixels:
switch( pixelFormat )
{
case Pixel::RGB888:
{
pngPixelFormat = PNG_COLOR_TYPE_RGB;
pixelBytes = 3;
break;
}
case Pixel::BGRA8888:
{
rgbaOrder = false;
///! No break: fall through:
}
case Pixel::RGBA8888:
{
pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
pixelBytes = 4;
break;
}
default:
{
DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" );
return false;
}
}
const int interlace = PNG_INTERLACE_NONE;
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr)
{
return false;
}
/* Allocate/initialize the image information data. REQUIRED */
png_infop info_ptr = png_create_info_struct( png_ptr );
if(!info_ptr)
{
png_destroy_write_struct(&png_ptr, NULL);
return false;
}
/* Set error handling. REQUIRED if you aren't supplying your own
* error handling functions in the png_create_write_struct() call.
*/
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
return false;
}
// Since we are going to write to memory instead of a file, lets provide
// libpng with a custom write function and ask it to pass back our
// Vector buffer each time it calls back to flush data to "file":
png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
// png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
png_set_compression_level(png_ptr, Z_BEST_SPEED);
// png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
// Explicitly limit the number of filters used per scanline to speed us up:
// png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
// PNG_FILTER_SUB |
// PNG_FILTER_UP |
// PNG_FILTER_AVE |
// PNG_FILTER_PAETH |
// PNG_ALL_FILTERS);
// Play with Zlib parameters in optimisation phase:
// png_set_compression_mem_level(png_ptr, 8);
// png_set_compression_strategy(png_ptr,
// Z_DEFAULT_STRATEGY);
// png_set_compression_window_bits(png_ptr, 15);
// png_set_compression_method(png_ptr, 8);
// png_set_compression_buffer_size(png_ptr, 8192)
// Let lib_png know if the pixel bytes are in BGR(A) order:
if(!rgbaOrder)
{
png_set_bgr( png_ptr );
}
// Set the image information:
png_set_IHDR(png_ptr, info_ptr, width, height, 8,
pngPixelFormat, interlace,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
// Start to output the PNG data to our buffer:
png_write_info(png_ptr, info_ptr);
// Walk the rows:
const unsigned row_step = width * pixelBytes;
png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
const png_bytep row_end = row_ptr + height * row_step;
for(; row_ptr < row_end; row_ptr += row_step)
{
png_write_row(png_ptr, row_ptr);
}
/* It is REQUIRED to call this to finish writing the rest of the file */
png_write_end(png_ptr, info_ptr);
/* Clean up after the write, and free any memory allocated */
png_destroy_write_struct(&png_ptr, &info_ptr);
return true;
}
} // namespace TizenPlatform
} // namespace Dali
<|endoftext|>
|
<commit_before>/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "spriterendercomponent.h"
#include "spriterendercomponentprivate.h"
#include <kgl/kglitem.h>
using namespace Gluon;
REGISTER_OBJECTTYPE(SpriteRenderComponent)
SpriteRenderComponent::SpriteRenderComponent ( QObject* parent ) : Component ( parent )
{
d = new SpriteRenderComponentPrivate;
d->item = new KGLItem;
}
SpriteRenderComponent::SpriteRenderComponent ( const Gluon::SpriteRenderComponent& other )
: Component ( other ),
d(other.d)
{
d->item = new KGLItem;
}
SpriteRenderComponent::~SpriteRenderComponent()
{
delete d->item;
}
GluonObject* SpriteRenderComponent::instantiate()
{
return new SpriteRenderComponent(this);
}
void SpriteRenderComponent::Update ( int elapsedMilliseconds )
{
}
void SpriteRenderComponent::Start()
{
//Gluon::Component::Start();
}
void SpriteRenderComponent::Draw ( int timeLapse )
{
//Gluon::Component::Draw ( timeLapse );
}
void Gluon::SpriteRenderComponent::setSize ( const QSizeF& size )
{
d->size = size;
//d->item->setSize(size);
}
QSizeF Gluon::SpriteRenderComponent::size()
{
return d->size;
}
<commit_msg>Nasty not-quite-fix-but-at-least-it-runs hackery...<commit_after>/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "spriterendercomponent.h"
#include "spriterendercomponentprivate.h"
#include <kgl/kglitem.h>
using namespace Gluon;
REGISTER_OBJECTTYPE(SpriteRenderComponent)
SpriteRenderComponent::SpriteRenderComponent ( QObject* parent ) : Component ( parent )
{
d = new SpriteRenderComponentPrivate;
#warning This really is not the way to fix this. Someone needs to take a
#warning long, hard look at KGLItem - being unable to instantiate it
#warning without a parent is pretty nasty
//d->item = new KGLItem;
}
SpriteRenderComponent::SpriteRenderComponent ( const Gluon::SpriteRenderComponent& other )
: Component ( other ),
d(other.d)
{
//d->item = new KGLItem;
}
SpriteRenderComponent::~SpriteRenderComponent()
{
delete d->item;
}
GluonObject* SpriteRenderComponent::instantiate()
{
return new SpriteRenderComponent(this);
}
void SpriteRenderComponent::Update ( int elapsedMilliseconds )
{
}
void SpriteRenderComponent::Start()
{
//Gluon::Component::Start();
}
void SpriteRenderComponent::Draw ( int timeLapse )
{
//Gluon::Component::Draw ( timeLapse );
}
void Gluon::SpriteRenderComponent::setSize ( const QSizeF& size )
{
d->size = size;
//d->item->setSize(size);
}
QSizeF Gluon::SpriteRenderComponent::size()
{
return d->size;
}
<|endoftext|>
|
<commit_before>/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "colorpropertywidgetitem.h"
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QDoubleSpinBox>
#include <QtGui/QColor>
#include <cfloat>
#include <core/gluonvarianttypes.h>
using namespace GluonCreator;
class ColorPropertyWidgetItem::ColorPropertyWidgetItemPrivate
{
public:
ColorPropertyWidgetItemPrivate() { }
QDoubleSpinBox* r;
QDoubleSpinBox* g;
QDoubleSpinBox* b;
QColor value;
};
ColorPropertyWidgetItem::ColorPropertyWidgetItem(QWidget* parent, Qt::WindowFlags f): PropertyWidgetItem(parent, f)
{
d = new ColorPropertyWidgetItemPrivate;
QWidget* base = new QWidget(this);
QHBoxLayout* layout = new QHBoxLayout();
base->setLayout(layout);
d->r = new QDoubleSpinBox(this);
d->r->setPrefix("R: ");
d->r->setRange(0.0f, 1.0f);
d->r->setSingleStep(0.001f);
layout->addWidget(d->r);
connect(d->r, SIGNAL(valueChanged(double)), SLOT(rValueChanged(double)));
d->g = new QDoubleSpinBox(this);
d->g->setPrefix("G: ");
d->g->setRange(0.0f, 1.0f);
d->g->setSingleStep(0.001f);
layout->addWidget(d->g);
connect(d->g, SIGNAL(valueChanged(double)), SLOT(gValueChanged(double)));
d->b = new QDoubleSpinBox(this);
d->b->setPrefix("B: ");
d->b->setRange(0.0f, 1.0f);
d->b->setSingleStep(0.001f);
layout->addWidget(d->b);
connect(d->b, SIGNAL(valueChanged(double)), SLOT(bValueChanged(double)));
setEditWidget(base);
}
ColorPropertyWidgetItem::~ColorPropertyWidgetItem()
{
delete d;
}
void ColorPropertyWidgetItem::setEditValue(const QVariant& value)
{
QColor color = value.value<QColor>();
d->value = color;
d->r->setValue(color.redF());
d->g->setValue(color.greenF());
d->b->setValue(color.blueF());
}
void ColorPropertyWidgetItem::rValueChanged(double value)
{
d->value.setRedF(value);
PropertyWidgetItem::valueChanged(QVariant::fromValue<QColor>(d->value));
}
void ColorPropertyWidgetItem::gValueChanged(double value)
{
d->value.setGreenF(value);
PropertyWidgetItem::valueChanged(QVariant::fromValue<QColor>(d->value));
}
void ColorPropertyWidgetItem::bValueChanged(double value)
{
d->value.setBlueF(value);
PropertyWidgetItem::valueChanged(QVariant::fromValue<QColor>(d->value));
}
#include "colorpropertywidgetitem.moc"
<commit_msg>Woops, 0.001 is a really small value...<commit_after>/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "colorpropertywidgetitem.h"
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QDoubleSpinBox>
#include <QtGui/QColor>
#include <cfloat>
#include <core/gluonvarianttypes.h>
using namespace GluonCreator;
class ColorPropertyWidgetItem::ColorPropertyWidgetItemPrivate
{
public:
ColorPropertyWidgetItemPrivate() { }
QDoubleSpinBox* r;
QDoubleSpinBox* g;
QDoubleSpinBox* b;
QColor value;
};
ColorPropertyWidgetItem::ColorPropertyWidgetItem(QWidget* parent, Qt::WindowFlags f): PropertyWidgetItem(parent, f)
{
d = new ColorPropertyWidgetItemPrivate;
QWidget* base = new QWidget(this);
QHBoxLayout* layout = new QHBoxLayout();
base->setLayout(layout);
d->r = new QDoubleSpinBox(this);
d->r->setPrefix("R: ");
d->r->setRange(0.0f, 1.0f);
d->r->setSingleStep(0.01f);
layout->addWidget(d->r);
connect(d->r, SIGNAL(valueChanged(double)), SLOT(rValueChanged(double)));
d->g = new QDoubleSpinBox(this);
d->g->setPrefix("G: ");
d->g->setRange(0.0f, 1.0f);
d->g->setSingleStep(0.01f);
layout->addWidget(d->g);
connect(d->g, SIGNAL(valueChanged(double)), SLOT(gValueChanged(double)));
d->b = new QDoubleSpinBox(this);
d->b->setPrefix("B: ");
d->b->setRange(0.0f, 1.0f);
d->b->setSingleStep(0.01f);
layout->addWidget(d->b);
connect(d->b, SIGNAL(valueChanged(double)), SLOT(bValueChanged(double)));
setEditWidget(base);
}
ColorPropertyWidgetItem::~ColorPropertyWidgetItem()
{
delete d;
}
void ColorPropertyWidgetItem::setEditValue(const QVariant& value)
{
QColor color = value.value<QColor>();
d->value = color;
d->r->setValue(color.redF());
d->g->setValue(color.greenF());
d->b->setValue(color.blueF());
}
void ColorPropertyWidgetItem::rValueChanged(double value)
{
d->value.setRedF(value);
PropertyWidgetItem::valueChanged(QVariant::fromValue<QColor>(d->value));
}
void ColorPropertyWidgetItem::gValueChanged(double value)
{
d->value.setGreenF(value);
PropertyWidgetItem::valueChanged(QVariant::fromValue<QColor>(d->value));
}
void ColorPropertyWidgetItem::bValueChanged(double value)
{
d->value.setBlueF(value);
PropertyWidgetItem::valueChanged(QVariant::fromValue<QColor>(d->value));
}
#include "colorpropertywidgetitem.moc"
<|endoftext|>
|
<commit_before>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Do not remove the include below
#include "Arduino.h"
#include "logger.h"
#include "ocstack.h"
#include <string.h>
#ifdef ARDUINOWIFI
// Arduino WiFi Shield
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#else
// Arduino Ethernet Shield
#include <EthernetServer.h>
#include <Ethernet.h>
#include <Dns.h>
#include <EthernetClient.h>
#include <util.h>
#include <EthernetUdp.h>
#include <Dhcp.h>
#endif
const char *getResult(OCStackResult result);
PROGMEM const char TAG[] = "ArduinoServer";
int gLEDUnderObservation = 0;
void createLEDResource();
typedef struct LEDRESOURCE{
OCResourceHandle handle;
bool state;
int power;
} LEDResource;
static LEDResource LED;
static char responsePayloadGet[] = "{\"href\":\"/a/led\",\"rep\":{\"state\":\"on\",\"power\":10}}";
static char responsePayloadPut[] = "{\"href\":\"/a/led\",\"rep\":{\"state\":\"off\",\"power\":0}}";
/// This is the port which Arduino Server will use for all unicast communication with it's peers
static uint16_t OC_WELL_KNOWN_PORT = 5683;
#ifdef ARDUINOWIFI
// Arduino WiFi Shield
// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
// this server will NOT be listening on 224.0.1.187 multicast address.
/// WiFi Shield firmware with Intel patches
static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
/// WiFi network info and credentials
char ssid[] = "mDNSAP";
char pass[] = "letmein9";
int ConnectToNetwork()
{
char *fwVersion;
int status = WL_IDLE_STATUS;
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD)
{
OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
return -1;
}
// Verify that WiFi Shield is running the firmware with all UDP fixes
fwVersion = WiFi.firmwareVersion();
OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
{
OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
return -1;
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED)
{
OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
IPAddress ip = WiFi.localIP();
OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
#else
// Arduino Ethernet Shield
int ConnectToNetwork()
{
// Note: ****Update the MAC address here with your shield's MAC address****
uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
uint8_t error = Ethernet.begin(ETHERNET_MAC);
if (error == 0)
{
OC_LOG_V(ERROR, TAG, "error is: %d", error);
return -1;
}
IPAddress ip = Ethernet.localIP();
OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
#endif //ARDUINOWIFI
// This is the entity handler for the registered resource.
// This is invoked by OCStack whenever it recevies a request for this resource.
OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
{
OCEntityHandlerResult ehRet = OC_EH_OK;
const char* typeOfMessage;
switch (flag)
{
case OC_INIT_FLAG:
typeOfMessage = "OC_INIT_FLAG";
break;
case OC_REQUEST_FLAG:
typeOfMessage = "OC_REQUEST_FLAG";
break;
case OC_OBSERVE_FLAG:
typeOfMessage = "OC_OBSERVE_FLAG";
break;
default:
typeOfMessage = "UNKNOWN";
}
OC_LOG_V(INFO, TAG, "Receiving message type: %s", typeOfMessage);
if(entityHandlerRequest && flag == OC_REQUEST_FLAG)
{
if(OC_REST_GET == entityHandlerRequest->method)
{
if (strlen(responsePayloadGet) < entityHandlerRequest->resJSONPayloadLen)
{
strncpy((char *)entityHandlerRequest->resJSONPayload, responsePayloadGet, entityHandlerRequest->resJSONPayloadLen);
}
else
{
ehRet = OC_EH_ERROR;
}
}
if(OC_REST_PUT == entityHandlerRequest->method)
{
//Do something with the 'put' payload
if (strlen(responsePayloadPut) < entityHandlerRequest->resJSONPayloadLen)
{
strncpy((char *)entityHandlerRequest->resJSONPayload, responsePayloadPut, entityHandlerRequest->resJSONPayloadLen);
}
else
{
ehRet = OC_EH_ERROR;
}
}
}
else if (entityHandlerRequest && flag == OC_OBSERVE_FLAG)
{
gLEDUnderObservation = 1;
}
return ehRet;
}
// This method is used to display 'Observe' functionality of OC Stack.
static uint8_t modCounter = 0;
void *ChangeLEDRepresentation (void *param)
{
(void)param;
OCStackResult result = OC_STACK_ERROR;
modCounter += 1;
if(modCounter % 10 == 0) // Matching the timing that the Linux Sample Server App uses for the same functionality.
{
LED.power += 5;
if (gLEDUnderObservation)
{
OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", LED.power);
result = OCNotifyObservers (LED.handle);
if (OC_STACK_NO_OBSERVERS == result)
{
gLEDUnderObservation = 0;
}
}
}
return NULL;
}
//The setup function is called once at startup of the sketch
void setup()
{
// Add your initialization code here
OC_LOG_INIT();
OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
uint16_t port = OC_WELL_KNOWN_PORT;
// Connect to Ethernet or WiFi network
if (ConnectToNetwork() != 0)
{
OC_LOG(ERROR, TAG, PCF("Unable to connect to network"));
return;
}
// Initialize the OC Stack in Server mode
if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
{
OC_LOG(ERROR, TAG, PCF("OCStack init error"));
return;
}
// Declare and create the example resource: LED
createLEDResource();
}
// The loop function is called in an endless loop
void loop()
{
// This artificial delay is kept here to avoid endless spinning
// of Arduino microcontroller. Modify it as per specfic application needs.
delay(2000);
if (OCProcess() != OC_STACK_OK)
{
OC_LOG(ERROR, TAG, PCF("OCStack process error"));
return;
}
ChangeLEDRepresentation(NULL);
}
void createLEDResource()
{
LED.state = false;
OCStackResult res = OCCreateResource(&LED.handle,
"core.led",
"oc.mi.def",
"/a/led",
OCEntityHandlerCb,
OC_DISCOVERABLE|OC_OBSERVABLE);
OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
}
const char *getResult(OCStackResult result) {
switch (result) {
case OC_STACK_OK:
return "OC_STACK_OK";
case OC_STACK_INVALID_URI:
return "OC_STACK_INVALID_URI";
case OC_STACK_INVALID_QUERY:
return "OC_STACK_INVALID_QUERY";
case OC_STACK_INVALID_IP:
return "OC_STACK_INVALID_IP";
case OC_STACK_INVALID_PORT:
return "OC_STACK_INVALID_PORT";
case OC_STACK_INVALID_CALLBACK:
return "OC_STACK_INVALID_CALLBACK";
case OC_STACK_INVALID_METHOD:
return "OC_STACK_INVALID_METHOD";
case OC_STACK_NO_MEMORY:
return "OC_STACK_NO_MEMORY";
case OC_STACK_COMM_ERROR:
return "OC_STACK_COMM_ERROR";
case OC_STACK_INVALID_PARAM:
return "OC_STACK_INVALID_PARAM";
case OC_STACK_NOTIMPL:
return "OC_STACK_NOTIMPL";
case OC_STACK_NO_RESOURCE:
return "OC_STACK_NO_RESOURCE";
case OC_STACK_RESOURCE_ERROR:
return "OC_STACK_RESOURCE_ERROR";
case OC_STACK_SLOW_RESOURCE:
return "OC_STACK_SLOW_RESOURCE";
case OC_STACK_NO_OBSERVERS:
return "OC_STACK_NO_OBSERVERS";
case OC_STACK_ERROR:
return "OC_STACK_ERROR";
default:
return "UNKNOWN";
}
}
<commit_msg>Updated Arduino sample app to reflect the current SRAM available. \n This will help in debugging Arduino crash issues in low SRAM scenarios Patch 2 : Updated code to execute only for MEGA2560 boards.<commit_after>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Do not remove the include below
#include "Arduino.h"
#include "logger.h"
#include "ocstack.h"
#include <string.h>
#ifdef ARDUINOWIFI
// Arduino WiFi Shield
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#else
// Arduino Ethernet Shield
#include <EthernetServer.h>
#include <Ethernet.h>
#include <Dns.h>
#include <EthernetClient.h>
#include <util.h>
#include <EthernetUdp.h>
#include <Dhcp.h>
#endif
const char *getResult(OCStackResult result);
PROGMEM const char TAG[] = "ArduinoServer";
int gLEDUnderObservation = 0;
void createLEDResource();
typedef struct LEDRESOURCE{
OCResourceHandle handle;
bool state;
int power;
} LEDResource;
static LEDResource LED;
static char responsePayloadGet[] = "{\"href\":\"/a/led\",\"rep\":{\"state\":\"on\",\"power\":10}}";
static char responsePayloadPut[] = "{\"href\":\"/a/led\",\"rep\":{\"state\":\"off\",\"power\":0}}";
/// This is the port which Arduino Server will use for all unicast communication with it's peers
static uint16_t OC_WELL_KNOWN_PORT = 5683;
#ifdef ARDUINOWIFI
// Arduino WiFi Shield
// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
// this server will NOT be listening on 224.0.1.187 multicast address.
/// WiFi Shield firmware with Intel patches
static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
/// WiFi network info and credentials
char ssid[] = "mDNSAP";
char pass[] = "letmein9";
int ConnectToNetwork()
{
char *fwVersion;
int status = WL_IDLE_STATUS;
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD)
{
OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
return -1;
}
// Verify that WiFi Shield is running the firmware with all UDP fixes
fwVersion = WiFi.firmwareVersion();
OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
{
OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
return -1;
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED)
{
OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
IPAddress ip = WiFi.localIP();
OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
#else
// Arduino Ethernet Shield
int ConnectToNetwork()
{
// Note: ****Update the MAC address here with your shield's MAC address****
uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
uint8_t error = Ethernet.begin(ETHERNET_MAC);
if (error == 0)
{
OC_LOG_V(ERROR, TAG, "error is: %d", error);
return -1;
}
IPAddress ip = Ethernet.localIP();
OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
#endif //ARDUINOWIFI
// On Arduino Atmel boards with Harvard memory architecture, the stack grows
// downwards from the top and the heap grows upwards. This method will print
// the distance(in terms of bytes) between those two.
// See here for more details :
// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
void PrintArduinoMemoryStats()
{
#ifdef ARDUINO_AVR_MEGA2560
//This var is declared in avr-libc/stdlib/malloc.c
//It keeps the largest address not allocated for heap
extern char *__brkval;
//address of tmp gives us the current stack boundry
int tmp;
OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
((unsigned int)&tmp - (unsigned int)__brkval));
#endif
}
// This is the entity handler for the registered resource.
// This is invoked by OCStack whenever it recevies a request for this resource.
OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
{
OCEntityHandlerResult ehRet = OC_EH_OK;
const char* typeOfMessage;
switch (flag)
{
case OC_INIT_FLAG:
typeOfMessage = "OC_INIT_FLAG";
break;
case OC_REQUEST_FLAG:
typeOfMessage = "OC_REQUEST_FLAG";
break;
case OC_OBSERVE_FLAG:
typeOfMessage = "OC_OBSERVE_FLAG";
break;
default:
typeOfMessage = "UNKNOWN";
}
OC_LOG_V(INFO, TAG, "Receiving message type: %s", typeOfMessage);
if(entityHandlerRequest && flag == OC_REQUEST_FLAG)
{
if(OC_REST_GET == entityHandlerRequest->method)
{
if (strlen(responsePayloadGet) < entityHandlerRequest->resJSONPayloadLen)
{
strncpy((char *)entityHandlerRequest->resJSONPayload, responsePayloadGet, entityHandlerRequest->resJSONPayloadLen);
}
else
{
ehRet = OC_EH_ERROR;
}
}
if(OC_REST_PUT == entityHandlerRequest->method)
{
//Do something with the 'put' payload
if (strlen(responsePayloadPut) < entityHandlerRequest->resJSONPayloadLen)
{
strncpy((char *)entityHandlerRequest->resJSONPayload, responsePayloadPut, entityHandlerRequest->resJSONPayloadLen);
}
else
{
ehRet = OC_EH_ERROR;
}
}
}
else if (entityHandlerRequest && flag == OC_OBSERVE_FLAG)
{
gLEDUnderObservation = 1;
}
return ehRet;
}
// This method is used to display 'Observe' functionality of OC Stack.
static uint8_t modCounter = 0;
void *ChangeLEDRepresentation (void *param)
{
(void)param;
OCStackResult result = OC_STACK_ERROR;
modCounter += 1;
if(modCounter % 10 == 0) // Matching the timing that the Linux Sample Server App uses for the same functionality.
{
LED.power += 5;
if (gLEDUnderObservation)
{
OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", LED.power);
result = OCNotifyObservers (LED.handle);
if (OC_STACK_NO_OBSERVERS == result)
{
gLEDUnderObservation = 0;
}
}
}
return NULL;
}
//The setup function is called once at startup of the sketch
void setup()
{
// Add your initialization code here
// Note : This will initialize Serial port on Arduino at 115200 bauds
OC_LOG_INIT();
OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
uint16_t port = OC_WELL_KNOWN_PORT;
// Connect to Ethernet or WiFi network
if (ConnectToNetwork() != 0)
{
OC_LOG(ERROR, TAG, PCF("Unable to connect to network"));
return;
}
// Initialize the OC Stack in Server mode
if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
{
OC_LOG(ERROR, TAG, PCF("OCStack init error"));
return;
}
// Declare and create the example resource: LED
createLEDResource();
}
// The loop function is called in an endless loop
void loop()
{
// This artificial delay is kept here to avoid endless spinning
// of Arduino microcontroller. Modify it as per specfic application needs.
delay(2000);
// This call displays the amount of free SRAM available on Arduino
PrintArduinoMemoryStats();
// Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
if (OCProcess() != OC_STACK_OK)
{
OC_LOG(ERROR, TAG, PCF("OCStack process error"));
return;
}
ChangeLEDRepresentation(NULL);
}
void createLEDResource()
{
LED.state = false;
OCStackResult res = OCCreateResource(&LED.handle,
"core.led",
"oc.mi.def",
"/a/led",
OCEntityHandlerCb,
OC_DISCOVERABLE|OC_OBSERVABLE);
OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
}
const char *getResult(OCStackResult result) {
switch (result) {
case OC_STACK_OK:
return "OC_STACK_OK";
case OC_STACK_INVALID_URI:
return "OC_STACK_INVALID_URI";
case OC_STACK_INVALID_QUERY:
return "OC_STACK_INVALID_QUERY";
case OC_STACK_INVALID_IP:
return "OC_STACK_INVALID_IP";
case OC_STACK_INVALID_PORT:
return "OC_STACK_INVALID_PORT";
case OC_STACK_INVALID_CALLBACK:
return "OC_STACK_INVALID_CALLBACK";
case OC_STACK_INVALID_METHOD:
return "OC_STACK_INVALID_METHOD";
case OC_STACK_NO_MEMORY:
return "OC_STACK_NO_MEMORY";
case OC_STACK_COMM_ERROR:
return "OC_STACK_COMM_ERROR";
case OC_STACK_INVALID_PARAM:
return "OC_STACK_INVALID_PARAM";
case OC_STACK_NOTIMPL:
return "OC_STACK_NOTIMPL";
case OC_STACK_NO_RESOURCE:
return "OC_STACK_NO_RESOURCE";
case OC_STACK_RESOURCE_ERROR:
return "OC_STACK_RESOURCE_ERROR";
case OC_STACK_SLOW_RESOURCE:
return "OC_STACK_SLOW_RESOURCE";
case OC_STACK_NO_OBSERVERS:
return "OC_STACK_NO_OBSERVERS";
case OC_STACK_ERROR:
return "OC_STACK_ERROR";
default:
return "UNKNOWN";
}
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_dmi_read_erepair.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <[email protected]>
/// *HWP HWP Backup Owner : Gary Peterson <[email protected]>
/// *HWP FW Owner : Jamie Knight <[email protected]>
/// *HWP Team : IO
/// *HWP Level : 2
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
#ifndef _P9_IO_DMI_READ_EREPAIR_H_
#define _P9_IO_DMI_READ_EREPAIR_H_
// ----------------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------------
#include <fapi2.H>
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_io_dmi_read_erepair_FP_t)
(const fapi2::Target < fapi2::TARGET_TYPE_DMI >&, std::vector< uint8_t >&);
extern "C"
{
/**
* @brief A HWP that runs Read eRepair. This procedure reads the current bad
* lanes and passes by reference the lane numbers in a vector. The rx vectors
* will return to the caller ( PRD or e-repair ) the bad lane numbers on this
* endpoint. The caller will duplicate the found rx bad lanes to the
* corresponding tx bad lanes on the connected target.
* @param[in] i_target Reference to Target
* @param[out] o_bad_lanes Vector of bad lanes
* @retval ReturnCode
*/
fapi2::ReturnCode
p9_io_dmi_read_erepair(const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
std::vector< uint8_t >& o_bad_lanes);
} // extern "C"
#endif // _P9_IO_DMI_READ_EREPAIR_H_
<commit_msg>I/O Metadata Cleanup<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_dmi_read_erepair.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <[email protected]>
/// *HWP HWP Backup Owner : Gary Peterson <[email protected]>
/// *HWP FW Owner : Jamie Knight <[email protected]>
/// *HWP Team : IO
/// *HWP Level : 3
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
#ifndef _P9_IO_DMI_READ_EREPAIR_H_
#define _P9_IO_DMI_READ_EREPAIR_H_
// ----------------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------------
#include <fapi2.H>
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_io_dmi_read_erepair_FP_t)
(const fapi2::Target < fapi2::TARGET_TYPE_DMI >&, std::vector< uint8_t >&);
extern "C"
{
/**
* @brief A HWP that runs Read eRepair. This procedure reads the current bad
* lanes and passes by reference the lane numbers in a vector. The rx vectors
* will return to the caller ( PRD or e-repair ) the bad lane numbers on this
* endpoint. The caller will duplicate the found rx bad lanes to the
* corresponding tx bad lanes on the connected target.
* @param[in] i_target Reference to Target
* @param[out] o_bad_lanes Vector of bad lanes
* @retval ReturnCode
*/
fapi2::ReturnCode
p9_io_dmi_read_erepair(const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
std::vector< uint8_t >& o_bad_lanes);
} // extern "C"
#endif // _P9_IO_DMI_READ_EREPAIR_H_
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_attr_update.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_attr_update.H
/// @brief Programatic over-rides related to effective config
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP FW Owner: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_ATTR_UPDATE__
#define __P9_MSS_ATTR_UPDATE__
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_mss_attr_update_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);
extern "C"
{
///
/// @brief Programatic over-rides related to effective config
/// @param[in] i_target, the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_attr_update( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target );
}
#endif
<commit_msg>Add MSS customization support from CRP0 Lx MVPD<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_attr_update.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_attr_update.H
/// @brief Programatic over-rides related to effective config
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP FW Owner: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_ATTR_UPDATE__
#define __P9_MSS_ATTR_UPDATE__
#include <fapi2.H>
// Lx version 1 parsing/extraction constants
// section offsets
constexpr uint8_t Lx_V1_R_OFFSET_TO_F0S = 24;
constexpr uint8_t Lx_V1_R_OFFSET_TO_F1S = 82;
constexpr uint8_t Lx_V1_R_OFFSET_TO_F2S = 140;
constexpr uint8_t Lx_V1_R_OFFSET_TO_F3S = 198;
typedef fapi2::ReturnCode (*p9_mss_attr_update_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);
// Define some of the helper API so we can test them in CI
///
/// @brief Given target and memory frequency, return MVPD Lx keyword and
/// offset to first byte in frequency-specific customization section
/// @param[in] i_target the port target (e.g., MCA)
/// @param[out] o_keyword Lx keyword ID for this port
/// @param[out] o_s_offset frequency-specific section byte offset
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_attr_update_get_lx_offsets( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
fapi2::MvpdKeyword& o_keyword,
uint8_t& o_s_offset);
extern "C"
{
///
/// @brief Programatic over-rides related to effective config
/// @param[in] i_target, the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_attr_update( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target );
}
#endif
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_sbe_hb_structures.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------------
//
/// @file p9_sbe_hb_structures.H
/// @brief Structures that the SBE and HB will both use
//
// *HWP HWP Owner: Joshua Hannan [email protected]
// *HWP FW Owner: Thi Tran [email protected]
// *HWP Team: Nest
// *HWP Level: 3
// *HWP Consumed by: SBE, HB
//-----------------------------------------------------------------------------------
#ifndef _SBE_HB_STRUCTURES_H_
#define _SBE_HB_STRUCTURES_H_
//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------------
// Used for version checking as the BootloaderConfigData_t structure changes
enum SbeBootloaderVersion
{
// Keep initial version formatted as it was originally
INIT = 0x901,
// Later versions use format [release:2][version:2]
SAB_ADDED = 0x00090002,
MMIO_BARS_ADDED = 0x00090003,
};
union BootloaderSecureSettings
{
uint8_t data8;
struct
{
// Bit Breakdown - sync with ATTR_SECURE_SETTINGS
uint8_t reserved : 5; // reserved
uint8_t allowAttrOverrides : 1; // Allow Attribute Overrides in
// Secure Mode
uint8_t securityOverride : 1; // Security Override
uint8_t secureAccessBit : 1; // Secure Access Bit
} __attribute__((packed));
};
// Structure starts at the bootloader zero address
struct BootloaderConfigData_t
{
uint32_t version; // bytes 4:7 Version field so we know if there is new data being added
uint8_t sbeBootSide; // byte 8 0=SBE side 0, 1=SBE side 1 [ATTR_SBE_BOOT_SIDE]
uint8_t pnorBootSide; // byte 9 0=PNOR side A, 1=PNOR side B [ATTR_PNOR_BOOT_SIDE]
uint16_t pnorSizeMB; // bytes 10:11 Size of PNOR in MB [ATTR_PNOR_SIZE]
uint64_t blLoadSize; // bytes 12:19 Size of Load (Exception vectors and Bootloader)
BootloaderSecureSettings secureSettings ; // byte 20
uint64_t xscomBAR; // bytes 21:28 XSCOM MMIO BAR
uint64_t lpcBAR; // bytes 29:36 LPC MMIO BAR
};
#endif
<commit_msg>Fix alignment issues in SBE-HB structure<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_sbe_hb_structures.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------------
//
/// @file p9_sbe_hb_structures.H
/// @brief Structures that the SBE and HB will both use
//
// *HWP HWP Owner: Joshua Hannan [email protected]
// *HWP FW Owner: Thi Tran [email protected]
// *HWP Team: Nest
// *HWP Level: 3
// *HWP Consumed by: SBE, HB
//-----------------------------------------------------------------------------------
#ifndef _SBE_HB_STRUCTURES_H_
#define _SBE_HB_STRUCTURES_H_
//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------------
// Used for version checking as the BootloaderConfigData_t structure changes
enum SbeBootloaderVersion
{
// Keep initial version formatted as it was originally
INIT = 0x901,
// Later versions use format [release:2][version:2]
SAB_ADDED = 0x00090002,
MMIO_BARS_ADDED = 0x00090003,
};
union BootloaderSecureSettings
{
uint8_t data8;
struct
{
// Bit Breakdown - sync with ATTR_SECURE_SETTINGS
uint8_t reserved : 5; // reserved
uint8_t allowAttrOverrides : 1; // Allow Attribute Overrides in
// Secure Mode
uint8_t securityOverride : 1; // Security Override
uint8_t secureAccessBit : 1; // Secure Access Bit
} __attribute__((packed));
};
// Structure starts at the bootloader zero address
// Note - this structure must remain 64-bit aligned to
// maintain compatibility with Hostboot
struct BootloaderConfigData_t
{
uint32_t version; // bytes 4:7 Version field so we know if there is new data being added
uint8_t sbeBootSide; // byte 8 0=SBE side 0, 1=SBE side 1 [ATTR_SBE_BOOT_SIDE]
uint8_t pnorBootSide; // byte 9 0=PNOR side A, 1=PNOR side B [ATTR_PNOR_BOOT_SIDE]
uint16_t pnorSizeMB; // bytes 10:11 Size of PNOR in MB [ATTR_PNOR_SIZE]
uint64_t blLoadSize; // bytes 12:19 Size of Load (Exception vectors and Bootloader)
BootloaderSecureSettings secureSettings ; // byte 20
uint8_t reserved[7]; // bytes 21:27 Reserved space to maintain 64-bit alignment
uint64_t xscomBAR; // bytes 28:35 XSCOM MMIO BAR
uint64_t lpcBAR; // bytes 36:43 LPC MMIO BAR
}; // Note: Want to use '__attribute__((packed))' but compiler won't let us
#endif
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
/// 1) Identify Partical good chiplet and configure Multicasting register
/// 2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
/// 3) Similar way, set fence for Nest and MC chiplet
/// 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
///
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V. Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_
#include <fapi2.H>
namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
HANG_PULSE_0X10 = 0x10,
HANG_PULSE_0X0F = 0x0F,
HANG_PULSE_0X06 = 0x06,
HANG_PULSE_0X17 = 0x17,
HANG_PULSE_0X18 = 0x18,
HANG_PULSE_0X22 = 0x22,
HANG_PULSE_0X13 = 0x13,
HANG_PULSE_0X03 = 0x03,
OPCG_ALIGN_SETTING = 0x5000000000003020ull,
INOP_ALIGN_SETTING_0X5 = 0x5,
OPCG_WAIT_CYCLE_0X020 = 0x020,
SCAN_RATIO_0X3 = 0x3,
SYNC_PULSE_DELAY_0X0 = 0X00,
SYNC_CONFIG_DEFAULT = 0X0000000000000000,
HANG_PULSE_0X00 = 0x00,
HANG_PULSE_0X01 = 0x01,
HANG_PULSE_0X04 = 0x04,
HANG_PULSE_0X1A = 0x1A,
NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
REGIONS_EXCEPT_VITAL = 0x7FF,
SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
SCAN_TYPES_TIME_GPTR_REPR = 0x230,
SCAN_RATIO_0X0 = 0x0,
SYNC_CONFIG_4TO1 = 0X0800000000000000,
HW_NS_DELAY = 200000, // unit is nano seconds
SIM_CYCLE_DELAY = 10000, // unit is cycles
HANG_PULSE_0X12 = 0x12,
HANG_PULSE_0X1C = 0x1C
};
}
typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Identify all good chiplets excluding EQ/EC
/// -- All chiplets will be reset and PLLs started
/// -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
/// -- Can't use the multicast for all non-nest chiplets
/// -- This is intended to be the eventual product setting
/// -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
/// -- Reset to default state
/// -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
/// -- Start vital clocks and release endpoint reset
/// -- PCB Slave error register Reset
///
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_sbe_chiplet_reset(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<commit_msg>partial good/hang pulse updates to support all sim models/clock ratios<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
/// 1) Identify Partical good chiplet and configure Multicasting register
/// 2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
/// 3) Similar way, set fence for Nest and MC chiplet
/// 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
///
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V. Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_
#include <fapi2.H>
namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
HANG_PULSE_0X10 = 0x10,
HANG_PULSE_0X0F = 0x0F,
HANG_PULSE_0X06 = 0x06,
HANG_PULSE_0X17 = 0x17,
HANG_PULSE_0X18 = 0x18,
HANG_PULSE_0X22 = 0x22,
HANG_PULSE_0X13 = 0x13,
HANG_PULSE_0X03 = 0x03,
OPCG_ALIGN_SETTING = 0x5000000000003020ull,
INOP_ALIGN_SETTING_0X5 = 0x5,
OPCG_WAIT_CYCLE_0X020 = 0x020,
SCAN_RATIO_0X3 = 0x3,
SYNC_PULSE_DELAY_0X0 = 0X00,
SYNC_CONFIG_DEFAULT = 0X0000000000000000,
HANG_PULSE_0X00 = 0x00,
HANG_PULSE_0X01 = 0x01,
HANG_PULSE_0X04 = 0x04,
HANG_PULSE_0X1A = 0x1A,
HANG_PULSE_0X08 = 0x08,
NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
REGIONS_EXCEPT_VITAL = 0x7FF,
SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
SCAN_TYPES_TIME_GPTR_REPR = 0x230,
SCAN_RATIO_0X0 = 0x0,
SYNC_CONFIG_4TO1 = 0X0800000000000000,
HW_NS_DELAY = 200000, // unit is nano seconds
SIM_CYCLE_DELAY = 10000, // unit is cycles
HANG_PULSE_0X12 = 0x12,
HANG_PULSE_0X1C = 0x1C
};
}
typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Identify all good chiplets excluding EQ/EC
/// -- All chiplets will be reset and PLLs started
/// -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
/// -- Can't use the multicast for all non-nest chiplets
/// -- This is intended to be the eventual product setting
/// -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
/// -- Reset to default state
/// -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
/// -- Start vital clocks and release endpoint reset
/// -- PCB Slave error register Reset
///
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_sbe_chiplet_reset(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Made ISO parsing in DateTime more flexible<commit_after><|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_set_fsi_gp_shadow.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_set_fsi_gp_shadow.C
///
/// @brief --IPL step 0.8 proc_prep_ipl
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_set_fsi_gp_shadow.H"
//## auto_generated
#include "p9_const_common.H"
#include <p9_perv_scom_addresses.H>
fapi2::ReturnCode p9_set_fsi_gp_shadow(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
fapi2::buffer<uint8_t> l_read_attr;
fapi2::buffer<uint32_t> l_cfam_data;
FAPI_INF("p9_set_fsi_gp_shadow: Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip,
l_read_attr));
if ( l_read_attr )
{
FAPI_DBG("Setting flush values for root_ctrl_copy and perv_ctrl_copy registers");
//Setting ROOT_CTRL0_COPY register value
//CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE));
//Setting ROOT_CTRL1_COPY register value
//CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE));
//Setting ROOT_CTRL2_COPY register value
//CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE));
//Setting ROOT_CTRL3_COPY register value
//CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE));
//Setting ROOT_CTRL4_COPY register value
//CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE));
//Setting ROOT_CTRL5_COPY register value
//CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
l_cfam_data));
l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) |
p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE;
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
l_cfam_data));
//Setting ROOT_CTRL6_COPY register value
//CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
l_cfam_data));
l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) |
p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE;
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
l_cfam_data));
//Setting ROOT_CTRL7_COPY register value
//CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE));
//Setting ROOT_CTRL8_COPY register value
//CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
l_cfam_data));
l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) |
p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE;
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
l_cfam_data));
//Setting PERV_CTRL0_COPY register value
//CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI,
p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE));
//Setting PERV_CTRL1_COPY register value
//CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI,
p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE));
}
FAPI_INF("p9_set_fsi_gp_shadow: Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Propagate "fused_core" IPL option into PU chip<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_set_fsi_gp_shadow.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_set_fsi_gp_shadow.C
///
/// @brief --IPL step 0.8 proc_prep_ipl
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_set_fsi_gp_shadow.H"
//## auto_generated
#include "p9_const_common.H"
#include <p9_perv_scom_addresses.H>
#include <p9n2_perv_scom_addresses_fld.H>
fapi2::ReturnCode p9_set_fsi_gp_shadow(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
fapi2::buffer<uint8_t> l_read_attr;
fapi2::buffer<uint32_t> l_cfam_data;
FAPI_INF("p9_set_fsi_gp_shadow: Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip,
l_read_attr));
if ( l_read_attr )
{
FAPI_DBG("Setting flush values for root_ctrl_copy and perv_ctrl_copy registers");
//Setting ROOT_CTRL0_COPY register value
//CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE));
//Setting ROOT_CTRL1_COPY register value
//CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE));
//Setting ROOT_CTRL2_COPY register value
//CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE));
//Setting ROOT_CTRL3_COPY register value
//CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE));
//Setting ROOT_CTRL4_COPY register value
//CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE));
//Setting ROOT_CTRL5_COPY register value
//CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
l_cfam_data));
l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) |
p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE;
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,
l_cfam_data));
//Setting ROOT_CTRL6_COPY register value
//CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
l_cfam_data));
l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) |
p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE;
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,
l_cfam_data));
//Setting ROOT_CTRL7_COPY register value
//CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI,
p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE));
//Setting ROOT_CTRL8_COPY register value
//CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
l_cfam_data));
l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) |
p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE;
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,
l_cfam_data));
//Setting PERV_CTRL0_COPY register value
//CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI,
p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE));
//Setting PERV_CTRL1_COPY register value
//CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI,
p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE));
}
/* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 */
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_read_attr));
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));
if (l_read_attr)
{
l_cfam_data.setBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>();
}
else
{
l_cfam_data.clearBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>();
}
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));
FAPI_INF("p9_set_fsi_gp_shadow: Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before><commit_msg>arch-riscv: reduced lr/sc implementation<commit_after><|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <utility>
#include <vector>
#include "absl/strings/match.h"
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/global_data.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/types.h"
namespace xla {
namespace {
// An enumerator for the client types that we want to iterate over in
// the various tests.
enum class ClientType { kLocal, kCompileOnly };
ClientType client_types[] = {ClientType::kLocal, ClientType::kCompileOnly};
class ComputeConstantTest : public ::testing::Test {
public:
explicit ComputeConstantTest(se::Platform* platform = nullptr)
: platform_(platform) {}
string TestName() const {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
Client* ClientOrDie(se::Platform* platform, ClientType client_type) {
if (client_type == ClientType::kLocal) {
StatusOr<Client*> result =
ClientLibrary::GetOrCreateLocalClient(platform);
TF_CHECK_OK(result.status())
<< "could not create LocalClient for testing";
return result.ValueOrDie();
} else if (client_type == ClientType::kCompileOnly) {
StatusOr<Client*> result =
ClientLibrary::GetOrCreateCompileOnlyClient(platform);
TF_CHECK_OK(result.status())
<< "could not create CompileOnlyClient for testing";
return result.ValueOrDie();
}
LOG(FATAL) << "invalid client_type value";
}
StatusOr<Literal> ComputeConstantLiteral(Client* client, const XlaOp& operand,
XlaBuilder* builder,
Layout* output_layout = nullptr) {
TF_ASSIGN_OR_RETURN(auto subgraph, builder->BuildConstantSubGraph(operand));
TF_ASSIGN_OR_RETURN(auto computed,
client->ComputeConstant(subgraph, output_layout));
return std::move(computed);
}
template <class Scalar>
StatusOr<Scalar> ComputeConstantScalar(Client* client, const XlaOp& operand,
XlaBuilder* builder) {
TF_ASSIGN_OR_RETURN(auto literal, ComputeConstantLiteral(client, operand,
builder, nullptr));
return literal.Get<Scalar>({});
}
bool IsConstant(const XlaOp& operand, XlaBuilder* builder) {
StatusOr<bool> result = builder->IsConstant(operand);
EXPECT_TRUE(result.ok()) << result.status();
return result.ok() ? result.ValueOrDie() : false;
}
se::Platform* platform_;
};
TEST_F(ComputeConstantTest, ScalarInt32Literal) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation = ConstantR0<int32>(&b, 42);
EXPECT_TRUE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<int32>(client, computation, &b);
ASSERT_TRUE(value.ok()) << value.status();
EXPECT_EQ(value.ValueOrDie(), 42);
}
}
TEST_F(ComputeConstantTest, ScalarFloatAdd) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation =
Add(ConstantR0<float>(&b, 42.5f), ConstantR0<float>(&b, 1.5f));
EXPECT_TRUE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<float>(client, computation, &b);
ASSERT_TRUE(value.ok()) << value.status();
EXPECT_EQ(value.ValueOrDie(), 44.0f);
}
}
TEST_F(ComputeConstantTest, ScalarRng) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation =
RngUniform(ConstantR0<float>(&b, 1.1f), ConstantR0<float>(&b, 2.1f),
ShapeUtil::MakeShape(F32, {}));
EXPECT_FALSE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<float>(client, computation, &b);
ASSERT_FALSE(value.ok())
<< "computing a RNG value should not be considered a constant";
}
}
TEST_F(ComputeConstantTest, DirectParamMissing) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {}), "param");
EXPECT_FALSE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<float>(client, computation, &b);
EXPECT_TRUE(
absl::StrContains(value.status().ToString(), "depends on a parameter"))
<< value.status();
}
}
TEST_F(ComputeConstantTest, GetDimensionSize) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto add =
Add(ConstantR1<float>(&b, {1.0f}), ConstantR1<float>(&b, {1.0f}));
auto get_dimension_size = GetDimensionSize(add, 0);
EXPECT_TRUE(IsConstant(get_dimension_size, &b));
TF_ASSERT_OK_AND_ASSIGN(auto value, ComputeConstantScalar<uint32>(
client, get_dimension_size, &b));
EXPECT_EQ(value, 1);
}
}
TEST_F(ComputeConstantTest, MultipleGetDimensionSize) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto add =
Add(ConstantR2<float>(&b, {{1.0f}}), ConstantR2<float>(&b, {{1.0f}}));
auto get_dimension_size = GetDimensionSize(add, 0);
auto get_dimension_size_2 = GetDimensionSize(add, 0);
auto add_2 = Add(get_dimension_size, get_dimension_size_2);
EXPECT_TRUE(IsConstant(add_2, &b));
TF_ASSERT_OK_AND_ASSIGN(auto value,
ComputeConstantScalar<uint32>(client, add_2, &b));
EXPECT_EQ(value, 2);
}
}
// Test computation of an expression interspersed with param nodes but
// the expression does not depend on the param nodes.
TEST_F(ComputeConstantTest, UnrelatedParam) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto param_a = Parameter(&b, 10, ShapeUtil::MakeShape(F32, {}), "param0");
auto constant_4 =
Add(ConstantR0<float>(&b, 2.5f), ConstantR0<float>(&b, 1.5f));
auto not_constant_a = Add(constant_4, param_a);
auto param_b = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {}), "param1");
auto constant_9 =
Mul(ConstantR0<float>(&b, 2.0f), ConstantR0<float>(&b, 4.5f));
auto not_constant_b = Add(param_b, constant_9);
auto constant_13 = Add(constant_4, constant_9);
Add(not_constant_b, Add(constant_13, not_constant_a));
EXPECT_TRUE(IsConstant(constant_13, &b));
TF_ASSERT_OK_AND_ASSIGN(
auto value, ComputeConstantScalar<float>(client, constant_13, &b));
EXPECT_EQ(value, 13.0f);
}
}
TEST_F(ComputeConstantTest, NonScalarAdd) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation =
Add(ConstantR1<int32>(&b, {1, 2}), ConstantR1<int32>(&b, {3, 4}));
EXPECT_TRUE(IsConstant(computation, &b));
TF_ASSERT_OK_AND_ASSIGN(auto computed,
ComputeConstantLiteral(client, computation, &b));
Literal expected_literal = LiteralUtil::CreateR1<int32>({4, 6});
EXPECT_TRUE(LiteralTestUtil::Equal(expected_literal, computed));
}
}
TEST_F(ComputeConstantTest, IntegerDivide) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation = Div(ConstantR0<int32>(&b, 15), ConstantR0<int32>(&b, 3));
EXPECT_TRUE(IsConstant(computation, &b));
TF_ASSERT_OK_AND_ASSIGN(auto computed,
ComputeConstantLiteral(client, computation, &b));
Literal expected_literal = LiteralUtil::CreateR0<int32>(5);
EXPECT_TRUE(LiteralTestUtil::Equal(expected_literal, computed));
}
}
XLA_TEST_F(ComputeConstantTest, Layout) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
std::vector<std::vector<int64>> layouts = {{0, 1}, {1, 0}};
for (const std::vector<int64>& layout : layouts) {
auto layout_proto = LayoutUtil::MakeLayout(layout);
TF_ASSERT_OK_AND_ASSIGN(
auto computed, ComputeConstantLiteral(
client,
Add(ConstantR2<int32>(&b, {{1, 2}, {3, 4}}),
ConstantR2<int32>(&b, {{10, 20}, {30, 40}})),
&b, &layout_proto));
Literal expected_literal = LiteralUtil::CreateR2WithLayout<int32>(
{{11, 22}, {33, 44}}, LayoutUtil::MakeLayout(layout));
ASSERT_TRUE(LiteralTestUtil::EqualShapesAndLayouts(
expected_literal.shape(), computed.shape()));
EXPECT_TRUE(LiteralTestUtil::Equal(expected_literal, computed));
}
}
}
} // namespace
} // namespace xla
<commit_msg>Fix compute constant test<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <utility>
#include <vector>
#include "absl/strings/match.h"
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/global_data.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/types.h"
namespace xla {
namespace {
// An enumerator for the client types that we want to iterate over in
// the various tests.
enum class ClientType { kLocal, kCompileOnly };
ClientType client_types[] = {ClientType::kLocal, ClientType::kCompileOnly};
class ComputeConstantTest : public ::testing::Test {
public:
explicit ComputeConstantTest(se::Platform* platform = nullptr)
: platform_(platform) {}
string TestName() const {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
Client* ClientOrDie(se::Platform* platform, ClientType client_type) {
if (client_type == ClientType::kLocal) {
StatusOr<Client*> result =
ClientLibrary::GetOrCreateLocalClient(platform);
TF_CHECK_OK(result.status())
<< "could not create LocalClient for testing";
return result.ValueOrDie();
} else if (client_type == ClientType::kCompileOnly) {
StatusOr<Client*> result =
ClientLibrary::GetOrCreateCompileOnlyClient(platform);
TF_CHECK_OK(result.status())
<< "could not create CompileOnlyClient for testing";
return result.ValueOrDie();
}
LOG(FATAL) << "invalid client_type value";
}
StatusOr<Literal> ComputeConstantLiteral(Client* client, const XlaOp& operand,
XlaBuilder* builder,
Layout* output_layout = nullptr) {
TF_ASSIGN_OR_RETURN(auto subgraph, builder->BuildConstantSubGraph(operand));
TF_ASSIGN_OR_RETURN(auto computed,
client->ComputeConstant(subgraph, output_layout));
return std::move(computed);
}
template <class Scalar>
StatusOr<Scalar> ComputeConstantScalar(Client* client, const XlaOp& operand,
XlaBuilder* builder) {
TF_ASSIGN_OR_RETURN(auto literal, ComputeConstantLiteral(client, operand,
builder, nullptr));
return literal.Get<Scalar>({});
}
bool IsConstant(const XlaOp& operand, XlaBuilder* builder) {
StatusOr<bool> result = builder->IsConstant(operand);
EXPECT_TRUE(result.ok()) << result.status();
return result.ok() ? result.ValueOrDie() : false;
}
se::Platform* platform_;
};
TEST_F(ComputeConstantTest, ScalarInt32Literal) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation = ConstantR0<int32>(&b, 42);
EXPECT_TRUE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<int32>(client, computation, &b);
ASSERT_TRUE(value.ok()) << value.status();
EXPECT_EQ(value.ValueOrDie(), 42);
}
}
TEST_F(ComputeConstantTest, ScalarFloatAdd) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation =
Add(ConstantR0<float>(&b, 42.5f), ConstantR0<float>(&b, 1.5f));
EXPECT_TRUE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<float>(client, computation, &b);
ASSERT_TRUE(value.ok()) << value.status();
EXPECT_EQ(value.ValueOrDie(), 44.0f);
}
}
TEST_F(ComputeConstantTest, ScalarRng) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation =
RngUniform(ConstantR0<float>(&b, 1.1f), ConstantR0<float>(&b, 2.1f),
ShapeUtil::MakeShape(F32, {}));
EXPECT_FALSE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<float>(client, computation, &b);
ASSERT_FALSE(value.ok())
<< "computing a RNG value should not be considered a constant";
}
}
TEST_F(ComputeConstantTest, DirectParamMissing) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {}), "param");
EXPECT_FALSE(IsConstant(computation, &b));
auto value = ComputeConstantScalar<float>(client, computation, &b);
EXPECT_TRUE(
absl::StrContains(value.status().ToString(), "depends on a parameter"))
<< value.status();
}
}
TEST_F(ComputeConstantTest, GetDimensionSize) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto add =
Add(ConstantR1<float>(&b, {1.0f}), ConstantR1<float>(&b, {1.0f}));
auto get_dimension_size = GetDimensionSize(add, 0);
EXPECT_TRUE(IsConstant(get_dimension_size, &b));
TF_ASSERT_OK_AND_ASSIGN(auto value, ComputeConstantScalar<int32>(
client, get_dimension_size, &b));
EXPECT_EQ(value, 1);
}
}
TEST_F(ComputeConstantTest, MultipleGetDimensionSize) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto add =
Add(ConstantR2<float>(&b, {{1.0f}}), ConstantR2<float>(&b, {{1.0f}}));
auto get_dimension_size = GetDimensionSize(add, 0);
auto get_dimension_size_2 = GetDimensionSize(add, 0);
auto add_2 = Add(get_dimension_size, get_dimension_size_2);
EXPECT_TRUE(IsConstant(add_2, &b));
TF_ASSERT_OK_AND_ASSIGN(auto value,
ComputeConstantScalar<int32>(client, add_2, &b));
EXPECT_EQ(value, 2);
}
}
// Test computation of an expression interspersed with param nodes but
// the expression does not depend on the param nodes.
TEST_F(ComputeConstantTest, UnrelatedParam) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto param_a = Parameter(&b, 10, ShapeUtil::MakeShape(F32, {}), "param0");
auto constant_4 =
Add(ConstantR0<float>(&b, 2.5f), ConstantR0<float>(&b, 1.5f));
auto not_constant_a = Add(constant_4, param_a);
auto param_b = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {}), "param1");
auto constant_9 =
Mul(ConstantR0<float>(&b, 2.0f), ConstantR0<float>(&b, 4.5f));
auto not_constant_b = Add(param_b, constant_9);
auto constant_13 = Add(constant_4, constant_9);
Add(not_constant_b, Add(constant_13, not_constant_a));
EXPECT_TRUE(IsConstant(constant_13, &b));
TF_ASSERT_OK_AND_ASSIGN(
auto value, ComputeConstantScalar<float>(client, constant_13, &b));
EXPECT_EQ(value, 13.0f);
}
}
TEST_F(ComputeConstantTest, NonScalarAdd) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation =
Add(ConstantR1<int32>(&b, {1, 2}), ConstantR1<int32>(&b, {3, 4}));
EXPECT_TRUE(IsConstant(computation, &b));
TF_ASSERT_OK_AND_ASSIGN(auto computed,
ComputeConstantLiteral(client, computation, &b));
Literal expected_literal = LiteralUtil::CreateR1<int32>({4, 6});
EXPECT_TRUE(LiteralTestUtil::Equal(expected_literal, computed));
}
}
TEST_F(ComputeConstantTest, IntegerDivide) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
auto computation = Div(ConstantR0<int32>(&b, 15), ConstantR0<int32>(&b, 3));
EXPECT_TRUE(IsConstant(computation, &b));
TF_ASSERT_OK_AND_ASSIGN(auto computed,
ComputeConstantLiteral(client, computation, &b));
Literal expected_literal = LiteralUtil::CreateR0<int32>(5);
EXPECT_TRUE(LiteralTestUtil::Equal(expected_literal, computed));
}
}
XLA_TEST_F(ComputeConstantTest, Layout) {
for (ClientType client_type : client_types) {
Client* client = ClientOrDie(platform_, client_type);
XlaBuilder b(TestName());
std::vector<std::vector<int64>> layouts = {{0, 1}, {1, 0}};
for (const std::vector<int64>& layout : layouts) {
auto layout_proto = LayoutUtil::MakeLayout(layout);
TF_ASSERT_OK_AND_ASSIGN(
auto computed, ComputeConstantLiteral(
client,
Add(ConstantR2<int32>(&b, {{1, 2}, {3, 4}}),
ConstantR2<int32>(&b, {{10, 20}, {30, 40}})),
&b, &layout_proto));
Literal expected_literal = LiteralUtil::CreateR2WithLayout<int32>(
{{11, 22}, {33, 44}}, LayoutUtil::MakeLayout(layout));
ASSERT_TRUE(LiteralTestUtil::EqualShapesAndLayouts(
expected_literal.shape(), computed.shape()));
EXPECT_TRUE(LiteralTestUtil::Equal(expected_literal, computed));
}
}
}
} // namespace
} // namespace xla
<|endoftext|>
|
<commit_before>/**
* The goal of these tests is to verify the behavior of all blob commands given
* the current state is verificationCompleted. This state is achieved as a out
* of verificationStarted.
*/
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include "status.hpp"
#include "util.hpp"
#include <cstdint>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace ipmi_flash
{
namespace
{
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::UnorderedElementsAreArray;
/*
* There are the following calls (parameters may vary):
* canHandleBlob(blob)
* getBlobIds
* deleteBlob(blob)
* stat(blob)
* stat(session)
* open(blob)
* close(session)
* writemeta(session)
* write(session)
* read(session)
* commit(session)
*
* Like the state verificationStarted, there is a file open in
* verificationCompleted. This state is transitioned to after a stat() command
* indicates a successful verification.
*/
class FirmwareHandlerVerificationCompletedTest
: public IpmiOnlyFirmwareStaticTest
{
protected:
void getToVerificationCompleted(VerifyCheckResponses checkResponse)
{
/* The hash was not sent up, as it's technically optional. Therefore,
* there is no active hash file.
*/
EXPECT_CALL(imageMock, open(staticLayoutBlobId)).WillOnce(Return(true));
EXPECT_TRUE(handler->open(session, flags, staticLayoutBlobId));
expectedState(FirmwareBlobHandler::UpdateState::uploadInProgress);
EXPECT_CALL(imageMock, close()).WillRepeatedly(Return());
handler->close(session);
expectedState(FirmwareBlobHandler::UpdateState::verificationPending);
EXPECT_TRUE(handler->open(session, flags, verifyBlobId));
EXPECT_CALL(*verifyMockPtr, triggerVerification())
.WillOnce(Return(true));
EXPECT_TRUE(handler->commit(session, {}));
expectedState(FirmwareBlobHandler::UpdateState::verificationStarted);
EXPECT_CALL(*verifyMockPtr, checkVerificationState())
.WillOnce(Return(checkResponse));
blobs::BlobMeta meta;
EXPECT_TRUE(handler->stat(session, &meta));
expectedState(FirmwareBlobHandler::UpdateState::verificationCompleted);
}
std::uint16_t session = 1;
std::uint16_t flags =
blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;
};
/* TODO: deleteBlob(blob) */
/*
* canHandleBlob
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
OnVerificationCompleteSuccessUpdateBlobIdNotPresent)
{
/* the uploadBlobId is only added on close() of the verifyBlobId. This is a
* consistent behavior with verifyBlobId only added when closing the image
* or hash.
*/
getToVerificationCompleted(VerifyCheckResponses::success);
EXPECT_FALSE(handler->canHandleBlob(updateBlobId));
}
TEST_F(FirmwareHandlerVerificationCompletedTest,
OnVerificationCompleteFailureUpdateBlobIdNotPresent)
{
getToVerificationCompleted(VerifyCheckResponses::failed);
EXPECT_FALSE(handler->canHandleBlob(updateBlobId));
}
/*
* getBlobIds
*/
TEST_F(FirmwareHandlerVerificationCompletedTest, GetBlobIdsReturnsExpectedList)
{
getToVerificationCompleted(VerifyCheckResponses::success);
std::vector<std::string> expected = {verifyBlobId, hashBlobId,
activeImageBlobId, staticLayoutBlobId};
EXPECT_THAT(handler->getBlobIds(), UnorderedElementsAreArray(expected));
}
/*
* stat(blob)
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
StatOnActiveImageReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationCompletedTest,
VerifyActiveHashIdMissingInThisCase)
{
/* The path taken to get to this state never opened the hash blob Id, which
* is fine. But let's verify it behaved as intended.
*/
getToVerificationCompleted(VerifyCheckResponses::success);
EXPECT_FALSE(handler->canHandleBlob(activeHashBlobId));
}
/* TODO: Add sufficient warning that you can get to verificationCompleted
* without ever opening the image blob id (or the tarball one).
*
* Although in this case, it's expected that any verification triggered would
* certainly fail. So, although it's possible, it's uninteresting.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest, StatOnVerifyBlobReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(verifyBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationCompletedTest,
StatOnNormalBlobsReturnsSuccess)
{
getToVerificationCompleted(VerifyCheckResponses::success);
blobs::BlobMeta expected;
expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
expected.size = 0;
std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
for (const auto& blob : testBlobs)
{
ASSERT_TRUE(handler->canHandleBlob(blob));
blobs::BlobMeta meta = {};
EXPECT_TRUE(handler->stat(blob, &meta));
EXPECT_EQ(expected, meta);
}
}
/*
* stat(session) - the verify blobid is open in this state, so stat on that once
* completed should have no effect.
*/
/*
* open(blob) - all open should fail
*/
/*
* writemeta(session) - write meta should fail.
*/
/*
* write(session) - write should fail.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
WriteToVerifyBlobReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->write(session, 0, bytes));
}
/*
* read(session) - read returns empty.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest, ReadOfVerifyBlobReturnsEmpty)
{
getToVerificationCompleted(VerifyCheckResponses::success);
EXPECT_THAT(handler->read(session, 0, 1), IsEmpty());
}
/*
* commit(session) - ?
*/
/*
* close(session) - close on the verify blobid:
* 1. if successful adds update blob id, changes state to UpdatePending
* 2. if unsuccessful doesn't add update blob id, changes state to?
*/
} // namespace
} // namespace ipmi_flash
<commit_msg>test: firmware verificationCompleted: writeMeta<commit_after>/**
* The goal of these tests is to verify the behavior of all blob commands given
* the current state is verificationCompleted. This state is achieved as a out
* of verificationStarted.
*/
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include "status.hpp"
#include "util.hpp"
#include <cstdint>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace ipmi_flash
{
namespace
{
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::UnorderedElementsAreArray;
/*
* There are the following calls (parameters may vary):
* canHandleBlob(blob)
* getBlobIds
* deleteBlob(blob)
* stat(blob)
* stat(session)
* open(blob)
* close(session)
* writemeta(session)
* write(session)
* read(session)
* commit(session)
*
* Like the state verificationStarted, there is a file open in
* verificationCompleted. This state is transitioned to after a stat() command
* indicates a successful verification.
*/
class FirmwareHandlerVerificationCompletedTest
: public IpmiOnlyFirmwareStaticTest
{
protected:
void getToVerificationCompleted(VerifyCheckResponses checkResponse)
{
/* The hash was not sent up, as it's technically optional. Therefore,
* there is no active hash file.
*/
EXPECT_CALL(imageMock, open(staticLayoutBlobId)).WillOnce(Return(true));
EXPECT_TRUE(handler->open(session, flags, staticLayoutBlobId));
expectedState(FirmwareBlobHandler::UpdateState::uploadInProgress);
EXPECT_CALL(imageMock, close()).WillRepeatedly(Return());
handler->close(session);
expectedState(FirmwareBlobHandler::UpdateState::verificationPending);
EXPECT_TRUE(handler->open(session, flags, verifyBlobId));
EXPECT_CALL(*verifyMockPtr, triggerVerification())
.WillOnce(Return(true));
EXPECT_TRUE(handler->commit(session, {}));
expectedState(FirmwareBlobHandler::UpdateState::verificationStarted);
EXPECT_CALL(*verifyMockPtr, checkVerificationState())
.WillOnce(Return(checkResponse));
blobs::BlobMeta meta;
EXPECT_TRUE(handler->stat(session, &meta));
expectedState(FirmwareBlobHandler::UpdateState::verificationCompleted);
}
std::uint16_t session = 1;
std::uint16_t flags =
blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;
};
/* TODO: deleteBlob(blob) */
/*
* canHandleBlob
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
OnVerificationCompleteSuccessUpdateBlobIdNotPresent)
{
/* the uploadBlobId is only added on close() of the verifyBlobId. This is a
* consistent behavior with verifyBlobId only added when closing the image
* or hash.
*/
getToVerificationCompleted(VerifyCheckResponses::success);
EXPECT_FALSE(handler->canHandleBlob(updateBlobId));
}
TEST_F(FirmwareHandlerVerificationCompletedTest,
OnVerificationCompleteFailureUpdateBlobIdNotPresent)
{
getToVerificationCompleted(VerifyCheckResponses::failed);
EXPECT_FALSE(handler->canHandleBlob(updateBlobId));
}
/*
* getBlobIds
*/
TEST_F(FirmwareHandlerVerificationCompletedTest, GetBlobIdsReturnsExpectedList)
{
getToVerificationCompleted(VerifyCheckResponses::success);
std::vector<std::string> expected = {verifyBlobId, hashBlobId,
activeImageBlobId, staticLayoutBlobId};
EXPECT_THAT(handler->getBlobIds(), UnorderedElementsAreArray(expected));
}
/*
* stat(blob)
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
StatOnActiveImageReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationCompletedTest,
VerifyActiveHashIdMissingInThisCase)
{
/* The path taken to get to this state never opened the hash blob Id, which
* is fine. But let's verify it behaved as intended.
*/
getToVerificationCompleted(VerifyCheckResponses::success);
EXPECT_FALSE(handler->canHandleBlob(activeHashBlobId));
}
/* TODO: Add sufficient warning that you can get to verificationCompleted
* without ever opening the image blob id (or the tarball one).
*
* Although in this case, it's expected that any verification triggered would
* certainly fail. So, although it's possible, it's uninteresting.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest, StatOnVerifyBlobReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(verifyBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationCompletedTest,
StatOnNormalBlobsReturnsSuccess)
{
getToVerificationCompleted(VerifyCheckResponses::success);
blobs::BlobMeta expected;
expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
expected.size = 0;
std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
for (const auto& blob : testBlobs)
{
ASSERT_TRUE(handler->canHandleBlob(blob));
blobs::BlobMeta meta = {};
EXPECT_TRUE(handler->stat(blob, &meta));
EXPECT_EQ(expected, meta);
}
}
/*
* stat(session) - the verify blobid is open in this state, so stat on that once
* completed should have no effect.
*/
/*
* open(blob) - all open should fail
*/
/*
* writemeta(session) - write meta should fail.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
WriteMetaToVerifyBlobReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->writeMeta(session, 0, bytes));
}
/*
* write(session) - write should fail.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest,
WriteToVerifyBlobReturnsFailure)
{
getToVerificationCompleted(VerifyCheckResponses::success);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->write(session, 0, bytes));
}
/*
* read(session) - read returns empty.
*/
TEST_F(FirmwareHandlerVerificationCompletedTest, ReadOfVerifyBlobReturnsEmpty)
{
getToVerificationCompleted(VerifyCheckResponses::success);
EXPECT_THAT(handler->read(session, 0, 1), IsEmpty());
}
/*
* commit(session) - ?
*/
/*
* close(session) - close on the verify blobid:
* 1. if successful adds update blob id, changes state to UpdatePending
* 2. if unsuccessful doesn't add update blob id, changes state to?
*/
} // namespace
} // namespace ipmi_flash
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "reports/ReportBuilder.h"
#include "reports/JoinedQueryTableSource.h"
#include "reports/CTRByPositionReport.h"
#include "reports/CTRReport.h"
#include "reports/CTRCounterMerge.h"
#include "reports/CTRCounterTableSink.h"
#include "reports/CTRCounterTableSource.h"
using namespace fnord;
using namespace cm;
Set<uint64_t> mkGenerations(
uint64_t window_secs,
uint64_t range_secs,
uint64_t now_secs = 0) {
Set<uint64_t> generations;
auto now = now_secs == 0 ? WallClock::unixMicros() : now_secs * kMicrosPerSecond;
auto gen_window = kMicrosPerSecond * window_secs;
for (uint64_t i = 1; i < kMicrosPerSecond * range_secs; i += gen_window) {
generations.emplace((now - i) / gen_window);
}
return generations;
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"artifacts",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
fnord::fts::Analyzer analyzer(flags.getString("conf"));
cm::ReportBuilder report_builder;
auto dir = flags.getString("artifacts");
/* 4 hourly reports */
for (const auto& g : mkGenerations(
4 * kSecondsPerHour,
60 * kSecondsPerDay)) {
/* dawanda: map joined queries */
auto jq_source = new JoinedQueryTableSource(
StringUtil::format("$0/dawanda_joined_queries.$1.sstable", dir, g));
report_builder.addReport(
new CTRByPositionReport(
jq_source,
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_by_position.$1.sstable",
dir,
g)),
ItemEligibility::ALL));
report_builder.addReport(
new CTRReport(
jq_source,
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_stats.$1.sstable",
dir,
g)),
ItemEligibility::ALL));
}
/* daily reports */
for (const auto& og : mkGenerations(
1 * kSecondsPerDay,
60 * kSecondsPerDay)) {
auto day_gens = mkGenerations(
4 * kSecondsPerHour,
1 * kSecondsPerDay,
og * kSecondsPerDay);
/* dawanda: roll up ctr positions */
Set<String> ctr_posi_sources;
for (const auto& ig : day_gens) {
ctr_posi_sources.emplace(
StringUtil::format("$0/dawanda_ctr_by_position.$1.sstable", dir, ig));
}
report_builder.addReport(
new CTRCounterMerge(
new CTRCounterTableSource(ctr_posi_sources),
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_by_position_daily.$1.sstable",
dir,
og))));
}
report_builder.buildAll();
return 0;
}
<commit_msg>roll up daily ctrstats<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "reports/ReportBuilder.h"
#include "reports/JoinedQueryTableSource.h"
#include "reports/CTRByPositionReport.h"
#include "reports/CTRReport.h"
#include "reports/CTRCounterMerge.h"
#include "reports/CTRCounterTableSink.h"
#include "reports/CTRCounterTableSource.h"
using namespace fnord;
using namespace cm;
Set<uint64_t> mkGenerations(
uint64_t window_secs,
uint64_t range_secs,
uint64_t now_secs = 0) {
Set<uint64_t> generations;
auto now = now_secs == 0 ? WallClock::unixMicros() : now_secs * kMicrosPerSecond;
auto gen_window = kMicrosPerSecond * window_secs;
for (uint64_t i = 1; i < kMicrosPerSecond * range_secs; i += gen_window) {
generations.emplace((now - i) / gen_window);
}
return generations;
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"artifacts",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
fnord::fts::Analyzer analyzer(flags.getString("conf"));
cm::ReportBuilder report_builder;
auto dir = flags.getString("artifacts");
/* 4 hourly reports */
for (const auto& g : mkGenerations(
4 * kSecondsPerHour,
60 * kSecondsPerDay)) {
/* dawanda: map joined queries */
auto jq_source = new JoinedQueryTableSource(
StringUtil::format("$0/dawanda_joined_queries.$1.sstable", dir, g));
report_builder.addReport(
new CTRByPositionReport(
jq_source,
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_by_position.$1.sstable",
dir,
g)),
ItemEligibility::ALL));
report_builder.addReport(
new CTRReport(
jq_source,
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_stats.$1.sstable",
dir,
g)),
ItemEligibility::ALL));
}
/* daily reports */
for (const auto& og : mkGenerations(
1 * kSecondsPerDay,
60 * kSecondsPerDay)) {
auto day_gens = mkGenerations(
4 * kSecondsPerHour,
1 * kSecondsPerDay,
og * kSecondsPerDay);
/* dawanda: roll up ctr stats */
Set<String> ctr_stats_sources;
for (const auto& ig : day_gens) {
ctr_stats_sources.emplace(
StringUtil::format("$0/dawanda_ctr_stats.$1.sstable", dir, ig));
}
report_builder.addReport(
new CTRCounterMerge(
new CTRCounterTableSource(ctr_stats_sources),
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_stats_daily.$1.sstable",
dir,
og))));
/* dawanda: roll up ctr positions */
Set<String> ctr_posi_sources;
for (const auto& ig : day_gens) {
ctr_posi_sources.emplace(
StringUtil::format("$0/dawanda_ctr_by_position.$1.sstable", dir, ig));
}
report_builder.addReport(
new CTRCounterMerge(
new CTRCounterTableSource(ctr_posi_sources),
new CTRCounterTableSink(
StringUtil::format(
"$0/dawanda_ctr_by_position_daily.$1.sstable",
dir,
og))));
}
report_builder.buildAll();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"
using namespace mfem;
namespace ceed_test
{
double coeff_function(const Vector &x)
{
return 1.0 + x[0]*x[0];
}
static std::string getString(AssemblyLevel assembly)
{
switch (assembly)
{
case AssemblyLevel::NONE:
return "NONE";
break;
case AssemblyLevel::PARTIAL:
return "PARTIAL";
break;
case AssemblyLevel::ELEMENT:
return "ELEMENT";
break;
case AssemblyLevel::FULL:
return "FULL";
break;
case AssemblyLevel::LEGACYFULL:
return "LEGACYFULL";
break;
}
}
static std::string getString(CeedCoeff coeff_type)
{
switch (coeff_type)
{
case CeedCoeff::Const:
return "Const";
break;
case CeedCoeff::Grid:
return "Grid";
break;
case CeedCoeff::Quad:
return "Quad";
break;
}
}
enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion};
static std::string getString(Problem pb)
{
switch (pb)
{
case Problem::Mass:
return "Mass";
break;
case Problem::Diffusion:
return "Diffusion";
break;
case Problem::VectorMass:
return "VectorMass";
break;
case Problem::VectorDiffusion:
return "VectorDiffusion";
break;
}
}
void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
const Problem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
BilinearForm k_test(&fes);
BilinearForm k_ref(&fes);
FiniteElementSpace coeff_fes(&mesh, &fec);
GridFunction gf(&coeff_fes);
FunctionCoefficient f_coeff(coeff_function);
Coefficient *coeff = nullptr;
switch (coeff_type)
{
case CeedCoeff::Const:
coeff = new ConstantCoefficient(1.0);
break;
case CeedCoeff::Grid:
gf.ProjectCoefficient(f_coeff);
coeff = new GridFunctionCoefficient(&gf);
break;
case CeedCoeff::Quad:
coeff = &f_coeff;
break;
}
switch (pb)
{
case Problem::Mass:
k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
break;
case Problem::Diffusion:
k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
break;
case Problem::VectorMass:
k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
break;
case Problem::VectorDiffusion:
k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
break;
}
k_ref.Assemble();
k_ref.Finalize();
k_test.SetAssemblyLevel(assembly);
k_test.Assemble();
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
}
TEST_CASE("CEED", "[CEED]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
Problem::VectorMass,Problem::VectorDiffusion);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/periodic-square.mesh",
"../../data/star-q2.mesh","../../data/fichera-q2.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
} // namespace ceed_test
<commit_msg>Remove compilation warnings in test_ceed.cpp.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"
using namespace mfem;
namespace ceed_test
{
double coeff_function(const Vector &x)
{
return 1.0 + x[0]*x[0];
}
static std::string getString(AssemblyLevel assembly)
{
switch (assembly)
{
case AssemblyLevel::NONE:
return "NONE";
break;
case AssemblyLevel::PARTIAL:
return "PARTIAL";
break;
case AssemblyLevel::ELEMENT:
return "ELEMENT";
break;
case AssemblyLevel::FULL:
return "FULL";
break;
case AssemblyLevel::LEGACYFULL:
return "LEGACYFULL";
break;
}
mfem_error("Unknown AssemblyLevel.");
return "";
}
static std::string getString(CeedCoeff coeff_type)
{
switch (coeff_type)
{
case CeedCoeff::Const:
return "Const";
break;
case CeedCoeff::Grid:
return "Grid";
break;
case CeedCoeff::Quad:
return "Quad";
break;
}
mfem_error("Unknown CeedCoeff.");
return "";
}
enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion};
static std::string getString(Problem pb)
{
switch (pb)
{
case Problem::Mass:
return "Mass";
break;
case Problem::Diffusion:
return "Diffusion";
break;
case Problem::VectorMass:
return "VectorMass";
break;
case Problem::VectorDiffusion:
return "VectorDiffusion";
break;
}
mfem_error("Unknown Problem.");
return "";
}
void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
const Problem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
BilinearForm k_test(&fes);
BilinearForm k_ref(&fes);
FiniteElementSpace coeff_fes(&mesh, &fec);
GridFunction gf(&coeff_fes);
FunctionCoefficient f_coeff(coeff_function);
Coefficient *coeff = nullptr;
switch (coeff_type)
{
case CeedCoeff::Const:
coeff = new ConstantCoefficient(1.0);
break;
case CeedCoeff::Grid:
gf.ProjectCoefficient(f_coeff);
coeff = new GridFunctionCoefficient(&gf);
break;
case CeedCoeff::Quad:
coeff = &f_coeff;
break;
}
switch (pb)
{
case Problem::Mass:
k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
break;
case Problem::Diffusion:
k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
break;
case Problem::VectorMass:
k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
break;
case Problem::VectorDiffusion:
k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
break;
}
k_ref.Assemble();
k_ref.Finalize();
k_test.SetAssemblyLevel(assembly);
k_test.Assemble();
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
}
TEST_CASE("CEED", "[CEED]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
Problem::VectorMass,Problem::VectorDiffusion);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/periodic-square.mesh",
"../../data/star-q2.mesh","../../data/fichera-q2.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
} // namespace ceed_test
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (C) 2016 ScyllaDB
*/
#include <seastar/core/thread.hh>
#include <seastar/core/do_with.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/testing/test_runner.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/print.hh>
#include <boost/range/irange.hpp>
#include <chrono>
using namespace seastar;
using namespace std::chrono_literals;
struct request {
fair_queue_ticket fqdesc;
unsigned index;
request(unsigned weight, unsigned index)
: fqdesc({weight, 0})
, index(index)
{}
};
class test_env {
fair_queue _fq;
std::vector<int> _results;
std::vector<std::vector<std::exception_ptr>> _exceptions;
std::vector<priority_class_ptr> _classes;
std::vector<request> _inflight;
void drain() {
do {} while (tick() != 0);
}
public:
test_env(unsigned capacity) : _fq(capacity)
{}
// As long as there is a request sitting in the queue, tick() will process
// at least one request. The only situation in which tick() will return nothing
// is if no requests were sent to the fair_queue (obviously).
//
// Because of this property, one useful use of tick() is to implement a drain()
// method (see above) in which all requests currently sent to the queue are drained
// before the queue is destroyed.
unsigned tick(unsigned n = 1) {
unsigned processed = 0;
_fq.dispatch_requests();
for (unsigned i = 0; i < n; ++i) {
std::vector<request> curr;
curr.swap(_inflight);
for (auto& req : curr) {
processed++;
_results[req.index]++;
_fq.notify_requests_finished(req.fqdesc);
}
_fq.dispatch_requests();
}
return processed;
}
~test_env() {
drain();
for (auto& p: _classes) {
_fq.unregister_priority_class(p);
}
}
size_t register_priority_class(uint32_t shares) {
_results.push_back(0);
_exceptions.push_back(std::vector<std::exception_ptr>());
_classes.push_back(_fq.register_priority_class(shares));
return _classes.size() - 1;
}
void do_op(unsigned index, unsigned weight) {
auto cl = _classes[index];
auto req = request(weight, index);
_fq.queue(cl, req.fqdesc, [this, index, req] () mutable noexcept {
try {
_inflight.push_back(std::move(req));
} catch (...) {
auto eptr = std::current_exception();
_exceptions[index].push_back(eptr);
_fq.notify_requests_finished(req.fqdesc);
}
});
}
void update_shares(unsigned index, uint32_t shares) {
auto cl = _classes[index];
cl->update_shares(shares);
}
void reset_results(unsigned index) {
_results[index] = 0;
}
// Verify if the ratios are what we expect. Because we can't be sure about
// precise timing issues, we can always be off by some percentage. In simpler
// tests we really expect it to very low, but in more complex tests, with share
// changes, for instance, they can accumulate
//
// The ratios argument is the ratios towards the first class
void verify(sstring name, std::vector<unsigned> ratios, unsigned expected_error = 1) {
assert(ratios.size() == _results.size());
auto str = name + ":";
for (auto i = 0ul; i < _results.size(); ++i) {
str += format(" r[{:d}] = {:d}", i, _results[i]);
}
std::cout << str << std::endl;
for (auto i = 0ul; i < ratios.size(); ++i) {
int min_expected = ratios[i] * (_results[0] - expected_error);
int max_expected = ratios[i] * (_results[0] + expected_error);
BOOST_REQUIRE(_results[i] >= min_expected);
BOOST_REQUIRE(_results[i] <= max_expected);
BOOST_REQUIRE(_exceptions[i].size() == 0);
}
}
};
// Equal ratios. Expected equal results.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_equal_2classes) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
env.verify("equal_2classes", {1, 1});
}
// Equal results, spread among 4 classes.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_equal_4classes) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
auto c = env.register_priority_class(10);
auto d = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
env.do_op(c, 1);
env.do_op(d, 1);
}
later().get();
// allow half the requests in
env.tick(200);
env.verify("equal_4classes", {1, 1, 1, 1});
}
// Class2 twice as powerful. Expected class2 to have 2 x more requests.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_different_shares) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(20);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
return env.verify("different_shares", {1, 2});
}
// Equal ratios, high capacity queue. Should still divide equally.
//
// Note that we sleep less because now more requests will be going through the
// queue.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_equal_hi_capacity_2classes) {
test_env env(10);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// queue has capacity 10, 10 x 10 = 100, allow half the requests in
env.tick(10);
env.verify("hi_capacity_2classes", {1, 1});
}
// Class2 twice as powerful, queue is high capacity. Still expected class2 to
// have 2 x more requests.
//
// Note that we sleep less because now more requests will be going through the
// queue.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_different_shares_hi_capacity) {
test_env env(10);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(20);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// queue has capacity 10, 10 x 10 = 100, allow half the requests in
env.tick(10);
env.verify("different_shares_hi_capacity", {1, 2});
}
// Classes equally powerful. But Class1 issues twice as expensive requests. Expected Class2 to have 2 x more requests.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_different_weights) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 2);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
env.verify("different_weights", {1, 2});
}
// Class2 pushes many requests over. Right after, don't expect Class2 to be able to push anything else.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_dominant_queue) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(b, 1);
}
later().get();
// consume all requests
env.tick(100);
// zero statistics.
env.reset_results(b);
for (int i = 0; i < 20; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
// allow half the requests in
env.tick(20);
env.verify("dominant_queue", {1, 0});
}
// Class2 pushes many requests at first. After enough time, this shouldn't matter anymore.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_forgiving_queue) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(b, 1);
}
later().get();
// consume all requests
env.tick(100);
sleep(500ms).get();
env.reset_results(b);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
env.verify("forgiving_queue", {1, 1});
}
// Classes push requests and then update swap their shares. In the end, should have executed
// the same number of requests.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_update_shares) {
test_env env(1);
auto a = env.register_priority_class(20);
auto b = env.register_priority_class(10);
for (int i = 0; i < 500; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow 25% of the requests in
env.tick(250);
env.update_shares(a, 10);
env.update_shares(b, 20);
later().get();
// allow 25% of the requests in
env.tick(250);
env.verify("update_shares", {1, 1}, 2);
}
// Classes run for a longer period of time. Balance must be kept over many timer
// periods.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_longer_run) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 20000; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
// In total allow half the requests in, but do it over a
// long period of time, ticking slowly
for (int i = 0; i < 1000; ++i) {
sleep(1ms).get();
env.tick(2);
}
env.verify("longer_run", {1, 1}, 2);
}
// Classes run for a longer period of time. Proportional balance must be kept over many timer
// periods, despite unequal shares..
SEASTAR_THREAD_TEST_CASE(test_fair_queue_longer_run_different_shares) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(20);
for (int i = 0; i < 20000; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
// In total allow half the requests in, but do it over a
// long period of time, ticking slowly
for (int i = 0; i < 1000; ++i) {
sleep(1ms).get();
env.tick(2);
}
env.verify("longer_run_different_shares", {1, 2}, 2);
}
// Classes run for a random period of time. Equal operations expected.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_random_run) {
test_env env(1);
auto a = env.register_priority_class(1);
auto b = env.register_priority_class(1);
std::default_random_engine& generator = testing::local_random_engine;
// multiples of 100usec - which is the approximate length of the request. We will
// put a minimum of 10. Below that, it is hard to guarantee anything. The maximum is
// about 50 seconds.
std::uniform_int_distribution<uint32_t> distribution(10, 500 * 1000);
auto reqs = distribution(generator);
// Enough requests for the maximum run (half per queue, + leeway)
for (uint32_t i = 0; i < reqs; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// In total allow half the requests in
env.tick(reqs);
// Accept 5 % error.
auto expected_error = std::max(1, int(round(reqs * 0.05)));
env.verify(format("random_run ({:d} requests)", reqs), {1, 1}, expected_error);
}
<commit_msg>test: Increase capacity of fair-queue unit test case<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (C) 2016 ScyllaDB
*/
#include <seastar/core/thread.hh>
#include <seastar/core/do_with.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/testing/test_runner.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/print.hh>
#include <boost/range/irange.hpp>
#include <chrono>
using namespace seastar;
using namespace std::chrono_literals;
struct request {
fair_queue_ticket fqdesc;
unsigned index;
request(unsigned weight, unsigned index)
: fqdesc({weight, 0})
, index(index)
{}
};
class test_env {
fair_queue _fq;
std::vector<int> _results;
std::vector<std::vector<std::exception_ptr>> _exceptions;
std::vector<priority_class_ptr> _classes;
std::vector<request> _inflight;
void drain() {
do {} while (tick() != 0);
}
public:
test_env(unsigned capacity) : _fq(capacity)
{}
// As long as there is a request sitting in the queue, tick() will process
// at least one request. The only situation in which tick() will return nothing
// is if no requests were sent to the fair_queue (obviously).
//
// Because of this property, one useful use of tick() is to implement a drain()
// method (see above) in which all requests currently sent to the queue are drained
// before the queue is destroyed.
unsigned tick(unsigned n = 1) {
unsigned processed = 0;
_fq.dispatch_requests();
for (unsigned i = 0; i < n; ++i) {
std::vector<request> curr;
curr.swap(_inflight);
for (auto& req : curr) {
processed++;
_results[req.index]++;
_fq.notify_requests_finished(req.fqdesc);
}
_fq.dispatch_requests();
}
return processed;
}
~test_env() {
drain();
for (auto& p: _classes) {
_fq.unregister_priority_class(p);
}
}
size_t register_priority_class(uint32_t shares) {
_results.push_back(0);
_exceptions.push_back(std::vector<std::exception_ptr>());
_classes.push_back(_fq.register_priority_class(shares));
return _classes.size() - 1;
}
void do_op(unsigned index, unsigned weight) {
auto cl = _classes[index];
auto req = request(weight, index);
_fq.queue(cl, req.fqdesc, [this, index, req] () mutable noexcept {
try {
_inflight.push_back(std::move(req));
} catch (...) {
auto eptr = std::current_exception();
_exceptions[index].push_back(eptr);
_fq.notify_requests_finished(req.fqdesc);
}
});
}
void update_shares(unsigned index, uint32_t shares) {
auto cl = _classes[index];
cl->update_shares(shares);
}
void reset_results(unsigned index) {
_results[index] = 0;
}
// Verify if the ratios are what we expect. Because we can't be sure about
// precise timing issues, we can always be off by some percentage. In simpler
// tests we really expect it to very low, but in more complex tests, with share
// changes, for instance, they can accumulate
//
// The ratios argument is the ratios towards the first class
void verify(sstring name, std::vector<unsigned> ratios, unsigned expected_error = 1) {
assert(ratios.size() == _results.size());
auto str = name + ":";
for (auto i = 0ul; i < _results.size(); ++i) {
str += format(" r[{:d}] = {:d}", i, _results[i]);
}
std::cout << str << std::endl;
for (auto i = 0ul; i < ratios.size(); ++i) {
int min_expected = ratios[i] * (_results[0] - expected_error);
int max_expected = ratios[i] * (_results[0] + expected_error);
BOOST_REQUIRE(_results[i] >= min_expected);
BOOST_REQUIRE(_results[i] <= max_expected);
BOOST_REQUIRE(_exceptions[i].size() == 0);
}
}
};
// Equal ratios. Expected equal results.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_equal_2classes) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
env.verify("equal_2classes", {1, 1});
}
// Equal results, spread among 4 classes.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_equal_4classes) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
auto c = env.register_priority_class(10);
auto d = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
env.do_op(c, 1);
env.do_op(d, 1);
}
later().get();
// allow half the requests in
env.tick(200);
env.verify("equal_4classes", {1, 1, 1, 1});
}
// Class2 twice as powerful. Expected class2 to have 2 x more requests.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_different_shares) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(20);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
return env.verify("different_shares", {1, 2});
}
// Equal ratios, high capacity queue. Should still divide equally.
//
// Note that we sleep less because now more requests will be going through the
// queue.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_equal_hi_capacity_2classes) {
test_env env(10);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// queue has capacity 10, 10 x 10 = 100, allow half the requests in
env.tick(10);
env.verify("hi_capacity_2classes", {1, 1});
}
// Class2 twice as powerful, queue is high capacity. Still expected class2 to
// have 2 x more requests.
//
// Note that we sleep less because now more requests will be going through the
// queue.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_different_shares_hi_capacity) {
test_env env(10);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(20);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// queue has capacity 10, 10 x 10 = 100, allow half the requests in
env.tick(10);
env.verify("different_shares_hi_capacity", {1, 2});
}
// Classes equally powerful. But Class1 issues twice as expensive requests. Expected Class2 to have 2 x more requests.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_different_weights) {
test_env env(2);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 2);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
env.verify("different_weights", {1, 2});
}
// Class2 pushes many requests over. Right after, don't expect Class2 to be able to push anything else.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_dominant_queue) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(b, 1);
}
later().get();
// consume all requests
env.tick(100);
// zero statistics.
env.reset_results(b);
for (int i = 0; i < 20; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
// allow half the requests in
env.tick(20);
env.verify("dominant_queue", {1, 0});
}
// Class2 pushes many requests at first. After enough time, this shouldn't matter anymore.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_forgiving_queue) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 100; ++i) {
env.do_op(b, 1);
}
later().get();
// consume all requests
env.tick(100);
sleep(500ms).get();
env.reset_results(b);
for (int i = 0; i < 100; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow half the requests in
env.tick(100);
env.verify("forgiving_queue", {1, 1});
}
// Classes push requests and then update swap their shares. In the end, should have executed
// the same number of requests.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_update_shares) {
test_env env(1);
auto a = env.register_priority_class(20);
auto b = env.register_priority_class(10);
for (int i = 0; i < 500; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// allow 25% of the requests in
env.tick(250);
env.update_shares(a, 10);
env.update_shares(b, 20);
later().get();
// allow 25% of the requests in
env.tick(250);
env.verify("update_shares", {1, 1}, 2);
}
// Classes run for a longer period of time. Balance must be kept over many timer
// periods.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_longer_run) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(10);
for (int i = 0; i < 20000; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
// In total allow half the requests in, but do it over a
// long period of time, ticking slowly
for (int i = 0; i < 1000; ++i) {
sleep(1ms).get();
env.tick(2);
}
env.verify("longer_run", {1, 1}, 2);
}
// Classes run for a longer period of time. Proportional balance must be kept over many timer
// periods, despite unequal shares..
SEASTAR_THREAD_TEST_CASE(test_fair_queue_longer_run_different_shares) {
test_env env(1);
auto a = env.register_priority_class(10);
auto b = env.register_priority_class(20);
for (int i = 0; i < 20000; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
// In total allow half the requests in, but do it over a
// long period of time, ticking slowly
for (int i = 0; i < 1000; ++i) {
sleep(1ms).get();
env.tick(2);
}
env.verify("longer_run_different_shares", {1, 2}, 2);
}
// Classes run for a random period of time. Equal operations expected.
SEASTAR_THREAD_TEST_CASE(test_fair_queue_random_run) {
test_env env(1);
auto a = env.register_priority_class(1);
auto b = env.register_priority_class(1);
std::default_random_engine& generator = testing::local_random_engine;
// multiples of 100usec - which is the approximate length of the request. We will
// put a minimum of 10. Below that, it is hard to guarantee anything. The maximum is
// about 50 seconds.
std::uniform_int_distribution<uint32_t> distribution(10, 500 * 1000);
auto reqs = distribution(generator);
// Enough requests for the maximum run (half per queue, + leeway)
for (uint32_t i = 0; i < reqs; ++i) {
env.do_op(a, 1);
env.do_op(b, 1);
}
later().get();
// In total allow half the requests in
env.tick(reqs);
// Accept 5 % error.
auto expected_error = std::max(1, int(round(reqs * 0.05)));
env.verify(format("random_run ({:d} requests)", reqs), {1, 1}, expected_error);
}
<|endoftext|>
|
<commit_before><commit_msg>Fixed calculation for getting correct bit for video<commit_after><|endoftext|>
|
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!\file BouncingBallTS.cpp
\brief \ref EMBouncingBall - C++ input file, Time-Stepping version -
V. Acary, F. Perignon.
A Ball bouncing on the ground.
Direct description of the model.
Simulation with a Time-Stepping scheme.
*/
#include "SiconosKernel.hpp"
using namespace std;
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 3; // degrees of freedom for the ball
double t0 = 0; // initial computation time
double T = 10; // final computation time
double h = 0.005; // time step
double position_init = 1.0; // initial position for lowest bead.
double velocity_init = 0.0; // initial velocity for lowest bead.
double theta = 0.5; // theta for MoreauJeanOSI integrator
double R = 0.1; // Ball radius
double height = 1.0; // height to the roof
double m = 1; // Ball mass
double g = 9.81; // Gravity
// -------------------------
// --- Dynamical systems ---
// -------------------------
cout << "====> Model loading ..." << endl;
SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof));
(*Mass)(0, 0) = m;
(*Mass)(1, 1) = m;
(*Mass)(2, 2) = 2. / 5 * m * R * R;
// -- Initial positions and velocities --
SP::SiconosVector q0(new SiconosVector(nDof));
SP::SiconosVector v0(new SiconosVector(nDof));
(*q0)(0) = position_init;
(*v0)(0) = velocity_init;
// -- The dynamical system --
SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass));
// -- Set external forces (weight) --
SP::SiconosVector weight(new SiconosVector(nDof));
(*weight)(0) = -m * g;
ball->setFExtPtr(weight);
// --------------------
// --- Interactions ---
// --------------------
// -- nslaw --
double e = 0.9;
// Interaction ball-roof with impact
//
SP::SimpleMatrix H(new SimpleMatrix(1, nDof));
(*H)(0, 0) = -1.0;
SP::SiconosVector b(new SiconosVector(1));
(*b)(0) = - R;
SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
SP::Relation relation(new LagrangianLinearTIR(H,b));
SP::Interaction inter(new Interaction(1, nslaw, relation));
// -- nslaw --
double stiffness = 10.0;
// Interaction ball-floor with a compliant spring
SP::SimpleMatrix Hfloor(new SimpleMatrix(1, nDof));
(*Hfloor)(0, 0) = 1.0;
SP::SimpleMatrix Kfloor(new SimpleMatrix(1, 1));
(*Kfloor)(0, 0) = stiffness;
SP::SiconosVector bfloor(new SiconosVector(1));
(*bfloor)(0) = height - R;
SP::NonSmoothLaw nslawfloor(new ComplementarityConditionNSL(1));
SP::Relation relationfloor(new LagrangianCompliantLinearTIR(Hfloor,Kfloor, bfloor));
SP::Interaction interfloor(new Interaction(1, nslawfloor, relationfloor));
// -------------
// --- Model ---
// -------------
SP::Model bouncingBall(new Model(t0, T));
// add the dynamical system in the non smooth dynamical system
bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball);
// link the interaction and the dynamical system
bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball);
// link the interaction and the dynamical system
bouncingBall->nonSmoothDynamicalSystem()->link(interfloor, ball);
// ------------------
// --- Simulation ---
// ------------------
// -- (1) OneStepIntegrators --
SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta));
// -- (2) Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
// -- (3) one step non smooth problem
SP::OneStepNSProblem osnspb(new LCP());
// -- (4) Simulation setup with (1) (2) (3)
SP::TimeStepping s(new TimeStepping(t, OSI, osnspb));
bouncingBall->setSimulation(s);
// =========================== End of model definition ===========================
// ================================= Computation =================================
// --- Simulation initialization ---
cout << "====> Initialisation ..." << endl;
//bouncingBall->nonSmoothDynamicalSystem()->topology()->setOSI(ball, OSI);
bouncingBall->initialize();
// -- set the integrator for the ball --
int N = ceil((T - t0) / h); // Number of time steps
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 5;
SimpleMatrix dataPlot(N + 1, outputSize);
SP::SiconosVector q = ball->q();
SP::SiconosVector v = ball->velocity();
SP::SiconosVector p = ball->p(1);
SP::SiconosVector lambda = inter->lambda(1);
dataPlot(0, 0) = bouncingBall->t0();
dataPlot(0, 1) = (*q)(0);
dataPlot(0, 2) = (*v)(0);
dataPlot(0, 3) = (*p)(0);
dataPlot(0, 4) = (*lambda)(0);
// --- Time loop ---
cout << "====> Start computation ... " << endl;
// ==== Simulation loop - Writing without explicit event handling =====
int k = 1;
boost::progress_display show_progress(N);
boost::timer time;
time.restart();
while (s->hasNextEvent())
{
s->computeOneStep();
// --- Get values to be plotted ---
dataPlot(k, 0) = s->nextTime();
dataPlot(k, 1) = (*q)(0);
dataPlot(k, 2) = (*v)(0);
dataPlot(k, 3) = (*p)(0);
dataPlot(k, 4) = (*lambda)(0);
s->nextStep();
++show_progress;
k++;
}
cout << "End of computation - Number of iterations done: " << k - 1 << endl;
cout << "Computation Time " << time.elapsed() << endl;
// // --- Output files ---
// cout << "====> Output file writing ..." << endl;
// dataPlot.resize(k, outputSize);
// ioMatrix::write("result.dat", "ascii", dataPlot, "noDim");
// std::cout << "Comparison with a reference file" << std::endl;
// SimpleMatrix dataPlotRef(dataPlot);
// dataPlotRef.zero();
// ioMatrix::read("result.ref", "ascii", dataPlotRef);
// double error = (dataPlot - dataPlotRef).normInf();
// std::cout << "error =" << error << std::endl;
// if (error> 1e-12)
// {
// std::cout << "Warning. The result is rather different from the reference file." << std::endl;
// return 1;
// }
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in BouncingBallTS.cpp" << endl;
}
}
<commit_msg>[examples] a first silly simulation with compliant contact<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!\file BouncingBallTS.cpp
\brief \ref EMBouncingBall - C++ input file, Time-Stepping version -
V. Acary, F. Perignon.
A Ball bouncing on the ground.
Direct description of the model.
Simulation with a Time-Stepping scheme.
*/
#include "SiconosKernel.hpp"
using namespace std;
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 3; // degrees of freedom for the ball
double t0 = 0; // initial computation time
double T = 10; // final computation time
double h = 0.0005; // time step
double position_init = 1.0; // initial position for lowest bead.
double velocity_init = 0.0; // initial velocity for lowest bead.
double theta = 0.5; // theta for MoreauJeanOSI integrator
double R = 0.1; // Ball radius
double height = 1.0; // height to the roof
double m = 1; // Ball mass
double g = 9.81; // Gravity
// -------------------------
// --- Dynamical systems ---
// -------------------------
cout << "====> Model loading ..." << endl;
SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof));
(*Mass)(0, 0) = m;
(*Mass)(1, 1) = m;
(*Mass)(2, 2) = 2. / 5 * m * R * R;
// -- Initial positions and velocities --
SP::SiconosVector q0(new SiconosVector(nDof));
SP::SiconosVector v0(new SiconosVector(nDof));
(*q0)(0) = position_init;
(*v0)(0) = velocity_init;
// -- The dynamical system --
SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass));
// -- Set external forces (weight) --
SP::SiconosVector weight(new SiconosVector(nDof));
(*weight)(0) = -m * g;
ball->setFExtPtr(weight);
// --------------------
// --- Interactions ---
// --------------------
// -- nslaw --
double e = 1.0;
// Interaction ball-roof with impact
//
SP::SimpleMatrix H(new SimpleMatrix(1, nDof));
(*H)(0, 0) = -1.0;
SP::SiconosVector b(new SiconosVector(1));
(*b)(0) = height - R- .2;
SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
SP::Relation relation(new LagrangianLinearTIR(H,b));
SP::Interaction inter(new Interaction(1, nslaw, relation));
// -- nslaw --
double compliance = 0.01;
// Interaction ball-floor with a compliant spring
SP::SimpleMatrix Hfloor(new SimpleMatrix(1, nDof));
(*Hfloor)(0, 0) = 1.0;
SP::SimpleMatrix Kfloor(new SimpleMatrix(1, 1));
(*Kfloor)(0, 0) = compliance;
SP::SiconosVector bfloor(new SiconosVector(1));
(*bfloor)(0) = - R;
SP::NonSmoothLaw nslawfloor(new ComplementarityConditionNSL(1));
SP::Relation relationfloor(new LagrangianCompliantLinearTIR(Hfloor,Kfloor, bfloor));
SP::Interaction interfloor(new Interaction(1, nslawfloor, relationfloor));
// -------------
// --- Model ---
// -------------
SP::Model bouncingBall(new Model(t0, T));
// add the dynamical system in the non smooth dynamical system
bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball);
// link the interaction and the dynamical system
bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball);
// link the interaction and the dynamical system
bouncingBall->nonSmoothDynamicalSystem()->link(interfloor, ball);
// ------------------
// --- Simulation ---
// ------------------
// -- (1) OneStepIntegrators --
SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta));
// -- (2) Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
// -- (3) one step non smooth problem
SP::OneStepNSProblem osnspb(new LCP());
// -- (4) Simulation setup with (1) (2) (3)
SP::TimeStepping s(new TimeStepping(t, OSI, osnspb));
bouncingBall->setSimulation(s);
// =========================== End of model definition ===========================
// ================================= Computation =================================
// --- Simulation initialization ---
cout << "====> Initialisation ..." << endl;
//bouncingBall->nonSmoothDynamicalSystem()->topology()->setOSI(ball, OSI);
bouncingBall->initialize();
// -- set the integrator for the ball --
int N = ceil((T - t0) / h); // Number of time steps
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 5;
SimpleMatrix dataPlot(N + 1, outputSize);
SP::SiconosVector q = ball->q();
SP::SiconosVector v = ball->velocity();
SP::SiconosVector p = ball->p(1);
SP::SiconosVector lambda = inter->lambda(1);
dataPlot(0, 0) = bouncingBall->t0();
dataPlot(0, 1) = (*q)(0);
dataPlot(0, 2) = (*v)(0);
dataPlot(0, 3) = (*p)(0);
dataPlot(0, 4) = (*lambda)(0);
// --- Time loop ---
cout << "====> Start computation ... " << endl;
// ==== Simulation loop - Writing without explicit event handling =====
int k = 1;
boost::progress_display show_progress(N);
boost::timer time;
time.restart();
while (s->hasNextEvent())
{
s->computeOneStep();
// --- Get values to be plotted ---
dataPlot(k, 0) = s->nextTime();
dataPlot(k, 1) = (*q)(0);
dataPlot(k, 2) = (*v)(0);
dataPlot(k, 3) = (*p)(0);
dataPlot(k, 4) = (*lambda)(0);
s->nextStep();
++show_progress;
k++;
}
cout << "End of computation - Number of iterations done: " << k - 1 << endl;
cout << "Computation Time " << time.elapsed() << endl;
// --- Output files ---
cout << "====> Output file writing ..." << endl;
dataPlot.resize(k, outputSize);
ioMatrix::write("result.dat", "ascii", dataPlot, "noDim");
// std::cout << "Comparison with a reference file" << std::endl;
// SimpleMatrix dataPlotRef(dataPlot);
// dataPlotRef.zero();
// ioMatrix::read("result.ref", "ascii", dataPlotRef);
// double error = (dataPlot - dataPlotRef).normInf();
// std::cout << "error =" << error << std::endl;
// if (error> 1e-12)
// {
// std::cout << "Warning. The result is rather different from the reference file." << std::endl;
// return 1;
// }
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in BouncingBallTS.cpp" << endl;
}
}
<|endoftext|>
|
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "viewport.hh"
#include "factory.hh"
namespace Rapicorn {
ViewportImpl::ViewportImpl () :
m_tunable_requisition_counter (0)
{}
ViewportImpl::~ViewportImpl ()
{}
void
ViewportImpl::negotiate_size (const Allocation *carea)
{
return_if_fail (requisitions_tunable() == false);
const bool have_allocation = carea != NULL;
Allocation area;
if (have_allocation)
{
area = *carea;
change_flags_silently (INVALID_ALLOCATION, true);
}
else // !have_allocation
area = allocation(); // keep x,y
/* this is the core of the resizing loop. via Item.tune_requisition(), we
* allow items to adjust the requisition from within size_allocate().
* whether the tuned requisition is honored at all, depends on
* m_tunable_requisition_counter.
* currently, we simply freeze the allocation after 3 iterations. for the
* future it's possible to honor the tuned requisition only partially or
* proportionally as m_tunable_requisition_counter decreases, so to mimick
* a simulated annealing process yielding the final layout.
*/
m_tunable_requisition_counter = 3;
while (test_flags (INVALID_REQUISITION | INVALID_ALLOCATION))
{
const Requisition creq = requisition(); // unsets INVALID_REQUISITION
if (!have_allocation)
{
// seed allocation from requisition
area.width = creq.width;
area.height = creq.height;
}
set_allocation (area); // unsets INVALID_ALLOCATION, may re-::invalidate_size()
if (m_tunable_requisition_counter)
m_tunable_requisition_counter--;
}
m_tunable_requisition_counter = 0;
}
void
ViewportImpl::allocate_size (const Allocation &area)
{
return_if_fail (area.width >= 0 && area.height >= 0);
negotiate_size (&area);
}
void
ViewportImpl::render (Display &display)
{
const IRect ia = allocation();
display.push_clip_rect (ia.x, ia.y, ia.width, ia.height);
// paint background
cairo_t *cr = display.create_cairo (background());
cairo_destroy (cr);
// paint children
SingleContainerImpl::render (display);
display.pop_clip_rect();
}
void
ViewportImpl::queue_expose_region (const Region ®ion)
{
if (!region.empty())
{
m_expose_region.add (region);
collapse_expose_region();
}
}
void
ViewportImpl::queue_expose_rect (const Rect &rect)
{
m_expose_region.add (rect);
collapse_expose_region();
}
void
ViewportImpl::expose_child (const Region ®ion)
{
// FIXME: need affine handling here?
queue_expose_region (region);
}
void
ViewportImpl::collapse_expose_region ()
{
/* check for excess expose fragment scenarios */
uint n_erects = m_expose_region.count_rects();
if (n_erects > 999) /* workable limit, considering O(n^2) collision complexity */
{
/* aparently the expose fragments we're combining are too small,
* so we can end up with spending too much time on expose rectangle
* compression (much more than needed for rendering).
* as a workaround, we simply force everything into a single expose
* rectangle which is good enough to avoid worst case explosion.
* note that this is only triggered in seldom pathological cases.
*/
m_expose_region.add (m_expose_region.extents());
// printerr ("collapsing due to too many expose rectangles: %u -> %u\n", n_erects, m_expose_region.count_rects());
}
}
} // Rapicorn
<commit_msg>UI: adjust expose rectangle compression threshold<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "viewport.hh"
#include "factory.hh"
namespace Rapicorn {
ViewportImpl::ViewportImpl () :
m_tunable_requisition_counter (0)
{}
ViewportImpl::~ViewportImpl ()
{}
void
ViewportImpl::negotiate_size (const Allocation *carea)
{
return_if_fail (requisitions_tunable() == false);
const bool have_allocation = carea != NULL;
Allocation area;
if (have_allocation)
{
area = *carea;
change_flags_silently (INVALID_ALLOCATION, true);
}
else // !have_allocation
area = allocation(); // keep x,y
/* this is the core of the resizing loop. via Item.tune_requisition(), we
* allow items to adjust the requisition from within size_allocate().
* whether the tuned requisition is honored at all, depends on
* m_tunable_requisition_counter.
* currently, we simply freeze the allocation after 3 iterations. for the
* future it's possible to honor the tuned requisition only partially or
* proportionally as m_tunable_requisition_counter decreases, so to mimick
* a simulated annealing process yielding the final layout.
*/
m_tunable_requisition_counter = 3;
while (test_flags (INVALID_REQUISITION | INVALID_ALLOCATION))
{
const Requisition creq = requisition(); // unsets INVALID_REQUISITION
if (!have_allocation)
{
// seed allocation from requisition
area.width = creq.width;
area.height = creq.height;
}
set_allocation (area); // unsets INVALID_ALLOCATION, may re-::invalidate_size()
if (m_tunable_requisition_counter)
m_tunable_requisition_counter--;
}
m_tunable_requisition_counter = 0;
}
void
ViewportImpl::allocate_size (const Allocation &area)
{
return_if_fail (area.width >= 0 && area.height >= 0);
negotiate_size (&area);
}
void
ViewportImpl::render (Display &display)
{
const IRect ia = allocation();
display.push_clip_rect (ia.x, ia.y, ia.width, ia.height);
// paint background
cairo_t *cr = display.create_cairo (background());
cairo_destroy (cr);
// paint children
SingleContainerImpl::render (display);
display.pop_clip_rect();
}
void
ViewportImpl::queue_expose_region (const Region ®ion)
{
if (!region.empty())
{
m_expose_region.add (region);
collapse_expose_region();
}
}
void
ViewportImpl::queue_expose_rect (const Rect &rect)
{
m_expose_region.add (rect);
collapse_expose_region();
}
void
ViewportImpl::expose_child (const Region ®ion)
{
// FIXME: need affine handling here?
queue_expose_region (region);
}
void
ViewportImpl::collapse_expose_region ()
{
// check for excess expose fragment scenarios
uint n_erects = m_expose_region.count_rects();
/* considering O(n^2) collision computation complexity, but also focus frame
* exposures which easily consist of 4+ fragments, a hundred rectangles turn
* out to be an emperically suitable threshold.
*/
if (n_erects > 99)
{
/* aparently the expose fragments we're combining are too small,
* so we can end up with spending too much time on expose rectangle
* compression (more time than needed for actual rendering).
* as a workaround, we simply force everything into a single expose
* rectangle which is good enough to avoid worst case explosion.
*/
m_expose_region.add (m_expose_region.extents());
// printerr ("collapsing due to too many expose rectangles: %u -> %u\n", n_erects, m_expose_region.count_rects());
}
}
} // Rapicorn
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#pragma once
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <limits>
#include <uavcan/stdint.hpp>
#include <uavcan/util/compile_time.hpp>
namespace uavcan
{
/**
* This interface is used by other library components that need dynamic memory.
*/
class UAVCAN_EXPORT IAllocator
{
public:
virtual ~IAllocator() { }
virtual void* allocate(std::size_t size) = 0;
virtual void deallocate(const void* ptr) = 0;
};
class UAVCAN_EXPORT IPoolAllocator : public IAllocator
{
public:
virtual bool isInPool(const void* ptr) const = 0;
virtual std::size_t getBlockSize() const = 0;
};
template <int MaxPools>
class UAVCAN_EXPORT PoolManager : public IAllocator, Noncopyable
{
IPoolAllocator* pools_[MaxPools];
static bool sortComparePoolAllocators(const IPoolAllocator* a, const IPoolAllocator* b)
{
const std::size_t a_size = a ? a->getBlockSize() : std::numeric_limits<std::size_t>::max();
const std::size_t b_size = b ? b->getBlockSize() : std::numeric_limits<std::size_t>::max();
return a_size < b_size;
}
public:
PoolManager()
{
std::memset(pools_, 0, sizeof(pools_));
}
bool addPool(IPoolAllocator* pool)
{
assert(pool);
bool retval = false;
for (int i = 0; i < MaxPools; i++)
{
assert(pools_[i] != pool);
if (pools_[i] == NULL || pools_[i] == pool)
{
pools_[i] = pool;
retval = true;
break;
}
}
// We need to keep the pools in order, so that smallest blocks go first
std::sort(pools_, pools_ + MaxPools, &PoolManager::sortComparePoolAllocators);
return retval;
}
void* allocate(std::size_t size)
{
for (int i = 0; i < MaxPools; i++)
{
if (pools_[i] == NULL)
{
break;
}
void* const pmem = pools_[i]->allocate(size);
if (pmem != NULL)
{
return pmem;
}
}
return NULL;
}
void deallocate(const void* ptr)
{
for (int i = 0; i < MaxPools; i++)
{
if (pools_[i] == NULL)
{
assert(0);
break;
}
if (pools_[i]->isInPool(ptr))
{
pools_[i]->deallocate(ptr);
break;
}
}
}
};
template <std::size_t PoolSize, std::size_t BlockSize>
class UAVCAN_EXPORT PoolAllocator : public IPoolAllocator, Noncopyable
{
union Node
{
uint8_t data[BlockSize];
Node* next;
};
Node* free_list_;
union
{
uint8_t bytes[PoolSize];
long double _aligner1;
long long _aligner2;
Node _aligner3;
} pool_;
public:
static const int NumBlocks = int(PoolSize / BlockSize);
PoolAllocator()
: free_list_(reinterpret_cast<Node*>(pool_.bytes))
{
memset(pool_.bytes, 0, PoolSize);
for (int i = 0; i < NumBlocks - 1; i++)
{
free_list_[i].next = free_list_ + i + 1;
}
free_list_[NumBlocks - 1].next = NULL;
}
void* allocate(std::size_t size)
{
if (free_list_ == NULL || size > BlockSize)
{
return NULL;
}
void* pmem = free_list_;
free_list_ = free_list_->next;
return pmem;
}
void deallocate(const void* ptr)
{
if (ptr == NULL)
{
return;
}
Node* p = static_cast<Node*>(const_cast<void*>(ptr));
#if DEBUG || UAVCAN_DEBUG
std::memset(p, 0, sizeof(Node));
#endif
p->next = free_list_;
free_list_ = p;
}
bool isInPool(const void* ptr) const
{
return
ptr >= pool_.bytes &&
ptr < (pool_.bytes + PoolSize);
}
std::size_t getBlockSize() const { return BlockSize; }
int getNumFreeBlocks() const
{
int num = 0;
Node* p = free_list_;
while (p)
{
num++;
assert(num <= NumBlocks);
p = p->next;
}
return num;
}
int getNumUsedBlocks() const
{
return NumBlocks - getNumFreeBlocks();
}
};
}
<commit_msg>Out of line methods in dynamic_memory.hpp<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#pragma once
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <limits>
#include <uavcan/stdint.hpp>
#include <uavcan/util/compile_time.hpp>
namespace uavcan
{
/**
* This interface is used by other library components that need dynamic memory.
*/
class UAVCAN_EXPORT IAllocator
{
public:
virtual ~IAllocator() { }
virtual void* allocate(std::size_t size) = 0;
virtual void deallocate(const void* ptr) = 0;
};
class UAVCAN_EXPORT IPoolAllocator : public IAllocator
{
public:
virtual bool isInPool(const void* ptr) const = 0;
virtual std::size_t getBlockSize() const = 0;
};
template <int MaxPools>
class UAVCAN_EXPORT PoolManager : public IAllocator, Noncopyable
{
IPoolAllocator* pools_[MaxPools];
static bool sortComparePoolAllocators(const IPoolAllocator* a, const IPoolAllocator* b)
{
const std::size_t a_size = a ? a->getBlockSize() : std::numeric_limits<std::size_t>::max();
const std::size_t b_size = b ? b->getBlockSize() : std::numeric_limits<std::size_t>::max();
return a_size < b_size;
}
public:
PoolManager()
{
std::memset(pools_, 0, sizeof(pools_));
}
bool addPool(IPoolAllocator* pool);
void* allocate(std::size_t size);
void deallocate(const void* ptr);
};
template <std::size_t PoolSize, std::size_t BlockSize>
class UAVCAN_EXPORT PoolAllocator : public IPoolAllocator, Noncopyable
{
union Node
{
uint8_t data[BlockSize];
Node* next;
};
Node* free_list_;
union
{
uint8_t bytes[PoolSize];
long double _aligner1;
long long _aligner2;
Node _aligner3;
} pool_;
public:
static const int NumBlocks = int(PoolSize / BlockSize);
PoolAllocator();
void* allocate(std::size_t size);
void deallocate(const void* ptr);
bool isInPool(const void* ptr) const;
std::size_t getBlockSize() const { return BlockSize; }
int getNumFreeBlocks() const;
int getNumUsedBlocks() const { return NumBlocks - getNumFreeBlocks(); }
};
// ----------------------------------------------------------------------------
/*
* PoolManager<>
*/
template <int MaxPools>
bool PoolManager<MaxPools>::addPool(IPoolAllocator* pool)
{
assert(pool);
bool retval = false;
for (int i = 0; i < MaxPools; i++)
{
assert(pools_[i] != pool);
if (pools_[i] == NULL || pools_[i] == pool)
{
pools_[i] = pool;
retval = true;
break;
}
}
// We need to keep the pools in order, so that smallest blocks go first
std::sort(pools_, pools_ + MaxPools, &PoolManager::sortComparePoolAllocators);
return retval;
}
template <int MaxPools>
void* PoolManager<MaxPools>::allocate(std::size_t size)
{
for (int i = 0; i < MaxPools; i++)
{
if (pools_[i] == NULL)
{
break;
}
void* const pmem = pools_[i]->allocate(size);
if (pmem != NULL)
{
return pmem;
}
}
return NULL;
}
template <int MaxPools>
void PoolManager<MaxPools>::deallocate(const void* ptr)
{
for (int i = 0; i < MaxPools; i++)
{
if (pools_[i] == NULL)
{
assert(0);
break;
}
if (pools_[i]->isInPool(ptr))
{
pools_[i]->deallocate(ptr);
break;
}
}
}
/*
* PoolAllocator<>
*/
template <std::size_t PoolSize, std::size_t BlockSize>
PoolAllocator<PoolSize, BlockSize>::PoolAllocator()
: free_list_(reinterpret_cast<Node*>(pool_.bytes))
{
memset(pool_.bytes, 0, PoolSize);
for (int i = 0; i < NumBlocks - 1; i++)
{
free_list_[i].next = free_list_ + i + 1;
}
free_list_[NumBlocks - 1].next = NULL;
}
template <std::size_t PoolSize, std::size_t BlockSize>
void* PoolAllocator<PoolSize, BlockSize>::allocate(std::size_t size)
{
if (free_list_ == NULL || size > BlockSize)
{
return NULL;
}
void* pmem = free_list_;
free_list_ = free_list_->next;
return pmem;
}
template <std::size_t PoolSize, std::size_t BlockSize>
void PoolAllocator<PoolSize, BlockSize>::deallocate(const void* ptr)
{
if (ptr == NULL)
{
return;
}
Node* p = static_cast<Node*>(const_cast<void*>(ptr));
#if DEBUG || UAVCAN_DEBUG
std::memset(p, 0, sizeof(Node));
#endif
p->next = free_list_;
free_list_ = p;
}
template <std::size_t PoolSize, std::size_t BlockSize>
bool PoolAllocator<PoolSize, BlockSize>::isInPool(const void* ptr) const
{
return ptr >= pool_.bytes &&
ptr < (pool_.bytes + PoolSize);
}
template <std::size_t PoolSize, std::size_t BlockSize>
int PoolAllocator<PoolSize, BlockSize>::getNumFreeBlocks() const
{
int num = 0;
Node* p = free_list_;
while (p)
{
num++;
assert(num <= NumBlocks);
p = p->next;
}
return num;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* editor_folding.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_folding.h"
#include "core/os/file_access.h"
#include "editor_inspector.h"
#include "editor_settings.h"
PoolVector<String> EditorFolding::_get_unfolds(const Object *p_object) {
PoolVector<String> sections;
sections.resize(p_object->editor_get_section_folding().size());
if (sections.size()) {
PoolVector<String>::Write w = sections.write();
int idx = 0;
for (const Set<String>::Element *E = p_object->editor_get_section_folding().front(); E; E = E->next()) {
w[idx++] = E->get();
}
}
return sections;
}
void EditorFolding::save_resource_folding(const RES &p_resource, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
PoolVector<String> unfolds = _get_unfolds(p_resource.ptr());
config->set_value("folding", "sections_unfolded", unfolds);
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
config->save(file);
}
void EditorFolding::_set_unfolds(Object *p_object, const PoolVector<String> &p_unfolds) {
int uc = p_unfolds.size();
PoolVector<String>::Read r = p_unfolds.read();
p_object->editor_clear_section_folding();
for (int i = 0; i < uc; i++) {
p_object->editor_set_section_unfold(r[i], true);
}
}
void EditorFolding::load_resource_folding(RES p_resource, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
if (config->load(file) != OK) {
return;
}
PoolVector<String> unfolds;
if (config->has_section_key("folding", "sections_unfolded")) {
unfolds = config->get_value("folding", "sections_unfolded");
}
_set_unfolds(p_resource.ptr(), unfolds);
}
void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Array &nodes_folded, Set<RES> &resources) {
if (p_root != p_node) {
if (!p_node->get_owner()) {
return; //not owned, bye
}
if (p_node->get_owner() != p_root && !p_root->is_editable_instance(p_node)) {
return;
}
}
if (p_node->is_displayed_folded()) {
nodes_folded.push_back(p_root->get_path_to(p_node));
}
PoolVector<String> unfolds = _get_unfolds(p_node);
if (unfolds.size()) {
p_folds.push_back(p_root->get_path_to(p_node));
p_folds.push_back(unfolds);
}
List<PropertyInfo> plist;
p_node->get_property_list(&plist);
for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
if (E->get().usage & PROPERTY_USAGE_EDITOR) {
if (E->get().type == Variant::OBJECT) {
RES res = p_node->get(E->get().name);
if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) {
PoolVector<String> res_unfolds = _get_unfolds(res.ptr());
resource_folds.push_back(res->get_path());
resource_folds.push_back(res_unfolds);
resources.insert(res);
}
}
}
}
for (int i = 0; i < p_node->get_child_count(); i++) {
_fill_folds(p_root, p_node->get_child(i), p_folds, resource_folds, nodes_folded, resources);
}
}
void EditorFolding::save_scene_folding(const Node *p_scene, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
Array unfolds, res_unfolds;
Set<RES> resources;
Array nodes_folded;
_fill_folds(p_scene, p_scene, unfolds, res_unfolds, nodes_folded, resources);
config->set_value("folding", "node_unfolds", unfolds);
config->set_value("folding", "resource_unfolds", res_unfolds);
config->set_value("folding", "nodes_folded", nodes_folded);
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
config->save(file);
}
void EditorFolding::load_scene_folding(Node *p_scene, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
if (config->load(file) != OK) {
return;
}
Array unfolds;
if (config->has_section_key("folding", "node_unfolds")) {
unfolds = config->get_value("folding", "node_unfolds");
}
Array res_unfolds;
if (config->has_section_key("folding", "resource_unfolds")) {
res_unfolds = config->get_value("folding", "resource_unfolds");
}
Array nodes_folded;
if (config->has_section_key("folding", "nodes_folded")) {
nodes_folded = config->get_value("folding", "nodes_folded");
}
ERR_FAIL_COND(unfolds.size() & 1);
ERR_FAIL_COND(res_unfolds.size() & 1);
for (int i = 0; i < unfolds.size(); i += 2) {
NodePath path2 = unfolds[i];
PoolVector<String> un = unfolds[i + 1];
Node *node = p_scene->get_node_or_null(path2);
if (!node) {
continue;
}
_set_unfolds(node, un);
}
for (int i = 0; i < res_unfolds.size(); i += 2) {
String path2 = res_unfolds[i];
RES res;
if (ResourceCache::has(path2)) {
res = RES(ResourceCache::get(path2));
}
if (res.is_null()) {
continue;
}
PoolVector<String> unfolds2 = res_unfolds[i + 1];
_set_unfolds(res.ptr(), unfolds2);
}
for (int i = 0; i < nodes_folded.size(); i++) {
NodePath fold_path = nodes_folded[i];
if (p_scene->has_node(fold_path)) {
Node *node = p_scene->get_node(fold_path);
node->set_display_folded(true);
}
}
}
bool EditorFolding::has_folding_data(const String &p_path) {
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
return FileAccess::exists(file);
}
void EditorFolding::_do_object_unfolds(Object *p_object, Set<RES> &resources) {
List<PropertyInfo> plist;
p_object->get_property_list(&plist);
String group_base;
String group;
Set<String> unfold_group;
for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
if (E->get().usage & PROPERTY_USAGE_CATEGORY) {
group = "";
group_base = "";
}
if (E->get().usage & PROPERTY_USAGE_GROUP) {
group = E->get().name;
group_base = E->get().hint_string;
if (group_base.ends_with("_")) {
group_base = group_base.substr(0, group_base.length() - 1);
}
}
//can unfold
if (E->get().usage & PROPERTY_USAGE_EDITOR) {
if (group != "") { //group
if (group_base == String() || E->get().name.begins_with(group_base)) {
bool can_revert = EditorPropertyRevert::can_property_revert(p_object, E->get().name);
if (can_revert) {
unfold_group.insert(group);
}
}
} else { //path
int last = E->get().name.find_last("/");
if (last != -1) {
bool can_revert = EditorPropertyRevert::can_property_revert(p_object, E->get().name);
if (can_revert) {
unfold_group.insert(E->get().name.substr(0, last));
}
}
}
}
if (E->get().type == Variant::OBJECT) {
RES res = p_object->get(E->get().name);
if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) {
resources.insert(res);
_do_object_unfolds(res.ptr(), resources);
}
}
}
for (Set<String>::Element *E = unfold_group.front(); E; E = E->next()) {
p_object->editor_set_section_unfold(E->get(), true);
}
}
void EditorFolding::_do_node_unfolds(Node *p_root, Node *p_node, Set<RES> &resources) {
if (p_root != p_node) {
if (!p_node->get_owner()) {
return; //not owned, bye
}
if (p_node->get_owner() != p_root && !p_root->is_editable_instance(p_node)) {
return;
}
}
_do_object_unfolds(p_node, resources);
for (int i = 0; i < p_node->get_child_count(); i++) {
_do_node_unfolds(p_root, p_node->get_child(i), resources);
}
}
void EditorFolding::unfold_scene(Node *p_scene) {
Set<RES> resources;
_do_node_unfolds(p_scene, p_scene, resources);
}
EditorFolding::EditorFolding() {
}
<commit_msg>Prevent crash when scene has path, but no file<commit_after>/*************************************************************************/
/* editor_folding.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_folding.h"
#include "core/os/file_access.h"
#include "editor_inspector.h"
#include "editor_settings.h"
PoolVector<String> EditorFolding::_get_unfolds(const Object *p_object) {
PoolVector<String> sections;
sections.resize(p_object->editor_get_section_folding().size());
if (sections.size()) {
PoolVector<String>::Write w = sections.write();
int idx = 0;
for (const Set<String>::Element *E = p_object->editor_get_section_folding().front(); E; E = E->next()) {
w[idx++] = E->get();
}
}
return sections;
}
void EditorFolding::save_resource_folding(const RES &p_resource, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
PoolVector<String> unfolds = _get_unfolds(p_resource.ptr());
config->set_value("folding", "sections_unfolded", unfolds);
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
config->save(file);
}
void EditorFolding::_set_unfolds(Object *p_object, const PoolVector<String> &p_unfolds) {
int uc = p_unfolds.size();
PoolVector<String>::Read r = p_unfolds.read();
p_object->editor_clear_section_folding();
for (int i = 0; i < uc; i++) {
p_object->editor_set_section_unfold(r[i], true);
}
}
void EditorFolding::load_resource_folding(RES p_resource, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
if (config->load(file) != OK) {
return;
}
PoolVector<String> unfolds;
if (config->has_section_key("folding", "sections_unfolded")) {
unfolds = config->get_value("folding", "sections_unfolded");
}
_set_unfolds(p_resource.ptr(), unfolds);
}
void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Array &nodes_folded, Set<RES> &resources) {
if (p_root != p_node) {
if (!p_node->get_owner()) {
return; //not owned, bye
}
if (p_node->get_owner() != p_root && !p_root->is_editable_instance(p_node)) {
return;
}
}
if (p_node->is_displayed_folded()) {
nodes_folded.push_back(p_root->get_path_to(p_node));
}
PoolVector<String> unfolds = _get_unfolds(p_node);
if (unfolds.size()) {
p_folds.push_back(p_root->get_path_to(p_node));
p_folds.push_back(unfolds);
}
List<PropertyInfo> plist;
p_node->get_property_list(&plist);
for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
if (E->get().usage & PROPERTY_USAGE_EDITOR) {
if (E->get().type == Variant::OBJECT) {
RES res = p_node->get(E->get().name);
if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) {
PoolVector<String> res_unfolds = _get_unfolds(res.ptr());
resource_folds.push_back(res->get_path());
resource_folds.push_back(res_unfolds);
resources.insert(res);
}
}
}
}
for (int i = 0; i < p_node->get_child_count(); i++) {
_fill_folds(p_root, p_node->get_child(i), p_folds, resource_folds, nodes_folded, resources);
}
}
void EditorFolding::save_scene_folding(const Node *p_scene, const String &p_path) {
FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
if (!file_check->file_exists(p_path)) //This can happen when creating scene from FilesystemDock. It has path, but no file.
return;
Ref<ConfigFile> config;
config.instance();
Array unfolds, res_unfolds;
Set<RES> resources;
Array nodes_folded;
_fill_folds(p_scene, p_scene, unfolds, res_unfolds, nodes_folded, resources);
config->set_value("folding", "node_unfolds", unfolds);
config->set_value("folding", "resource_unfolds", res_unfolds);
config->set_value("folding", "nodes_folded", nodes_folded);
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
config->save(file);
}
void EditorFolding::load_scene_folding(Node *p_scene, const String &p_path) {
Ref<ConfigFile> config;
config.instance();
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
if (config->load(file) != OK) {
return;
}
Array unfolds;
if (config->has_section_key("folding", "node_unfolds")) {
unfolds = config->get_value("folding", "node_unfolds");
}
Array res_unfolds;
if (config->has_section_key("folding", "resource_unfolds")) {
res_unfolds = config->get_value("folding", "resource_unfolds");
}
Array nodes_folded;
if (config->has_section_key("folding", "nodes_folded")) {
nodes_folded = config->get_value("folding", "nodes_folded");
}
ERR_FAIL_COND(unfolds.size() & 1);
ERR_FAIL_COND(res_unfolds.size() & 1);
for (int i = 0; i < unfolds.size(); i += 2) {
NodePath path2 = unfolds[i];
PoolVector<String> un = unfolds[i + 1];
Node *node = p_scene->get_node_or_null(path2);
if (!node) {
continue;
}
_set_unfolds(node, un);
}
for (int i = 0; i < res_unfolds.size(); i += 2) {
String path2 = res_unfolds[i];
RES res;
if (ResourceCache::has(path2)) {
res = RES(ResourceCache::get(path2));
}
if (res.is_null()) {
continue;
}
PoolVector<String> unfolds2 = res_unfolds[i + 1];
_set_unfolds(res.ptr(), unfolds2);
}
for (int i = 0; i < nodes_folded.size(); i++) {
NodePath fold_path = nodes_folded[i];
if (p_scene->has_node(fold_path)) {
Node *node = p_scene->get_node(fold_path);
node->set_display_folded(true);
}
}
}
bool EditorFolding::has_folding_data(const String &p_path) {
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file);
return FileAccess::exists(file);
}
void EditorFolding::_do_object_unfolds(Object *p_object, Set<RES> &resources) {
List<PropertyInfo> plist;
p_object->get_property_list(&plist);
String group_base;
String group;
Set<String> unfold_group;
for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
if (E->get().usage & PROPERTY_USAGE_CATEGORY) {
group = "";
group_base = "";
}
if (E->get().usage & PROPERTY_USAGE_GROUP) {
group = E->get().name;
group_base = E->get().hint_string;
if (group_base.ends_with("_")) {
group_base = group_base.substr(0, group_base.length() - 1);
}
}
//can unfold
if (E->get().usage & PROPERTY_USAGE_EDITOR) {
if (group != "") { //group
if (group_base == String() || E->get().name.begins_with(group_base)) {
bool can_revert = EditorPropertyRevert::can_property_revert(p_object, E->get().name);
if (can_revert) {
unfold_group.insert(group);
}
}
} else { //path
int last = E->get().name.find_last("/");
if (last != -1) {
bool can_revert = EditorPropertyRevert::can_property_revert(p_object, E->get().name);
if (can_revert) {
unfold_group.insert(E->get().name.substr(0, last));
}
}
}
}
if (E->get().type == Variant::OBJECT) {
RES res = p_object->get(E->get().name);
if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) {
resources.insert(res);
_do_object_unfolds(res.ptr(), resources);
}
}
}
for (Set<String>::Element *E = unfold_group.front(); E; E = E->next()) {
p_object->editor_set_section_unfold(E->get(), true);
}
}
void EditorFolding::_do_node_unfolds(Node *p_root, Node *p_node, Set<RES> &resources) {
if (p_root != p_node) {
if (!p_node->get_owner()) {
return; //not owned, bye
}
if (p_node->get_owner() != p_root && !p_root->is_editable_instance(p_node)) {
return;
}
}
_do_object_unfolds(p_node, resources);
for (int i = 0; i < p_node->get_child_count(); i++) {
_do_node_unfolds(p_root, p_node->get_child(i), resources);
}
}
void EditorFolding::unfold_scene(Node *p_scene) {
Set<RES> resources;
_do_node_unfolds(p_scene, p_scene, resources);
}
EditorFolding::EditorFolding() {
}
<|endoftext|>
|
<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include <TTree.h>
#include <TError.h>
#include <AliLog.h>
#include <AliAnalysisManager.h>
#include <AliAnalysisDataContainer.h>
#include <AliMESbaseTask.h>
#include <AliMEStenderV2.h>
#endif
AliMEStenderV2 *AddMEStenderV2(Bool_t mc, Int_t configuration = 0)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
AliMEStenderV2 *tender = new AliMEStenderV2((char*)"MEStenderV2");
mgr->AddTask(tender);
// task set-up
tender->SetMCdata(mc);
tender->SetDebugLevel(1);
switch (configuration) {
case 0:
tender->ConfigTask( AliMEStenderV2::AliMESconfigTender::k7TeV, // event cuts
AliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2010, // track cuts
AliMEStenderV2::AliMESconfigTender::kIterative); // PID priors
break;
case 1:
tender->ConfigTask( AliMEStenderV2::AliMESconfigTender::k13TeV, // event cuts
AliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2011, // track cuts
AliMEStenderV2::AliMESconfigTender::kTPC); // PID priors
break;
default: printf("Configuration not defined\n");
break;
}
tender->SetPriors(); // always call this after ConfigTask !!
// connect input
mgr->ConnectInput (tender, 0, mgr->GetCommonInputContainer());
// create output containers
AliAnalysisDataContainer *co[AliMESbaseTask::kNcontainers] = {NULL};
co[0] = mgr->CreateContainer("tenderQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:MES", mgr->GetCommonFileName()));
co[AliMESbaseTask::kEventInfo] = mgr->CreateContainer("MESeventInfo", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
co[AliMESbaseTask::kTracks] = mgr->CreateContainer("MEStracks", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
if(mc){
co[AliMESbaseTask::kMCeventInfo] = mgr->CreateContainer("MESMCeventInfo", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
co[AliMESbaseTask::kMCtracks] = mgr->CreateContainer("MESMCtracks", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
}
// connect output
for(Int_t ios(0);ios<AliMESbaseTask::kNcontainers;ios++)
if(co[ios]) mgr->ConnectOutput(tender, ios+1, co[ios]);
return tender;
}
<commit_msg>fix Invalid AliEn path string error<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TTree.h>
#include <TError.h>
#include <AliLog.h>
#include <AliAnalysisManager.h>
#include <AliAnalysisDataContainer.h>
#include <AliMESbaseTask.h>
#include <AliMEStenderV2.h>
#endif
AliMEStenderV2 *AddMEStenderV2(Bool_t mc, Int_t configuration = 1, const AliVEvent *event)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
AliCDBManager *man = AliCDBManager::Instance();
if (man)
{
if (!man->IsDefaultStorageSet())
{
man->SetDefaultStorage(Form("alien://folder=/alice/data/2015/OCDB?cacheFolder=%s/local", gSystem->ExpandPathName("$HOME")));
man->SetRun(event->GetRunNumber());
AliGRPObject *grp = (AliGRPObject *)man->Get("GRP/GRP/Data")->GetObject();
}
}
AliMEStenderV2 *tender = new AliMEStenderV2((char *)"MEStenderV2");
mgr->AddTask(tender);
// task set-up
tender->SetMCdata(mc);
tender->SetDebugLevel(1);
switch (configuration)
{
case 0:
tender->ConfigTask(AliMEStenderV2::AliMESconfigTender::k7TeV, // event cuts
AliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2010, // track cuts
AliMEStenderV2::AliMESconfigTender::kIterative); // PID priors
break;
case 1:
tender->ConfigTask(AliMEStenderV2::AliMESconfigTender::k13TeV, // event cuts
AliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2011, // track cuts
AliMEStenderV2::AliMESconfigTender::kNoPP); // PID priors
break;
default:
printf("Configuration not defined\n");
break;
}
tender->SetPriors(); // always call this after ConfigTask !!
// connect input
mgr->ConnectInput(tender, 0, mgr->GetCommonInputContainer());
// create output containers
AliAnalysisDataContainer *co[AliMESbaseTask::kNcontainers] = {NULL};
co[0] = mgr->CreateContainer("tenderQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:MES", mgr->GetCommonFileName()));
co[AliMESbaseTask::kEventInfo] = mgr->CreateContainer("MESeventInfo", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
co[AliMESbaseTask::kTracks] = mgr->CreateContainer("MEStracks", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
if (mc)
{
co[AliMESbaseTask::kMCeventInfo] = mgr->CreateContainer("MESMCeventInfo", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
co[AliMESbaseTask::kMCtracks] = mgr->CreateContainer("MESMCtracks", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
}
// connect output
for (Int_t ios(0); ios < AliMESbaseTask::kNcontainers; ios++)
if (co[ios])
mgr->ConnectOutput(tender, ios + 1, co[ios]);
return tender;
}
<|endoftext|>
|
<commit_before>
#include "MaxSatInstance.hh"
bool MaxSatInstance::isTautologicalClause( int lits[ MAX_NUM_LITERALS ], int& numLits, const int clauseNum ) {
// sort the clause and remove redundant literals
//!! For large clauses better use sort()
int temp, tempLit;
for (int i=0; i<numLits-1; tempLit = lits[i++]) {
for (int j=i+1; j<numLits; j++) {
if (abs(tempLit) > abs(lits[j])) {
temp = lits[j];
lits[j] = tempLit;
tempLit = temp;
} else if (tempLit == lits[j]) {
lits[j--] = lits[--numLits];
printf("c literal %d is redundant in clause %d\n", tempLit, clauseNum);
} else if (abs(tempLit) == abs(lits[j])) {
printf("c Clause %d is tautological.\n", clauseNum);
return true;
}
}
}
return false;
}
MaxSatInstance::MaxSatInstance( const char* filename )
{
ifstream infile(filename);
if (!infile) {
fprintf(stderr, "c Error: could not read from %s.\n", filename);
exit(1);
}
while (infile.get() != 'p') {
infile.ignore(MAX_LINE_LENGTH, '\n');
}
char strbuf[MAX_LINE_LENGTH];
infile >> strbuf;
if( strcmp(strbuf, "cnf")==0 ) {
format = CNF;
} else if( strcmp(strbuf, "wcnf")==0 ) {
format = WEIGHTED;
} else if( strcmp(strbuf, "pcnf")==0 ) {
format = PARTIAL;
} else if( strcmp(strbuf, "wpcnf")==0 ) {
format = WEIGHTED_PARTIAL;
} else {
fprintf(stderr, "c Error: Can only understand cnf format!\n");
exit(1);
}
infile >> numVars >> numClauses;
clauseLengths = new int[ numClauses ];
negClausesWithVar = new vector<int>[ numVars+1 ];
posClausesWithVar = new vector<int>[ numVars+1 ];
unitClauses = binaryClauses = ternaryClauses = 0;
int lits[ MAX_NUM_LITERALS ];
for (int clauseNum=0; clauseNum<numClauses; clauseNum++) {
int numLits = 0;
infile >> lits[numLits];
while (lits[numLits] != 0)
infile >> lits[++numLits];
if ( numLits == 1 or !isTautologicalClause( lits, numLits, clauseNum )) {
clauseLengths[clauseNum] = numLits;
switch( numLits ) {
case 1: unitClauses++; break;
case 2: binaryClauses++; break;
case 3: ternaryClauses++; break;
}
for (int litNum = 0; litNum < numLits; litNum++)
if (lits[litNum] < 0)
negClausesWithVar[abs(lits[litNum])].push_back(clauseNum);
else
posClausesWithVar[lits[litNum]].push_back(clauseNum);
} else {
clauseNum--;
numClauses--;
}
}
}
MaxSatInstance::~MaxSatInstance() {
delete clauseLengths;
}
void MaxSatInstance::printInfo(ostream& os) {
os << "Num vars: " << numVars << endl;
os << "Num clauses: " << numClauses << endl;
os << "Ratio c/v: " << (float)numClauses/numVars << endl;
int negClauses = 0, posClauses = 0;
for (int varNum=1; varNum<=numVars; varNum++) {
negClauses += negClausesWithVar[ varNum ].size();
posClauses += posClausesWithVar[ varNum ].size();
}
os << "Neg : " << (float)negClauses/numClauses << endl;
os << "Pos : " << (float)posClauses/numClauses << endl;
os << "Unary: " << (float)unitClauses/numClauses << endl;
os << "Binary: " << (float)binaryClauses/numClauses << endl;
os << "Ternary: " << (float)ternaryClauses/numClauses << endl;
}
<commit_msg>msz format with explained features Always add explanation in mszFormat.txt file about features you add in MaxSatInstance.cc program<commit_after>
#include "MaxSatInstance.hh"
bool MaxSatInstance::isTautologicalClause( int lits[ MAX_NUM_LITERALS ], int& numLits, const int clauseNum ) {
// sort the clause and remove redundant literals
//!! For large clauses better use sort()
int temp, tempLit;
for (int i=0; i<numLits-1; tempLit = lits[i++]) {
for (int j=i+1; j<numLits; j++) {
if (abs(tempLit) > abs(lits[j])) {
temp = lits[j];
lits[j] = tempLit;
tempLit = temp;
} else if (tempLit == lits[j]) {
lits[j--] = lits[--numLits];
printf("c literal %d is redundant in clause %d\n", tempLit, clauseNum);
} else if (abs(tempLit) == abs(lits[j])) {
printf("c Clause %d is tautological.\n", clauseNum);
return true;
}
}
}
return false;
}
MaxSatInstance::MaxSatInstance( const char* filename )
{
ifstream infile(filename);
if (!infile) {
fprintf(stderr, "c Error: could not read from %s.\n", filename);
exit(1);
}
while (infile.get() != 'p') {
infile.ignore(MAX_LINE_LENGTH, '\n');
}
char strbuf[MAX_LINE_LENGTH];
infile >> strbuf;
if( strcmp(strbuf, "cnf")==0 ) {
format = CNF;
} else if( strcmp(strbuf, "wcnf")==0 ) {
format = WEIGHTED;
} else if( strcmp(strbuf, "pcnf")==0 ) {
format = PARTIAL;
} else if( strcmp(strbuf, "wpcnf")==0 ) {
format = WEIGHTED_PARTIAL;
} else {
fprintf(stderr, "c Error: Can only understand cnf format!\n");
exit(1);
}
infile >> numVars >> numClauses;
clauseLengths = new int[ numClauses ];
negClausesWithVar = new vector<int>[ numVars+1 ];
posClausesWithVar = new vector<int>[ numVars+1 ];
unitClauses = binaryClauses = ternaryClauses = 0;
int lits[ MAX_NUM_LITERALS ];
for (int clauseNum=0; clauseNum<numClauses; clauseNum++) {
int numLits = 0;
infile >> lits[numLits];
while (lits[numLits] != 0)
infile >> lits[++numLits];
if ( numLits == 1 or !isTautologicalClause( lits, numLits, clauseNum )) {
clauseLengths[clauseNum] = numLits;
switch( numLits ) {
case 1: unitClauses++; break;
case 2: binaryClauses++; break;
case 3: ternaryClauses++; break;
}
for (int litNum = 0; litNum < numLits; litNum++)
if (lits[litNum] < 0)
negClausesWithVar[abs(lits[litNum])].push_back(clauseNum);
else
posClausesWithVar[lits[litNum]].push_back(clauseNum);
} else {
clauseNum--;
numClauses--;
}
}
}
MaxSatInstance::~MaxSatInstance() {
delete clauseLengths;
}
void MaxSatInstance::printInfo(ostream& os) {
os << "Vrs " << numVars << endl;
os << "Cls " << numClauses << endl;
os << "C/V: " << (float)numClauses/numVars << endl;
int negClauses = 0, posClauses = 0;
for (int varNum=1; varNum<=numVars; varNum++) {
negClauses += negClausesWithVar[ varNum ].size();
posClauses += posClausesWithVar[ varNum ].size();
}
os << "Neg " << (float)negClauses/numClauses << endl;
os << "Pos " << (float)posClauses/numClauses << endl;
os << "Una " << (float)unitClauses/numClauses << endl;
os << "Bin " << (float)binaryClauses/numClauses << endl;
os << "Ter " << (float)ternaryClauses/numClauses << endl;
}
<|endoftext|>
|
<commit_before>/*
* Originally written by Xinef - Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "vault_of_archavon.h"
#include "SpellAuras.h"
#include "SpellScript.h"
enum Archavon
{
SPELL_ROCK_SHARDS = 58678,
SPELL_CRUSHING_LEAP_10 = 58960,
SPELL_CRUSHING_LEAP_25 = 60894, //Instant (10-80yr range) -- Leaps at an enemy, inflicting 8000 Physical damage, knocking all nearby enemies away, and creating a cloud of choking debris.
SPELL_STOMP_10 = 58663,
SPELL_STOMP_25 = 60880,
SPELL_IMPALE_10 = 58666,
SPELL_IMPALE_25 = 60882, //Lifts an enemy off the ground with a spiked fist, inflicting 47125 to 52875 Physical damage and 9425 to 10575 additional damage each second for 8 sec.
SPELL_BERSERK = 47008,
};
enum
{
EMOTE_BERSERK = 0,
EMOTE_LEAP = 1 // Not in use
};
enum Events
{
EVENT_ROCK_SHARDS = 1,
EVENT_CHOKING_CLOUD = 2,
EVENT_STOMP = 3,
EVENT_IMPALE = 4,
EVENT_BERSERK = 5,
};
class boss_archavon : public CreatureScript
{
public:
boss_archavon() : CreatureScript("boss_archavon") { }
struct boss_archavonAI : public ScriptedAI
{
boss_archavonAI(Creature* creature) : ScriptedAI(creature)
{
pInstance = me->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
void Reset()
{
events.Reset();
if (pInstance)
{
if (pInstance->GetData(DATA_STONED))
{
if (Aura* aur = me->AddAura(SPELL_STONED_AURA, me))
{
aur->SetMaxDuration(60 * MINUTE* IN_MILLISECONDS);
aur->SetDuration(60 * MINUTE* IN_MILLISECONDS);
}
}
pInstance->SetData(EVENT_ARCHAVON, NOT_STARTED);
}
}
void AttackStart(Unit* who)
{
if (me->HasAura(SPELL_STONED_AURA))
return;
ScriptedAI::AttackStart(who);
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_ROCK_SHARDS, 15000);
events.ScheduleEvent(EVENT_CHOKING_CLOUD, 30000);
events.ScheduleEvent(EVENT_STOMP, 45000);
events.ScheduleEvent(EVENT_BERSERK, 300000);
if (pInstance)
pInstance->SetData(EVENT_ARCHAVON, IN_PROGRESS);
}
void JustDied(Unit* )
{
if (pInstance)
pInstance->SetData(EVENT_ARCHAVON, DONE);
}
void UpdateAI(uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
switch (events.GetEvent())
{
case EVENT_ROCK_SHARDS:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
me->CastSpell(target, SPELL_ROCK_SHARDS, false);
events.RepeatEvent(15000);
break;
case EVENT_CHOKING_CLOUD:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1))
me->CastSpell(target, RAID_MODE(SPELL_CRUSHING_LEAP_10, SPELL_CRUSHING_LEAP_25), true); //10y~80y, ignore range
events.RepeatEvent(30000);
break;
case EVENT_STOMP:
{
char buffer[100];
sprintf(buffer, "Archavon the Stone Watcher lunges for %s!", me->GetVictim()->GetName().c_str());
me->MonsterTextEmote(buffer, 0);
me->CastSpell(me->GetVictim(), RAID_MODE(SPELL_STOMP_10, SPELL_STOMP_25), false);
events.RepeatEvent(45000);
events.ScheduleEvent(EVENT_IMPALE, 3000);
break;
}
case EVENT_IMPALE:
me->CastSpell(me->GetVictim(), RAID_MODE(SPELL_IMPALE_10, SPELL_IMPALE_25), false);
events.PopEvent();
break;
case EVENT_BERSERK:
me->CastSpell(me, SPELL_BERSERK, true);
Talk(EMOTE_BERSERK);
events.PopEvent();
break;
default:
break;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_archavonAI(creature);
}
};
class spell_archavon_rock_shards : public SpellScriptLoader
{
public:
spell_archavon_rock_shards() : SpellScriptLoader("spell_archavon_rock_shards") { }
class spell_archavon_rock_shards_SpellScript : public SpellScript
{
PrepareSpellScript(spell_archavon_rock_shards_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
Unit* target = GetHitUnit();
Unit* caster = GetOriginalCaster();
if (target && caster && caster->GetMap())
{
for (uint32 i = 0; i < 3; ++i)
{
caster->CastSpell(target, 58689, true);
caster->CastSpell(target, 58692, true);
}
caster->CastSpell(target, caster->GetMap()->Is25ManRaid() ? 60883 : 58695, true);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_archavon_rock_shards_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const
{
return new spell_archavon_rock_shards_SpellScript();
}
};
void AddSC_boss_archavon()
{
new boss_archavon();
new spell_archavon_rock_shards();
}
<commit_msg>Fixed Archavon's Stone Breath knockback on tank.<commit_after>/*
* Originally written by Xinef - Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "vault_of_archavon.h"
#include "SpellAuras.h"
#include "SpellScript.h"
enum Archavon
{
SPELL_ROCK_SHARDS = 58678,
SPELL_CRUSHING_LEAP_10 = 58960,
SPELL_CRUSHING_LEAP_25 = 60894, //Instant (10-80yr range) -- Leaps at an enemy, inflicting 8000 Physical damage, knocking all nearby enemies away, and creating a cloud of choking debris.
SPELL_STOMP_10 = 58663,
SPELL_STOMP_25 = 60880,
SPELL_IMPALE_10 = 58666,
SPELL_IMPALE_25 = 60882, //Lifts an enemy off the ground with a spiked fist, inflicting 47125 to 52875 Physical damage and 9425 to 10575 additional damage each second for 8 sec.
SPELL_BERSERK = 47008,
};
enum
{
EMOTE_BERSERK = 0,
EMOTE_LEAP = 1 // Not in use
};
enum Events
{
EVENT_ROCK_SHARDS = 1,
EVENT_CHOKING_CLOUD = 2,
EVENT_STOMP = 3,
EVENT_IMPALE = 4,
EVENT_BERSERK = 5,
};
class boss_archavon : public CreatureScript
{
public:
boss_archavon() : CreatureScript("boss_archavon") { }
struct boss_archavonAI : public ScriptedAI
{
boss_archavonAI(Creature* creature) : ScriptedAI(creature)
{
pInstance = me->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
void Reset()
{
events.Reset();
if (pInstance)
{
if (pInstance->GetData(DATA_STONED))
{
if (Aura* aur = me->AddAura(SPELL_STONED_AURA, me))
{
aur->SetMaxDuration(60 * MINUTE* IN_MILLISECONDS);
aur->SetDuration(60 * MINUTE* IN_MILLISECONDS);
}
}
pInstance->SetData(EVENT_ARCHAVON, NOT_STARTED);
}
}
void AttackStart(Unit* who)
{
if (me->HasAura(SPELL_STONED_AURA))
return;
ScriptedAI::AttackStart(who);
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_ROCK_SHARDS, 15000);
events.ScheduleEvent(EVENT_CHOKING_CLOUD, 30000);
events.ScheduleEvent(EVENT_STOMP, 45000);
events.ScheduleEvent(EVENT_BERSERK, 300000);
if (pInstance)
pInstance->SetData(EVENT_ARCHAVON, IN_PROGRESS);
}
void JustDied(Unit* )
{
if (pInstance)
pInstance->SetData(EVENT_ARCHAVON, DONE);
}
void UpdateAI(uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
switch (events.GetEvent())
{
case EVENT_ROCK_SHARDS:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
me->CastSpell(target, SPELL_ROCK_SHARDS, false);
events.RepeatEvent(15000);
break;
case EVENT_CHOKING_CLOUD:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1))
me->CastSpell(target, RAID_MODE(SPELL_CRUSHING_LEAP_10, SPELL_CRUSHING_LEAP_25), true); //10y~80y, ignore range
events.RepeatEvent(30000);
break;
case EVENT_STOMP:
{
char buffer[100];
sprintf(buffer, "Archavon the Stone Watcher lunges for %s!", me->GetVictim()->GetName().c_str());
me->MonsterTextEmote(buffer, 0);
me->CastSpell(me->GetVictim(), RAID_MODE(SPELL_STOMP_10, SPELL_STOMP_25), false);
me->GetVictim()->KnockbackFrom(me->GetPositionX(), me->GetPositionY(), 3.0f, 40.0f);
events.RepeatEvent(45000);
events.ScheduleEvent(EVENT_IMPALE, 3000);
break;
}
case EVENT_IMPALE:
me->CastSpell(me->GetVictim(), RAID_MODE(SPELL_IMPALE_10, SPELL_IMPALE_25), false);
events.PopEvent();
break;
case EVENT_BERSERK:
me->CastSpell(me, SPELL_BERSERK, true);
Talk(EMOTE_BERSERK);
events.PopEvent();
break;
default:
break;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_archavonAI(creature);
}
};
class spell_archavon_rock_shards : public SpellScriptLoader
{
public:
spell_archavon_rock_shards() : SpellScriptLoader("spell_archavon_rock_shards") { }
class spell_archavon_rock_shards_SpellScript : public SpellScript
{
PrepareSpellScript(spell_archavon_rock_shards_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
Unit* target = GetHitUnit();
Unit* caster = GetOriginalCaster();
if (target && caster && caster->GetMap())
{
for (uint32 i = 0; i < 3; ++i)
{
caster->CastSpell(target, 58689, true);
caster->CastSpell(target, 58692, true);
}
caster->CastSpell(target, caster->GetMap()->Is25ManRaid() ? 60883 : 58695, true);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_archavon_rock_shards_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const
{
return new spell_archavon_rock_shards_SpellScript();
}
};
void AddSC_boss_archavon()
{
new boss_archavon();
new spell_archavon_rock_shards();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
const std::string number_lookup[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
const std::string suit_lookup[] = {"D", "C", "H", "S"};
int player_cash = 100;
class Card {
public:
int number;
int suit;
Card() {
number = (double) rand()/RAND_MAX*13;
suit = (double) rand()/RAND_MAX*4;
}
Card(int n, int s) {
number = n;
suit = s;
}
std::string getString() {
std::string s;
s = number_lookup[number];
s.append(suit_lookup[suit]);
return s;
}
};
void new_game(void) {
int player_bet;
// Get user input from player for bet amount and subtract it
std::cout << "Player: $" << player_cash << "\nPay for this round: ";
std::cin >> player_bet;
player_cash -= player_bet;
// std::cout << player_cash << endl; // Debug print
Card test_card;
std::cout << "Debug: " << test_card.getString() << std::endl;
}
int main(void){
srand(time(0)); // initialize random number generator
new_game();
return 0;
}
<commit_msg>added player, and game class, tested some functions<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <vector>
const std::string number_lookup[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
const std::string suit_lookup[] = {"D", "C", "H", "S"};
const int face_value[] = { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
#define INITIAL_CASH 100
class Card {
private:
int number;
int suit;
public:
Card() {
number = (double) rand()/RAND_MAX*13;
suit = (double) rand()/RAND_MAX*4;
}
Card(int n, int s) {
number = n;
suit = s;
}
std::string getString() {
std::string s;
s = number_lookup[number];
s.append(suit_lookup[suit]);
return s;
}
int getValue() {
return face_value[number];
}
bool isAce() {
return (number == 0);
}
};
class Player {
public:
int hasAce;
std::vector<Card> hand;
Player() {
hasAce = 0;
}
int getScore() {
int score;
for (std::vector<Card>::iterator it = hand.begin() ; it != hand.end(); ++it) {
if (it->isAce()) {
hasAce = true;
}
score += it->getValue();
}
while (hasAce && score > 21) {
score -= 10;
}
return score;
}
std::string getHand() {
std::string s = "";
for (std::vector<Card>::iterator it = hand.begin() ; it != hand.end(); ++it) {
s.append(it->getString());
s.append(" ");
}
std::cout << s << std::endl;
return s;
}
void drawCard() {
Card card;
if (card.isAce()) {
hasAce++;
}
hand.push_back(card);
}
};
class Game {
public:
int player_cash;
Player player, dealer;
void newGame() {
player_cash = 100;
int player_bet;
std::cout << "Player: $" << player_cash << "\nPay for this round: "; // Get player bet amount and deduct it
std::cin >> player_bet;
player_cash -= player_bet;
player.drawCard(); // Draw cards for player and dealer
player.drawCard();
dealer.drawCard();
playRound();
}
void playRound() {
std::cout << "Dealer : * " << dealer.getHand() << "\nPlayer : " << player.getHand() << "\nDraw? (Y/N) ";
char ch;
while (ch != 'y' || ch != 'n') {
std::cin >> ch;
ch = tolower(ch);
if (ch == 'y') {
player.drawCard();
playRound();
}
else {
finishRound();
}
}
}
void finishRound() {
std::cout << "Debug: finish_round" << std::endl;
}
int checkWin(Player player, Player dealer) { // 0 = loss, 1 = tie, 2 = win
if (player.getScore() > 21) {
return 0;
}
else if (dealer.getScore() > 21) {
return 2;
}
else if (dealer.getScore() == player.getScore()) {
return 1;
}
else if (dealer.getScore() > player.getScore()) {
return 0;
}
else {
return 2;
}
}
};
int main() {
srand(time(0)); // initialize random number generator
Card test_card;
std::cout << "Debug: " << test_card.getString() << std::endl;
Game game;
game.newGame();
}
<|endoftext|>
|
<commit_before>// Natron
//
/* 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/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "OfxClipInstance.h"
#include <cfloat>
#include <limits>
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/Settings.h"
#include "Engine/ImageFetcher.h"
#include "Engine/Image.h"
#include "Engine/Hash64.h"
#include "Global/AppManager.h"
#include "Global/Macros.h"
using namespace Natron;
OfxClipInstance::OfxClipInstance(OfxEffectInstance* nodeInstance
,Natron::OfxImageEffectInstance* effect
,int /*index*/
, OFX::Host::ImageEffect::ClipDescriptor* desc)
: OFX::Host::ImageEffect::ClipInstance(effect, *desc)
, _nodeInstance(nodeInstance)
, _effect(effect)
{
}
/// Get the Raw Unmapped Pixel Depth from the host. We are always 8 bits in our example
const std::string& OfxClipInstance::getUnmappedBitDepth() const
{
// we always use floats
static const std::string v(kOfxBitDepthFloat);
return v;
}
/// Get the Raw Unmapped Components from the host. In our example we are always RGBA
const std::string &OfxClipInstance::getUnmappedComponents() const
{
static const std::string rgbStr(kOfxImageComponentRGB);
static const std::string noneStr(kOfxImageComponentNone);
static const std::string rgbaStr(kOfxImageComponentRGBA);
static const std::string alphaStr(kOfxImageComponentAlpha);
//bool rgb = false;
//bool alpha = false;
//const ChannelSet& channels = _effect->info().channels();
//if(channels & alpha) alpha = true;
//if(channels & Mask_RGB) rgb = true;
// if(!rgb && !alpha) return noneStr;
// else if(rgb && !alpha) return rgbStr;
// else if(!rgb && alpha) return alphaStr;
return rgbaStr;
}
// PreMultiplication -
//
// kOfxImageOpaque - the image is opaque and so has no premultiplication state
// kOfxImagePreMultiplied - the image is premultiplied by it's alpha
// kOfxImageUnPreMultiplied - the image is unpremultiplied
const std::string &OfxClipInstance::getPremult() const
{
static const std::string v(kOfxImageUnPreMultiplied);
return v;
}
// Pixel Aspect Ratio -
//
// The pixel aspect ratio of a clip or image.
double OfxClipInstance::getAspectRatio() const
{
return _effect->getProjectPixelAspectRatio();
}
// Frame Rate -
double OfxClipInstance::getFrameRate() const
{
return _effect->getFrameRate();
}
// Frame Range (startFrame, endFrame) -
//
// The frame range over which a clip has images.
void OfxClipInstance::getFrameRange(double &startFrame, double &endFrame) const
{
SequenceTime first = 0,last = 0;
EffectInstance* n = getAssociatedNode();
if(n)
n->getFrameRange(&first, &last);
startFrame = first;
endFrame = last;
}
/// Field Order - Which spatial field occurs temporally first in a frame.
/// \returns
/// - kOfxImageFieldNone - the clip material is unfielded
/// - kOfxImageFieldLower - the clip material is fielded, with image rows 0,2,4.... occuring first in a frame
/// - kOfxImageFieldUpper - the clip material is fielded, with image rows line 1,3,5.... occuring first in a frame
const std::string &OfxClipInstance::getFieldOrder() const
{
return _effect->getDefaultOutputFielding();
}
// Connected -
//
// Says whether the clip is actually connected at the moment.
bool OfxClipInstance::getConnected() const
{
return getAssociatedNode() != NULL;
}
// Unmapped Frame Rate -
//
// The unmaped frame range over which an output clip has images.
double OfxClipInstance::getUnmappedFrameRate() const
{
//return getNode().asImageEffectNode().getOutputFrameRate();
return 25;
}
// Unmapped Frame Range -
//
// The unmaped frame range over which an output clip has images.
// this is applicable only to hosts and plugins that allow a plugin to change frame rates
void OfxClipInstance::getUnmappedFrameRange(double &unmappedStartFrame, double &unmappedEndFrame) const
{
unmappedStartFrame = 1;
unmappedEndFrame = 1;
}
// Continuous Samples -
//
// 0 if the images can only be sampled at discreet times (eg: the clip is a sequence of frames),
// 1 if the images can only be sampled continuously (eg: the clip is infact an animating roto spline and can be rendered anywhen).
bool OfxClipInstance::getContinuousSamples() const
{
return false;
}
/// override this to return the rod on the clip cannoical coords!
OfxRectD OfxClipInstance::getRegionOfDefinition(OfxTime time) const
{
OfxRectD ret;
RectI rod;
EffectInstance* n = getAssociatedNode();
if(n){
n->getRegionOfDefinition(time,&rod);
ret.x1 = rod.left();
ret.x2 = rod.right();
ret.y1 = rod.bottom();
ret.y2 = rod.top();
}
else{
_nodeInstance->effectInstance()->getProjectOffset(ret.x1, ret.y1);
_nodeInstance->effectInstance()->getProjectExtent(ret.x2, ret.y2);
}
return ret;
}
/// override this to fill in the image at the given time.
/// The bounds of the image on the image plane should be
/// 'appropriate', typically the value returned in getRegionsOfInterest
/// on the effect instance. Outside a render call, the optionalBounds should
/// be 'appropriate' for the.
/// If bounds is not null, fetch the indicated section of the canonical image plane.
OFX::Host::ImageEffect::Image* OfxClipInstance::getImage(OfxTime time, OfxRectD *optionalBounds)
{
return getImageInternal(time,_viewRendered.localData(),optionalBounds);
}
OFX::Host::ImageEffect::Image* OfxClipInstance::getImageInternal(OfxTime time, int view, OfxRectD */*optionalBounds*/){
if(isOutput()){
boost::shared_ptr<Natron::Image> outputImage = _nodeInstance->getImageBeingRendered(time,view);
assert(outputImage);
return new OfxImage(outputImage,*this);
}else{
RenderScale scale;
scale.x = scale.y = 1.;
// input has been rendered just find it in the cache
EffectInstance* input = getAssociatedNode();
if(isOptional() && !input) {
//make an empty image
boost::shared_ptr<Natron::Image> outputImage = _nodeInstance->getImageBeingRendered(time,view);
assert(outputImage);
const RectI& rod = outputImage->getRoD();
boost::shared_ptr<Natron::Image> image(new Natron::Image(rod,scale,time));
image->defaultInitialize();
return new OfxImage(image,*this);
}
assert(input);
int inputIndex = 0;
for (int i = 0; i < _nodeInstance->maximumInputs(); ++i) {
EffectInstance* n = _nodeInstance->input(i);
if (n == input) {
inputIndex = i;
break;
}
}
return new OfxImage(boost::const_pointer_cast<Natron::Image>(_nodeInstance->getImage(inputIndex,time, scale,view)),*this);
}
}
OfxImage::OfxImage(boost::shared_ptr<Natron::Image> internalImage,OfxClipInstance &clip):
OFX::Host::ImageEffect::Image(clip)
,_bitDepth(OfxImage::eBitDepthFloat)
,_floatImage(internalImage)
{
RenderScale scale = internalImage->getRenderScale();
setDoubleProperty(kOfxImageEffectPropRenderScale, scale.x, 0);
setDoubleProperty(kOfxImageEffectPropRenderScale, scale.y, 1);
// data ptr
const RectI& rod = internalImage->getRoD();
setPointerProperty(kOfxImagePropData,internalImage->pixelAt(rod.left(), rod.bottom()));
// bounds and rod
setIntProperty(kOfxImagePropBounds, rod.left(), 0);
setIntProperty(kOfxImagePropBounds, rod.bottom(), 1);
setIntProperty(kOfxImagePropBounds, rod.right(), 2);
setIntProperty(kOfxImagePropBounds, rod.top(), 3);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.left(), 0);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.bottom(), 1);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.right(), 2);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.top(), 3);
// row bytes
setIntProperty(kOfxImagePropRowBytes, rod.width()*4*sizeof(float));
setStringProperty(kOfxImageEffectPropComponents, kOfxImageComponentRGBA);
}
OfxRGBAColourF* OfxImage::pixelF(int x, int y) const{
assert(_bitDepth == eBitDepthFloat);
const RectI& bounds = _floatImage->getRoD();
if ((x >= bounds.left()) && ( x < bounds.right()) && ( y >= bounds.bottom()) && ( y < bounds.top()) )
{
return reinterpret_cast<OfxRGBAColourF*>(_floatImage->pixelAt(x, y));
}
return 0;
}
Natron::EffectInstance* OfxClipInstance::getAssociatedNode() const {
if(_isOutput)
return _nodeInstance;
else{
int index = 0;
OfxEffectInstance::MappedInputV inputs = _nodeInstance->inputClipsCopyWithoutOutput();
for (U32 i = 0; i < inputs.size(); ++i) {
if (inputs[i]->getName() == getName()) {
index = i;
break;
}
}
return _nodeInstance->input(inputs.size()-1-index);
}
}
OFX::Host::ImageEffect::Image* OfxClipInstance::getStereoscopicImage(OfxTime time, int view, OfxRectD *optionalBounds) {
return getImageInternal(time,view,optionalBounds);
}
void OfxClipInstance::setView(int view){
_viewRendered.setLocalData(view);
}
<commit_msg>Unconnected masks are now always initialized to 1 for RGBA instead of 0 for color and 1 for alpha. It makes a lot of plugins work with un-connected masks.<commit_after>// Natron
//
/* 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/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "OfxClipInstance.h"
#include <cfloat>
#include <limits>
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/Settings.h"
#include "Engine/ImageFetcher.h"
#include "Engine/Image.h"
#include "Engine/Hash64.h"
#include "Global/AppManager.h"
#include "Global/Macros.h"
using namespace Natron;
OfxClipInstance::OfxClipInstance(OfxEffectInstance* nodeInstance
,Natron::OfxImageEffectInstance* effect
,int /*index*/
, OFX::Host::ImageEffect::ClipDescriptor* desc)
: OFX::Host::ImageEffect::ClipInstance(effect, *desc)
, _nodeInstance(nodeInstance)
, _effect(effect)
{
}
/// Get the Raw Unmapped Pixel Depth from the host. We are always 8 bits in our example
const std::string& OfxClipInstance::getUnmappedBitDepth() const
{
// we always use floats
static const std::string v(kOfxBitDepthFloat);
return v;
}
/// Get the Raw Unmapped Components from the host. In our example we are always RGBA
const std::string &OfxClipInstance::getUnmappedComponents() const
{
static const std::string rgbStr(kOfxImageComponentRGB);
static const std::string noneStr(kOfxImageComponentNone);
static const std::string rgbaStr(kOfxImageComponentRGBA);
static const std::string alphaStr(kOfxImageComponentAlpha);
//bool rgb = false;
//bool alpha = false;
//const ChannelSet& channels = _effect->info().channels();
//if(channels & alpha) alpha = true;
//if(channels & Mask_RGB) rgb = true;
// if(!rgb && !alpha) return noneStr;
// else if(rgb && !alpha) return rgbStr;
// else if(!rgb && alpha) return alphaStr;
return rgbaStr;
}
// PreMultiplication -
//
// kOfxImageOpaque - the image is opaque and so has no premultiplication state
// kOfxImagePreMultiplied - the image is premultiplied by it's alpha
// kOfxImageUnPreMultiplied - the image is unpremultiplied
const std::string &OfxClipInstance::getPremult() const
{
static const std::string v(kOfxImageUnPreMultiplied);
return v;
}
// Pixel Aspect Ratio -
//
// The pixel aspect ratio of a clip or image.
double OfxClipInstance::getAspectRatio() const
{
return _effect->getProjectPixelAspectRatio();
}
// Frame Rate -
double OfxClipInstance::getFrameRate() const
{
return _effect->getFrameRate();
}
// Frame Range (startFrame, endFrame) -
//
// The frame range over which a clip has images.
void OfxClipInstance::getFrameRange(double &startFrame, double &endFrame) const
{
SequenceTime first = 0,last = 0;
EffectInstance* n = getAssociatedNode();
if(n)
n->getFrameRange(&first, &last);
startFrame = first;
endFrame = last;
}
/// Field Order - Which spatial field occurs temporally first in a frame.
/// \returns
/// - kOfxImageFieldNone - the clip material is unfielded
/// - kOfxImageFieldLower - the clip material is fielded, with image rows 0,2,4.... occuring first in a frame
/// - kOfxImageFieldUpper - the clip material is fielded, with image rows line 1,3,5.... occuring first in a frame
const std::string &OfxClipInstance::getFieldOrder() const
{
return _effect->getDefaultOutputFielding();
}
// Connected -
//
// Says whether the clip is actually connected at the moment.
bool OfxClipInstance::getConnected() const
{
return getAssociatedNode() != NULL;
}
// Unmapped Frame Rate -
//
// The unmaped frame range over which an output clip has images.
double OfxClipInstance::getUnmappedFrameRate() const
{
//return getNode().asImageEffectNode().getOutputFrameRate();
return 25;
}
// Unmapped Frame Range -
//
// The unmaped frame range over which an output clip has images.
// this is applicable only to hosts and plugins that allow a plugin to change frame rates
void OfxClipInstance::getUnmappedFrameRange(double &unmappedStartFrame, double &unmappedEndFrame) const
{
unmappedStartFrame = 1;
unmappedEndFrame = 1;
}
// Continuous Samples -
//
// 0 if the images can only be sampled at discreet times (eg: the clip is a sequence of frames),
// 1 if the images can only be sampled continuously (eg: the clip is infact an animating roto spline and can be rendered anywhen).
bool OfxClipInstance::getContinuousSamples() const
{
return false;
}
/// override this to return the rod on the clip cannoical coords!
OfxRectD OfxClipInstance::getRegionOfDefinition(OfxTime time) const
{
OfxRectD ret;
RectI rod;
EffectInstance* n = getAssociatedNode();
if(n){
n->getRegionOfDefinition(time,&rod);
ret.x1 = rod.left();
ret.x2 = rod.right();
ret.y1 = rod.bottom();
ret.y2 = rod.top();
}
else{
_nodeInstance->effectInstance()->getProjectOffset(ret.x1, ret.y1);
_nodeInstance->effectInstance()->getProjectExtent(ret.x2, ret.y2);
}
return ret;
}
/// override this to fill in the image at the given time.
/// The bounds of the image on the image plane should be
/// 'appropriate', typically the value returned in getRegionsOfInterest
/// on the effect instance. Outside a render call, the optionalBounds should
/// be 'appropriate' for the.
/// If bounds is not null, fetch the indicated section of the canonical image plane.
OFX::Host::ImageEffect::Image* OfxClipInstance::getImage(OfxTime time, OfxRectD *optionalBounds)
{
return getImageInternal(time,_viewRendered.localData(),optionalBounds);
}
OFX::Host::ImageEffect::Image* OfxClipInstance::getImageInternal(OfxTime time, int view, OfxRectD */*optionalBounds*/){
if(isOutput()){
boost::shared_ptr<Natron::Image> outputImage = _nodeInstance->getImageBeingRendered(time,view);
assert(outputImage);
return new OfxImage(outputImage,*this);
}else{
RenderScale scale;
scale.x = scale.y = 1.;
// input has been rendered just find it in the cache
EffectInstance* input = getAssociatedNode();
if(isOptional() && !input) {
//make an empty image
boost::shared_ptr<Natron::Image> outputImage = _nodeInstance->getImageBeingRendered(time,view);
assert(outputImage);
const RectI& rod = outputImage->getRoD();
boost::shared_ptr<Natron::Image> image(new Natron::Image(rod,scale,time));
if(isMask()){
image->defaultInitialize(1.f,1.f);
}else{
image->defaultInitialize();
}
return new OfxImage(image,*this);
}
assert(input);
int inputIndex = 0;
for (int i = 0; i < _nodeInstance->maximumInputs(); ++i) {
EffectInstance* n = _nodeInstance->input(i);
if (n == input) {
inputIndex = i;
break;
}
}
return new OfxImage(boost::const_pointer_cast<Natron::Image>(_nodeInstance->getImage(inputIndex,time, scale,view)),*this);
}
}
OfxImage::OfxImage(boost::shared_ptr<Natron::Image> internalImage,OfxClipInstance &clip):
OFX::Host::ImageEffect::Image(clip)
,_bitDepth(OfxImage::eBitDepthFloat)
,_floatImage(internalImage)
{
RenderScale scale = internalImage->getRenderScale();
setDoubleProperty(kOfxImageEffectPropRenderScale, scale.x, 0);
setDoubleProperty(kOfxImageEffectPropRenderScale, scale.y, 1);
// data ptr
const RectI& rod = internalImage->getRoD();
setPointerProperty(kOfxImagePropData,internalImage->pixelAt(rod.left(), rod.bottom()));
// bounds and rod
setIntProperty(kOfxImagePropBounds, rod.left(), 0);
setIntProperty(kOfxImagePropBounds, rod.bottom(), 1);
setIntProperty(kOfxImagePropBounds, rod.right(), 2);
setIntProperty(kOfxImagePropBounds, rod.top(), 3);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.left(), 0);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.bottom(), 1);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.right(), 2);
setIntProperty(kOfxImagePropRegionOfDefinition, rod.top(), 3);
// row bytes
setIntProperty(kOfxImagePropRowBytes, rod.width()*4*sizeof(float));
setStringProperty(kOfxImageEffectPropComponents, kOfxImageComponentRGBA);
}
OfxRGBAColourF* OfxImage::pixelF(int x, int y) const{
assert(_bitDepth == eBitDepthFloat);
const RectI& bounds = _floatImage->getRoD();
if ((x >= bounds.left()) && ( x < bounds.right()) && ( y >= bounds.bottom()) && ( y < bounds.top()) )
{
return reinterpret_cast<OfxRGBAColourF*>(_floatImage->pixelAt(x, y));
}
return 0;
}
Natron::EffectInstance* OfxClipInstance::getAssociatedNode() const {
if(_isOutput)
return _nodeInstance;
else{
int index = 0;
OfxEffectInstance::MappedInputV inputs = _nodeInstance->inputClipsCopyWithoutOutput();
for (U32 i = 0; i < inputs.size(); ++i) {
if (inputs[i]->getName() == getName()) {
index = i;
break;
}
}
return _nodeInstance->input(inputs.size()-1-index);
}
}
OFX::Host::ImageEffect::Image* OfxClipInstance::getStereoscopicImage(OfxTime time, int view, OfxRectD *optionalBounds) {
return getImageInternal(time,view,optionalBounds);
}
void OfxClipInstance::setView(int view){
_viewRendered.setLocalData(view);
}
<|endoftext|>
|
<commit_before>#include "ConsoleReporter.h"
#include <chrono>
#include <cstdio>
#include <iostream>
#include <memory>
#include <mutex>
#include <unordered_map>
#if defined (_WIN32)
#include <Windows.h>
#undef ReportEvent
namespace
{
class ResetConsoleColors
{
public:
ResetConsoleColors()
: stdOut(GetStdHandle(STD_OUTPUT_HANDLE))
{
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(stdOut, &info);
attributes = info.wAttributes;
}
~ResetConsoleColors()
{
Reset();
}
void Reset()
{
SetConsoleTextAttribute(stdOut, attributes);
}
private:
HANDLE stdOut;
WORD attributes;
} resetConsoleColors;
}
#else
#endif
#include "xUnit++/LineInfo.h"
#include "xUnit++/TestDetails.h"
#include "xUnit++/TestEvent.h"
namespace
{
static const std::string TestSeparator = "\n ";
enum class Color : unsigned short
{
Default = 65535,
Black = 0,
DarkBlue,
DarkGreen,
DarkCyan,
DarkRed,
DarkMagenta,
DarkYellow,
LightGray,
DarkGray,
Blue,
Green,
Cyan,
Red,
Magenta,
Yellow,
White,
Debug = DarkMagenta,
Info = DarkCyan,
Warning = Yellow,
Check = Red,
Assert = Red,
Skip = Yellow,
Suite = White,
Separator = DarkGray,
TestName = White,
FileAndLine = Default,
Success = Green,
Failure = Red,
TimeSummary = DarkGray,
Call = White,
Expected = Cyan,
Actual = Cyan,
// this value is to match the Win32 value
// there is a special test in to_ansicode
Fatal = (0x40 + White),
};
Color to_color(xUnitpp::EventLevel level)
{
switch (level)
{
case xUnitpp::EventLevel::Debug:
return Color::Debug;
case xUnitpp::EventLevel::Info:
return Color::Info;
case xUnitpp::EventLevel::Warning:
return Color::Warning;
case xUnitpp::EventLevel::Check:
return Color::Check;
case xUnitpp::EventLevel::Assert:
return Color::Assert;
case xUnitpp::EventLevel::Fatal:
return Color::Fatal;
}
return Color::Default;
}
std::string to_ansicode(Color color)
{
static const std::string codes[] =
{
"\033[0;30m",
"\033[0;34m",
"\033[0;32m",
"\033[0;36m",
"\033[0;31m",
"\033[0;35m",
"\033[0;33m",
"\033[0;37m",
"\033[0;1;30m", // the 0 at the start clears the background color
"\033[0;1;34m", // then the 1 sets the color to bold
"\033[0;1;32m",
"\033[0;1;36m",
"\033[0;1;31m",
"\033[0;1;35m",
"\033[0;1;33m",
"\033[0;1;37m",
};
if (color == Color::Fatal)
{
return "\033[1;37;41m";
}
if (color != Color::Default)
{
return codes[(int)color];
}
return "\033[m";
}
std::string FileAndLine(const xUnitpp::TestDetails &td, const xUnitpp::LineInfo &lineInfo)
{
auto result = to_string(lineInfo);
if (result.empty())
{
result = to_string(td.LineInfo);
}
return result;
}
template<typename TStream>
TStream &operator <<(TStream &stream, Color color)
{
#if defined (_WIN32)
stream.flush();
if (color != Color::Default)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (unsigned short)color);
}
else
{
resetConsoleColors.Reset();
}
#else
stream << to_ansicode(color);
#endif
return stream;
}
}
namespace xUnitpp
{
class ConsoleReporter::ReportCache
{
class TestOutput
{
public:
struct Fragment
{
Fragment(Color color, const std::string &message)
: color(color)
, message(message)
{
}
friend std::ostream &operator <<(std::ostream &stream, const Fragment &fragment)
{
return stream << fragment.color << fragment.message;
}
Color color;
std::string message;
};
TestOutput(const xUnitpp::TestDetails &td, bool verbose)
: testDetails(td)
, failed(false)
, verbose(verbose)
{
}
void Print(bool grouped)
{
if (failed || verbose || !fragments.empty())
{
if (!grouped)
{
std::cout << "\n";
}
if (failed)
{
std::cout << Fragment(Color::Failure, "[ Failure ] ");
}
else
{
std::cout << Fragment(Color::Success, "[ Success ] ");
}
if (!grouped)
{
if (!testDetails.Suite.empty())
{
std::cout << Fragment(Color::Suite, testDetails.Suite);
std::cout << Fragment(Color::Separator, TestSeparator);
}
}
std::cout << Fragment(Color::TestName, testDetails.FullName() + "\n");
}
if (!fragments.empty())
{
for (auto &&msg : fragments)
{
std::cout << msg;
}
}
}
void Skip(const std::string &reason)
{
fragments.emplace_back(Color::FileAndLine, to_string(testDetails.LineInfo));
fragments.emplace_back(Color::Separator, ": ");
fragments.emplace_back(Color::Skip, reason);
fragments.emplace_back(Color::Default, "\n");
}
TestOutput &operator <<(const xUnitpp::TestEvent &event)
{
if (event.IsFailure())
{
failed = true;
}
fragments.emplace_back(Color::FileAndLine, FileAndLine(testDetails, event.LineInfo()));
fragments.emplace_back(Color::Separator, ": ");
fragments.emplace_back(to_color(event.Level()), to_string(event.Level()));
fragments.emplace_back(Color::Separator, ": ");
// unfortunately, this code should almost completely match the to_string(const TestEvent &)
// function found in TestEvent.cpp, but is kept separate because of the color coding
if (event.IsAssertType())
{
auto &&assert = event.Assert();
fragments.emplace_back(Color::Call, assert.Call() + "()");
std::string message = " failure";
std::string userMessage = assert.UserMessage();
if (!userMessage.empty())
{
message += ": " + userMessage;
if (!assert.CustomMessage().empty())
{
message += "\n " + assert.CustomMessage();
}
}
else if (!assert.CustomMessage().empty())
{
message += ": " + assert.CustomMessage();
}
else
{
message += ".";
}
fragments.emplace_back(Color::Default, message);
if (!assert.Expected().empty() || !assert.Actual().empty())
{
fragments.emplace_back(Color::Expected, "\n Expected: ");
fragments.emplace_back(Color::Default, assert.Expected());
fragments.emplace_back(Color::Actual, "\n Actual: ");
fragments.emplace_back(Color::Default, assert.Actual());
}
}
else
{
fragments.emplace_back(Color::Default, event.Message());
}
fragments.emplace_back(Color::Default, "\n");
return *this;
}
TestOutput &operator <<(xUnitpp::Time::Duration time)
{
if (verbose)
{
fragments.emplace_back(Color::TimeSummary, "Test completed in " + xUnitpp::Time::to_string(time) + ".\n");
}
return *this;
}
const xUnitpp::TestDetails &TestDetails() const
{
return testDetails;
}
private:
TestOutput(const TestOutput &) /* = delete */;
TestOutput &operator =(TestOutput) /* = delete */;
private:
const xUnitpp::TestDetails &testDetails;
std::vector<Fragment> fragments;
bool failed;
bool verbose;
};
typedef std::unordered_map<int, std::shared_ptr<TestOutput>> OutputCache;
public:
ReportCache(bool verbose, bool sort, bool group)
: verbose(verbose)
, sort(sort)
, group(group)
{
}
void Instant(Color color, const std::string &message)
{
std::cout << TestOutput::Fragment(color, message);
}
TestOutput &Cache(const xUnitpp::TestDetails &td)
{
auto it = cache.find(td.Id);
if (it == cache.end())
{
cache.insert(std::make_pair(td.Id, std::make_shared<TestOutput>(td, verbose)));
}
return *cache[td.Id];
}
void Skip(const xUnitpp::TestDetails &testDetails, const std::string &reason)
{
if (!sort)
{
Instant(Color::Skip, "\n[ Skipped ] ");
if (!testDetails.Suite.empty())
{
Instant(Color::Suite, testDetails.Suite);
Instant(Color::Separator, TestSeparator);
}
Instant(Color::TestName, testDetails.Name + "\n");
Instant(Color::FileAndLine, to_string(testDetails.LineInfo) + ": ");
Instant(Color::Skip, reason);
Instant(Color::Default, "\n");
}
else
{
Cache(testDetails).Skip(reason);
}
}
void Finish(const xUnitpp::TestDetails &td)
{
if (!sort)
{
auto it = cache.find(td.Id);
if (it != cache.end())
{
it->second->Print(false);
cache.erase(it);
}
}
}
void Finish()
{
if (sort)
{
std::vector<std::shared_ptr<TestOutput>> finalResults;
finalResults.reserve(cache.size());
for (auto x : cache)
{
finalResults.push_back(x.second);
}
std::sort(finalResults.begin(), finalResults.end(),
[](const std::shared_ptr<TestOutput> &lhs, const std::shared_ptr<TestOutput> &rhs)
{
if (lhs->TestDetails().Suite != rhs->TestDetails().Suite)
{
return lhs->TestDetails().Suite < rhs->TestDetails().Suite;
}
return lhs->TestDetails().Name < rhs->TestDetails().Name;
});
std::string curSuite = "";
for (auto result : finalResults)
{
if (group)
{
if (curSuite != result->TestDetails().Suite)
{
curSuite = result->TestDetails().Suite;
std::cout << TestOutput::Fragment(Color::Suite, "\n\n==========\n[ " + curSuite + " ]\n==========\n");
}
}
result->Print(group);
}
}
}
private:
OutputCache cache;
bool verbose;
bool sort;
bool group;
};
ConsoleReporter::ConsoleReporter(bool verbose, bool sort, bool group)
: cache(new ReportCache(verbose, sort, group))
{
std::cout.sync_with_stdio(false);
}
void ConsoleReporter::ReportStart(const TestDetails &)
{
}
void ConsoleReporter::ReportEvent(const TestDetails &testDetails, const TestEvent &evt)
{
cache->Cache(testDetails) << evt;
}
void ConsoleReporter::ReportSkip(const TestDetails &testDetails, const std::string &reason)
{
cache->Skip(testDetails, reason);
}
void ConsoleReporter::ReportFinish(const TestDetails &testDetails, Time::Duration timeTaken)
{
cache->Cache(testDetails) << timeTaken;
cache->Finish(testDetails);
}
void ConsoleReporter::ReportAllTestsComplete(size_t testCount, size_t skipped, size_t failureCount, Time::Duration totalTime)
{
cache->Finish();
Color failColor = Color::Default;
Color skipColor = Color::Default;
if (failureCount > 0)
{
failColor = Color::Failure;
cache->Instant(failColor, "\nFAILURE");
}
else if (skipped > 0)
{
skipColor = Color::Warning;
cache->Instant(skipColor, "\nWARNING");
}
else
{
cache->Instant(Color::Success, "\nSuccess");
}
cache->Instant(Color::Default, ": " + std::to_string(testCount) + " tests, ");
cache->Instant(failColor, std::to_string(failureCount) + " failed");
cache->Instant(Color::Default, ", ");
cache->Instant(skipColor, std::to_string(skipped) + " skipped");
cache->Instant(Color::Default, ".");
std::string report = "\nTest time: ";
auto ms = Time::ToMilliseconds(totalTime);
if (ms.count() > 500)
{
report += std::to_string(Time::ToSeconds(totalTime).count()) + " seconds.";
}
else
{
report += std::to_string(ms.count()) + " milliseconds.";
}
cache->Instant(Color::TimeSummary, report);
cache->Instant(Color::Default, "\n");
}
}
<commit_msg>this line was causing some segfaults in ubuntu builds<commit_after>#include "ConsoleReporter.h"
#include <chrono>
#include <cstdio>
#include <iostream>
#include <memory>
#include <mutex>
#include <unordered_map>
#if defined (_WIN32)
#include <Windows.h>
#undef ReportEvent
namespace
{
class ResetConsoleColors
{
public:
ResetConsoleColors()
: stdOut(GetStdHandle(STD_OUTPUT_HANDLE))
{
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(stdOut, &info);
attributes = info.wAttributes;
}
~ResetConsoleColors()
{
Reset();
}
void Reset()
{
SetConsoleTextAttribute(stdOut, attributes);
}
private:
HANDLE stdOut;
WORD attributes;
} resetConsoleColors;
}
#else
#endif
#include "xUnit++/LineInfo.h"
#include "xUnit++/TestDetails.h"
#include "xUnit++/TestEvent.h"
namespace
{
static const std::string TestSeparator = "\n ";
enum class Color : unsigned short
{
Default = 65535,
Black = 0,
DarkBlue,
DarkGreen,
DarkCyan,
DarkRed,
DarkMagenta,
DarkYellow,
LightGray,
DarkGray,
Blue,
Green,
Cyan,
Red,
Magenta,
Yellow,
White,
Debug = DarkMagenta,
Info = DarkCyan,
Warning = Yellow,
Check = Red,
Assert = Red,
Skip = Yellow,
Suite = White,
Separator = DarkGray,
TestName = White,
FileAndLine = Default,
Success = Green,
Failure = Red,
TimeSummary = DarkGray,
Call = White,
Expected = Cyan,
Actual = Cyan,
// this value is to match the Win32 value
// there is a special test in to_ansicode
Fatal = (0x40 + White),
};
Color to_color(xUnitpp::EventLevel level)
{
switch (level)
{
case xUnitpp::EventLevel::Debug:
return Color::Debug;
case xUnitpp::EventLevel::Info:
return Color::Info;
case xUnitpp::EventLevel::Warning:
return Color::Warning;
case xUnitpp::EventLevel::Check:
return Color::Check;
case xUnitpp::EventLevel::Assert:
return Color::Assert;
case xUnitpp::EventLevel::Fatal:
return Color::Fatal;
}
return Color::Default;
}
std::string to_ansicode(Color color)
{
static const std::string codes[] =
{
"\033[0;30m",
"\033[0;34m",
"\033[0;32m",
"\033[0;36m",
"\033[0;31m",
"\033[0;35m",
"\033[0;33m",
"\033[0;37m",
"\033[0;1;30m", // the 0 at the start clears the background color
"\033[0;1;34m", // then the 1 sets the color to bold
"\033[0;1;32m",
"\033[0;1;36m",
"\033[0;1;31m",
"\033[0;1;35m",
"\033[0;1;33m",
"\033[0;1;37m",
};
if (color == Color::Fatal)
{
return "\033[1;37;41m";
}
if (color != Color::Default)
{
return codes[(int)color];
}
return "\033[m";
}
std::string FileAndLine(const xUnitpp::TestDetails &td, const xUnitpp::LineInfo &lineInfo)
{
auto result = to_string(lineInfo);
if (result.empty())
{
result = to_string(td.LineInfo);
}
return result;
}
template<typename TStream>
TStream &operator <<(TStream &stream, Color color)
{
#if defined (_WIN32)
stream.flush();
if (color != Color::Default)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (unsigned short)color);
}
else
{
resetConsoleColors.Reset();
}
#else
stream << to_ansicode(color);
#endif
return stream;
}
}
namespace xUnitpp
{
class ConsoleReporter::ReportCache
{
class TestOutput
{
public:
struct Fragment
{
Fragment(Color color, const std::string &message)
: color(color)
, message(message)
{
}
friend std::ostream &operator <<(std::ostream &stream, const Fragment &fragment)
{
return stream << fragment.color << fragment.message;
}
Color color;
std::string message;
};
TestOutput(const xUnitpp::TestDetails &td, bool verbose)
: testDetails(td)
, failed(false)
, verbose(verbose)
{
}
void Print(bool grouped)
{
if (failed || verbose || !fragments.empty())
{
if (!grouped)
{
std::cout << "\n";
}
if (failed)
{
std::cout << Fragment(Color::Failure, "[ Failure ] ");
}
else
{
std::cout << Fragment(Color::Success, "[ Success ] ");
}
if (!grouped)
{
if (!testDetails.Suite.empty())
{
std::cout << Fragment(Color::Suite, testDetails.Suite);
std::cout << Fragment(Color::Separator, TestSeparator);
}
}
std::cout << Fragment(Color::TestName, testDetails.FullName() + "\n");
}
if (!fragments.empty())
{
for (auto &&msg : fragments)
{
std::cout << msg;
}
}
}
void Skip(const std::string &reason)
{
fragments.emplace_back(Color::FileAndLine, to_string(testDetails.LineInfo));
fragments.emplace_back(Color::Separator, ": ");
fragments.emplace_back(Color::Skip, reason);
fragments.emplace_back(Color::Default, "\n");
}
TestOutput &operator <<(const xUnitpp::TestEvent &event)
{
if (event.IsFailure())
{
failed = true;
}
fragments.emplace_back(Color::FileAndLine, FileAndLine(testDetails, event.LineInfo()));
fragments.emplace_back(Color::Separator, ": ");
fragments.emplace_back(to_color(event.Level()), to_string(event.Level()));
fragments.emplace_back(Color::Separator, ": ");
// unfortunately, this code should almost completely match the to_string(const TestEvent &)
// function found in TestEvent.cpp, but is kept separate because of the color coding
if (event.IsAssertType())
{
auto &&assert = event.Assert();
fragments.emplace_back(Color::Call, assert.Call() + "()");
std::string message = " failure";
std::string userMessage = assert.UserMessage();
if (!userMessage.empty())
{
message += ": " + userMessage;
if (!assert.CustomMessage().empty())
{
message += "\n " + assert.CustomMessage();
}
}
else if (!assert.CustomMessage().empty())
{
message += ": " + assert.CustomMessage();
}
else
{
message += ".";
}
fragments.emplace_back(Color::Default, message);
if (!assert.Expected().empty() || !assert.Actual().empty())
{
fragments.emplace_back(Color::Expected, "\n Expected: ");
fragments.emplace_back(Color::Default, assert.Expected());
fragments.emplace_back(Color::Actual, "\n Actual: ");
fragments.emplace_back(Color::Default, assert.Actual());
}
}
else
{
fragments.emplace_back(Color::Default, event.Message());
}
fragments.emplace_back(Color::Default, "\n");
return *this;
}
TestOutput &operator <<(xUnitpp::Time::Duration time)
{
if (verbose)
{
fragments.emplace_back(Color::TimeSummary, "Test completed in " + xUnitpp::Time::to_string(time) + ".\n");
}
return *this;
}
const xUnitpp::TestDetails &TestDetails() const
{
return testDetails;
}
private:
TestOutput(const TestOutput &) /* = delete */;
TestOutput &operator =(TestOutput) /* = delete */;
private:
const xUnitpp::TestDetails &testDetails;
std::vector<Fragment> fragments;
bool failed;
bool verbose;
};
typedef std::unordered_map<int, std::shared_ptr<TestOutput>> OutputCache;
public:
ReportCache(bool verbose, bool sort, bool group)
: verbose(verbose)
, sort(sort)
, group(group)
{
}
void Instant(Color color, const std::string &message)
{
std::cout << TestOutput::Fragment(color, message);
}
TestOutput &Cache(const xUnitpp::TestDetails &td)
{
auto it = cache.find(td.Id);
if (it == cache.end())
{
cache.insert(std::make_pair(td.Id, std::make_shared<TestOutput>(td, verbose)));
}
return *cache[td.Id];
}
void Skip(const xUnitpp::TestDetails &testDetails, const std::string &reason)
{
if (!sort)
{
Instant(Color::Skip, "\n[ Skipped ] ");
if (!testDetails.Suite.empty())
{
Instant(Color::Suite, testDetails.Suite);
Instant(Color::Separator, TestSeparator);
}
Instant(Color::TestName, testDetails.Name + "\n");
Instant(Color::FileAndLine, to_string(testDetails.LineInfo) + ": ");
Instant(Color::Skip, reason);
Instant(Color::Default, "\n");
}
else
{
Cache(testDetails).Skip(reason);
}
}
void Finish(const xUnitpp::TestDetails &td)
{
if (!sort)
{
auto it = cache.find(td.Id);
if (it != cache.end())
{
it->second->Print(false);
cache.erase(it);
}
}
}
void Finish()
{
if (sort)
{
std::vector<std::shared_ptr<TestOutput>> finalResults;
finalResults.reserve(cache.size());
for (auto x : cache)
{
finalResults.push_back(x.second);
}
std::sort(finalResults.begin(), finalResults.end(),
[](const std::shared_ptr<TestOutput> &lhs, const std::shared_ptr<TestOutput> &rhs)
{
if (lhs->TestDetails().Suite != rhs->TestDetails().Suite)
{
return lhs->TestDetails().Suite < rhs->TestDetails().Suite;
}
return lhs->TestDetails().Name < rhs->TestDetails().Name;
});
std::string curSuite = "";
for (auto result : finalResults)
{
if (group)
{
if (curSuite != result->TestDetails().Suite)
{
curSuite = result->TestDetails().Suite;
std::cout << TestOutput::Fragment(Color::Suite, "\n\n==========\n[ " + curSuite + " ]\n==========\n");
}
}
result->Print(group);
}
}
}
private:
OutputCache cache;
bool verbose;
bool sort;
bool group;
};
ConsoleReporter::ConsoleReporter(bool verbose, bool sort, bool group)
: cache(new ReportCache(verbose, sort, group))
{
//std::cout.sync_with_stdio(false);
}
void ConsoleReporter::ReportStart(const TestDetails &)
{
}
void ConsoleReporter::ReportEvent(const TestDetails &testDetails, const TestEvent &evt)
{
cache->Cache(testDetails) << evt;
}
void ConsoleReporter::ReportSkip(const TestDetails &testDetails, const std::string &reason)
{
cache->Skip(testDetails, reason);
}
void ConsoleReporter::ReportFinish(const TestDetails &testDetails, Time::Duration timeTaken)
{
cache->Cache(testDetails) << timeTaken;
cache->Finish(testDetails);
}
void ConsoleReporter::ReportAllTestsComplete(size_t testCount, size_t skipped, size_t failureCount, Time::Duration totalTime)
{
cache->Finish();
Color failColor = Color::Default;
Color skipColor = Color::Default;
if (failureCount > 0)
{
failColor = Color::Failure;
cache->Instant(failColor, "\nFAILURE");
}
else if (skipped > 0)
{
skipColor = Color::Warning;
cache->Instant(skipColor, "\nWARNING");
}
else
{
cache->Instant(Color::Success, "\nSuccess");
}
cache->Instant(Color::Default, ": " + std::to_string(testCount) + " tests, ");
cache->Instant(failColor, std::to_string(failureCount) + " failed");
cache->Instant(Color::Default, ", ");
cache->Instant(skipColor, std::to_string(skipped) + " skipped");
cache->Instant(Color::Default, ".");
std::string report = "\nTest time: ";
auto ms = Time::ToMilliseconds(totalTime);
if (ms.count() > 500)
{
report += std::to_string(Time::ToSeconds(totalTime).count()) + " seconds.";
}
else
{
report += std::to_string(ms.count()) + " milliseconds.";
}
cache->Instant(Color::TimeSummary, report);
cache->Instant(Color::Default, "\n");
}
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "mmult.h"
void matrix_multiply_ref(out_T offsets[CLASSES], w_T weights[CLASSES][FEAT], in_T in[BATCH][FEAT], out_T out[BATCH][CLASSES])
{
// matrix multiplication of a A*B matrix
for (int i = 0; i < BATCH; ++i) {
for (int j = 0; j < CLASSES; ++j) {
out_T sum = offsets[j];
for (int k = 0; k < FEAT; ++k) {
sum += in[i][k] * weights[j][k];
}
out[i][j] = sum;
}
}
return;
}
int main(void)
{
int i,j,err;
out_T offsets[CLASSES];
w_T weights[CLASSES][FEAT];
in_T inputs[BATCH][FEAT];
out_T output_sw[BATCH][CLASSES];
out_T output_hw[BATCH][CLASSES];
/** Matrix Initiation */
for(i = 0; i<CLASSES; i++) {
offsets[i] = (out_T) ((rand()%(1ULL<<OUT_WIDTH)) - (1ULL<<(OUT_WIDTH-1)));
}
for(i = 0; i<CLASSES; i++) {
for(j = 0; j<FEAT; j++) {
weights[i][j] = (w_T) ((rand()%(1ULL<<W_WIDTH)) - (1ULL<<(W_WIDTH-1)));
}
}
for(i = 0; i<BATCH; i++) {
for(j = 0; j<FEAT; j++) {
inputs[i][j] = (in_T) (rand() % (1ULL<<IN_WIDTH));
}
}
/** End of Initiation */
printf("DEBUGGING AXI4 STREAMING DATA TYPES!\r\n");
// prepare data for the DUT
AXI_VAL in_stream[IS_SIZE];
AXI_VAL out_stream[OS_SIZE];
// Input and output stream indices
int is_idx = 0;
int os_idx = 0;
// stream in the offset vector
for(int i=0; i<CLASSES-OUT_WIDTH_RATIO; i+=OUT_WIDTH_RATIO) {
axi_T packet = 0;
PACK_OFF: for (int w = 0; w < OUT_WIDTH_RATIO; w++) {
out_bit_T bits = *((out_bit_T*) &offsets[i+w]);
packet |= (bits & ((1ULL<<OUT_WIDTH)-1))<<(w*OUT_WIDTH);
};
in_stream[is_idx++] = push_stream(packet, 0);
}
// pad the last packet in case things don't align
axi_T packet = 0;
FINISH_OFF: for (int i = CLASSES-OUT_WIDTH_RATIO; i < CLASSES; i++) {
out_bit_T bits = *((out_bit_T*) &offsets[i]);
packet |= (bits & ((1ULL<<OUT_WIDTH)-1))<<((i%OUT_WIDTH_RATIO)*OUT_WIDTH);
}
in_stream[is_idx++] = push_stream(packet, 0);
// stream in the weigth matrix
for(int i=0; i<CLASSES; i++) {
for(int j=0; j<FEAT; j+=W_WIDTH_RATIO) {
axi_T packet = 0;
PACK_W: for (int w = 0; w <W_WIDTH_RATIO; w++) {
w_bit_T bits = *((w_bit_T*) &weights[i][j+w]);
packet |= (bits & ((1ULL<<W_WIDTH)-1))<<(w*W_WIDTH);
};
in_stream[is_idx++] = push_stream(packet, 0);
}
}
// stream in the input matrix
for(int i=0; i<BATCH; i++) {
for(int j=0; j<FEAT; j+=IN_WIDTH_RATIO) {
axi_T packet = 0;
PACK_IN: for (int w = 0; w <IN_WIDTH_RATIO; w++) {
in_bit_T bits = *((in_bit_T*) &inputs[i][j+w]);
packet |= (bits & ((1ULL<<IN_WIDTH)-1))<<(w*IN_WIDTH);
};
in_stream[is_idx++] = push_stream(packet, is_idx==(IS_SIZE));
}
}
//call the DUT
mmult_hw(in_stream, out_stream);
// extract the output matrix from the out stream
for(int i=0; i<BATCH; i++) {
for(int j=0; j<CLASSES-OUT_WIDTH_RATIO; j+=OUT_WIDTH_RATIO) {
axi_T packet = pop_stream(out_stream[os_idx++]);
UNPACK_OUT: for (int w = 0; w < OUT_WIDTH_RATIO; w++) {
out_bit_T bits = (packet>>(w*OUT_WIDTH)) & ((1ULL<<OUT_WIDTH)-1);
output_hw[i][j+w] = *((out_T*) &bits);
}
}
// Pop last AXI data packet
axi_T packet = pop_stream(out_stream[os_idx++]);
FINISH_OUT: for (int j = CLASSES-OUT_WIDTH_RATIO; j < CLASSES; j++) {
out_bit_T bits = (packet>>((j%OUT_WIDTH_RATIO)*OUT_WIDTH)) & ((1ULL<<OUT_WIDTH)-1);
output_hw[i][j] = *((out_T*) &bits);
}
}
/* reference Matrix Multiplication */
matrix_multiply_ref(offsets, weights, inputs, output_sw);
/** Matrix comparison */
err = 0;
for (i = 0; i<BATCH; i++) {
for (j = 0; j<CLASSES; j++) {
if (output_sw[i][j] != output_hw[i][j]) {
err++;
std::cout << i << "," << j << ": expected " << output_sw[i][j] << " but got " << output_hw[i][j] << std::endl;
}
}
}
if (err == 0)
printf("Matrices identical ... Test successful!\r\n");
else
printf("Test failed!\r\n");
return err;
}
<commit_msg>ap_fixed support below 8-bits patch<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "mmult.h"
void matrix_multiply_ref(out_T offsets[CLASSES], w_T weights[CLASSES][FEAT], in_T in[BATCH][FEAT], out_T out[BATCH][CLASSES])
{
// matrix multiplication of a A*B matrix
for (int i = 0; i < BATCH; ++i) {
for (int j = 0; j < CLASSES; ++j) {
out_T sum = offsets[j];
for (int k = 0; k < FEAT; ++k) {
sum += in[i][k] * weights[j][k];
}
out[i][j] = sum;
}
}
return;
}
int main(void)
{
int i,j,err;
out_T offsets[CLASSES];
w_T weights[CLASSES][FEAT];
in_T inputs[BATCH][FEAT];
out_T output_sw[BATCH][CLASSES];
out_T output_hw[BATCH][CLASSES];
/** Matrix Initiation */
for(i = 0; i<CLASSES; i++) {
offsets[i] = (out_T) ((rand()%(1ULL<<OUT_WIDTH)) - (1ULL<<(OUT_WIDTH-1)));
}
for(i = 0; i<CLASSES; i++) {
for(j = 0; j<FEAT; j++) {
weights[i][j] = (w_T) ((rand()%(1ULL<<W_WIDTH)) - (1ULL<<(W_WIDTH-1)));
}
}
for(i = 0; i<BATCH; i++) {
for(j = 0; j<FEAT; j++) {
inputs[i][j] = (in_T) (rand() % (1ULL<<IN_WIDTH));
}
}
/** End of Initiation */
printf("DEBUGGING AXI4 STREAMING DATA TYPES!\r\n");
// prepare data for the DUT
AXI_VAL in_stream[IS_SIZE];
AXI_VAL out_stream[OS_SIZE];
// Input and output stream indices
int is_idx = 0;
int os_idx = 0;
// stream in the offset vector
for(int i=0; i<CLASSES-OUT_WIDTH_RATIO; i+=OUT_WIDTH_RATIO) {
axi_T packet = 0;
PACK_OFF: for (int w = 0; w < OUT_WIDTH_RATIO; w++) {
out_bit_T bits = *((out_bit_T*) &offsets[i+w]);
packet |= (bits & ((1ULL<<OUT_WIDTH)-1))<<(w*OUT_WIDTH);
};
in_stream[is_idx++] = push_stream(packet, 0);
}
// pad the last packet in case things don't align
axi_T packet = 0;
FINISH_OFF: for (int i = CLASSES-OUT_WIDTH_RATIO; i < CLASSES; i++) {
out_bit_T bits = *((out_bit_T*) &offsets[i]);
packet |= (bits & ((1ULL<<OUT_WIDTH)-1))<<((i%OUT_WIDTH_RATIO)*OUT_WIDTH);
}
in_stream[is_idx++] = push_stream(packet, 0);
// stream in the weigth matrix
for(int i=0; i<CLASSES; i++) {
for(int j=0; j<FEAT; j+=W_WIDTH_RATIO) {
axi_T packet = 0;
PACK_W: for (int w = 0; w <W_WIDTH_RATIO; w++) {
w_bit_T bits = *((w_bit_T*) &weights[i][j+w]);
packet |= (bits & ((1ULL<<W_WIDTH)-1))<<(w*W_WIDTH);
};
in_stream[is_idx++] = push_stream(packet, 0);
}
}
// stream in the input matrix
for(int i=0; i<BATCH; i++) {
for(int j=0; j<FEAT; j+=IN_WIDTH_RATIO) {
axi_T packet = 0;
PACK_IN: for (int w = 0; w <IN_WIDTH_RATIO; w++) {
in_bit_T bits = *((in_bit_T*) &inputs[i][j+w]);
packet |= (bits & ((1ULL<<IN_WIDTH)-1))<<(w*IN_WIDTH);
};
in_stream[is_idx++] = push_stream(packet, is_idx==(IS_SIZE));
}
}
//call the DUT
mmult_hw(in_stream, out_stream);
// extract the output matrix from the out stream
for(int i=0; i<BATCH; i++) {
for(int j=0; j<CLASSES-OUT_WIDTH_RATIO; j+=OUT_WIDTH_RATIO) {
axi_T packet = pop_stream(out_stream[os_idx++]);
UNPACK_OUT: for (int w = 0; w < OUT_WIDTH_RATIO; w++) {
out_bit_T bits = (packet>>(w*OUT_WIDTH));
output_hw[i][j+w] = *((out_T*) &bits) & ((1ULL<<OUT_WIDTH)-1);
}
}
// Pop last AXI data packet
axi_T packet = pop_stream(out_stream[os_idx++]);
FINISH_OUT: for (int j = CLASSES-OUT_WIDTH_RATIO; j < CLASSES; j++) {
out_bit_T bits = (packet>>((j%OUT_WIDTH_RATIO)*OUT_WIDTH));
output_hw[i][j] = *((out_T*) &bits) & ((1ULL<<OUT_WIDTH)-1);
}
}
/* reference Matrix Multiplication */
matrix_multiply_ref(offsets, weights, inputs, output_sw);
/** Matrix comparison */
err = 0;
for (i = 0; i<BATCH; i++) {
for (j = 0; j<CLASSES; j++) {
if (output_sw[i][j] != output_hw[i][j]) {
err++;
std::cout << i << "," << j << ": expected " << output_sw[i][j] << " but got " << output_hw[i][j] << std::endl;
}
}
}
if (err == 0)
printf("Matrices identical ... Test successful!\r\n");
else
printf("Test failed!\r\n");
return err;
}
<|endoftext|>
|
<commit_before>/*
* SegmentTracker.cpp
*****************************************************************************
* Copyright (C) 2014 - VideoLAN and VLC authors
*
* 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.1 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 Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "SegmentTracker.hpp"
#include "playlist/AbstractPlaylist.hpp"
#include "playlist/BaseRepresentation.h"
#include "playlist/BaseAdaptationSet.h"
#include "playlist/Segment.h"
#include "playlist/SegmentChunk.hpp"
#include "logic/AbstractAdaptationLogic.h"
using namespace adaptative;
using namespace adaptative::logic;
using namespace adaptative::playlist;
SegmentTrackerEvent::SegmentTrackerEvent(SegmentChunk *s)
{
type = DISCONTINUITY;
u.discontinuity.sc = s;
}
SegmentTrackerEvent::SegmentTrackerEvent(BaseRepresentation *prev, BaseRepresentation *next)
{
type = SWITCHING;
u.switching.prev = prev;
u.switching.next = next;
}
SegmentTrackerEvent::SegmentTrackerEvent(const StreamFormat *fmt)
{
type = FORMATCHANGE;
u.format.f = fmt;
}
SegmentTracker::SegmentTracker(AbstractAdaptationLogic *logic_, BaseAdaptationSet *adaptSet)
{
first = true;
next = 0;
initializing = true;
index_sent = false;
init_sent = false;
curRepresentation = NULL;
setAdaptationLogic(logic_);
adaptationSet = adaptSet;
format = StreamFormat::UNSUPPORTED;
}
SegmentTracker::~SegmentTracker()
{
reset();
}
void SegmentTracker::setAdaptationLogic(AbstractAdaptationLogic *logic_)
{
logic = logic_;
registerListener(logic);
}
bool SegmentTracker::segmentsListReady() const
{
BaseRepresentation *rep = curRepresentation;
if(!rep)
rep = logic->getNextRepresentation(adaptationSet, NULL);
if(rep && rep->getPlaylist()->isLive())
return rep->getMinAheadTime(curNumber) > 0;
return true;
}
void SegmentTracker::reset()
{
notify(SegmentTrackerEvent(curRepresentation, NULL));
curRepresentation = NULL;
init_sent = false;
index_sent = false;
initializing = true;
format = StreamFormat::UNSUPPORTED;
}
SegmentChunk * SegmentTracker::getNextChunk(bool switch_allowed, HTTPConnectionManager *connManager)
{
BaseRepresentation *rep = NULL, *prevRep = NULL;
ISegment *segment;
if(!adaptationSet)
return NULL;
/* Ensure we don't keep chaining init/index without data */
if( initializing )
{
if( curRepresentation )
switch_allowed = false;
else
switch_allowed = true;
}
if( !switch_allowed ||
(curRepresentation && curRepresentation->getSwitchPolicy() == SegmentInformation::SWITCH_UNAVAILABLE) )
rep = curRepresentation;
else
rep = logic->getNextRepresentation(adaptationSet, curRepresentation);
if ( rep == NULL )
return NULL;
if(rep != curRepresentation)
{
notify(SegmentTrackerEvent(curRepresentation, rep));
prevRep = curRepresentation;
curRepresentation = rep;
init_sent = false;
index_sent = false;
initializing = true;
}
bool b_updated = false;
/* Ensure ephemere content is updated/loaded */
if(rep->needsUpdate())
b_updated = rep->runLocalUpdates(getPlaybackTime(), curNumber, false);
if(prevRep && !rep->consistentSegmentNumber())
{
/* Convert our segment number */
next = rep->translateSegmentNumber(next, prevRep);
}
else if(first && rep->getPlaylist()->isLive())
{
next = rep->getLiveStartSegmentNumber(next);
first = false;
}
if(b_updated)
{
if(!rep->consistentSegmentNumber())
curRepresentation->pruneBySegmentNumber(curNumber);
curRepresentation->scheduleNextUpdate(curNumber);
}
if(!init_sent)
{
init_sent = true;
segment = rep->getSegment(BaseRepresentation::INFOTYPE_INIT);
if(segment)
return segment->toChunk(next, rep, connManager);
}
if(!index_sent)
{
index_sent = true;
segment = rep->getSegment(BaseRepresentation::INFOTYPE_INDEX);
if(segment)
return segment->toChunk(next, rep, connManager);
}
bool b_gap = false;
segment = rep->getNextSegment(BaseRepresentation::INFOTYPE_MEDIA, next, &next, &b_gap);
if(!segment)
{
reset();
return NULL;
}
if(initializing)
{
b_gap = false;
/* stop initializing after 1st chunk */
initializing = false;
}
SegmentChunk *chunk = segment->toChunk(next, rep, connManager);
/* We need to check segment/chunk format changes, as we can't rely on representation's (HLS)*/
if(chunk && format != chunk->getStreamFormat())
{
format = chunk->getStreamFormat();
notify(SegmentTrackerEvent(&format));
}
/* Handle both implicit and explicit discontinuities */
if( (b_gap && next) || (chunk && chunk->discontinuity) )
{
notify(SegmentTrackerEvent(chunk));
}
if(chunk)
{
curNumber = next;
next++;
}
return chunk;
}
bool SegmentTracker::setPositionByTime(mtime_t time, bool restarted, bool tryonly)
{
uint64_t segnumber;
BaseRepresentation *rep = curRepresentation;
if(!rep)
rep = logic->getNextRepresentation(adaptationSet, NULL);
if(rep &&
rep->getSegmentNumberByTime(time, &segnumber))
{
if(!tryonly)
setPositionByNumber(segnumber, restarted);
return true;
}
return false;
}
void SegmentTracker::setPositionByNumber(uint64_t segnumber, bool restarted)
{
if(restarted)
{
initializing = true;
index_sent = false;
init_sent = false;
}
curNumber = next = segnumber;
}
mtime_t SegmentTracker::getPlaybackTime() const
{
if(curRepresentation)
return curRepresentation->getPlaybackTimeBySegmentNumber(next);
else
return 0;
}
mtime_t SegmentTracker::getMinAheadTime() const
{
BaseRepresentation *rep = curRepresentation;
if(!rep)
rep = logic->getNextRepresentation(adaptationSet, NULL);
if(rep)
return rep->getMinAheadTime(curNumber);
return 0;
}
void SegmentTracker::registerListener(SegmentTrackerListenerInterface *listener)
{
listeners.push_back(listener);
}
void SegmentTracker::updateSelected()
{
if(curRepresentation && curRepresentation->needsUpdate())
{
curRepresentation->runLocalUpdates(getPlaybackTime(), curNumber, true);
curRepresentation->scheduleNextUpdate(curNumber);
}
}
void SegmentTracker::notify(const SegmentTrackerEvent &event)
{
std::list<SegmentTrackerListenerInterface *>::const_iterator it;
for(it=listeners.begin();it != listeners.end(); ++it)
(*it)->trackerEvent(event);
}
<commit_msg>demux: adaptative: fix uninitialized member (cid #1346986)<commit_after>/*
* SegmentTracker.cpp
*****************************************************************************
* Copyright (C) 2014 - VideoLAN and VLC authors
*
* 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.1 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 Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "SegmentTracker.hpp"
#include "playlist/AbstractPlaylist.hpp"
#include "playlist/BaseRepresentation.h"
#include "playlist/BaseAdaptationSet.h"
#include "playlist/Segment.h"
#include "playlist/SegmentChunk.hpp"
#include "logic/AbstractAdaptationLogic.h"
using namespace adaptative;
using namespace adaptative::logic;
using namespace adaptative::playlist;
SegmentTrackerEvent::SegmentTrackerEvent(SegmentChunk *s)
{
type = DISCONTINUITY;
u.discontinuity.sc = s;
}
SegmentTrackerEvent::SegmentTrackerEvent(BaseRepresentation *prev, BaseRepresentation *next)
{
type = SWITCHING;
u.switching.prev = prev;
u.switching.next = next;
}
SegmentTrackerEvent::SegmentTrackerEvent(const StreamFormat *fmt)
{
type = FORMATCHANGE;
u.format.f = fmt;
}
SegmentTracker::SegmentTracker(AbstractAdaptationLogic *logic_, BaseAdaptationSet *adaptSet)
{
first = true;
curNumber = next = 0;
initializing = true;
index_sent = false;
init_sent = false;
curRepresentation = NULL;
setAdaptationLogic(logic_);
adaptationSet = adaptSet;
format = StreamFormat::UNSUPPORTED;
}
SegmentTracker::~SegmentTracker()
{
reset();
}
void SegmentTracker::setAdaptationLogic(AbstractAdaptationLogic *logic_)
{
logic = logic_;
registerListener(logic);
}
bool SegmentTracker::segmentsListReady() const
{
BaseRepresentation *rep = curRepresentation;
if(!rep)
rep = logic->getNextRepresentation(adaptationSet, NULL);
if(rep && rep->getPlaylist()->isLive())
return rep->getMinAheadTime(curNumber) > 0;
return true;
}
void SegmentTracker::reset()
{
notify(SegmentTrackerEvent(curRepresentation, NULL));
curRepresentation = NULL;
init_sent = false;
index_sent = false;
initializing = true;
format = StreamFormat::UNSUPPORTED;
}
SegmentChunk * SegmentTracker::getNextChunk(bool switch_allowed, HTTPConnectionManager *connManager)
{
BaseRepresentation *rep = NULL, *prevRep = NULL;
ISegment *segment;
if(!adaptationSet)
return NULL;
/* Ensure we don't keep chaining init/index without data */
if( initializing )
{
if( curRepresentation )
switch_allowed = false;
else
switch_allowed = true;
}
if( !switch_allowed ||
(curRepresentation && curRepresentation->getSwitchPolicy() == SegmentInformation::SWITCH_UNAVAILABLE) )
rep = curRepresentation;
else
rep = logic->getNextRepresentation(adaptationSet, curRepresentation);
if ( rep == NULL )
return NULL;
if(rep != curRepresentation)
{
notify(SegmentTrackerEvent(curRepresentation, rep));
prevRep = curRepresentation;
curRepresentation = rep;
init_sent = false;
index_sent = false;
initializing = true;
}
bool b_updated = false;
/* Ensure ephemere content is updated/loaded */
if(rep->needsUpdate())
b_updated = rep->runLocalUpdates(getPlaybackTime(), curNumber, false);
if(prevRep && !rep->consistentSegmentNumber())
{
/* Convert our segment number */
next = rep->translateSegmentNumber(next, prevRep);
}
else if(first && rep->getPlaylist()->isLive())
{
next = rep->getLiveStartSegmentNumber(next);
first = false;
}
if(b_updated)
{
if(!rep->consistentSegmentNumber())
curRepresentation->pruneBySegmentNumber(curNumber);
curRepresentation->scheduleNextUpdate(curNumber);
}
if(!init_sent)
{
init_sent = true;
segment = rep->getSegment(BaseRepresentation::INFOTYPE_INIT);
if(segment)
return segment->toChunk(next, rep, connManager);
}
if(!index_sent)
{
index_sent = true;
segment = rep->getSegment(BaseRepresentation::INFOTYPE_INDEX);
if(segment)
return segment->toChunk(next, rep, connManager);
}
bool b_gap = false;
segment = rep->getNextSegment(BaseRepresentation::INFOTYPE_MEDIA, next, &next, &b_gap);
if(!segment)
{
reset();
return NULL;
}
if(initializing)
{
b_gap = false;
/* stop initializing after 1st chunk */
initializing = false;
}
SegmentChunk *chunk = segment->toChunk(next, rep, connManager);
/* We need to check segment/chunk format changes, as we can't rely on representation's (HLS)*/
if(chunk && format != chunk->getStreamFormat())
{
format = chunk->getStreamFormat();
notify(SegmentTrackerEvent(&format));
}
/* Handle both implicit and explicit discontinuities */
if( (b_gap && next) || (chunk && chunk->discontinuity) )
{
notify(SegmentTrackerEvent(chunk));
}
if(chunk)
{
curNumber = next;
next++;
}
return chunk;
}
bool SegmentTracker::setPositionByTime(mtime_t time, bool restarted, bool tryonly)
{
uint64_t segnumber;
BaseRepresentation *rep = curRepresentation;
if(!rep)
rep = logic->getNextRepresentation(adaptationSet, NULL);
if(rep &&
rep->getSegmentNumberByTime(time, &segnumber))
{
if(!tryonly)
setPositionByNumber(segnumber, restarted);
return true;
}
return false;
}
void SegmentTracker::setPositionByNumber(uint64_t segnumber, bool restarted)
{
if(restarted)
{
initializing = true;
index_sent = false;
init_sent = false;
}
curNumber = next = segnumber;
}
mtime_t SegmentTracker::getPlaybackTime() const
{
if(curRepresentation)
return curRepresentation->getPlaybackTimeBySegmentNumber(next);
else
return 0;
}
mtime_t SegmentTracker::getMinAheadTime() const
{
BaseRepresentation *rep = curRepresentation;
if(!rep)
rep = logic->getNextRepresentation(adaptationSet, NULL);
if(rep)
return rep->getMinAheadTime(curNumber);
return 0;
}
void SegmentTracker::registerListener(SegmentTrackerListenerInterface *listener)
{
listeners.push_back(listener);
}
void SegmentTracker::updateSelected()
{
if(curRepresentation && curRepresentation->needsUpdate())
{
curRepresentation->runLocalUpdates(getPlaybackTime(), curNumber, true);
curRepresentation->scheduleNextUpdate(curNumber);
}
}
void SegmentTracker::notify(const SegmentTrackerEvent &event)
{
std::list<SegmentTrackerListenerInterface *>::const_iterator it;
for(it=listeners.begin();it != listeners.end(); ++it)
(*it)->trackerEvent(event);
}
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ChemicalReactionsTestApp.h"
#include "ChemicalReactionsApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "MooseSyntax.h"
template <>
InputParameters
validParams<ChemicalReactionsTestApp>()
{
InputParameters params = validParams<ChemicalReactionsApp>();
return params;
}
registerKnownLabel("ChemicalReactionsTestApp");
ChemicalReactionsTestApp::ChemicalReactionsTestApp(InputParameters parameters)
: MooseApp(parameters)
{
ChemicalReactionsTestApp::registerAll(
_factory, _action_factory, _syntax, getParam<bool>("allow_test_objects"));
}
ChemicalReactionsTestApp::~ChemicalReactionsTestApp() {}
void
ChemicalReactionsTestApp::registerAll(Factory & f,
ActionFactory & af,
Syntax & s,
bool use_test_objects)
{
ChemicalReactionsApp::registerAll(f, af, s);
if (use_test_objects)
{
Registry::registerObjectsTo(f, {"ChemicalReactionsTestApp"});
Registry::registerActionsTo(af, {"ChemicalReactionsTestApp"});
}
}
void
ChemicalReactionsTestApp::registerApps()
{
registerApp(ChemicalReactionsApp);
registerApp(ChemicalReactionsTestApp);
}
void
ChemicalReactionsTestApp::registerObjects(Factory & factory)
{
mooseDeprecated("use registerAll instead of registerObjects");
Registry::registerObjectsTo(factory, {"ChemicalReactionsTestApp"});
}
void
ChemicalReactionsTestApp::associateSyntax(Syntax & /*syntax*/, ActionFactory & action_factory)
{
mooseDeprecated("use registerAll instead of associateSyntax");
Registry::registerActionsTo(action_factory, {"ChemicalReactionsTestApp"});
}
void
ChemicalReactionsTestApp::registerExecFlags(Factory & /*factory*/)
{
mooseDeprecated("use registerAll instead of registerExecFlags");
}
extern "C" void
ChemicalReactionsApp__registerAll(Factory & f, ActionFactory & af, Syntax & s)
{
ChemicalReactionsTestApp::registerAll(f, af, s);
}
// External entry point for dynamic application loading
extern "C" void
ChemicalReactionsTestApp__registerApps()
{
ChemicalReactionsTestApp::registerApps();
}
<commit_msg>fix paste typo that breaks static builds<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ChemicalReactionsTestApp.h"
#include "ChemicalReactionsApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "MooseSyntax.h"
template <>
InputParameters
validParams<ChemicalReactionsTestApp>()
{
InputParameters params = validParams<ChemicalReactionsApp>();
return params;
}
registerKnownLabel("ChemicalReactionsTestApp");
ChemicalReactionsTestApp::ChemicalReactionsTestApp(InputParameters parameters)
: MooseApp(parameters)
{
ChemicalReactionsTestApp::registerAll(
_factory, _action_factory, _syntax, getParam<bool>("allow_test_objects"));
}
ChemicalReactionsTestApp::~ChemicalReactionsTestApp() {}
void
ChemicalReactionsTestApp::registerAll(Factory & f,
ActionFactory & af,
Syntax & s,
bool use_test_objects)
{
ChemicalReactionsApp::registerAll(f, af, s);
if (use_test_objects)
{
Registry::registerObjectsTo(f, {"ChemicalReactionsTestApp"});
Registry::registerActionsTo(af, {"ChemicalReactionsTestApp"});
}
}
void
ChemicalReactionsTestApp::registerApps()
{
registerApp(ChemicalReactionsApp);
registerApp(ChemicalReactionsTestApp);
}
void
ChemicalReactionsTestApp::registerObjects(Factory & factory)
{
mooseDeprecated("use registerAll instead of registerObjects");
Registry::registerObjectsTo(factory, {"ChemicalReactionsTestApp"});
}
void
ChemicalReactionsTestApp::associateSyntax(Syntax & /*syntax*/, ActionFactory & action_factory)
{
mooseDeprecated("use registerAll instead of associateSyntax");
Registry::registerActionsTo(action_factory, {"ChemicalReactionsTestApp"});
}
void
ChemicalReactionsTestApp::registerExecFlags(Factory & /*factory*/)
{
mooseDeprecated("use registerAll instead of registerExecFlags");
}
extern "C" void
ChemicalReactionsTestApp__registerAll(Factory & f, ActionFactory & af, Syntax & s)
{
ChemicalReactionsTestApp::registerAll(f, af, s);
}
// External entry point for dynamic application loading
extern "C" void
ChemicalReactionsTestApp__registerApps()
{
ChemicalReactionsTestApp::registerApps();
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/encoding/populationcode_derivs/mutex_populationcode.h"
#include "elm/core/sampler.h"
#include "elm/core/signal.h"
using std::string;
using cv::Mat1f;
using namespace elm;
MutexPopulationCode::MutexPopulationCode()
: base_PopulationCode()
{
}
MutexPopulationCode::MutexPopulationCode(const LayerConfig &config)
: base_PopulationCode(config)
{
}
void MutexPopulationCode::State(const Mat1f& in, const VecMat1f& kernels)
{
pop_code_ = Mat1f::zeros(in.rows, in.cols*2);
for(int i=0, j=0; i < static_cast<int>(in.total()); i++, j+=2) {
int k = (in(i) < 0.5f) ? 0 : 1;
pop_code_(j+k) = 1.f;
}
}
Mat1f MutexPopulationCode::PopCode()
{
return pop_code_;
}
<commit_msg>mutex pop code: call Clear() and Reset() from constructors<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/encoding/populationcode_derivs/mutex_populationcode.h"
#include "elm/core/sampler.h"
#include "elm/core/signal.h"
using std::string;
using cv::Mat1f;
using namespace elm;
MutexPopulationCode::MutexPopulationCode()
: base_PopulationCode()
{
Clear();
}
MutexPopulationCode::MutexPopulationCode(const LayerConfig &config)
: base_PopulationCode(config)
{
Reset(config);
}
void MutexPopulationCode::State(const Mat1f& in, const VecMat1f& kernels)
{
pop_code_ = Mat1f::zeros(in.rows, in.cols*2);
for(int i=0, j=0; i < static_cast<int>(in.total()); i++, j+=2) {
int k = (in(i) < 0.5f) ? 0 : 1;
pop_code_(j+k) = 1.f;
}
}
Mat1f MutexPopulationCode::PopCode()
{
return pop_code_;
}
<|endoftext|>
|
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
* $Log$
* Revision 1.3 2006/02/09 15:52:47 strk
* GEOSException derived from std::exception; always thrown and cought by const ref.
*
* Revision 1.2 2005/01/28 09:47:51 strk
* Replaced sprintf uses with ostringstream.
*
* Revision 1.1 2004/07/08 19:41:27 strk
* renamed to reflect JTS API.
*
* Revision 1.6 2004/07/02 13:28:26 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.5 2003/11/07 01:23:42 pramsey
* Add standard CVS headers licence notices and copyrights to all cpp and h
* files.
*
*
**********************************************************************/
#include "CustomCoordinateSequenceExample.h"
#include <sstream>
//#include <stdio.h>
using namespace geos;
CustomPointCoordinateSequence::CustomPointCoordinateSequence(point_3d *newPts,int newSize) {
pts=newPts;
size=newSize;
}
CustomPointCoordinateSequence::CustomPointCoordinateSequence(const CustomPointCoordinateSequence &c) {
pts=c.pts;
size=c.size;
}
void CustomPointCoordinateSequence::setPoints(const vector<Coordinate> &v) {
if(v.size()==size) {
point_3d pt;
for(int i=0;i<(int)v.size(); i++) {
pt.x=v[i].x;
pt.y=v[i].y;
pt.z=v[i].z;
pts[i]=pt;
}
} else {
throw CPCLException("size mismatch\n");
}
}
void CustomPointCoordinateSequence::setPoints(const vector<point_3d> &v) {
if(v.size()==size) {
for(int i=0;i<(int)v.size(); i++) {
pts[i]=v[i];
}
} else {
throw CPCLException("size mismatch\n");
}
}
vector<Coordinate>* CustomPointCoordinateSequence::toVector() {
vector<Coordinate>* v=new vector<Coordinate>();
for(int i=0;i<size;i++) {
v->push_back(*(new Coordinate(pts[i].x,pts[i].y,pts[i].z)));
}
return v;
}
vector<point_3d>* CustomPointCoordinateSequence::toPointVector() {
vector<point_3d>* v=new vector<point_3d>();
for(int i=0;i<size;i++) {
v->push_back(pts[i]);
}
return v;
}
bool CustomPointCoordinateSequence::isEmpty() {
return size==0;
}
void CustomPointCoordinateSequence::add(Coordinate& c){
throw CPCLException("list's size can't be modified\n");
}
void CustomPointCoordinateSequence::add(point_3d p){
throw CPCLException("list's size can't be modified\n");
}
int CustomPointCoordinateSequence::getSize(){
return size;
}
Coordinate& CustomPointCoordinateSequence::getAt(int pos){
point_3d pt;
if (pos>=0 && pos<size) {
pt=pts[pos];
return *(new Coordinate(pt.x,pt.y,pt.z));
} else
throw CPCLException("can't retrieve element\n");
}
point_3d CustomPointCoordinateSequence::getPointAt(int pos){
if (pos>=0 && pos<size) {
return pts[pos];
} else
throw CPCLException("can't retrieve element\n");
}
void CustomPointCoordinateSequence::setAt(Coordinate& c, int pos){
point_3d pt={c.x,c.y,c.z};
if (pos>=0 && pos<size)
pts[pos]=pt;
else
throw CPCLException("can't change element\n");
}
void CustomPointCoordinateSequence::setAt(point_3d p, int pos){
if (pos>=0 && pos<size)
pts[pos]=p;
else
throw CPCLException("can't change element\n");
}
void CustomPointCoordinateSequence::deleteAt(int pos){
throw CPCLException("list's size can't be modified\n");
}
string CustomPointCoordinateSequence::toString() {
ostringstream s;
//string result("");
//char buffer[100];
for (int i=0;i<size;i++) {
point_3d c=pts[i];
//sprintf(buffer,"(%g,%g,%g) ",c.x,c.y,c.z);
s<<"("<<c.x<<","<<c.y<<","<<c.z<<") ";
//result.append(buffer);
}
//result.append("");
//return result;
return s.str();
}
<commit_msg>Added missing <iostream> header to CustomPointCoordinateSequence.cpp.<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
* $Log$
* Revision 1.3 2006/02/09 15:52:47 strk
* GEOSException derived from std::exception; always thrown and cought by const ref.
*
* Revision 1.2 2005/01/28 09:47:51 strk
* Replaced sprintf uses with ostringstream.
*
* Revision 1.1 2004/07/08 19:41:27 strk
* renamed to reflect JTS API.
*
* Revision 1.6 2004/07/02 13:28:26 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.5 2003/11/07 01:23:42 pramsey
* Add standard CVS headers licence notices and copyrights to all cpp and h
* files.
*
*
**********************************************************************/
#include "CustomCoordinateSequenceExample.h"
#include <sstream>
#include <iostream>
using namespace geos;
CustomPointCoordinateSequence::CustomPointCoordinateSequence(point_3d *newPts,int newSize) {
pts=newPts;
size=newSize;
}
CustomPointCoordinateSequence::CustomPointCoordinateSequence(const CustomPointCoordinateSequence &c) {
pts=c.pts;
size=c.size;
}
void CustomPointCoordinateSequence::setPoints(const vector<Coordinate> &v) {
if(v.size()==size) {
point_3d pt;
for(int i=0;i<(int)v.size(); i++) {
pt.x=v[i].x;
pt.y=v[i].y;
pt.z=v[i].z;
pts[i]=pt;
}
} else {
throw CPCLException("size mismatch\n");
}
}
void CustomPointCoordinateSequence::setPoints(const vector<point_3d> &v) {
if(v.size()==size) {
for(int i=0;i<(int)v.size(); i++) {
pts[i]=v[i];
}
} else {
throw CPCLException("size mismatch\n");
}
}
vector<Coordinate>* CustomPointCoordinateSequence::toVector() {
vector<Coordinate>* v=new vector<Coordinate>();
for(int i=0;i<size;i++) {
v->push_back(*(new Coordinate(pts[i].x,pts[i].y,pts[i].z)));
}
return v;
}
vector<point_3d>* CustomPointCoordinateSequence::toPointVector() {
vector<point_3d>* v=new vector<point_3d>();
for(int i=0;i<size;i++) {
v->push_back(pts[i]);
}
return v;
}
bool CustomPointCoordinateSequence::isEmpty() {
return size==0;
}
void CustomPointCoordinateSequence::add(Coordinate& c){
throw CPCLException("list's size can't be modified\n");
}
void CustomPointCoordinateSequence::add(point_3d p){
throw CPCLException("list's size can't be modified\n");
}
int CustomPointCoordinateSequence::getSize(){
return size;
}
Coordinate& CustomPointCoordinateSequence::getAt(int pos){
point_3d pt;
if (pos>=0 && pos<size) {
pt=pts[pos];
return *(new Coordinate(pt.x,pt.y,pt.z));
} else
throw CPCLException("can't retrieve element\n");
}
point_3d CustomPointCoordinateSequence::getPointAt(int pos){
if (pos>=0 && pos<size) {
return pts[pos];
} else
throw CPCLException("can't retrieve element\n");
}
void CustomPointCoordinateSequence::setAt(Coordinate& c, int pos){
point_3d pt={c.x,c.y,c.z};
if (pos>=0 && pos<size)
pts[pos]=pt;
else
throw CPCLException("can't change element\n");
}
void CustomPointCoordinateSequence::setAt(point_3d p, int pos){
if (pos>=0 && pos<size)
pts[pos]=p;
else
throw CPCLException("can't change element\n");
}
void CustomPointCoordinateSequence::deleteAt(int pos){
throw CPCLException("list's size can't be modified\n");
}
string CustomPointCoordinateSequence::toString() {
ostringstream s;
//string result("");
//char buffer[100];
for (int i=0;i<size;i++) {
point_3d c=pts[i];
//sprintf(buffer,"(%g,%g,%g) ",c.x,c.y,c.z);
s<<"("<<c.x<<","<<c.y<<","<<c.z<<") ";
//result.append(buffer);
}
//result.append("");
//return result;
return s.str();
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName NFIClusterClientModule.hpp
// @Author LvSheng.Huang
// @Date 2015-01-4
// @Module NFIClusterClientModule
//
// -------------------------------------------------------------------------
#ifndef _NFI_CLUSTER_CLIENT_MODULE_H_
#define _NFI_CLUSTER_CLIENT_MODULE_H_
#include <iostream>
#include "NFILogicModule.h"
#include "NFINetModule.h"
struct ServerData
{
ServerData()
{
nGameID = 0;
nPort = 0;
strName = "";
strIP = "";
m_pNetModule = NULL;
eServerType = NFST_NONE;
eState = NFMsg::EServerState::EST_CRASH;
}
int nGameID;
NF_SERVER_TYPE eServerType;
std::string strIP;
int nPort;
std::string strName;
NFMsg::EServerState eState;
NFINetModule* m_pNetModule;
};
class NFIClusterClientModule
{
public:
virtual bool Execute(const float fLastFrametime, const float fStartedTime)
{
ServerData* pServerData = mxServerMap.First();
while (pServerData)
{
pServerData->m_pNetModule.Execute(fLastFrametime, fStartedTime);
pServerData = mxServerMap.Next();
}
return true;
}
void AddServer(const ServerData& xInfo)
{
ServerData* pServerData = mxServerMap.find(xInfo.nGameID);
if (pServerData)
{
if (EServerState.EST_MAINTEN == pServerData->eState
|| EServerState.EST_CRASH == pServerData->eState)
{
//
}
else
{
}
}
else
{
if (EServerState.EST_MAINTEN == pServerData->eState
|| EServerState.EST_CRASH == pServerData->eState)
{
//
}
else
{
}
}
}
virtual void SendByServerID(const int nServerID, const std::string& strData)
{
}
virtual void SendBySuit(const std::string& strData)
{
}
protected:
private:
NFMap<int, ServerData> mxServerMap;
};<commit_msg>FIXED CLUSTER CLIENT OF NET<commit_after>// -------------------------------------------------------------------------
// @FileName NFIClusterClientModule.hpp
// @Author LvSheng.Huang
// @Date 2015-01-4
// @Module NFIClusterClientModule
//
// -------------------------------------------------------------------------
#ifndef _NFI_CLUSTER_CLIENT_MODULE_H_
#define _NFI_CLUSTER_CLIENT_MODULE_H_
#include <iostream>
#include "NFILogicModule.h"
#include "NFINetModule.h"
struct ServerData
{
ServerData()
{
nGameID = 0;
nPort = 0;
strName = "";
strIP = "";
eServerType = NFST_NONE;
eState = NFMsg::EServerState::EST_CRASH;
}
int nGameID;
NF_SERVER_TYPE eServerType;
std::string strIP;
int nPort;
std::string strName;
NFMsg::EServerState eState;
NF_SHARE_PTR<NFINetModule> mxNetModule;
};
class NFIClusterClientModule
{
public:
virtual void OnNetCreated(NF_SHARE_PTR<ServerData> xServerData) = 0;
virtual bool Execute(const float fLastFrametime, const float fStartedTime)
{
ServerData* pServerData = mxServerMap.First();
while (pServerData)
{
pServerData->mxNetModule->Execute(fLastFrametime, fStartedTime);
pServerData = mxServerMap.Next();
}
return true;
}
void AddServer(const ServerData& xInfo)
{
NF_SHARE_PTR<ServerData> xServerData = mxServerMap.find(xInfo.nGameID);
if (xServerData)
{
if (EServerState.EST_MAINTEN == xServerData->eState
|| EServerState.EST_CRASH == xServerData->eState)
{
//ˣ
}
else
{
//ϸ״̬
}
}
else
{
if (EServerState.EST_MAINTEN == xInfo->eState
|| EServerState.EST_CRASH == xInfo->eState)
{
//
}
else
{
//·
xServerData = NF_SHARE_PTR<ServerData>(NF_NEW ServerData());
xServerData->nGameID = xInfo.nGameID;
xServerData->eServerType = xInfo->eState;
xServerData->strIP = xInfo.strIP;
xServerData->strName = xInfo.strName;
xServerData->eState = xInfo.eState;
xServerData->mxNetModule = NF_SHARE_PTR<NFINetModule>(NF_NEW NFINetModule());
OnNetCreated(xServerData);
//xServerData->m_pNetModule->Initialization(NFIMsgHead::NF_Head::NF_HEAD_LENGTH, this, &NFCGameServerNet_ServerModule::OnRecivePack, &NFCGameServerNet_ServerModule::OnSocketEvent, nMaxConnect, nPort, nCpus);
mxServerMap.AddElement(xInfo.nGameID, xServerData);
}
}
}
virtual void SendByServerID(const int nServerID, const std::string& strData)
{
}
virtual void SendBySuit(const std::string& strData)
{
}
protected:
private:
NFMapEx<int, ServerData> mxServerMap;
};<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbSarRadiometricCalibrationToImageFilter.h"
namespace otb
{
namespace Wrapper
{
class SARCalibration : public Application
{
public:
/** Standard class typedefs. */
typedef SARCalibration Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(SARCalibration, otb::Application);
typedef otb::SarRadiometricCalibrationToImageFilter<ComplexFloatImageType, FloatImageType> CalibrationFilterType;
private:
void DoInit() override
{
SetName("SARCalibration");
SetDescription(
"Perform radiometric calibration of SAR images. Following sensors are supported: TerraSAR-X, Sentinel1 and Radarsat-2.Both Single Look Complex(SLC) "
"and detected products are supported as input.");
// Documentation
SetDocLongDescription(
"The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This "
"application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically "
"retrieved from image products.The application supports complex and non-complex images (SLC or detected products).");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Calibration);
AddDocTag(Tags::SAR);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "Input complex image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output calibrated image. This image contains the backscatter (sigmaNought) of the input image.");
AddParameter(ParameterType_Bool, "noise", "Disable Noise");
SetParameterDescription("noise", "Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product.");
AddParameter(ParameterType_Choice, "lut", "Lookup table");
SetParameterDescription(
"lut", "Lookup table values are not available with all SAR products. Products that provide lookup table with metadata are: Sentinel1, Radarsat2.");
AddChoice("lut.sigma", "Use sigma nought lookup");
SetParameterDescription("lut.sigma", "Use Sigma nought lookup value from product metadata");
AddChoice("lut.gamma", "Use gamma nought lookup");
SetParameterDescription("lut.gamma", "Use Gamma nought lookup value from product metadata");
AddChoice("lut.beta", "Use beta nought lookup");
SetParameterDescription("lut.beta", "Use Beta nought lookup value from product metadata");
AddChoice("lut.dn", "Use DN value lookup");
SetParameterDescription("lut.dn", "Use DN value lookup value from product metadata");
SetDefaultParameterInt("lut", 0);
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "RSAT_imagery_HH.tif");
SetDocExampleParameterValue("out", "SarRadiometricCalibration.tif");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
}
void DoExecute() override
{
// Get the input complex image
ComplexFloatImageType* floatComplexImage = GetParameterComplexFloatImage("in");
// Set the filer input
m_CalibrationFilter = CalibrationFilterType::New();
m_CalibrationFilter->SetInput(floatComplexImage);
m_CalibrationFilter->SetEnableNoise(!bool(GetParameterInt("noise")));
m_CalibrationFilter->SetLookupSelected(GetParameterInt("lut"));
// Set the output image
SetParameterOutputImage("out", m_CalibrationFilter->GetOutput());
}
CalibrationFilterType::Pointer m_CalibrationFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SARCalibration)
<commit_msg>Fixed lookup table stacking order<commit_after>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbSarRadiometricCalibrationToImageFilter.h"
namespace otb
{
namespace Wrapper
{
class SARCalibration : public Application
{
public:
/** Standard class typedefs. */
typedef SARCalibration Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(SARCalibration, otb::Application);
typedef otb::SarRadiometricCalibrationToImageFilter<ComplexFloatImageType, FloatImageType> CalibrationFilterType;
private:
void DoInit() override
{
SetName("SARCalibration");
SetDescription(
"Perform radiometric calibration of SAR images. Following sensors are supported: TerraSAR-X, Sentinel1 and Radarsat-2.Both Single Look Complex(SLC) "
"and detected products are supported as input.");
// Documentation
SetDocLongDescription(
"The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This "
"application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically "
"retrieved from image products.The application supports complex and non-complex images (SLC or detected products).");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Calibration);
AddDocTag(Tags::SAR);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "Input complex image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output calibrated image. This image contains the backscatter (sigmaNought) of the input image.");
AddParameter(ParameterType_Bool, "noise", "Disable Noise");
SetParameterDescription("noise", "Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product.");
AddParameter(ParameterType_Choice, "lut", "Lookup table");
SetParameterDescription(
"lut", "Lookup table values are not available with all SAR products. Products that provide lookup table with metadata are: Sentinel1, Radarsat2.");
AddChoice("lut.sigma", "Use sigma nought lookup");
SetParameterDescription("lut.sigma", "Use Sigma nought lookup value from product metadata");
AddChoice("lut.beta", "Use beta nought lookup");
SetParameterDescription("lut.beta", "Use Beta nought lookup value from product metadata");
AddChoice("lut.gamma", "Use gamma nought lookup");
SetParameterDescription("lut.gamma", "Use Gamma nought lookup value from product metadata");
AddChoice("lut.dn", "Use DN value lookup");
SetParameterDescription("lut.dn", "Use DN value lookup value from product metadata");
SetDefaultParameterInt("lut", 0);
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "RSAT_imagery_HH.tif");
SetDocExampleParameterValue("out", "SarRadiometricCalibration.tif");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
}
void DoExecute() override
{
// Get the input complex image
ComplexFloatImageType* floatComplexImage = GetParameterComplexFloatImage("in");
// Set the filer input
m_CalibrationFilter = CalibrationFilterType::New();
m_CalibrationFilter->SetInput(floatComplexImage);
m_CalibrationFilter->SetEnableNoise(!bool(GetParameterInt("noise")));
m_CalibrationFilter->SetLookupSelected(GetParameterInt("lut"));
// Set the output image
SetParameterOutputImage("out", m_CalibrationFilter->GetOutput());
}
CalibrationFilterType::Pointer m_CalibrationFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SARCalibration)
<|endoftext|>
|
<commit_before>#include "HaxeRuntime.h"
#include <CoreUObject.h>
#include <unordered_map>
#include "ClassMap.h"
struct WrapperCacheEntry {
int32 typeID;
void* wrapper;
};
static std::unordered_map<UClass *,HaxeWrap>& getClassMap() {
// lazy instantiation
static std::unordered_map<UClass *,HaxeWrap> classMap;
return classMap;
}
static std::unordered_map<void*, WrapperCacheEntry>& getWrapperMap() {
static std::unordered_map<void*, WrapperCacheEntry> wrapperMap;
return wrapperMap;
}
bool ::unreal::helpers::ClassMap_obj::addWrapper(void *inUClass, HaxeWrap inWrapper) {
getClassMap()[(UClass *)inUClass] = inWrapper;
return true;
}
void *::unreal::helpers::ClassMap_obj::wrap(void *inUObject) {
if (inUObject == nullptr) return nullptr;
UObject *obj = (UObject *) inUObject;
UClass *cls = obj->GetClass();
auto& map = getClassMap();
while (cls != nullptr) {
if (cls->HasAllClassFlags(CLASS_Native)) {
auto it = map.find(cls);
if (it != map.end()) {
return (it->second)(inUObject);
}
}
cls = cls->GetSuperClass();
}
UE_LOG(LogTemp,Fatal,TEXT("No haxe wrapper was found for the uobject from class %s nor from any of its superclasses"), *obj->GetClass()->GetName());
// won't get here
return nullptr;
}
static void* s_lastNativeLookup = nullptr;
static void* s_lastWrappedLookup = nullptr;
static int32 s_lastWrappedTypeID = -1;
void* ::unreal::helpers::ClassMap_obj::findWrapper(void* inNative, int32 typeID) {
check(IsInGameThread());
if (s_lastNativeLookup == inNative && s_lastWrappedTypeID == typeID && s_lastWrappedLookup) {
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("RETC %x %x"), inNative, s_lastWrappedLookup);
}
return s_lastWrappedLookup;
}
auto& wrappers = getWrapperMap();
auto it = wrappers.find(inNative);
if (it != wrappers.end() && it->second.typeID == typeID) {
s_lastNativeLookup = inNative;
s_lastWrappedTypeID = it->second.typeID;
s_lastWrappedLookup = it->second.wrapper;
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("RETL %x %x"), inNative, s_lastWrappedLookup);
}
return s_lastWrappedLookup;
}
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("NORET %x"), inNative);
}
return nullptr;
}
void ::unreal::helpers::ClassMap_obj::registerWrapper(void* inNative, void* inWrapper, int32 typeID) {
check(IsInGameThread());
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("REGISTER %x %x"), inNative, inWrapper);
}
getWrapperMap()[inNative] = {typeID, inWrapper};
s_lastNativeLookup = inNative;
s_lastWrappedLookup = inWrapper;
s_lastWrappedTypeID = typeID;
}
void ::unreal::helpers::ClassMap_obj::unregisterWrapper(void* inNative) {
auto& wrappers = getWrapperMap();
auto it = wrappers.find(inNative);
if (it != wrappers.end() && it->second.typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("UNREGISTER %x %x"), inNative);
}
check(IsInGameThread());
getWrapperMap().erase(inNative);
if (s_lastNativeLookup == inNative) {
s_lastNativeLookup = nullptr;
s_lastWrappedLookup = nullptr;
s_lastWrappedTypeID = -1;
}
}<commit_msg>fix log<commit_after>#include "HaxeRuntime.h"
#include <CoreUObject.h>
#include <unordered_map>
#include "ClassMap.h"
struct WrapperCacheEntry {
int32 typeID;
void* wrapper;
};
static std::unordered_map<UClass *,HaxeWrap>& getClassMap() {
// lazy instantiation
static std::unordered_map<UClass *,HaxeWrap> classMap;
return classMap;
}
static std::unordered_map<void*, WrapperCacheEntry>& getWrapperMap() {
static std::unordered_map<void*, WrapperCacheEntry> wrapperMap;
return wrapperMap;
}
bool ::unreal::helpers::ClassMap_obj::addWrapper(void *inUClass, HaxeWrap inWrapper) {
getClassMap()[(UClass *)inUClass] = inWrapper;
return true;
}
void *::unreal::helpers::ClassMap_obj::wrap(void *inUObject) {
if (inUObject == nullptr) return nullptr;
UObject *obj = (UObject *) inUObject;
UClass *cls = obj->GetClass();
auto& map = getClassMap();
while (cls != nullptr) {
if (cls->HasAllClassFlags(CLASS_Native)) {
auto it = map.find(cls);
if (it != map.end()) {
return (it->second)(inUObject);
}
}
cls = cls->GetSuperClass();
}
UE_LOG(LogTemp,Fatal,TEXT("No haxe wrapper was found for the uobject from class %s nor from any of its superclasses"), *obj->GetClass()->GetName());
// won't get here
return nullptr;
}
static void* s_lastNativeLookup = nullptr;
static void* s_lastWrappedLookup = nullptr;
static int32 s_lastWrappedTypeID = -1;
void* ::unreal::helpers::ClassMap_obj::findWrapper(void* inNative, int32 typeID) {
check(IsInGameThread());
if (s_lastNativeLookup == inNative && s_lastWrappedTypeID == typeID && s_lastWrappedLookup) {
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("RETC %x %x"), inNative, s_lastWrappedLookup);
}
return s_lastWrappedLookup;
}
auto& wrappers = getWrapperMap();
auto it = wrappers.find(inNative);
if (it != wrappers.end() && it->second.typeID == typeID) {
s_lastNativeLookup = inNative;
s_lastWrappedTypeID = it->second.typeID;
s_lastWrappedLookup = it->second.wrapper;
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("RETL %x %x"), inNative, s_lastWrappedLookup);
}
return s_lastWrappedLookup;
}
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("NORET %x"), inNative);
}
return nullptr;
}
void ::unreal::helpers::ClassMap_obj::registerWrapper(void* inNative, void* inWrapper, int32 typeID) {
check(IsInGameThread());
if (typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("REGISTER %x %x"), inNative, inWrapper);
}
getWrapperMap()[inNative] = {typeID, inWrapper};
s_lastNativeLookup = inNative;
s_lastWrappedLookup = inWrapper;
s_lastWrappedTypeID = typeID;
}
void ::unreal::helpers::ClassMap_obj::unregisterWrapper(void* inNative) {
auto& wrappers = getWrapperMap();
auto it = wrappers.find(inNative);
if (it != wrappers.end() && it->second.typeID == 1210865730) {
UE_LOG(LogTemp, Warning, TEXT("UNREGISTER %x"), inNative);
}
check(IsInGameThread());
getWrapperMap().erase(inNative);
if (s_lastNativeLookup == inNative) {
s_lastNativeLookup = nullptr;
s_lastWrappedLookup = nullptr;
s_lastWrappedTypeID = -1;
}
}<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ・割り込みマネージャー
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2016,2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/icu.hpp"
#include "RX24T/peripheral.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 割り込みマネージャー・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct icu_mgr {
//-----------------------------------------------------------------//
/*!
@brief 割り込みを設定する(ベクター別)
@param[in] vec 割り込みベクター
@param[in] lvl 割り込みレベル(0の場合、割り込み禁止)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
static bool set_level(ICU::VECTOR vec, uint8_t lvl)
{
bool ret = true;
bool ena = lvl != 0 ? true : false;
switch(vec) {
case ICU::VECTOR::TGIA0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGIA0 = ena;
break;
case ICU::VECTOR::TGIB0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGIB0 = ena;
break;
case ICU::VECTOR::TGIC0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGIC0 = ena;
break;
case ICU::VECTOR::TGID0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGID0 = ena;
break;
case ICU::VECTOR::TCIV0:
ICU::IPR.MTU0_VEF = lvl;
ICU::IER.TCIV0 = ena;
break;
case ICU::VECTOR::TGIE0:
ICU::IPR.MTU0_VEF = lvl;
ICU::IER.TGIE0 = ena;
break;
case ICU::VECTOR::TGIF0:
ICU::IPR.MTU0_VEF = lvl;
ICU::IER.TGIF0 = ena;
break;
case ICU::VECTOR::TGIA1:
ICU::IPR.MTU1_AB = lvl;
ICU::IER.TGIA1 = ena;
break;
case ICU::VECTOR::TGIB1:
ICU::IPR.MTU1_AB = lvl;
ICU::IER.TGIB1 = ena;
break;
case ICU::VECTOR::TCIV1:
ICU::IPR.MTU1_VU = lvl;
ICU::IER.TCIV1 = ena;
break;
case ICU::VECTOR::TCIU1:
ICU::IPR.MTU1_VU = lvl;
ICU::IER.TCIU1 = ena;
break;
case ICU::VECTOR::TGIA2:
ICU::IPR.MTU2_AB = lvl;
ICU::IER.TGIA2 = ena;
break;
case ICU::VECTOR::TGIB2:
ICU::IPR.MTU2_AB = lvl;
ICU::IER.TGIB2 = ena;
break;
case ICU::VECTOR::TCIV2:
ICU::IPR.MTU2_VU = lvl;
ICU::IER.TCIV2 = ena;
break;
case ICU::VECTOR::TCIU2:
ICU::IPR.MTU2_VU = lvl;
ICU::IER.TCIU2 = ena;
break;
case ICU::VECTOR::TGIA3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGIA3 = ena;
break;
case ICU::VECTOR::TGIB3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGIB3 = ena;
break;
case ICU::VECTOR::TGIC3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGIC3 = ena;
break;
case ICU::VECTOR::TGID3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGID3 = ena;
break;
case ICU::VECTOR::TCIV3:
ICU::IPR.MTU3_V = lvl;
ICU::IER.TCIV3 = ena;
break;
case ICU::VECTOR::TGIA4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGIA4 = ena;
break;
case ICU::VECTOR::TGIB4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGIB4 = ena;
break;
case ICU::VECTOR::TGIC4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGIC4 = ena;
break;
case ICU::VECTOR::TGID4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGID4 = ena;
break;
case ICU::VECTOR::TCIV4:
ICU::IPR.MTU4_V = lvl;
ICU::IER.TCIV4 = ena;
break;
case ICU::VECTOR::TGIU5:
ICU::IPR.MTU5_UVW = lvl;
ICU::IER.TGIU5 = ena;
break;
case ICU::VECTOR::TGIV5:
ICU::IPR.MTU5_UVW = lvl;
ICU::IER.TGIV5 = ena;
break;
case ICU::VECTOR::TGIW5:
ICU::IPR.MTU5_UVW = lvl;
ICU::IER.TGIW5 = ena;
break;
case ICU::VECTOR::TGIA6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGIA6 = ena;
break;
case ICU::VECTOR::TGIB6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGIB6 = ena;
break;
case ICU::VECTOR::TGIC6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGIC6 = ena;
break;
case ICU::VECTOR::TGID6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGID6 = ena;
break;
case ICU::VECTOR::TCIV6:
ICU::IPR.MTU6_V = lvl;
ICU::IER.TCIV6 = ena;
break;
case ICU::VECTOR::TGIA7:
ICU::IPR.MTU7_AB = lvl;
ICU::IER.TGIA7 = ena;
break;
case ICU::VECTOR::TGIB7:
ICU::IPR.MTU7_AB = lvl;
ICU::IER.TGIB7 = ena;
break;
case ICU::VECTOR::TGIC7:
ICU::IPR.MTU7_CD = lvl;
ICU::IER.TGIC7 = ena;
break;
case ICU::VECTOR::TGID7:
ICU::IPR.MTU7_CD = lvl;
ICU::IER.TGID7 = ena;
break;
case ICU::VECTOR::TCIV7:
ICU::IPR.MTU7_V = lvl;
ICU::IER.TCIV7 = ena;
break;
case ICU::VECTOR::TGIA9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGIA9 = ena;
break;
case ICU::VECTOR::TGIB9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGIB9 = ena;
break;
case ICU::VECTOR::TGIC9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGIC9 = ena;
break;
case ICU::VECTOR::TGID9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGID9 = ena;
break;
case ICU::VECTOR::TCIV9:
ICU::IPR.MTU9_VEF = lvl;
ICU::IER.TCIV9 = ena;
break;
case ICU::VECTOR::TGIE9:
ICU::IPR.MTU9_VEF = lvl;
ICU::IER.TGIE9 = ena;
break;
case ICU::VECTOR::TGIF9:
ICU::IPR.MTU9_VEF = lvl;
ICU::IER.TGIF9 = ena;
break;
default:
ret = false;
break;
}
return ret;
}
//-----------------------------------------------------------------//
/*!
@brief 割り込みを設定する
@param[in] t 周辺機器タイプ
@param[in] lvl 割り込みレベル(0の場合、割り込み禁止)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
static bool set_level(peripheral t, uint8_t lvl)
{
bool ret = true;
bool ena = lvl != 0 ? true : false;
switch(t) {
case peripheral::CMT0:
ICU::IPR.CMI0 = lvl;
ICU::IER.CMI0 = ena;
break;
case peripheral::CMT1:
ICU::IPR.CMI1 = lvl;
ICU::IER.CMI1 = ena;
break;
case peripheral::CMT2:
ICU::IPR.CMI2 = lvl;
ICU::IER.CMI2 = ena;
break;
case peripheral::CMT3:
ICU::IPR.CMI3 = lvl;
ICU::IER.CMI3 = ena;
break;
case peripheral::RSPI0:
ICU::IPR.RSPI0 = lvl;
ICU::IER.SPRI0 = ena;
ICU::IER.SPTI0 = ena;
break;
case peripheral::SCI1:
case peripheral::SCI1C:
ICU::IPR.SCI1 = lvl;
ICU::IER.RXI1 = ena;
ICU::IER.TEI1 = ena;
break;
case peripheral::SCI5:
case peripheral::SCI5C:
ICU::IPR.SCI5 = lvl;
ICU::IER.RXI5 = ena;
ICU::IER.TEI5 = ena;
break;
case peripheral::SCI6:
case peripheral::SCI6C:
ICU::IPR.SCI6 = lvl;
ICU::IER.RXI6 = ena;
ICU::IER.TEI6 = ena;
break;
case peripheral::RIIC0:
ICU::IPR.EEI0 = lvl;
ICU::IPR.RXI0 = lvl;
ICU::IPR.TXI0 = lvl;
ICU::IPR.TEI0 = lvl;
ICU::IER.EEI0 = ena;
ICU::IER.RXI0 = ena;
ICU::IER.TXI0 = ena;
ICU::IER.TEI0 = ena;
break;
case peripheral::S12AD:
ICU::IPR.S12ADI = lvl;
ICU::IPR.GBADI = lvl;
ICU::IPR.GCADI = lvl;
ICU::IER.S12ADI = ena;
ICU::IER.GBADI = ena;
ICU::IER.GCADI = ena;
break;
case peripheral::S12AD1:
ICU::IPR.S12ADI1 = lvl;
ICU::IPR.GBADI1 = lvl;
ICU::IPR.GCADI1 = lvl;
ICU::IER.S12ADI1 = ena;
ICU::IER.GBADI1 = ena;
ICU::IER.GCADI1 = ena;
break;
case peripheral::S12AD2:
ICU::IPR.S12ADI2 = lvl;
ICU::IPR.GBADI2 = lvl;
ICU::IPR.GCADI2 = lvl;
ICU::IER.S12ADI2 = ena;
ICU::IER.GBADI2 = ena;
ICU::IER.GCADI2 = ena;
break;
default:
ret = false;
break;
}
return ret;
}
};
}
<commit_msg>update: CMT/ICU<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ・割り込みマネージャー
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2016,2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/peripheral.hpp"
#include "RX24T/icu.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 割り込みマネージャー・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct icu_mgr {
//-----------------------------------------------------------------//
/*!
@brief 割り込みを設定する(ベクター別)
@param[in] vec 割り込みベクター
@param[in] lvl 割り込みレベル(0の場合、割り込み禁止)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
static bool set_level(ICU::VECTOR vec, uint8_t lvl)
{
bool ret = true;
bool ena = lvl != 0 ? true : false;
switch(vec) {
case ICU::VECTOR::CMI0:
ICU::IPR.CMI0 = lvl;
ICU::IER.CMI0 = ena;
break;
case ICU::VECTOR::CMI1:
ICU::IPR.CMI1 = lvl;
ICU::IER.CMI1 = ena;
break;
case ICU::VECTOR::CMI2:
ICU::IPR.CMI2 = lvl;
ICU::IER.CMI2 = ena;
break;
case ICU::VECTOR::CMI3:
ICU::IPR.CMI3 = lvl;
ICU::IER.CMI3 = ena;
break;
case ICU::VECTOR::TGIA0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGIA0 = ena;
break;
case ICU::VECTOR::TGIB0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGIB0 = ena;
break;
case ICU::VECTOR::TGIC0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGIC0 = ena;
break;
case ICU::VECTOR::TGID0:
ICU::IPR.MTU0_ABCD = lvl;
ICU::IER.TGID0 = ena;
break;
case ICU::VECTOR::TCIV0:
ICU::IPR.MTU0_VEF = lvl;
ICU::IER.TCIV0 = ena;
break;
case ICU::VECTOR::TGIE0:
ICU::IPR.MTU0_VEF = lvl;
ICU::IER.TGIE0 = ena;
break;
case ICU::VECTOR::TGIF0:
ICU::IPR.MTU0_VEF = lvl;
ICU::IER.TGIF0 = ena;
break;
case ICU::VECTOR::TGIA1:
ICU::IPR.MTU1_AB = lvl;
ICU::IER.TGIA1 = ena;
break;
case ICU::VECTOR::TGIB1:
ICU::IPR.MTU1_AB = lvl;
ICU::IER.TGIB1 = ena;
break;
case ICU::VECTOR::TCIV1:
ICU::IPR.MTU1_VU = lvl;
ICU::IER.TCIV1 = ena;
break;
case ICU::VECTOR::TCIU1:
ICU::IPR.MTU1_VU = lvl;
ICU::IER.TCIU1 = ena;
break;
case ICU::VECTOR::TGIA2:
ICU::IPR.MTU2_AB = lvl;
ICU::IER.TGIA2 = ena;
break;
case ICU::VECTOR::TGIB2:
ICU::IPR.MTU2_AB = lvl;
ICU::IER.TGIB2 = ena;
break;
case ICU::VECTOR::TCIV2:
ICU::IPR.MTU2_VU = lvl;
ICU::IER.TCIV2 = ena;
break;
case ICU::VECTOR::TCIU2:
ICU::IPR.MTU2_VU = lvl;
ICU::IER.TCIU2 = ena;
break;
case ICU::VECTOR::TGIA3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGIA3 = ena;
break;
case ICU::VECTOR::TGIB3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGIB3 = ena;
break;
case ICU::VECTOR::TGIC3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGIC3 = ena;
break;
case ICU::VECTOR::TGID3:
ICU::IPR.MTU3_ABCD = lvl;
ICU::IER.TGID3 = ena;
break;
case ICU::VECTOR::TCIV3:
ICU::IPR.MTU3_V = lvl;
ICU::IER.TCIV3 = ena;
break;
case ICU::VECTOR::TGIA4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGIA4 = ena;
break;
case ICU::VECTOR::TGIB4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGIB4 = ena;
break;
case ICU::VECTOR::TGIC4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGIC4 = ena;
break;
case ICU::VECTOR::TGID4:
ICU::IPR.MTU4_ABCD = lvl;
ICU::IER.TGID4 = ena;
break;
case ICU::VECTOR::TCIV4:
ICU::IPR.MTU4_V = lvl;
ICU::IER.TCIV4 = ena;
break;
case ICU::VECTOR::TGIU5:
ICU::IPR.MTU5_UVW = lvl;
ICU::IER.TGIU5 = ena;
break;
case ICU::VECTOR::TGIV5:
ICU::IPR.MTU5_UVW = lvl;
ICU::IER.TGIV5 = ena;
break;
case ICU::VECTOR::TGIW5:
ICU::IPR.MTU5_UVW = lvl;
ICU::IER.TGIW5 = ena;
break;
case ICU::VECTOR::TGIA6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGIA6 = ena;
break;
case ICU::VECTOR::TGIB6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGIB6 = ena;
break;
case ICU::VECTOR::TGIC6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGIC6 = ena;
break;
case ICU::VECTOR::TGID6:
ICU::IPR.MTU6_ABCD = lvl;
ICU::IER.TGID6 = ena;
break;
case ICU::VECTOR::TCIV6:
ICU::IPR.MTU6_V = lvl;
ICU::IER.TCIV6 = ena;
break;
case ICU::VECTOR::TGIA7:
ICU::IPR.MTU7_AB = lvl;
ICU::IER.TGIA7 = ena;
break;
case ICU::VECTOR::TGIB7:
ICU::IPR.MTU7_AB = lvl;
ICU::IER.TGIB7 = ena;
break;
case ICU::VECTOR::TGIC7:
ICU::IPR.MTU7_CD = lvl;
ICU::IER.TGIC7 = ena;
break;
case ICU::VECTOR::TGID7:
ICU::IPR.MTU7_CD = lvl;
ICU::IER.TGID7 = ena;
break;
case ICU::VECTOR::TCIV7:
ICU::IPR.MTU7_V = lvl;
ICU::IER.TCIV7 = ena;
break;
case ICU::VECTOR::TGIA9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGIA9 = ena;
break;
case ICU::VECTOR::TGIB9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGIB9 = ena;
break;
case ICU::VECTOR::TGIC9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGIC9 = ena;
break;
case ICU::VECTOR::TGID9:
ICU::IPR.MTU9_ABCD = lvl;
ICU::IER.TGID9 = ena;
break;
case ICU::VECTOR::TCIV9:
ICU::IPR.MTU9_VEF = lvl;
ICU::IER.TCIV9 = ena;
break;
case ICU::VECTOR::TGIE9:
ICU::IPR.MTU9_VEF = lvl;
ICU::IER.TGIE9 = ena;
break;
case ICU::VECTOR::TGIF9:
ICU::IPR.MTU9_VEF = lvl;
ICU::IER.TGIF9 = ena;
break;
default:
ret = false;
break;
}
return ret;
}
//-----------------------------------------------------------------//
/*!
@brief 割り込みを設定する
@param[in] t 周辺機器タイプ
@param[in] lvl 割り込みレベル(0の場合、割り込み禁止)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
static bool set_level(peripheral t, uint8_t lvl)
{
bool ret = true;
bool ena = lvl != 0 ? true : false;
switch(t) {
case peripheral::RSPI0:
ICU::IPR.RSPI0 = lvl;
ICU::IER.SPRI0 = ena;
ICU::IER.SPTI0 = ena;
break;
case peripheral::SCI1:
case peripheral::SCI1C:
ICU::IPR.SCI1 = lvl;
ICU::IER.RXI1 = ena;
ICU::IER.TXI1 = ena;
break;
case peripheral::SCI5:
case peripheral::SCI5C:
ICU::IPR.SCI5 = lvl;
ICU::IER.RXI5 = ena;
ICU::IER.TXI5 = ena;
break;
case peripheral::SCI6:
case peripheral::SCI6C:
ICU::IPR.SCI6 = lvl;
ICU::IER.RXI6 = ena;
ICU::IER.TXI6 = ena;
break;
case peripheral::RIIC0:
ICU::IPR.EEI0 = lvl;
ICU::IPR.RXI0 = lvl;
ICU::IPR.TXI0 = lvl;
ICU::IPR.TEI0 = lvl;
ICU::IER.EEI0 = ena;
ICU::IER.RXI0 = ena;
ICU::IER.TXI0 = ena;
ICU::IER.TEI0 = ena;
break;
case peripheral::S12AD:
ICU::IPR.S12ADI = lvl;
ICU::IPR.GBADI = lvl;
ICU::IPR.GCADI = lvl;
ICU::IER.S12ADI = ena;
ICU::IER.GBADI = ena;
ICU::IER.GCADI = ena;
break;
case peripheral::S12AD1:
ICU::IPR.S12ADI1 = lvl;
ICU::IPR.GBADI1 = lvl;
ICU::IPR.GCADI1 = lvl;
ICU::IER.S12ADI1 = ena;
ICU::IER.GBADI1 = ena;
ICU::IER.GCADI1 = ena;
break;
case peripheral::S12AD2:
ICU::IPR.S12ADI2 = lvl;
ICU::IPR.GBADI2 = lvl;
ICU::IPR.GCADI2 = lvl;
ICU::IER.S12ADI2 = ena;
ICU::IER.GBADI2 = ena;
ICU::IER.GCADI2 = ena;
break;
default:
ret = false;
break;
}
return ret;
}
};
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
const int UFSIZE = 100010;
int union_find[UFSIZE];
void init() {
for (auto i=0; i<UFSIZE; i++) {
union_find[i] = i;
}
}
int root(int a) {
if (a == union_find[a]) return a;
return (union_find[a] = root(union_find[a]));
}
bool issame(int a, int b) {
return root(a) == root(b);
}
void unite(int a, int b) {
union_find[root(a)] = root(b);
}
bool isroot(int a) {
return root(a) == a;
}
int N, M;
int a[100010];
int b[100010];
int Q;
int x[100010];
int y[100010];
tuple<int, int> parent[100010];
int d[100010][20];
int depth[100010];
vector<int> V[100010];
int lca(int u, int v) {
if (depth[u] > depth[v]) swap(u, v);
for (auto k = 0; k < 20; ++k) {
if ((depth[v] - depth[u]) >> k & 1) {
v = d[v][k];
}
}
if (u == v) return u;
for (auto k = 19; k >= 0; --k) {
if (d[k][u] != d[k][v]) {
u = d[u][k];
v = d[v][k];
}
}
return d[u][0];
}
int main() {
// initが必要
init();
fill(&d[0][0], &d[0][0]+100010*20, -1);
fill(parent, parent+100010, make_tuple(-1, 0));
cin >> N >> M;
for (auto i = 0; i < M; ++i) {
cin >> a[i] >> b[i];
a[i]--;
b[i]--;
}
cin >> Q;
for (auto i = 0; i < Q; ++i) {
cin >> x[i] >> y[i];
x[i]--;
y[i]--;
}
for (auto i = 0; i < M; ++i) {
if (!issame(a[i], b[i])) {
parent[root(a[i])] = make_tuple(root(b[i]), i);
//cerr << "parent[" << root(a[i]) << "] = "
// << root(b[i]) << endl;
V[root(b[i])].push_back(root(a[i]));
unite(a[i], b[i]);
}
}
for (auto i = 0; i < N; ++i) {
d[i][0] = get<0>(parent[i]);
//cerr << "d[" << i << "][" << 0 << "] = " << d[i][0] << endl;
}
for (auto i = 1; i < 20; ++i) {
for (auto j = 0; j < N; ++j) {
if (d[j][i-1] >= 0) {
d[j][i] = d[d[j][i-1]][i-1];
}
}
}
fill(depth, depth+100010, -1);
for (auto i = 0; i < N; ++i) {
if (d[i][0] == -1) {
stack<tuple<int, int> > S;
S.push(make_tuple(i, 0));
while (!S.empty()) {
int now = get<0>(S.top());
int dep = get<1>(S.top());
S.pop();
if (depth[now] == -1) {
depth[now] = dep;
for (auto x : V[now]) {
if (depth[x] == -1) {
S.push(make_tuple(x, dep+1));
}
}
}
}
}
}
//for (auto i = 0; i < N; ++i) {
// cerr << "depth[" << i << "] = " << depth[i] << endl;
//}
for (auto i = 0; i < Q; ++i) {
if (!issame(x[i], y[i])) {
cout << -1 << endl;
} else {
int c = lca(x[i], y[i]);
cerr << "lca(" << x[i] << ", " << y[i] << ") = " << c << endl;
cout << get<1>(parent[c])+1 << endl;
}
}
}
<commit_msg>tried H.cpp to 'H'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
const int UFSIZE = 100010;
int union_find[UFSIZE];
void init() {
for (auto i=0; i<UFSIZE; i++) {
union_find[i] = i;
}
}
int root(int a) {
if (a == union_find[a]) return a;
return (union_find[a] = root(union_find[a]));
}
bool issame(int a, int b) {
return root(a) == root(b);
}
void unite(int a, int b) {
union_find[root(a)] = root(b);
}
bool isroot(int a) {
return root(a) == a;
}
int N, M;
int a[100010];
int b[100010];
int Q;
int x[100010];
int y[100010];
tuple<int, int> parent[100010];
int d[100010][20];
int depth[100010];
vector<int> V[100010];
int lca(int u, int v) {
if (depth[u] > depth[v]) swap(u, v);
for (auto k = 0; k < 20; ++k) {
if ((depth[v] - depth[u]) >> k & 1) {
v = d[v][k];
}
}
if (u == v) return u;
for (auto k = 19; k >= 0; --k) {
if (d[k][u] != d[k][v]) {
u = d[u][k];
v = d[v][k];
}
}
return d[u][0];
}
int main() {
// initが必要
init();
fill(&d[0][0], &d[0][0]+100010*20, -1);
fill(parent, parent+100010, make_tuple(-1, 0));
cin >> N >> M;
for (auto i = 0; i < M; ++i) {
cin >> a[i] >> b[i];
a[i]--;
b[i]--;
}
cin >> Q;
for (auto i = 0; i < Q; ++i) {
cin >> x[i] >> y[i];
x[i]--;
y[i]--;
}
for (auto i = 0; i < M; ++i) {
if (!issame(a[i], b[i])) {
parent[root(a[i])] = make_tuple(root(b[i]), i);
cerr << "parent[" << root(a[i]) << "] = "
<< root(b[i]) << ", " << i << endl;
V[root(b[i])].push_back(root(a[i]));
unite(a[i], b[i]);
}
}
for (auto i = 0; i < N; ++i) {
d[i][0] = get<0>(parent[i]);
//cerr << "d[" << i << "][" << 0 << "] = " << d[i][0] << endl;
}
for (auto i = 1; i < 20; ++i) {
for (auto j = 0; j < N; ++j) {
if (d[j][i-1] >= 0) {
d[j][i] = d[d[j][i-1]][i-1];
}
}
}
fill(depth, depth+100010, -1);
for (auto i = 0; i < N; ++i) {
if (d[i][0] == -1) {
stack<tuple<int, int> > S;
S.push(make_tuple(i, 0));
while (!S.empty()) {
int now = get<0>(S.top());
int dep = get<1>(S.top());
S.pop();
if (depth[now] == -1) {
depth[now] = dep;
for (auto x : V[now]) {
if (depth[x] == -1) {
S.push(make_tuple(x, dep+1));
}
}
}
}
}
}
//for (auto i = 0; i < N; ++i) {
// cerr << "depth[" << i << "] = " << depth[i] << endl;
//}
for (auto i = 0; i < Q; ++i) {
if (!issame(x[i], y[i])) {
cout << -1 << endl;
} else {
int c = lca(x[i], y[i]);
cerr << "lca(" << x[i] << ", " << y[i] << ") = " << c << endl;
cout << get<1>(parent[c])+1 << endl;
}
}
}
<|endoftext|>
|
<commit_before>#ifndef OBJECTS_H
#define OBJECTS_H
/*
Defines an Object::ref type, which is a tagged pointer type.
Usage:
Object::ref x = Object::to_ref(1);//smallint
Object::ref y = Object::to_ref(new(hp) Generic()); //object
if(is_a<int>(x)) {
std::cout << "x = " << as_a<int>(x) << std::endl;
}
if(is_a<Generic*>(y)) {
std::cout << "y.field = " << as_a<Generic*>(y)->field
<< std::endl;
}
*/
#include<stdint.h>
#include<climits>
#include"unichars.hpp"
class Generic;
class Symbol;
class Cons;
class Closure;
class KClosure;
namespace Object {
/*-----------------------------------------------------------------------------
Declare
-----------------------------------------------------------------------------*/
class ref;
template<typename T> struct tag_traits;
/*assume we won't ever need more than 7 bits of tag*/
typedef unsigned char tag_type;
template<typename T> static inline ref to_ref(T);
template<typename T> static inline bool _is_a(ref);
template<typename T> static inline T _as_a(ref);
static inline ref t(void);
static inline bool _is_t(ref);
static inline ref nil(void);
static inline bool _is_nil(ref);
static inline ref from_a_scaled_int(int);
static inline int to_a_scaled_int(ref);
}
void throw_TypeError(Object::ref, char const*);
void throw_RangeError(char const*);
template<typename T> static inline bool is_a(Object::ref);
template<typename T> static inline T as_a(Object::ref);
static inline bool is_t(Object::ref);
namespace Object {
/*-----------------------------------------------------------------------------
Configuration
-----------------------------------------------------------------------------*/
static const unsigned char tag_bits = 2;// can bump up to 3 maybe...
template<> struct tag_traits<int> {
static const tag_type tag = 0x1;
};
template<> struct tag_traits<Generic*> {
static const tag_type tag = 0x0;
};
template<> struct tag_traits<Symbol*> {
static const tag_type tag = 0x2;
};
template<> struct tag_traits<UnicodeChar> {
static const tag_type tag = 0x3;
};
/*-----------------------------------------------------------------------------
Provided information
-----------------------------------------------------------------------------*/
static const tag_type alignment = 1 << tag_bits;
static const tag_type tag_mask = alignment - 1;
/*the real range is the smaller of the range of intptr_t
shifted down by tag bits, or the range of the `int' type
*/
static const intptr_t smallint_min =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MIN >> tag_bits :
/*otherwise*/
INT_MIN;
static const intptr_t smallint_max =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MAX >> tag_bits :
/*otherwise*/
INT_MAX;
/*value for "t"*/
static const intptr_t t_value = ~((intptr_t) tag_mask);
/*-----------------------------------------------------------------------------
The tagged pointer type
-----------------------------------------------------------------------------*/
/*stefano prefers to use:
typedef void* ref;
or maybe:
typedef intptr_t ref;
I may change this later on, but for now
I want to see whether the conceptual
separation will help and if compilers,
in general, will be smart enough to
optimize away the structure.
*/
class ref {
private:
intptr_t dat;
ref(intptr_t x) : dat(x) {}
public:
ref(void) : dat(0) {}
inline bool operator==(ref b) {
return dat == b.dat;
}
inline bool operator!=(ref b) {
return dat != b.dat;
}
inline bool operator!(void) {
return dat == 0;
}
/*safe bool idiom*/
typedef intptr_t (ref::*unspecified_bool_type);
inline operator unspecified_bool_type(void) {
return dat != 0 ? &ref::dat : 0;
}
template<typename T> friend ref to_ref(T);
template<typename T> friend bool _is_a(ref);
template<typename T> friend T _as_a(ref);
friend int to_a_scaled_int(ref);
friend ref from_a_scaled_int(int);
friend ref t(void);
friend bool _is_t(ref);
};
/*-----------------------------------------------------------------------------
Tagged pointer factories
-----------------------------------------------------------------------------*/
template<typename T>
static inline ref to_ref(T x) {
/* default to Generic* */
return to_ref<Generic*>(x);
}
template<>
ref to_ref<Generic*>(Generic* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Generic*>::tag);
}
template<>
ref to_ref<Symbol*>(Symbol* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Symbol*>::tag);
}
template<>
ref to_ref<int>(int x) {
#ifdef DEBUG
#if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN)
if(x < smallint_min || x > smallint_max) {
throw_RangeError(
"int out of range of smallint"
);
}
#endif
#endif
intptr_t tmp = (((intptr_t) x) << tag_bits);
return ref(tmp + tag_traits<int>::tag);
}
template<>
ref to_ref<UnicodeChar>(UnicodeChar x) {
intptr_t tmp = x.dat << tag_bits;
return ref(tmp + tag_traits<UnicodeChar>::tag);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert an int computed using
Object::to_a_scaled_int back to an Object::ref. It is not
intended to be used for any other int's.
This function is intended for optimized smallint
mathematics.
*/
static inline ref from_a_scaled_int(int x) {
return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag);
}
static inline ref nil(void) {
return ref();
}
static inline ref t(void) {
return ref(t_value);
}
/*-----------------------------------------------------------------------------
Tagged pointer checking
-----------------------------------------------------------------------------*/
static inline bool _is_nil(ref obj) {
return !obj;
}
static inline bool _is_t(ref obj) {
return obj.dat == t_value;
}
template<typename T>
static inline bool _is_a(ref obj) {
if(tag_traits<T>::tag != 0x0) {
return (obj.dat & tag_mask) == tag_traits<T>::tag;
} else {
return (obj.dat & tag_mask) == tag_traits<T>::tag
&& !_is_nil(obj) && !_is_t(obj);
}
}
/*-----------------------------------------------------------------------------
Tagged pointer referencing
-----------------------------------------------------------------------------*/
template<typename T>
static inline T _as_a(ref obj) {
#ifdef DEBUG
if(!_is_a<T>(obj)) {
throw_TypeError(obj,
"incorrect type for pointer"
);
}
#endif
intptr_t tmp = obj.dat;
return reinterpret_cast<T>(tmp - tag_traits<T>::tag);
/*use subtraction instead of masking, in order to
allow smart compilers to merge a field access with
the tag removal. i.e. the pointers are pointers to
structures, so they will be accessed via fields, and
in all probability those fields will be at some
offset from the actual structure address, meaning
that the processor itself will perform an addition
to access the field. The smart compiler can then
merge the addition of the field offset with the
subtraction of the tag.
*/
}
template<>
int _as_a<int>(ref obj) {
#ifdef DEBUG
if(!_is_a<int>(obj)) {
throw_TypeError(obj,
"incorrect type for small integer"
);
}
#endif
intptr_t tmp = obj.dat;
return (int)(tmp >> tag_bits);
}
template<>
UnicodeChar _as_a<UnicodeChar>(ref obj) {
uint32_t tmp = obj.dat;
return UnicodeChar(tmp >> tag_bits);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert a smallint Object::ref
to a useable int that is equal to the "real" int, shifted
to the left by the number of tag bits (i.e. scaled). It
should be used only for optimizing smallint math operations.
*/
static inline int to_a_scaled_int(ref obj) {
intptr_t tmp = obj.dat;
return (int)((tmp - tag_traits<int>::tag)>>tag_bits);
/*use subtraction instead of masking, again to
allow smart compilers to merge tag adding and
subtracting. For example the typical case would
be something like:
Object::ref result =
Object::from_a_scaled_int(
Object::to_a_scaled_int(a) +
Object::to_a_scaled_int(b)
);
The above case can be reduced by the compiler to:
intptr_t result =
(tag_traits<int>::tag +
a - tag_traits<int>::tag +
b - tag_traits<int>::tag
);
It can then do some maths and cancel out a tag:
intptr_t result = a + b - tag_traits<int>::tag;
*/
}
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
static inline size_t round_up_to_alignment(size_t x) {
return
(x & tag_mask) ? (x + alignment - (x & tag_mask)) :
/*otherwise*/ x ;
}
}
/*-----------------------------------------------------------------------------
Reflectors outside of the namespace
-----------------------------------------------------------------------------*/
template<typename T>
static inline bool is_a(Object::ref obj) {
return Object::_is_a<T>(obj);
}
template<typename T>
static inline T as_a(Object::ref obj) {
return Object::_as_a<T>(obj);
}
static inline bool is_nil(Object::ref obj) {
return Object::_is_nil(obj);
}
static inline bool is_t(Object::ref obj) {
return Object::_is_t(obj);
}
#endif //OBJECTS_H
<commit_msg>inc/objects.hpp: Added hash_is() as friend of Object::ref<commit_after>#ifndef OBJECTS_H
#define OBJECTS_H
/*
Defines an Object::ref type, which is a tagged pointer type.
Usage:
Object::ref x = Object::to_ref(1);//smallint
Object::ref y = Object::to_ref(new(hp) Generic()); //object
if(is_a<int>(x)) {
std::cout << "x = " << as_a<int>(x) << std::endl;
}
if(is_a<Generic*>(y)) {
std::cout << "y.field = " << as_a<Generic*>(y)->field
<< std::endl;
}
*/
#include<stdint.h>
#include<climits>
#include"unichars.hpp"
class Generic;
class Symbol;
class Cons;
class Closure;
class KClosure;
namespace Object {
/*-----------------------------------------------------------------------------
Declare
-----------------------------------------------------------------------------*/
class ref;
template<typename T> struct tag_traits;
/*assume we won't ever need more than 7 bits of tag*/
typedef unsigned char tag_type;
template<typename T> static inline ref to_ref(T);
template<typename T> static inline bool _is_a(ref);
template<typename T> static inline T _as_a(ref);
static inline ref t(void);
static inline bool _is_t(ref);
static inline ref nil(void);
static inline bool _is_nil(ref);
static inline ref from_a_scaled_int(int);
static inline int to_a_scaled_int(ref);
}
void throw_TypeError(Object::ref, char const*);
void throw_RangeError(char const*);
template<typename T> static inline bool is_a(Object::ref);
template<typename T> static inline T as_a(Object::ref);
static inline bool is_t(Object::ref);
size_t hash_is(Object::ref);
namespace Object {
/*-----------------------------------------------------------------------------
Configuration
-----------------------------------------------------------------------------*/
static const unsigned char tag_bits = 2;// can bump up to 3 maybe...
template<> struct tag_traits<int> {
static const tag_type tag = 0x1;
};
template<> struct tag_traits<Generic*> {
static const tag_type tag = 0x0;
};
template<> struct tag_traits<Symbol*> {
static const tag_type tag = 0x2;
};
template<> struct tag_traits<UnicodeChar> {
static const tag_type tag = 0x3;
};
/*-----------------------------------------------------------------------------
Provided information
-----------------------------------------------------------------------------*/
static const tag_type alignment = 1 << tag_bits;
static const tag_type tag_mask = alignment - 1;
/*the real range is the smaller of the range of intptr_t
shifted down by tag bits, or the range of the `int' type
*/
static const intptr_t smallint_min =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MIN >> tag_bits :
/*otherwise*/
INT_MIN;
static const intptr_t smallint_max =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MAX >> tag_bits :
/*otherwise*/
INT_MAX;
/*value for "t"*/
static const intptr_t t_value = ~((intptr_t) tag_mask);
/*-----------------------------------------------------------------------------
The tagged pointer type
-----------------------------------------------------------------------------*/
/*stefano prefers to use:
typedef void* ref;
or maybe:
typedef intptr_t ref;
I may change this later on, but for now
I want to see whether the conceptual
separation will help and if compilers,
in general, will be smart enough to
optimize away the structure.
*/
class ref {
private:
intptr_t dat;
ref(intptr_t x) : dat(x) {}
public:
ref(void) : dat(0) {}
inline bool operator==(ref b) {
return dat == b.dat;
}
inline bool operator!=(ref b) {
return dat != b.dat;
}
inline bool operator!(void) {
return dat == 0;
}
/*safe bool idiom*/
typedef intptr_t (ref::*unspecified_bool_type);
inline operator unspecified_bool_type(void) {
return dat != 0 ? &ref::dat : 0;
}
template<typename T> friend ref to_ref(T);
template<typename T> friend bool _is_a(ref);
template<typename T> friend T _as_a(ref);
friend int to_a_scaled_int(ref);
friend ref from_a_scaled_int(int);
friend ref t(void);
friend bool _is_t(ref);
friend size_t ::hash_is(Object::ref);
};
/*-----------------------------------------------------------------------------
Tagged pointer factories
-----------------------------------------------------------------------------*/
template<typename T>
static inline ref to_ref(T x) {
/* default to Generic* */
return to_ref<Generic*>(x);
}
template<>
ref to_ref<Generic*>(Generic* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Generic*>::tag);
}
template<>
ref to_ref<Symbol*>(Symbol* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Symbol*>::tag);
}
template<>
ref to_ref<int>(int x) {
#ifdef DEBUG
#if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN)
if(x < smallint_min || x > smallint_max) {
throw_RangeError(
"int out of range of smallint"
);
}
#endif
#endif
intptr_t tmp = (((intptr_t) x) << tag_bits);
return ref(tmp + tag_traits<int>::tag);
}
template<>
ref to_ref<UnicodeChar>(UnicodeChar x) {
intptr_t tmp = x.dat << tag_bits;
return ref(tmp + tag_traits<UnicodeChar>::tag);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert an int computed using
Object::to_a_scaled_int back to an Object::ref. It is not
intended to be used for any other int's.
This function is intended for optimized smallint
mathematics.
*/
static inline ref from_a_scaled_int(int x) {
return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag);
}
static inline ref nil(void) {
return ref();
}
static inline ref t(void) {
return ref(t_value);
}
/*-----------------------------------------------------------------------------
Tagged pointer checking
-----------------------------------------------------------------------------*/
static inline bool _is_nil(ref obj) {
return !obj;
}
static inline bool _is_t(ref obj) {
return obj.dat == t_value;
}
template<typename T>
static inline bool _is_a(ref obj) {
if(tag_traits<T>::tag != 0x0) {
return (obj.dat & tag_mask) == tag_traits<T>::tag;
} else {
return (obj.dat & tag_mask) == tag_traits<T>::tag
&& !_is_nil(obj) && !_is_t(obj);
}
}
/*-----------------------------------------------------------------------------
Tagged pointer referencing
-----------------------------------------------------------------------------*/
template<typename T>
static inline T _as_a(ref obj) {
#ifdef DEBUG
if(!_is_a<T>(obj)) {
throw_TypeError(obj,
"incorrect type for pointer"
);
}
#endif
intptr_t tmp = obj.dat;
return reinterpret_cast<T>(tmp - tag_traits<T>::tag);
/*use subtraction instead of masking, in order to
allow smart compilers to merge a field access with
the tag removal. i.e. the pointers are pointers to
structures, so they will be accessed via fields, and
in all probability those fields will be at some
offset from the actual structure address, meaning
that the processor itself will perform an addition
to access the field. The smart compiler can then
merge the addition of the field offset with the
subtraction of the tag.
*/
}
template<>
int _as_a<int>(ref obj) {
#ifdef DEBUG
if(!_is_a<int>(obj)) {
throw_TypeError(obj,
"incorrect type for small integer"
);
}
#endif
intptr_t tmp = obj.dat;
return (int)(tmp >> tag_bits);
}
template<>
UnicodeChar _as_a<UnicodeChar>(ref obj) {
uint32_t tmp = obj.dat;
return UnicodeChar(tmp >> tag_bits);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert a smallint Object::ref
to a useable int that is equal to the "real" int, shifted
to the left by the number of tag bits (i.e. scaled). It
should be used only for optimizing smallint math operations.
*/
static inline int to_a_scaled_int(ref obj) {
intptr_t tmp = obj.dat;
return (int)((tmp - tag_traits<int>::tag)>>tag_bits);
/*use subtraction instead of masking, again to
allow smart compilers to merge tag adding and
subtracting. For example the typical case would
be something like:
Object::ref result =
Object::from_a_scaled_int(
Object::to_a_scaled_int(a) +
Object::to_a_scaled_int(b)
);
The above case can be reduced by the compiler to:
intptr_t result =
(tag_traits<int>::tag +
a - tag_traits<int>::tag +
b - tag_traits<int>::tag
);
It can then do some maths and cancel out a tag:
intptr_t result = a + b - tag_traits<int>::tag;
*/
}
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
static inline size_t round_up_to_alignment(size_t x) {
return
(x & tag_mask) ? (x + alignment - (x & tag_mask)) :
/*otherwise*/ x ;
}
}
/*-----------------------------------------------------------------------------
Reflectors outside of the namespace
-----------------------------------------------------------------------------*/
template<typename T>
static inline bool is_a(Object::ref obj) {
return Object::_is_a<T>(obj);
}
template<typename T>
static inline T as_a(Object::ref obj) {
return Object::_as_a<T>(obj);
}
static inline bool is_nil(Object::ref obj) {
return Object::_is_nil(obj);
}
static inline bool is_t(Object::ref obj) {
return Object::_is_t(obj);
}
#endif //OBJECTS_H
<|endoftext|>
|
<commit_before>#ifndef OBJECTS_H
#define OBJECTS_H
/*
Defines an Object::ref type, which is a tagged pointer type.
Usage:
Object::ref x = Object::to_ref(1);//smallint
Object::ref y = Object::to_ref(new(hp) Generic()); //object
if(is_a<int>(x)) {
std::cout << "x = " << as_a<int>(x) << std::endl;
}
if(is_a<Generic*>(y)) {
std::cout << "y.field = " << as_a<Generic*>(y)->field
<< std::endl;
}
*/
#include<stdint.h>
#include<climits>
#include"unichars.hpp"
#ifdef MY_COMPILER
// without these my compiler signals an error -- stefano
// I suggest you try it now with all_defines.hpp
// included in all source files -- almkglor
#define INTPTR_MIN (-2147483647-1)
#define INTPTR_MAX (2147483647)
#endif // MY_COMPILER
class Generic;
class Symbol;
class Cons;
class Closure;
class KClosure;
namespace Object {
/*-----------------------------------------------------------------------------
Declare
-----------------------------------------------------------------------------*/
class ref;
template<typename T> struct tag_traits;
/*assume we won't ever need more than 7 bits of tag*/
typedef unsigned char tag_type;
template<typename T> static inline ref to_ref(T);
template<typename T> static inline bool _is_a(ref);
template<typename T> static inline T _as_a(ref);
static inline ref t(void);
static inline bool _is_t(ref);
static inline ref nil(void);
static inline bool _is_nil(ref);
static inline ref from_a_scaled_int(int);
static inline int to_a_scaled_int(ref);
}
void throw_TypeError(Object::ref, char const*);
void throw_RangeError(char const*);
template<typename T> static inline bool is_a(Object::ref);
template<typename T> static inline T as_a(Object::ref);
static inline bool is_t(Object::ref);
namespace Object {
/*-----------------------------------------------------------------------------
Configuration
-----------------------------------------------------------------------------*/
static const unsigned char tag_bits = 2;// can bump up to 3 maybe...
template<> struct tag_traits<int> {
static const tag_type tag = 0x1;
};
template<> struct tag_traits<Generic*> {
static const tag_type tag = 0x0;
};
template<> struct tag_traits<Symbol*> {
static const tag_type tag = 0x2;
};
template<> struct tag_traits<UnicodeChar> {
static const tag_type tag = 0x3;
};
/*-----------------------------------------------------------------------------
Provided information
-----------------------------------------------------------------------------*/
static const tag_type alignment = 1 << tag_bits;
static const tag_type tag_mask = alignment - 1;
/*the real range is the smaller of the range of intptr_t
shifted down by tag bits, or the range of the `int' type
*/
static const intptr_t smallint_min =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MIN >> tag_bits :
/*otherwise*/
INT_MIN;
static const intptr_t smallint_max =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MAX >> tag_bits :
/*otherwise*/
INT_MAX;
/*value for "t"*/
static const intptr_t t_value = ~((intptr_t) tag_mask);
/*-----------------------------------------------------------------------------
The tagged pointer type
-----------------------------------------------------------------------------*/
/*stefano prefers to use:
typedef void* ref;
or maybe:
typedef intptr_t ref;
I may change this later on, but for now
I want to see whether the conceptual
separation will help and if compilers,
in general, will be smart enough to
optimize away the structure.
*/
class ref {
private:
intptr_t dat;
ref(intptr_t x) : dat(x) {}
public:
ref(void) : dat(0) {}
inline bool operator==(ref b) {
return dat == b.dat;
}
inline bool operator!=(ref b) {
return dat != b.dat;
}
inline bool operator!(void) {
return dat == 0;
}
/*safe bool idiom*/
typedef intptr_t (*ref::unspecified_bool_type);
inline operator unspecified_bool_type(void) {
return dat != 0 ? &ref::dat : 0;
}
template<typename T> friend ref to_ref(T);
template<typename T> friend bool _is_a(ref);
template<typename T> friend T _as_a(ref);
friend int to_a_scaled_int(ref);
friend ref from_a_scaled_int(int);
friend ref t(void);
friend bool _is_t(ref);
};
/*-----------------------------------------------------------------------------
Tagged pointer factories
-----------------------------------------------------------------------------*/
template<typename T>
static inline ref to_ref(T x) {
/* default to Generic* */
return to_ref<Generic*>(x);
}
template<>
static inline ref to_ref<Generic*>(Generic* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Generic*>::tag);
}
template<>
static inline ref to_ref<Symbol*>(Symbol* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Symbol*>::tag);
}
template<>
static inline ref to_ref<int>(int x) {
#ifdef DEBUG
#if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN)
if(x < smallint_min || x > smallint_max) {
throw_RangeError(
"int out of range of smallint"
);
}
#endif
#endif
intptr_t tmp = (((intptr_t) x) << tag_bits);
return ref(tmp + tag_traits<int>::tag);
}
template<>
static inline ref to_ref<UnicodeChar>(UnicodeChar x) {
intptr_t tmp = x.dat << tag_bits;
return ref(tmp + tag_traits<UnicodeChar>::tag);
}
/*no checking, even in debug mode... achtung!*/
static inline ref from_a_scaled_int(int x) {
return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag);
}
static inline ref nil(void) {
return ref();
}
static inline ref t(void) {
return ref(t_value);
}
/*-----------------------------------------------------------------------------
Tagged pointer checking
-----------------------------------------------------------------------------*/
static inline bool _is_nil(ref obj) {
return !obj;
}
static inline bool _is_t(ref obj) {
return obj.dat == t_value;
}
template<typename T>
static inline bool _is_a(ref obj) {
if(tag_traits<T>::tag != 0x0) {
return (obj.dat & tag_mask) == tag_traits<T>::tag;
} else {
return (obj.dat & tag_mask) == tag_traits<T>::tag
&& !_is_nil(obj) && !_is_t(obj);
}
}
/*-----------------------------------------------------------------------------
Tagged pointer referencing
-----------------------------------------------------------------------------*/
template<typename T>
static inline T _as_a(ref obj) {
#ifdef DEBUG
if(!_is_a<T>(obj)) {
throw_TypeError(obj,
"incorrect type for pointer"
);
}
#endif
intptr_t tmp = obj.dat;
return reinterpret_cast<T>(tmp - tag_traits<T>::tag);
/*use subtraction instead of masking, in order to
allow smart compilers to merge a field access with
the tag removal. i.e. the pointers are pointers to
structures, so they will be accessed via fields, and
in all probability those fields will be at some
offset from the actual structure address, meaning
that the processor itself will perform an addition
to access the field. The smart compiler can then
merge the addition of the field offset with the
subtraction of the tag.
*/
}
template<>
static inline int _as_a<int>(ref obj) {
#ifdef DEBUG
if(!_is_a<int>(obj)) {
throw_TypeError(obj,
"incorrect type for small integer"
);
}
#endif
intptr_t tmp = obj.dat;
return (int)(tmp >> tag_bits);
}
template<>
static inline UnicodeChar _as_a<UnicodeChar>(ref obj) {
uint32_t tmp = obj.dat;
return UnicodeChar(tmp >> tag_bits);
}
/*no checking, even in debug mode... achtung!*/
static inline int to_a_scaled_int(ref obj) {
intptr_t tmp = obj.dat;
return (int)((tmp - tag_traits<int>::tag)>>tag_bits);
/*use subtraction instead of masking, again to
allow smart compilers to merge tag adding and
subtracting. For example the typical case would
be something like:
Object::ref result =
Object::from_a_scaled_int(
Object::to_a_scaled_int(a) +
Object::to_a_scaled_int(b)
);
The above case can be reduced by the compiler to:
intptr_t result =
(tag_traits<int>::tag +
a - tag_traits<int>::tag +
b - tag_traits<int>::tag
);
It can then do some maths and cancel out a tag:
intptr_t result = a + b - tag_traits<int>::tag;
*/
}
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
static inline size_t round_up_to_alignment(size_t x) {
return
(x & tag_mask) ? (x + alignment - (x & tag_mask)) :
/*otherwise*/ x ;
}
}
/*-----------------------------------------------------------------------------
Reflectors outside of the namespace
-----------------------------------------------------------------------------*/
template<typename T>
static inline bool is_a(Object::ref obj) {
return Object::_is_a<T>(obj);
}
template<typename T>
static inline T as_a(Object::ref obj) {
return Object::_as_a<T>(obj);
}
static inline bool is_nil(Object::ref obj) {
return Object::_is_nil(obj);
}
static inline bool is_t(Object::ref obj) {
return Object::_is_t(obj);
}
#endif //OBJECTS_H
<commit_msg>inc/objects.hpp: Corrected safe bool idiom<commit_after>#ifndef OBJECTS_H
#define OBJECTS_H
/*
Defines an Object::ref type, which is a tagged pointer type.
Usage:
Object::ref x = Object::to_ref(1);//smallint
Object::ref y = Object::to_ref(new(hp) Generic()); //object
if(is_a<int>(x)) {
std::cout << "x = " << as_a<int>(x) << std::endl;
}
if(is_a<Generic*>(y)) {
std::cout << "y.field = " << as_a<Generic*>(y)->field
<< std::endl;
}
*/
#include<stdint.h>
#include<climits>
#include"unichars.hpp"
#ifdef MY_COMPILER
// without these my compiler signals an error -- stefano
// I suggest you try it now with all_defines.hpp
// included in all source files -- almkglor
#define INTPTR_MIN (-2147483647-1)
#define INTPTR_MAX (2147483647)
#endif // MY_COMPILER
class Generic;
class Symbol;
class Cons;
class Closure;
class KClosure;
namespace Object {
/*-----------------------------------------------------------------------------
Declare
-----------------------------------------------------------------------------*/
class ref;
template<typename T> struct tag_traits;
/*assume we won't ever need more than 7 bits of tag*/
typedef unsigned char tag_type;
template<typename T> static inline ref to_ref(T);
template<typename T> static inline bool _is_a(ref);
template<typename T> static inline T _as_a(ref);
static inline ref t(void);
static inline bool _is_t(ref);
static inline ref nil(void);
static inline bool _is_nil(ref);
static inline ref from_a_scaled_int(int);
static inline int to_a_scaled_int(ref);
}
void throw_TypeError(Object::ref, char const*);
void throw_RangeError(char const*);
template<typename T> static inline bool is_a(Object::ref);
template<typename T> static inline T as_a(Object::ref);
static inline bool is_t(Object::ref);
namespace Object {
/*-----------------------------------------------------------------------------
Configuration
-----------------------------------------------------------------------------*/
static const unsigned char tag_bits = 2;// can bump up to 3 maybe...
template<> struct tag_traits<int> {
static const tag_type tag = 0x1;
};
template<> struct tag_traits<Generic*> {
static const tag_type tag = 0x0;
};
template<> struct tag_traits<Symbol*> {
static const tag_type tag = 0x2;
};
template<> struct tag_traits<UnicodeChar> {
static const tag_type tag = 0x3;
};
/*-----------------------------------------------------------------------------
Provided information
-----------------------------------------------------------------------------*/
static const tag_type alignment = 1 << tag_bits;
static const tag_type tag_mask = alignment - 1;
/*the real range is the smaller of the range of intptr_t
shifted down by tag bits, or the range of the `int' type
*/
static const intptr_t smallint_min =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MIN >> tag_bits :
/*otherwise*/
INT_MIN;
static const intptr_t smallint_max =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MAX >> tag_bits :
/*otherwise*/
INT_MAX;
/*value for "t"*/
static const intptr_t t_value = ~((intptr_t) tag_mask);
/*-----------------------------------------------------------------------------
The tagged pointer type
-----------------------------------------------------------------------------*/
/*stefano prefers to use:
typedef void* ref;
or maybe:
typedef intptr_t ref;
I may change this later on, but for now
I want to see whether the conceptual
separation will help and if compilers,
in general, will be smart enough to
optimize away the structure.
*/
class ref {
private:
intptr_t dat;
ref(intptr_t x) : dat(x) {}
public:
ref(void) : dat(0) {}
inline bool operator==(ref b) {
return dat == b.dat;
}
inline bool operator!=(ref b) {
return dat != b.dat;
}
inline bool operator!(void) {
return dat == 0;
}
/*safe bool idiom*/
typedef intptr_t (ref::*unspecified_bool_type);
inline operator unspecified_bool_type(void) {
return dat != 0 ? &ref::dat : 0;
}
template<typename T> friend ref to_ref(T);
template<typename T> friend bool _is_a(ref);
template<typename T> friend T _as_a(ref);
friend int to_a_scaled_int(ref);
friend ref from_a_scaled_int(int);
friend ref t(void);
friend bool _is_t(ref);
};
/*-----------------------------------------------------------------------------
Tagged pointer factories
-----------------------------------------------------------------------------*/
template<typename T>
static inline ref to_ref(T x) {
/* default to Generic* */
return to_ref<Generic*>(x);
}
template<>
static inline ref to_ref<Generic*>(Generic* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Generic*>::tag);
}
template<>
static inline ref to_ref<Symbol*>(Symbol* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Symbol*>::tag);
}
template<>
static inline ref to_ref<int>(int x) {
#ifdef DEBUG
#if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN)
if(x < smallint_min || x > smallint_max) {
throw_RangeError(
"int out of range of smallint"
);
}
#endif
#endif
intptr_t tmp = (((intptr_t) x) << tag_bits);
return ref(tmp + tag_traits<int>::tag);
}
template<>
static inline ref to_ref<UnicodeChar>(UnicodeChar x) {
intptr_t tmp = x.dat << tag_bits;
return ref(tmp + tag_traits<UnicodeChar>::tag);
}
/*no checking, even in debug mode... achtung!*/
static inline ref from_a_scaled_int(int x) {
return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag);
}
static inline ref nil(void) {
return ref();
}
static inline ref t(void) {
return ref(t_value);
}
/*-----------------------------------------------------------------------------
Tagged pointer checking
-----------------------------------------------------------------------------*/
static inline bool _is_nil(ref obj) {
return !obj;
}
static inline bool _is_t(ref obj) {
return obj.dat == t_value;
}
template<typename T>
static inline bool _is_a(ref obj) {
if(tag_traits<T>::tag != 0x0) {
return (obj.dat & tag_mask) == tag_traits<T>::tag;
} else {
return (obj.dat & tag_mask) == tag_traits<T>::tag
&& !_is_nil(obj) && !_is_t(obj);
}
}
/*-----------------------------------------------------------------------------
Tagged pointer referencing
-----------------------------------------------------------------------------*/
template<typename T>
static inline T _as_a(ref obj) {
#ifdef DEBUG
if(!_is_a<T>(obj)) {
throw_TypeError(obj,
"incorrect type for pointer"
);
}
#endif
intptr_t tmp = obj.dat;
return reinterpret_cast<T>(tmp - tag_traits<T>::tag);
/*use subtraction instead of masking, in order to
allow smart compilers to merge a field access with
the tag removal. i.e. the pointers are pointers to
structures, so they will be accessed via fields, and
in all probability those fields will be at some
offset from the actual structure address, meaning
that the processor itself will perform an addition
to access the field. The smart compiler can then
merge the addition of the field offset with the
subtraction of the tag.
*/
}
template<>
static inline int _as_a<int>(ref obj) {
#ifdef DEBUG
if(!_is_a<int>(obj)) {
throw_TypeError(obj,
"incorrect type for small integer"
);
}
#endif
intptr_t tmp = obj.dat;
return (int)(tmp >> tag_bits);
}
template<>
static inline UnicodeChar _as_a<UnicodeChar>(ref obj) {
uint32_t tmp = obj.dat;
return UnicodeChar(tmp >> tag_bits);
}
/*no checking, even in debug mode... achtung!*/
static inline int to_a_scaled_int(ref obj) {
intptr_t tmp = obj.dat;
return (int)((tmp - tag_traits<int>::tag)>>tag_bits);
/*use subtraction instead of masking, again to
allow smart compilers to merge tag adding and
subtracting. For example the typical case would
be something like:
Object::ref result =
Object::from_a_scaled_int(
Object::to_a_scaled_int(a) +
Object::to_a_scaled_int(b)
);
The above case can be reduced by the compiler to:
intptr_t result =
(tag_traits<int>::tag +
a - tag_traits<int>::tag +
b - tag_traits<int>::tag
);
It can then do some maths and cancel out a tag:
intptr_t result = a + b - tag_traits<int>::tag;
*/
}
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
static inline size_t round_up_to_alignment(size_t x) {
return
(x & tag_mask) ? (x + alignment - (x & tag_mask)) :
/*otherwise*/ x ;
}
}
/*-----------------------------------------------------------------------------
Reflectors outside of the namespace
-----------------------------------------------------------------------------*/
template<typename T>
static inline bool is_a(Object::ref obj) {
return Object::_is_a<T>(obj);
}
template<typename T>
static inline T as_a(Object::ref obj) {
return Object::_as_a<T>(obj);
}
static inline bool is_nil(Object::ref obj) {
return Object::_is_nil(obj);
}
static inline bool is_t(Object::ref obj) {
return Object::_is_t(obj);
}
#endif //OBJECTS_H
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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 "jingle/notifier/listener/push_notifications_thread.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "jingle/notifier/listener/notification_defines.h"
#include "talk/xmpp/xmppclient.h"
namespace notifier {
PushNotificationsThread::PushNotificationsThread(
const NotifierOptions& notifier_options, const std::string& from)
: MediatorThreadImpl(notifier_options), from_(from) {
}
PushNotificationsThread::~PushNotificationsThread() {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
}
void PushNotificationsThread::ListenForUpdates() {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
worker_message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&PushNotificationsThread::ListenForPushNotifications));
}
void PushNotificationsThread::SubscribeForUpdates(
const std::vector<std::string>& subscribed_services_list) {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
worker_message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&PushNotificationsThread::SubscribeForPushNotifications,
subscribed_services_list));
}
void PushNotificationsThread::SendNotification(
const OutgoingNotificationData& data) {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
}
void PushNotificationsThread::ListenForPushNotifications() {
DCHECK_EQ(MessageLoop::current(), worker_message_loop());
PushNotificationsListenTask* listener =
new PushNotificationsListenTask(base_task_, this);
listener->Start();
}
void PushNotificationsThread::SubscribeForPushNotifications(
const std::vector<std::string>& subscribed_services_list) {
std::vector<PushNotificationsSubscribeTask::PushSubscriptionInfo>
channels_list;
for (std::vector<std::string>::const_iterator iter =
subscribed_services_list.begin();
iter != subscribed_services_list.end(); iter++) {
PushNotificationsSubscribeTask::PushSubscriptionInfo subscription;
subscription.channel = *iter;
subscription.from = from_;
channels_list.push_back(subscription);
}
DCHECK_EQ(MessageLoop::current(), worker_message_loop());
PushNotificationsSubscribeTask* subscription =
new PushNotificationsSubscribeTask(base_task_, channels_list, this);
subscription->Start();
}
void PushNotificationsThread::OnSubscribed() {
OnSubscriptionStateChange(true);
}
void PushNotificationsThread::OnSubscriptionError() {
OnSubscriptionStateChange(false);
}
void PushNotificationsThread::OnNotificationReceived(
const IncomingNotificationData& notification) {
OnIncomingNotification(notification);
}
} // namespace notifier
<commit_msg>Fixed crash during the xmpp reconnection for cloud printing.<commit_after>// Copyright (c) 2010 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 "jingle/notifier/listener/push_notifications_thread.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "jingle/notifier/listener/notification_defines.h"
#include "talk/xmpp/xmppclient.h"
namespace notifier {
PushNotificationsThread::PushNotificationsThread(
const NotifierOptions& notifier_options, const std::string& from)
: MediatorThreadImpl(notifier_options), from_(from) {
}
PushNotificationsThread::~PushNotificationsThread() {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
}
void PushNotificationsThread::ListenForUpdates() {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
worker_message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&PushNotificationsThread::ListenForPushNotifications));
}
void PushNotificationsThread::SubscribeForUpdates(
const std::vector<std::string>& subscribed_services_list) {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
worker_message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&PushNotificationsThread::SubscribeForPushNotifications,
subscribed_services_list));
}
void PushNotificationsThread::SendNotification(
const OutgoingNotificationData& data) {
DCHECK_EQ(MessageLoop::current(), parent_message_loop_);
}
void PushNotificationsThread::ListenForPushNotifications() {
DCHECK_EQ(MessageLoop::current(), worker_message_loop());
if (!base_task_.get())
return;
PushNotificationsListenTask* listener =
new PushNotificationsListenTask(base_task_, this);
listener->Start();
}
void PushNotificationsThread::SubscribeForPushNotifications(
const std::vector<std::string>& subscribed_services_list) {
DCHECK_EQ(MessageLoop::current(), worker_message_loop());
if (!base_task_.get())
return;
std::vector<PushNotificationsSubscribeTask::PushSubscriptionInfo>
channels_list;
for (std::vector<std::string>::const_iterator iter =
subscribed_services_list.begin();
iter != subscribed_services_list.end(); iter++) {
PushNotificationsSubscribeTask::PushSubscriptionInfo subscription;
subscription.channel = *iter;
subscription.from = from_;
channels_list.push_back(subscription);
}
DCHECK_EQ(MessageLoop::current(), worker_message_loop());
PushNotificationsSubscribeTask* subscription =
new PushNotificationsSubscribeTask(base_task_, channels_list, this);
subscription->Start();
}
void PushNotificationsThread::OnSubscribed() {
OnSubscriptionStateChange(true);
}
void PushNotificationsThread::OnSubscriptionError() {
OnSubscriptionStateChange(false);
}
void PushNotificationsThread::OnNotificationReceived(
const IncomingNotificationData& notification) {
OnIncomingNotification(notification);
}
} // namespace notifier
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "spline.h"
#include "asdf_multiplat/data/gl_vertex_spec.h"
namespace asdf {
using namespace vertex_attrib;
namespace hexmap {
namespace data
{
/* --Save Format--
write the number of nodes (64-bit unsigned integer)
write the nodes
write the number of control nodes (64-bit unsigned integer)
write the control nodes
*/
void spline_t::save_to_file(SDL_RWops* io) const
{
ASSERT(io, "");
{
LOG("offset when writing spline node count: %zu", SDL_RWtell(io));
uint64_t sz = nodes.size();
SDL_RWwrite(io, reinterpret_cast<const void*>(&sz), sizeof(uint64_t), 1);
LOG("wrote node count (%zu bytes)", sizeof(uint64_t));
LOG("offset after writing spline node count: %zu", SDL_RWtell(io));
size_t n = SDL_RWwrite(io, nodes.data(), sizeof(line_node_t), nodes.size());
ASSERT(n == nodes.size(), "error writing spline_t::nodes");
LOG("wrote %zu spline nodes (%zu bytes)", n, n * sizeof(line_node_t));
}
{
uint64_t sz = control_nodes.size();
SDL_RWwrite(io, reinterpret_cast<const void*>(&sz), sizeof(uint64_t), 1);
LOG("wrote control_node count (%zu bytes)", sizeof(uint64_t));
size_t n = SDL_RWwrite(io, control_nodes.data(), sizeof(control_node_t), control_nodes.size());
ASSERT(n == control_nodes.size(), "error writing spline_t::control_nodes");
LOG("wrote %zu control_nodes nodes (%zu bytes)", n, n * sizeof(control_node_t));
}
size_t sz = SDL_RWwrite(io, reinterpret_cast<const void*>(&spline_type), sizeof(interpolation_e), 1);
ASSERT(sz == 1, "");
}
void spline_t::load_from_file(SDL_RWops* io)
{
ASSERT(io, "");
{
{
LOG("offset when loading spline node count: %zu", SDL_RWtell(io));
uint64_t sz = 0;
size_t n = SDL_RWread(io, reinterpret_cast<void*>(&sz), sizeof(uint64_t), 1);
ASSERT(n == 1, "Error writing spline node count");
LOG("offset after loading spline node count: %zu", SDL_RWtell(io));
nodes.resize(sz);
n = SDL_RWread(io, nodes.data(), sizeof(line_node_t), sz);
ASSERT(n == sz, "Error loading spline nodes");
}
{
uint64_t sz = 0;
SDL_RWread(io, reinterpret_cast<void*>(&sz), sizeof(uint64_t), 1);
control_nodes.resize(sz);
size_t n = SDL_RWread(io, control_nodes.data(), sizeof(line_node_t), sz);
ASSERT(n == sz, "Error loading spline control nodes");
}
size_t n = SDL_RWread(io, reinterpret_cast<void*>(&spline_type), sizeof(interpolation_e), 1);
ASSERT(n == 1, "Error reading spline interpolation type");
}
}
bool point_intersects_spline(glm::vec2 const& world_pos, spline_t const& spline, float dist_threshold)
{
if(spline.nodes.size() == 0)
{
return false;
}
else if(spline.nodes.size() == 1)
{
auto dist = glm::length(spline.nodes[0].position - world_pos);
return dist <= dist_threshold;
}
else
{
//get two closest point
spline_node_index_t closest = 0;
auto cv = spline.nodes[0].position - world_pos;
auto closest_dist_sq = (cv.x*cv.x)+(cv.y+cv.y);
for(size_t i = 0; i < spline.nodes.size(); ++i)
{
auto v = spline.nodes[i].position - world_pos;
auto dsq = (v.x*v.x)+(v.y+v.y);
if(dsq < closest_dist_sq)
{
closest = i;
closest_dist_sq = dsq;
}
}
auto n1 = spline.nodes[closest].position;
//TODO: get prev or next node, whichever is closest (and exists)
switch(spline.spline_type)
{
case spline_t::linear:
//return circle_intersects_line(world_pos, dist_threshold, n1, n2);
case spline_t::bezier:
{
//auto c1 = spline.control_nodes[2*inds[0]+0].position;
//auto c2 = spline.control_nodes[2*inds[0]+1].position;
//return circle_intersects_bezier(world_pos, dist_threshold
// n1.position, c1, c2, n2.position);
}
default: EXPLODE("TODO: implement intersection with %s splines", spline_interpolation_names[spline.spline_type]);
break;
}
}
}
bool circle_intersects_line(glm::vec2 const& circle_pos, float radius, glm::vec2 const& p0, glm::vec2 const& p1)
{
return false;
}
bool circle_intersects_bezier(glm::vec2 circle_pos, float radius, glm::vec2 p0, glm::vec2 p1, glm::vec2 p2, glm::vec2 p3)
{
EXPLODE("todo");
return false;
}
void spline_selection_t::select_spline(spline_t& spline)
{
std::vector<size_t> new_inds;
new_inds.reserve(spline.size());
for(size_t i = 0; i < spline.size(); ++i)
{
new_inds.push_back(i);
}
select_spline_nodes(spline, std::move(new_inds));
}
void spline_selection_t::select_spline_nodes(spline_t& spline, std::vector<size_t> node_inds)
{
if(is_control_node)
{
deselect_all();
is_control_node = false;
}
splines.push_back(&spline);
node_indices.push_back(std::move(node_inds));
}
void spline_selection_t::select_control_node(spline_t& spline, size_t control_node_index)
{
deselect_all();
is_control_node = true;
splines.push_back(&spline);
node_indices.resize(1);
node_indices[0].push_back(control_node_index);
}
void spline_selection_t::deselect_all()
{
splines.clear();
node_indices.clear();
}
}
}
}
<commit_msg>implemented code to get the second closest spline node for testing intersections (still a WIP)<commit_after>#include "stdafx.h"
#include "spline.h"
#include <glm/gtx/norm.hpp>
#include "asdf_multiplat/data/gl_vertex_spec.h"
namespace asdf {
using namespace vertex_attrib;
namespace hexmap {
namespace data
{
/* --Save Format--
write the number of nodes (64-bit unsigned integer)
write the nodes
write the number of control nodes (64-bit unsigned integer)
write the control nodes
*/
void spline_t::save_to_file(SDL_RWops* io) const
{
ASSERT(io, "");
{
LOG("offset when writing spline node count: %zu", SDL_RWtell(io));
uint64_t sz = nodes.size();
SDL_RWwrite(io, reinterpret_cast<const void*>(&sz), sizeof(uint64_t), 1);
LOG("wrote node count (%zu bytes)", sizeof(uint64_t));
LOG("offset after writing spline node count: %zu", SDL_RWtell(io));
size_t n = SDL_RWwrite(io, nodes.data(), sizeof(line_node_t), nodes.size());
ASSERT(n == nodes.size(), "error writing spline_t::nodes");
LOG("wrote %zu spline nodes (%zu bytes)", n, n * sizeof(line_node_t));
}
{
uint64_t sz = control_nodes.size();
SDL_RWwrite(io, reinterpret_cast<const void*>(&sz), sizeof(uint64_t), 1);
LOG("wrote control_node count (%zu bytes)", sizeof(uint64_t));
size_t n = SDL_RWwrite(io, control_nodes.data(), sizeof(control_node_t), control_nodes.size());
ASSERT(n == control_nodes.size(), "error writing spline_t::control_nodes");
LOG("wrote %zu control_nodes nodes (%zu bytes)", n, n * sizeof(control_node_t));
}
size_t sz = SDL_RWwrite(io, reinterpret_cast<const void*>(&spline_type), sizeof(interpolation_e), 1);
ASSERT(sz == 1, "");
}
void spline_t::load_from_file(SDL_RWops* io)
{
ASSERT(io, "");
{
{
LOG("offset when loading spline node count: %zu", SDL_RWtell(io));
uint64_t sz = 0;
size_t n = SDL_RWread(io, reinterpret_cast<void*>(&sz), sizeof(uint64_t), 1);
ASSERT(n == 1, "Error writing spline node count");
LOG("offset after loading spline node count: %zu", SDL_RWtell(io));
nodes.resize(sz);
n = SDL_RWread(io, nodes.data(), sizeof(line_node_t), sz);
ASSERT(n == sz, "Error loading spline nodes");
}
{
uint64_t sz = 0;
SDL_RWread(io, reinterpret_cast<void*>(&sz), sizeof(uint64_t), 1);
control_nodes.resize(sz);
size_t n = SDL_RWread(io, control_nodes.data(), sizeof(line_node_t), sz);
ASSERT(n == sz, "Error loading spline control nodes");
}
size_t n = SDL_RWread(io, reinterpret_cast<void*>(&spline_type), sizeof(interpolation_e), 1);
ASSERT(n == 1, "Error reading spline interpolation type");
}
}
bool point_intersects_spline(glm::vec2 const& world_pos, spline_t const& spline, float dist_threshold)
{
if(spline.nodes.size() == 0)
{
return false;
}
else if(spline.nodes.size() == 1)
{
auto dist = glm::length(spline.nodes[0].position - world_pos);
return dist <= dist_threshold;
}
else
{
//get closest point to world_pos
spline_node_index_t closest = 0;
auto cv = spline.nodes[0].position - world_pos;
auto closest_dist_sq = glm::length2(cv);
for(size_t i = 1; i < spline.nodes.size(); ++i)
{
auto v = spline.nodes[i].position - world_pos;
auto dsq = glm::length2(v);
if(dsq < closest_dist_sq)
{
closest = i;
closest_dist_sq = dsq;
}
}
auto const& p0 = spline.nodes[closest].position;
// get prev or next node, whichever is closest to world_pos (and exists)
line_node_t const* prev = nullptr;
line_node_t const* next = nullptr;
if(spline.loops)
{
prev = (closest == 0) ? &(*spline.nodes.end()) : &(spline.nodes[closest-1]);
next = (closest+1 == spline.nodes.size()) ? &(spline.nodes[0]) : &(spline.nodes[closest+1]);
}
else
{
prev = (closest==0) ? nullptr : &(spline.nodes[closest-1]);
next = (closest+1 == spline.nodes.size()) ? nullptr : &(spline.nodes[closest+1]);
}
ASSERT(next || prev, "somehow both next and prev are null");
//if prev is null, use next, else use prev
auto* second_closest = (prev != nullptr) ? prev : next;
//if both are not-null, grab the closest one
if(prev && next)
{
auto d_prev = glm::length2(prev->position - p0);
auto d_next = glm::length2(next->position - p0);
second_closest = (d_prev > d_next) ? next : prev;
}
auto p1 = second_closest->position;
switch(spline.spline_type)
{
case spline_t::linear:
return circle_intersects_line(world_pos, dist_threshold, p0, p1);
// case spline_t::bezier:
{
//auto c1 = spline.control_nodes[2*inds[0]+0].position;
//auto c2 = spline.control_nodes[2*inds[0]+1].position;
//return circle_intersects_bezier(world_pos, dist_threshold
// n1.position, c1, c2, n2.position);
}
default: EXPLODE("TODO: implement intersection with %s splines", spline_interpolation_names[spline.spline_type]);
return false;
}
}
}
bool circle_intersects_line(glm::vec2 const& circle_pos, float radius, glm::vec2 const& p0, glm::vec2 const& p1)
{
return false;
}
bool circle_intersects_bezier(glm::vec2 circle_pos, float radius, glm::vec2 p0, glm::vec2 p1, glm::vec2 p2, glm::vec2 p3)
{
EXPLODE("todo");
return false;
}
void spline_selection_t::select_spline(spline_t& spline)
{
std::vector<size_t> new_inds;
new_inds.reserve(spline.size());
for(size_t i = 0; i < spline.size(); ++i)
{
new_inds.push_back(i);
}
select_spline_nodes(spline, std::move(new_inds));
}
void spline_selection_t::select_spline_nodes(spline_t& spline, std::vector<size_t> node_inds)
{
if(is_control_node)
{
deselect_all();
is_control_node = false;
}
splines.push_back(&spline);
node_indices.push_back(std::move(node_inds));
}
void spline_selection_t::select_control_node(spline_t& spline, size_t control_node_index)
{
deselect_all();
is_control_node = true;
splines.push_back(&spline);
node_indices.resize(1);
node_indices[0].push_back(control_node_index);
}
void spline_selection_t::deselect_all()
{
splines.clear();
node_indices.clear();
}
}
}
}
<|endoftext|>
|
<commit_before>/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#ifndef SAPI_HAL_HPP_
#define SAPI_HAL_HPP_
/*! \brief Hardware Abstraction Layer
* \details The hal namespace includes classes for accessing
* mcu peripheral hardware and other devices.
*
* All objects in the hal namespace inherit either:
*
* - api::HalWorkObject
* - api::InfoObject
*
* Work objects inherit fs::File and allow access to the hardware
* using a POSIX style API (open(), close(), read(), write() and ioctl()).
*
* Info objects contain attributes that facilitate configuring and
* querying hardware.
*
*
*
*/
namespace hal {}
#include "hal/Dev.hpp"
#include "hal/Device.hpp"
#include "hal/DeviceSignal.hpp"
#include "hal/Adc.hpp"
#include "hal/Dac.hpp"
#include "hal/Drive.hpp"
#include "hal/Core.hpp"
#include "hal/Eint.hpp"
#include "hal/Fifo.hpp"
#include "hal/FFifo.hpp"
#include "hal/CFifo.hpp"
#include "hal/Led.hpp"
#include "hal/I2C.hpp"
#include "hal/I2S.hpp"
#include "hal/PinAssignment.hpp"
#include "hal/StreamFFifo.hpp"
#include "hal/Pin.hpp"
#include "hal/Pwm.hpp"
#include "hal/Rtc.hpp"
#include "hal/Tmr.hpp"
#include "hal/Switchboard.hpp"
#include "hal/Spi.hpp"
#include "hal/Uart.hpp"
#include "hal/Usb.hpp"
#if !defined __link
#include "hal/Display.hpp"
#include "hal/DisplayDevice.hpp"
#include "hal/DeviceSignal.hpp"
#endif
using namespace hal;
#endif /* SAPI_HAL_HPP_ */
<commit_msg>Update hal.hpp<commit_after>/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#ifndef SAPI_HAL_HPP_
#define SAPI_HAL_HPP_
/*! \brief Hardware Abstraction Layer
* \details The hal namespace includes classes for accessing
* mcu peripheral hardware and other devices.
*
* All objects in the hal namespace inherit either:
*
* - api::HalWorkObject
* - api::InfoObject
*
* Work objects inherit fs::File and allow access to the hardware
* using a POSIX style API (open(), close(), read(), write() and ioctl()).
*
* Info objects contain attributes that facilitate configuring and
* querying hardware.
*
*
*
*/
namespace hal {}
#include "hal/Dev.hpp"
#include "hal/Device.hpp"
#include "hal/DeviceSignal.hpp"
#include "hal/Adc.hpp"
#include "hal/Dac.hpp"
#include "hal/Drive.hpp"
#include "hal/Core.hpp"
#include "hal/Eint.hpp"
#include "hal/Fifo.hpp"
#include "hal/FFifo.hpp"
#include "hal/CFifo.hpp"
#include "hal/Led.hpp"
#include "hal/I2C.hpp"
#include "hal/I2S.hpp"
#include "hal/PinAssignment.hpp"
#include "hal/StreamFfifo.hpp"
#include "hal/Pin.hpp"
#include "hal/Pwm.hpp"
#include "hal/Rtc.hpp"
#include "hal/Tmr.hpp"
#include "hal/Switchboard.hpp"
#include "hal/Spi.hpp"
#include "hal/Uart.hpp"
#include "hal/Usb.hpp"
#if !defined __link
#include "hal/Display.hpp"
#include "hal/DisplayDevice.hpp"
#include "hal/DeviceSignal.hpp"
#endif
using namespace hal;
#endif /* SAPI_HAL_HPP_ */
<|endoftext|>
|
<commit_before>#pragma once
#include<iostream>
void dummy()
{
std::cout << "HI" << std::endl;
}
<commit_msg>Task 1.7 tested if opencv libs added<commit_after>#pragma once
#include<iostream>
#include <opencv2/opencv.hpp>
void dummy()
{
std::cout << "HI" << std::endl;
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <cryptopp/dh.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "RouterContext.h"
#include "Timestamp.h"
#include "util.h"
#include "version.h"
namespace i2p
{
RouterContext context;
RouterContext::RouterContext ():
m_LastUpdateTime (0)
{
if (!Load ())
CreateNewRouter ();
UpdateRouterInfo ();
}
void RouterContext::CreateNewRouter ()
{
m_Keys = i2p::data::CreateRandomKeys ();
SaveKeys ();
NewRouterInfo ();
}
void RouterContext::NewRouterInfo ()
{
i2p::data::RouterInfo routerInfo;
routerInfo.SetRouterIdentity (GetIdentity ().GetStandardIdentity ());
int port = i2p::util::config::GetArg("-port", 0);
if (!port)
port = m_Rnd.GenerateWord32 (9111, 30777); // I2P network ports range
routerInfo.AddSSUAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port, routerInfo.GetIdentHash ());
routerInfo.AddNTCPAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port);
routerInfo.SetCaps (i2p::data::RouterInfo::eReachable); // LR
routerInfo.SetProperty ("coreVersion", I2P_VERSION);
routerInfo.SetProperty ("netId", "2");
routerInfo.SetProperty ("router.version", I2P_VERSION);
routerInfo.SetProperty ("start_uptime", "90m");
routerInfo.CreateBuffer (m_Keys);
m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ());
}
void RouterContext::UpdateRouterInfo ()
{
m_RouterInfo.CreateBuffer (m_Keys);
m_RouterInfo.SaveToFile (i2p::util::filesystem::GetFullPath (ROUTER_INFO));
m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch ();
}
void RouterContext::OverrideNTCPAddress (const char * host, int port)
{
m_RouterInfo.CreateBuffer (m_Keys);
auto address = const_cast<i2p::data::RouterInfo::Address *>(m_RouterInfo.GetNTCPAddress ());
if (address)
{
address->host = boost::asio::ip::address::from_string (host);
address->port = port;
}
UpdateRouterInfo ();
}
void RouterContext::UpdateAddress (const char * host)
{
bool updated = false;
auto newAddress = boost::asio::ip::address::from_string (host);
for (auto& address : m_RouterInfo.GetAddresses ())
{
if (address.host != newAddress)
{
address.host = newAddress;
updated = true;
}
}
auto ts = i2p::util::GetSecondsSinceEpoch ();
if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL)
UpdateRouterInfo ();
}
void RouterContext::AddIntroducer (const i2p::data::RouterInfo& routerInfo, uint32_t tag)
{
auto address = routerInfo.GetSSUAddress ();
if (address)
{
if (m_RouterInfo.AddIntroducer (address, tag))
UpdateRouterInfo ();
}
}
void RouterContext::RemoveIntroducer (uint32_t tag)
{
if (m_RouterInfo.RemoveIntroducer (tag))
UpdateRouterInfo ();
}
bool RouterContext::Load ()
{
std::ifstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ifstream::binary | std::ofstream::in);
if (!fk.is_open ()) return false;
i2p::data::Keys keys;
fk.read ((char *)&keys, sizeof (keys));
m_Keys = keys;
i2p::data::RouterInfo routerInfo(i2p::util::filesystem::GetFullPath (ROUTER_INFO)); // TODO
m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ());
m_RouterInfo.SetProperty ("coreVersion", I2P_VERSION);
m_RouterInfo.SetProperty ("router.version", I2P_VERSION);
return true;
}
void RouterContext::SaveKeys ()
{
std::ofstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ofstream::binary | std::ofstream::out);
i2p::data::Keys keys;
memcpy (keys.privateKey, m_Keys.GetPrivateKey (), sizeof (keys.privateKey));
memcpy (keys.signingPrivateKey, m_Keys.GetSigningPrivateKey (), sizeof (keys.signingPrivateKey));
auto& ident = GetIdentity ().GetStandardIdentity ();
memcpy (keys.publicKey, ident.publicKey, sizeof (keys.publicKey));
memcpy (keys.signingKey, ident.signingKey, sizeof (keys.signingKey));
fk.write ((char *)&keys, sizeof (keys));
}
}
<commit_msg>fixed typo<commit_after>#include <fstream>
#include <cryptopp/dh.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "RouterContext.h"
#include "Timestamp.h"
#include "util.h"
#include "version.h"
namespace i2p
{
RouterContext context;
RouterContext::RouterContext ():
m_LastUpdateTime (0)
{
if (!Load ())
CreateNewRouter ();
UpdateRouterInfo ();
}
void RouterContext::CreateNewRouter ()
{
m_Keys = i2p::data::CreateRandomKeys ();
SaveKeys ();
NewRouterInfo ();
}
void RouterContext::NewRouterInfo ()
{
i2p::data::RouterInfo routerInfo;
routerInfo.SetRouterIdentity (GetIdentity ().GetStandardIdentity ());
int port = i2p::util::config::GetArg("-port", 0);
if (!port)
port = m_Rnd.GenerateWord32 (9111, 30777); // I2P network ports range
routerInfo.AddSSUAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port, routerInfo.GetIdentHash ());
routerInfo.AddNTCPAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port);
routerInfo.SetCaps (i2p::data::RouterInfo::eReachable); // LR
routerInfo.SetProperty ("coreVersion", I2P_VERSION);
routerInfo.SetProperty ("netId", "2");
routerInfo.SetProperty ("router.version", I2P_VERSION);
routerInfo.SetProperty ("stat_uptime", "90m");
routerInfo.CreateBuffer (m_Keys);
m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ());
}
void RouterContext::UpdateRouterInfo ()
{
m_RouterInfo.CreateBuffer (m_Keys);
m_RouterInfo.SaveToFile (i2p::util::filesystem::GetFullPath (ROUTER_INFO));
m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch ();
}
void RouterContext::OverrideNTCPAddress (const char * host, int port)
{
m_RouterInfo.CreateBuffer (m_Keys);
auto address = const_cast<i2p::data::RouterInfo::Address *>(m_RouterInfo.GetNTCPAddress ());
if (address)
{
address->host = boost::asio::ip::address::from_string (host);
address->port = port;
}
UpdateRouterInfo ();
}
void RouterContext::UpdateAddress (const char * host)
{
bool updated = false;
auto newAddress = boost::asio::ip::address::from_string (host);
for (auto& address : m_RouterInfo.GetAddresses ())
{
if (address.host != newAddress)
{
address.host = newAddress;
updated = true;
}
}
auto ts = i2p::util::GetSecondsSinceEpoch ();
if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL)
UpdateRouterInfo ();
}
void RouterContext::AddIntroducer (const i2p::data::RouterInfo& routerInfo, uint32_t tag)
{
auto address = routerInfo.GetSSUAddress ();
if (address)
{
if (m_RouterInfo.AddIntroducer (address, tag))
UpdateRouterInfo ();
}
}
void RouterContext::RemoveIntroducer (uint32_t tag)
{
if (m_RouterInfo.RemoveIntroducer (tag))
UpdateRouterInfo ();
}
bool RouterContext::Load ()
{
std::ifstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ifstream::binary | std::ofstream::in);
if (!fk.is_open ()) return false;
i2p::data::Keys keys;
fk.read ((char *)&keys, sizeof (keys));
m_Keys = keys;
i2p::data::RouterInfo routerInfo(i2p::util::filesystem::GetFullPath (ROUTER_INFO)); // TODO
m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ());
m_RouterInfo.SetProperty ("coreVersion", I2P_VERSION);
m_RouterInfo.SetProperty ("router.version", I2P_VERSION);
return true;
}
void RouterContext::SaveKeys ()
{
std::ofstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ofstream::binary | std::ofstream::out);
i2p::data::Keys keys;
memcpy (keys.privateKey, m_Keys.GetPrivateKey (), sizeof (keys.privateKey));
memcpy (keys.signingPrivateKey, m_Keys.GetSigningPrivateKey (), sizeof (keys.signingPrivateKey));
auto& ident = GetIdentity ().GetStandardIdentity ();
memcpy (keys.publicKey, ident.publicKey, sizeof (keys.publicKey));
memcpy (keys.signingKey, ident.signingKey, sizeof (keys.signingKey));
fk.write ((char *)&keys, sizeof (keys));
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "FTSPI.h"
CFTSPI::CFTSPI() : bValid(FALSE)
{
bValid = Init();
}
CFTSPI::~CFTSPI()
{
for (int i = 0; i < SPIChannel.size(); i++) {
FT_STATUS status = FT_Close(SPIChannel[i].ftHandle);
}
}
BOOL CFTSPI::Init()
{
FT_STATUS status = FT_OK;
DWORD numDevices = 0;
status = FT_ListDevices(&numDevices, 0, FT_LIST_NUMBER_ONLY);
assert(status == FT_OK);
//printf("Number of available SPI channels = %d\n", (int)channels);
status = FT_CreateDeviceInfoList(&numDevices);
assert(status == FT_OK);
FT_DEVICE_LIST_INFO_NODE* devList = new FT_DEVICE_LIST_INFO_NODE[numDevices];
status = FT_GetDeviceInfoList(devList, &numDevices);
assert(status == FT_OK);
for (DWORD i = 0; i < numDevices; i++) {
if (strncmp(devList[i].Description, _T("FTSPI"), 5) == 0) {
sprintf_s(description, _countof(description), _T("%s(%s)"), devList[i].Description, devList[i].SerialNumber);
SPIINFO spiinfo;
spiinfo.index = i;
spiinfo.rptr = spiinfo.wptr = 0;
status = FT_Open(i, &spiinfo.ftHandle);
assert(status == FT_OK);
SPIChannel.push_back(spiinfo);
status = SPI_InitChannel(SPIChannel.size() - 1);
assert(status == FT_OK);
}
}
delete[] devList;
return (numDevices != 0);
}
FT_STATUS CFTSPI::SPI_InitChannel(UINT32 index)
{
FT_STATUS ret = FT_OTHER_ERROR;
if (index < SPIChannel.size()) {
//ret = FT_SetBaudRate(SPIChannel[index].ftHandle, 2000000L); //1Mbps
//if (ret != FT_OK) return ret;
ret = FT_Purge(SPIChannel[index].ftHandle, FT_PURGE_RX | FT_PURGE_TX);
if (ret != FT_OK) return ret;
::Sleep(10);
ret = FT_SetLatencyTimer(SPIChannel[index].ftHandle, 1); //1ms
if (ret != FT_OK) return ret;
ret = FT_SetBitMode(SPIChannel[index].ftHandle, 0x0, 0x00); //reset mode
if (ret != FT_OK) return ret;
::Sleep(10);
ret = FT_SetBitMode(SPIChannel[index].ftHandle, 0x00, 0x02); //MPSSE mode
if (ret != FT_OK) return ret;
ret = FT_Purge(SPIChannel[index].ftHandle, FT_PURGE_RX);
if (ret != FT_OK) return ret;
::Sleep(20);
SPI_Push(index, 0x80); //Set initial value of ADBUS
SPI_Push(index, 0xf8); //
SPI_Push(index, 0xfb); //
SPI_Push(index, 0x82); //Set initial value of ACBUS
SPI_Push(index, 0xff); //
SPI_Push(index, 0xff); //
SPI_Push(index, 0x8a); //disable initial devide
SPI_Push(index, 0x86); //CK devisor
SPI_Push(index, 0x02);
SPI_Push(index, 0x00);
SPI_Push(index, 0x85); //disable loopback
SPI_Push(index, 0x8d); //disable 3 phase clocking
ret = SPI_Flush(index);
::Sleep(100);
if (ret != FT_OK) return ret;
}
return ret;
}
void CFTSPI::SPI_Push(UINT32 index, BYTE data)
{
SPIChannel[index].cmdbuf[SPIChannel[index].wptr++] = data;
if (SPIChannel[index].wptr == (BUFSIZE-1)) { SPI_Flush(index); }
}
void CFTSPI::SPI_Push(UINT32 index, BYTE* data, UINT32 length)
{
if ((SPIChannel[index].wptr + length) >= (BUFSIZE-1)) { SPI_Flush(index); }
memcpy(&SPIChannel[index].cmdbuf[SPIChannel[index].wptr], data, length);
SPIChannel[index].wptr += length;
}
FT_STATUS CFTSPI::SPI_Read(UINT32 index, UINT8* buffer, UINT32 sizeToTransfer, UINT32 cs)
{
FT_STATUS ret = FT_OK;
return ret;
}
FT_STATUS CFTSPI::SPI_Write(UINT32 index, UINT8* buffer, UINT32 sizeToTransfer, UINT32 cs)
{
FT_STATUS ret = FT_OK;
UINT8 csmask = ~(1 << (cs + 3));
if (index < SPIChannel.size() && sizeToTransfer) {
UINT16 length = sizeToTransfer-1;
SPI_Push(index, 0x80); //assert CS
SPI_Push(index, 0xf8 & csmask); //
SPI_Push(index, 0xfb); //
SPI_Push(index, 0x11); //ve+ edge MSB first no read
SPI_Push(index, (BYTE*)(&length), 2); //length
SPI_Push(index, buffer, sizeToTransfer);
SPI_Push(index, 0x80); //dessert CS
SPI_Push(index, 0xf8); //
SPI_Push(index, 0xfb); //
SPI_Flush(index);
}
return ret;
}
UINT32 CFTSPI::GetChannelIndex(UINT32 index)
{
if (index < SPIChannel.size()) {
return SPIChannel[index].index;
}
return UINT32(-1);
}
FT_HANDLE CFTSPI::GetChannelHandle(UINT32 index)
{
if (index < SPIChannel.size() != NULL) {
return SPIChannel[index].ftHandle;
}
return FT_HANDLE(0);
}
FT_STATUS CFTSPI::FT_WriteGPIO(UINT32 index, UINT8 dir, UINT8 value)
{
FT_STATUS ret = FT_OK;
if (index < SPIChannel.size()) {
SPI_Push(index, 0x82); //Set high byte
SPI_Push(index, value); //
SPI_Push(index, dir); //
SPI_Flush(index);
}
return ret;
}
FT_STATUS CFTSPI::SPI_Flush(UINT32 index)
{
FT_STATUS ret = FT_OTHER_ERROR;
if (index < SPIChannel.size()) {
DWORD written = 0;
if (SPIChannel[index].wptr) {
//SPIChannel[index].cmdbuf[SPIChannel[index].wptr++] = 0x87; //force flush
ret = FT_Write(SPIChannel[index].ftHandle, SPIChannel[index].cmdbuf, SPIChannel[index].wptr, &written);
SPIChannel[index].wptr = 0;
//BYTE forceflush = 0x87;
//ret = FT_Write(SPIChannel[index].ftHandle, &forceflush, 1, &written);
}
else {
ret = FT_OK;
}
}
return ret;
}
void CFTSPI::SPI_Flush()
{
for (UINT32 i = 0; i < SPIChannel.size(); i++) {
FT_STATUS status = SPI_Flush(i);
assert(status == FT_OK);
}
}
void CFTSPI::InitialClear()
{
for (int index = 0; index < SPIChannel.size(); index++) {
SPI_Push(index, 0x82); //Set high byte
SPI_Push(index, 0x00); //assert IC
SPI_Push(index, 0xff); //dir
SPI_Flush(index);
::Sleep(10);
SPI_Push(index, 0x82); //Set high byte
SPI_Push(index, 0xff); //dessert IC
SPI_Push(index, 0xff); //dir
SPI_Flush(index);
}
}
void CFTSPI::GetInterfaceDesc(TCHAR* str, int len)
{
sprintf_s(str, len, _T("%s"), description);
}<commit_msg>chg: FT232H detection using 'chip type' instead of 'description'<commit_after>#include "stdafx.h"
#include "FTSPI.h"
CFTSPI::CFTSPI() : bValid(FALSE)
{
bValid = Init();
}
CFTSPI::~CFTSPI()
{
for (int i = 0; i < SPIChannel.size(); i++) {
FT_STATUS status = FT_Close(SPIChannel[i].ftHandle);
}
}
BOOL CFTSPI::Init()
{
FT_STATUS status = FT_OK;
DWORD numDevices = 0;
status = FT_ListDevices(&numDevices, 0, FT_LIST_NUMBER_ONLY);
assert(status == FT_OK);
//printf("Number of available SPI channels = %d\n", (int)channels);
status = FT_CreateDeviceInfoList(&numDevices);
assert(status == FT_OK);
FT_DEVICE_LIST_INFO_NODE* devList = new FT_DEVICE_LIST_INFO_NODE[numDevices];
status = FT_GetDeviceInfoList(devList, &numDevices);
assert(status == FT_OK);
for (DWORD i = 0; i < numDevices; i++) {
if (devList[i].Type == FT_DEVICE_232H) {
sprintf_s(description, _countof(description), _T("%s(%s)"), devList[i].Description, devList[i].SerialNumber);
SPIINFO spiinfo;
spiinfo.index = i;
spiinfo.rptr = spiinfo.wptr = 0;
status = FT_Open(i, &spiinfo.ftHandle);
assert(status == FT_OK);
SPIChannel.push_back(spiinfo);
status = SPI_InitChannel(SPIChannel.size() - 1);
assert(status == FT_OK);
}
}
delete[] devList;
return (numDevices != 0);
}
FT_STATUS CFTSPI::SPI_InitChannel(UINT32 index)
{
FT_STATUS ret = FT_OTHER_ERROR;
if (index < SPIChannel.size()) {
//ret = FT_SetBaudRate(SPIChannel[index].ftHandle, 2000000L); //1Mbps
//if (ret != FT_OK) return ret;
ret = FT_Purge(SPIChannel[index].ftHandle, FT_PURGE_RX | FT_PURGE_TX);
if (ret != FT_OK) return ret;
::Sleep(10);
ret = FT_SetLatencyTimer(SPIChannel[index].ftHandle, 1); //1ms
if (ret != FT_OK) return ret;
ret = FT_SetBitMode(SPIChannel[index].ftHandle, 0x0, 0x00); //reset mode
if (ret != FT_OK) return ret;
::Sleep(10);
ret = FT_SetBitMode(SPIChannel[index].ftHandle, 0x00, 0x02); //MPSSE mode
if (ret != FT_OK) return ret;
ret = FT_Purge(SPIChannel[index].ftHandle, FT_PURGE_RX);
if (ret != FT_OK) return ret;
::Sleep(20);
SPI_Push(index, 0x80); //Set initial value of ADBUS
SPI_Push(index, 0xf8); //
SPI_Push(index, 0xfb); //
SPI_Push(index, 0x82); //Set initial value of ACBUS
SPI_Push(index, 0xff); //
SPI_Push(index, 0xff); //
SPI_Push(index, 0x8a); //disable initial devide
SPI_Push(index, 0x86); //CK devisor
SPI_Push(index, 0x02);
SPI_Push(index, 0x00);
SPI_Push(index, 0x85); //disable loopback
SPI_Push(index, 0x8d); //disable 3 phase clocking
ret = SPI_Flush(index);
::Sleep(100);
if (ret != FT_OK) return ret;
}
return ret;
}
void CFTSPI::SPI_Push(UINT32 index, BYTE data)
{
SPIChannel[index].cmdbuf[SPIChannel[index].wptr++] = data;
if (SPIChannel[index].wptr == (BUFSIZE-1)) { SPI_Flush(index); }
}
void CFTSPI::SPI_Push(UINT32 index, BYTE* data, UINT32 length)
{
if ((SPIChannel[index].wptr + length) >= (BUFSIZE-1)) { SPI_Flush(index); }
memcpy(&SPIChannel[index].cmdbuf[SPIChannel[index].wptr], data, length);
SPIChannel[index].wptr += length;
}
FT_STATUS CFTSPI::SPI_Read(UINT32 index, UINT8* buffer, UINT32 sizeToTransfer, UINT32 cs)
{
FT_STATUS ret = FT_OK;
return ret;
}
FT_STATUS CFTSPI::SPI_Write(UINT32 index, UINT8* buffer, UINT32 sizeToTransfer, UINT32 cs)
{
FT_STATUS ret = FT_OK;
UINT8 csmask = ~(1 << (cs + 3));
if (index < SPIChannel.size() && sizeToTransfer) {
UINT16 length = sizeToTransfer-1;
SPI_Push(index, 0x80); //assert CS
SPI_Push(index, 0xf8 & csmask); //
SPI_Push(index, 0xfb); //
SPI_Push(index, 0x11); //ve+ edge MSB first no read
SPI_Push(index, (BYTE*)(&length), 2); //length
SPI_Push(index, buffer, sizeToTransfer);
SPI_Push(index, 0x80); //dessert CS
SPI_Push(index, 0xf8); //
SPI_Push(index, 0xfb); //
SPI_Flush(index);
}
return ret;
}
UINT32 CFTSPI::GetChannelIndex(UINT32 index)
{
if (index < SPIChannel.size()) {
return SPIChannel[index].index;
}
return UINT32(-1);
}
FT_HANDLE CFTSPI::GetChannelHandle(UINT32 index)
{
if (index < SPIChannel.size() != NULL) {
return SPIChannel[index].ftHandle;
}
return FT_HANDLE(0);
}
FT_STATUS CFTSPI::FT_WriteGPIO(UINT32 index, UINT8 dir, UINT8 value)
{
FT_STATUS ret = FT_OK;
if (index < SPIChannel.size()) {
SPI_Push(index, 0x82); //Set high byte
SPI_Push(index, value); //
SPI_Push(index, dir); //
SPI_Flush(index);
}
return ret;
}
FT_STATUS CFTSPI::SPI_Flush(UINT32 index)
{
FT_STATUS ret = FT_OTHER_ERROR;
if (index < SPIChannel.size()) {
DWORD written = 0;
if (SPIChannel[index].wptr) {
//SPIChannel[index].cmdbuf[SPIChannel[index].wptr++] = 0x87; //force flush
ret = FT_Write(SPIChannel[index].ftHandle, SPIChannel[index].cmdbuf, SPIChannel[index].wptr, &written);
SPIChannel[index].wptr = 0;
//BYTE forceflush = 0x87;
//ret = FT_Write(SPIChannel[index].ftHandle, &forceflush, 1, &written);
}
else {
ret = FT_OK;
}
}
return ret;
}
void CFTSPI::SPI_Flush()
{
for (UINT32 i = 0; i < SPIChannel.size(); i++) {
FT_STATUS status = SPI_Flush(i);
assert(status == FT_OK);
}
}
void CFTSPI::InitialClear()
{
for (int index = 0; index < SPIChannel.size(); index++) {
SPI_Push(index, 0x82); //Set high byte
SPI_Push(index, 0x00); //assert IC
SPI_Push(index, 0xff); //dir
SPI_Flush(index);
::Sleep(10);
SPI_Push(index, 0x82); //Set high byte
SPI_Push(index, 0xff); //dessert IC
SPI_Push(index, 0xff); //dir
SPI_Flush(index);
}
}
void CFTSPI::GetInterfaceDesc(TCHAR* str, int len)
{
sprintf_s(str, len, _T("%s"), description);
}<|endoftext|>
|
<commit_before>// FONcTransmitter.cc
// This file is part of BES Netcdf File Out Module
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <[email protected]> and Jose Garcia <[email protected]>
//
// 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
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <[email protected]>
// jgarcia Jose Garcia <[email protected]>
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h> // For umask
#include <sys/stat.h>
#include <sys/types.h> // For umask
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <DataDDS.h>
#include <BaseType.h>
#include <escaping.h>
using namespace::libdap ;
#include "FONcTransmitter.h"
#include "FONcTransform.h"
#include <BESInternalError.h>
#include <TheBESKeys.h>
#include <BESContextManager.h>
#include <BESDataDDSResponse.h>
#include <BESDapNames.h>
#include <BESDataNames.h>
#include <BESDebug.h>
#define FONC_TEMP_DIR "/tmp"
string FONcTransmitter::temp_dir ;
/** @brief Construct the FONcTransmitter, adding it with name netcdf to be
* able to transmit a data response
*
* The transmitter is created to add the ability to return OPeNDAP data
* objects (DataDDS) as a netcdf file.
*
* The OPeNDAP data object is written to a netcdf file locally in a
* temporary directory specified by the BES configuration parameter
* FONc.Tempdir. If this variable is not found or is not set then it
* defaults to the macro definition FONC_TEMP_DIR.
*/
FONcTransmitter::FONcTransmitter()
: BESBasicTransmitter()
{
add_method( DATA_SERVICE, FONcTransmitter::send_data ) ;
if( FONcTransmitter::temp_dir.empty() )
{
// Where is the temp directory for creating these files
bool found = false ;
string key = "FONc.Tempdir" ;
TheBESKeys::TheKeys()->get_value( key,
FONcTransmitter::temp_dir, found ) ;
if( !found || FONcTransmitter::temp_dir.empty() )
{
FONcTransmitter::temp_dir = FONC_TEMP_DIR ;
}
string::size_type len = FONcTransmitter::temp_dir.length() ;
if( FONcTransmitter::temp_dir[len - 1] == '/' )
{
FONcTransmitter::temp_dir =
FONcTransmitter::temp_dir.substr( 0, len- 1 ) ;
}
}
}
/** @brief The static method registered to transmit OPeNDAP data objects as
* a netcdf file.
*
* This function takes the OPeNDAP DataDDS object, reads in the data (can be
* used with any data handler), transforms the data into a netcdf file, and
* streams back that netcdf file back to the requester using the stream
* specified in the BESDataHandlerInterface.
*
* @param obj The BESResponseObject containing the OPeNDAP DataDDS object
* @param dhi BESDataHandlerInterface containing information about the
* request and response
* @throws BESInternalError if the response is not an OPeNDAP DataDDS or if
* there are any problems reading the data, writing to a netcdf file, or
* streaming the netcdf file
*/
void
FONcTransmitter::send_data( BESResponseObject *obj,
BESDataHandlerInterface &dhi )
{
BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj) ;
if( !bdds )
{
throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;
}
DataDDS *dds = bdds->get_dds() ;
if( !dds )
{
string err = (string)"No DataDDS has been created for transmit" ;
BESInternalError pe( err, __FILE__, __LINE__ ) ;
throw pe ;
}
ostream &strm = dhi.get_output_stream() ;
if( !strm )
{
string err = (string)"Output stream is not set, can not return as" ;
BESInternalError pe( err, __FILE__, __LINE__ ) ;
throw pe ;
}
BESDEBUG( "fonc",
"FONcTransmitter::send_data - parsing the constraint" << endl ) ;
// ticket 1248 jhrg 2/23/09
string ce = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26");
try
{
bdds->get_ce().parse_constraint( ce, *dds);
}
catch( Error &e )
{
string em = e.get_error_message() ;
string err = "Failed to parse the constraint expression: " + em ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
catch( ... )
{
string err = (string)"Failed to parse the constraint expression: "
+ "Unknown exception caught" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
// The dataset_name is no longer used in the constraint evaluator, so no
// need to get here. Plus, just getting the first containers dataset
// name would not have worked with multiple containers.
// pwest Jan 4, 2009
string dataset_name = "" ;
// now we need to read the data
BESDEBUG( "fonc", "FONcTransmitter::send_data - reading data into DataDDS"
<< endl ) ;
// This is used to record whetehr this is a functional CE or not. If so,
// the code allocates a new DDS object to hold the BaseType returned by
// the function and we need to delete that DDS before exiting this code.
bool functional_constraint = false;
try
{
// Handle *functional* constraint expressions specially
if (bdds->get_ce().function_clauses())
{
BESDEBUG( "fonc", "processing a functional constraint clause(s)." << endl );
dds = bdds->get_ce().eval_function_clauses(*dds);
}
#if 0
if( bdds->get_ce().functional_expression() )
{
// This returns a new BaseType, not a pointer to one in the DataDDS
// So once the data has been read using this var create a new
// DataDDS and add this new var to the it.
BaseType *var = bdds->get_ce().eval_function( *dds, dataset_name ) ;
if (!var)
throw Error(unknown_error, "Error calling the CE function.");
var->read( ) ;
dds = new DataDDS( NULL, "virtual" ) ;
// Set 'functional_constraint' here so that below we know that if
// it's true we must delete 'dds'.
functional_constraint = true;
dds->add_var( var ) ;
}
#endif
else
{
// Iterate through the variables in the DataDDS and read
// in the data if the variable has the send flag set.
// Note the special case for Sequence. The
// transfer_data() method uses the same logic as
// serialize() to read values but transfers them to the
// d_values field instead of writing them to a XDR sink
// pointer. jhrg 9/13/06
for( DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++ )
{
if( (*i)->send_p() )
{
// FIXME: we don't have sequences in netcdf so let's not
// worry about that right now.
(*i)->intern_data(bdds->get_ce(), *dds);
}
}
}
}
catch( Error &e )
{
if (functional_constraint)
delete dds;
string em = e.get_error_message() ;
string err = "Failed to read data: " + em ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
catch( ... )
{
if (functional_constraint)
delete dds;
string err = "Failed to read data: Unknown exception caught" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
string temp_file_name = FONcTransmitter::temp_dir + '/' + "ncXXXXXX";
char *temp_full = new char[temp_file_name.length() + 1];
string::size_type len = temp_file_name.copy(temp_full, temp_file_name.length());
*(temp_full + len) = '\0';
// cover the case where older versions of mkstemp() create the file using
// a mode of 666.
mode_t original_mode = umask( 077 );
int fd = mkstemp( temp_full ) ;
umask( original_mode );
if( fd == -1 )
{
delete [] temp_full;
if (functional_constraint)
delete dds;
string err = string("Failed to open the temporary file: ")
+ temp_file_name ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
// transform the OPeNDAP DataDDS to the netcdf file
BESDEBUG( "fonc",
"FONcTransmitter::send_data - transforming into temporary file "
<< temp_full << endl ) ;
try
{
FONcTransform ft( dds, dhi, temp_full ) ;
ft.transform() ;
BESDEBUG( "fonc",
"FONcTransmitter::send_data - transmitting temp file "
<< temp_full << endl ) ;
FONcTransmitter::return_temp_stream( temp_full, strm ) ;
}
catch( BESError &e )
{
close(fd);
(void)unlink( temp_full ) ;
delete[] temp_full;
if (functional_constraint)
delete dds;
throw;
}
catch( ... )
{
close(fd);
(void)unlink( temp_full ) ;
delete[] temp_full;
if (functional_constraint)
delete dds;
string err = (string)"File out netcdf, "
+ "was not able to transform to netcdf, unknown error" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
close(fd);
(void)unlink( temp_full ) ;
delete[] temp_full;
if (functional_constraint)
delete dds;
BESDEBUG( "fonc",
"FONcTransmitter::send_data - done transmitting to netcdf"
<< endl ) ;
}
/** @brief stream the temporary netcdf file back to the requester
*
* Streams the temporary netcdf file specified by filename to the specified
* C++ ostream
*
* @param filename The name of the file to stream back to the requester
* @param strm C++ ostream to write the contents of the file to
* @throws BESInternalError if problem opening the file
*/
void
FONcTransmitter::return_temp_stream( const string &filename,
ostream &strm )
{
// int bytes = 0 ; // Not used; jhrg 3/16/11
ifstream os ;
os.open( filename.c_str(), ios::binary|ios::in ) ;
if( !os )
{
string err = "Can not connect to file " + filename ;
BESInternalError pe(err, __FILE__, __LINE__ ) ;
throw pe ;
}
int nbytes ;
char block[4096] ;
os.read( block, sizeof block ) ;
nbytes = os.gcount() ;
if( nbytes > 0 )
{
bool found = false ;
string context = "transmit_protocol" ;
string protocol =
BESContextManager::TheManager()->get_context( context, found ) ;
if( protocol == "HTTP" )
{
strm << "HTTP/1.0 200 OK\n" ;
strm << "Content-type: application/octet-stream\n" ;
strm << "Content-Description: " << "BES dataset" << "\n" ;
strm << "Content-Disposition: filename=" << filename << ".nc;\n\n" ;
strm << flush ;
}
strm.write( block, nbytes ) ;
//bytes += nbytes ;
}
else
{
// close the stream before we leave.
os.close() ;
string err = (string)"0XAAE234F: failed to stream. Internal server "
+ "error, got zero count on stream buffer." + filename ;
BESInternalError pe( err, __FILE__, __LINE__ ) ;
throw pe ;
}
while (os)
{
os.read( block, sizeof block ) ;
nbytes = os.gcount() ;
strm.write( block, nbytes ) ;
//write( fileno( stdout ),(void*)block, nbytes ) ;
//bytes += nbytes ;
}
os.close();
}
<commit_msg>Cleaned up a warning where a bool was (not) used because the code to process functional CEs was never used.<commit_after>// FONcTransmitter.cc
// This file is part of BES Netcdf File Out Module
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <[email protected]> and Jose Garcia <[email protected]>
//
// 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
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <[email protected]>
// jgarcia Jose Garcia <[email protected]>
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h> // For umask
#include <sys/stat.h>
#include <sys/types.h> // For umask
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <DataDDS.h>
#include <BaseType.h>
#include <escaping.h>
using namespace::libdap ;
#include "FONcTransmitter.h"
#include "FONcTransform.h"
#include <BESInternalError.h>
#include <TheBESKeys.h>
#include <BESContextManager.h>
#include <BESDataDDSResponse.h>
#include <BESDapNames.h>
#include <BESDataNames.h>
#include <BESDebug.h>
#define FONC_TEMP_DIR "/tmp"
string FONcTransmitter::temp_dir ;
/** @brief Construct the FONcTransmitter, adding it with name netcdf to be
* able to transmit a data response
*
* The transmitter is created to add the ability to return OPeNDAP data
* objects (DataDDS) as a netcdf file.
*
* The OPeNDAP data object is written to a netcdf file locally in a
* temporary directory specified by the BES configuration parameter
* FONc.Tempdir. If this variable is not found or is not set then it
* defaults to the macro definition FONC_TEMP_DIR.
*/
FONcTransmitter::FONcTransmitter()
: BESBasicTransmitter()
{
add_method( DATA_SERVICE, FONcTransmitter::send_data ) ;
if( FONcTransmitter::temp_dir.empty() )
{
// Where is the temp directory for creating these files
bool found = false ;
string key = "FONc.Tempdir" ;
TheBESKeys::TheKeys()->get_value( key,
FONcTransmitter::temp_dir, found ) ;
if( !found || FONcTransmitter::temp_dir.empty() )
{
FONcTransmitter::temp_dir = FONC_TEMP_DIR ;
}
string::size_type len = FONcTransmitter::temp_dir.length() ;
if( FONcTransmitter::temp_dir[len - 1] == '/' )
{
FONcTransmitter::temp_dir =
FONcTransmitter::temp_dir.substr( 0, len- 1 ) ;
}
}
}
/** @brief The static method registered to transmit OPeNDAP data objects as
* a netcdf file.
*
* This function takes the OPeNDAP DataDDS object, reads in the data (can be
* used with any data handler), transforms the data into a netcdf file, and
* streams back that netcdf file back to the requester using the stream
* specified in the BESDataHandlerInterface.
*
* @param obj The BESResponseObject containing the OPeNDAP DataDDS object
* @param dhi BESDataHandlerInterface containing information about the
* request and response
* @throws BESInternalError if the response is not an OPeNDAP DataDDS or if
* there are any problems reading the data, writing to a netcdf file, or
* streaming the netcdf file
*/
void
FONcTransmitter::send_data( BESResponseObject *obj,
BESDataHandlerInterface &dhi )
{
BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj) ;
if( !bdds )
{
throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;
}
DataDDS *dds = bdds->get_dds() ;
if( !dds )
{
string err = (string)"No DataDDS has been created for transmit" ;
BESInternalError pe( err, __FILE__, __LINE__ ) ;
throw pe ;
}
ostream &strm = dhi.get_output_stream() ;
if( !strm )
{
string err = (string)"Output stream is not set, can not return as" ;
BESInternalError pe( err, __FILE__, __LINE__ ) ;
throw pe ;
}
BESDEBUG( "fonc",
"FONcTransmitter::send_data - parsing the constraint" << endl ) ;
// ticket 1248 jhrg 2/23/09
string ce = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26");
try
{
bdds->get_ce().parse_constraint( ce, *dds);
}
catch( Error &e )
{
string em = e.get_error_message() ;
string err = "Failed to parse the constraint expression: " + em ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
catch( ... )
{
string err = (string)"Failed to parse the constraint expression: "
+ "Unknown exception caught" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
// The dataset_name is no longer used in the constraint evaluator, so no
// need to get here. Plus, just getting the first containers dataset
// name would not have worked with multiple containers.
// pwest Jan 4, 2009
string dataset_name = "" ;
// now we need to read the data
BESDEBUG( "fonc", "FONcTransmitter::send_data - reading data into DataDDS"
<< endl ) ;
// I removed the functional_constraint bool and the (dead) code that used it.
// This kind of temporary object should use auto_ptr<>, but in this case it
// seems like it's not a supported feature of the handler. 12.27.2011 jhrg
#define FUNCTIONAL_CE_SUPPORTED 0
#if FUNCTIONAL_CE_SUPPORTED
// This is used to record whether this is a functional CE or not. If so,
// the code allocates a new DDS object to hold the BaseType returned by
// the function and we need to delete that DDS before exiting this code.
bool functional_constraint = false;
#endif
try
{
// Handle *functional* constraint expressions specially
if (bdds->get_ce().function_clauses())
{
BESDEBUG( "fonc", "processing a functional constraint clause(s)." << endl );
dds = bdds->get_ce().eval_function_clauses(*dds);
}
#if FUNCTIONAL_CE_SUPPORTED
if( bdds->get_ce().functional_expression() )
{
// This returns a new BaseType, not a pointer to one in the DataDDS
// So once the data has been read using this var create a new
// DataDDS and add this new var to the it.
BaseType *var = bdds->get_ce().eval_function( *dds, dataset_name ) ;
if (!var)
throw Error(unknown_error, "Error calling the CE function.");
var->read( ) ;
dds = new DataDDS( NULL, "virtual" ) ;
// Set 'functional_constraint' here so that below we know that if
// it's true we must delete 'dds'.
functional_constraint = true;
dds->add_var( var ) ;
}
#endif
else
{
// Iterate through the variables in the DataDDS and read
// in the data if the variable has the send flag set.
// Note the special case for Sequence. The
// transfer_data() method uses the same logic as
// serialize() to read values but transfers them to the
// d_values field instead of writing them to a XDR sink
// pointer. jhrg 9/13/06
for( DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++ )
{
if( (*i)->send_p() )
{
// FIXME: we don't have sequences in netcdf so let's not
// worry about that right now.
(*i)->intern_data(bdds->get_ce(), *dds);
}
}
}
}
catch( Error &e )
{
#if FUNCTIONAL_CE_SUPPORTED
if (functional_constraint)
delete dds;
#endif
string em = e.get_error_message() ;
string err = "Failed to read data: " + em ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
catch( ... )
{
#if FUNCTIONAL_CE_SUPPORTED
if (functional_constraint)
delete dds;
#endif
string err = "Failed to read data: Unknown exception caught" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
string temp_file_name = FONcTransmitter::temp_dir + '/' + "ncXXXXXX";
char *temp_full = new char[temp_file_name.length() + 1];
string::size_type len = temp_file_name.copy(temp_full, temp_file_name.length());
*(temp_full + len) = '\0';
// cover the case where older versions of mkstemp() create the file using
// a mode of 666.
mode_t original_mode = umask( 077 );
int fd = mkstemp( temp_full ) ;
umask( original_mode );
if( fd == -1 )
{
delete [] temp_full;
#if FUNCTIONAL_CE_SUPPORTED
if (functional_constraint)
delete dds;
#endif
string err = string("Failed to open the temporary file: ")
+ temp_file_name ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
// transform the OPeNDAP DataDDS to the netcdf file
BESDEBUG( "fonc",
"FONcTransmitter::send_data - transforming into temporary file "
<< temp_full << endl ) ;
try
{
FONcTransform ft( dds, dhi, temp_full ) ;
ft.transform() ;
BESDEBUG( "fonc",
"FONcTransmitter::send_data - transmitting temp file "
<< temp_full << endl ) ;
FONcTransmitter::return_temp_stream( temp_full, strm ) ;
}
catch( BESError &e )
{
close(fd);
(void)unlink( temp_full ) ;
delete[] temp_full;
#if FUNCTIONAL_CE_SUPPORTED
if (functional_constraint)
delete dds;
#endif
throw;
}
catch( ... )
{
close(fd);
(void)unlink( temp_full ) ;
delete[] temp_full;
#if FUNCTIONAL_CE_SUPPORTED
if (functional_constraint)
delete dds;
#endif
string err = (string)"File out netcdf, "
+ "was not able to transform to netcdf, unknown error" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
close(fd);
(void)unlink( temp_full ) ;
delete[] temp_full;
#if FUNCTIONAL_CE_SUPPORTED
if (functional_constraint)
delete dds;
#endif
BESDEBUG( "fonc",
"FONcTransmitter::send_data - done transmitting to netcdf"
<< endl ) ;
}
/** @brief stream the temporary netcdf file back to the requester
*
* Streams the temporary netcdf file specified by filename to the specified
* C++ ostream
*
* @param filename The name of the file to stream back to the requester
* @param strm C++ ostream to write the contents of the file to
* @throws BESInternalError if problem opening the file
*/
void
FONcTransmitter::return_temp_stream( const string &filename,
ostream &strm )
{
// int bytes = 0 ; // Not used; jhrg 3/16/11
ifstream os ;
os.open( filename.c_str(), ios::binary|ios::in ) ;
if( !os )
{
string err = "Can not connect to file " + filename ;
BESInternalError pe(err, __FILE__, __LINE__ ) ;
throw pe ;
}
int nbytes ;
char block[4096] ;
os.read( block, sizeof block ) ;
nbytes = os.gcount() ;
if( nbytes > 0 )
{
bool found = false ;
string context = "transmit_protocol" ;
string protocol =
BESContextManager::TheManager()->get_context( context, found ) ;
if( protocol == "HTTP" )
{
strm << "HTTP/1.0 200 OK\n" ;
strm << "Content-type: application/octet-stream\n" ;
strm << "Content-Description: " << "BES dataset" << "\n" ;
strm << "Content-Disposition: filename=" << filename << ".nc;\n\n" ;
strm << flush ;
}
strm.write( block, nbytes ) ;
//bytes += nbytes ;
}
else
{
// close the stream before we leave.
os.close() ;
string err = (string)"0XAAE234F: failed to stream. Internal server "
+ "error, got zero count on stream buffer." + filename ;
BESInternalError pe( err, __FILE__, __LINE__ ) ;
throw pe ;
}
while (os)
{
os.read( block, sizeof block ) ;
nbytes = os.gcount() ;
strm.write( block, nbytes ) ;
//write( fileno( stdout ),(void*)block, nbytes ) ;
//bytes += nbytes ;
}
os.close();
}
<|endoftext|>
|
<commit_before>// serial.cxx -- Unix serial I/O support
//
// Written by Curtis Olson, started November 1998.
//
// Copyright (C) 1998 Curtis L. Olson - [email protected]
//
// 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 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
// (Log is kept at end of this file)
#include <errno.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <Debug/logstream.hxx>
#include "serial.hxx"
fgSERIAL::fgSERIAL() {
dev_open = false;
}
fgSERIAL::fgSERIAL(const string& device, int baud) {
open_port(device);
if ( dev_open ) {
set_baud(baud);
}
}
fgSERIAL::~fgSERIAL() {
close(fd);
}
bool fgSERIAL::open_port(const string& device) {
struct termios config;
if ( (fd = open(device.c_str(), O_RDWR | O_NONBLOCK)) == -1 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Cannot open " << device
<< " for serial I/O" );
return false;
} else {
dev_open = true;
}
// set required port parameters
if ( tcgetattr( fd, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to poll port settings" );
return false;
}
cfmakeraw( &config );
// cout << "config.c_iflag = " << config.c_iflag << endl;
// software flow control on
// config.c_iflag |= IXON;
// config.c_iflag |= IXOFF;
// disable hardware flow control
// config.c_cflag |= CRTSCTS;
// cout << "config.c_iflag = " << config.c_iflag << endl;
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to update port settings" );
return false;
}
return true;
}
bool fgSERIAL::set_baud(int baud) {
struct termios config;
speed_t speed = B9600;
if ( tcgetattr( fd, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to poll port settings" );
return false;
}
if ( baud == 300 ) {
speed = B300;
} else if ( baud == 1200 ) {
speed = B1200;
} else if ( baud == 2400 ) {
speed = B2400;
} else if ( baud == 4800 ) {
speed = B4800;
} else if ( baud == 9600 ) {
speed = B9600;
} else if ( baud == 19200 ) {
speed = B19200;
} else if ( baud == 38400 ) {
speed = B38400;
} else if ( baud == 57600 ) {
speed = B57600;
} else if ( baud == 115200 ) {
speed = B115200;
#if defined( linux ) || defined( __FreeBSD__ )
} else if ( baud == 230400 ) {
speed = B230400;
#endif
} else {
FG_LOG( FG_SERIAL, FG_ALERT, "Unsupported baud rate " << baud );
return false;
}
if ( cfsetispeed( &config, speed ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Problem setting input baud rate" );
return false;
}
if ( cfsetospeed( &config, speed ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Problem setting output baud rate" );
return false;
}
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to update port settings" );
return false;
}
return true;
}
string fgSERIAL::read_port() {
const int max_count = 1024;
char buffer[max_count+1];
int count;
string result;
count = read(fd, buffer, max_count);
// cout << "read " << count << " bytes" << endl;
if ( count < 0 ) {
// error condition
if ( errno != EAGAIN ) {
FG_LOG( FG_SERIAL, FG_ALERT,
"Serial I/O on read, error number = " << errno );
}
return "";
} else {
buffer[count] = '\0';
result = buffer;
return result;
}
}
int fgSERIAL::write_port(const string& value) {
int count;
count = write(fd, value.c_str(), value.length());
// cout << "write '" << value << "' " << count << " bytes" << endl;
if ( (int)count != (int)value.length() ) {
FG_LOG( FG_SERIAL, FG_ALERT,
"Serial I/O on write, error number = " << errno );
}
return count;
}
// $Log$
// Revision 1.4 1998/11/23 21:47:00 curt
// Cygnus tools compatibility tweaks.
//
// Revision 1.3 1998/11/19 13:52:54 curt
// port configuration tweaks & experiments.
//
// Revision 1.2 1998/11/19 03:35:43 curt
// Updates ...
//
// Revision 1.1 1998/11/16 13:53:02 curt
// Initial revision.
//
<commit_msg>Remove call to cfmakeraw()<commit_after>// serial.cxx -- Unix serial I/O support
//
// Written by Curtis Olson, started November 1998.
//
// Copyright (C) 1998 Curtis L. Olson - [email protected]
//
// 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 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
// (Log is kept at end of this file)
#include <errno.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <Debug/logstream.hxx>
#include "serial.hxx"
fgSERIAL::fgSERIAL() {
dev_open = false;
}
fgSERIAL::fgSERIAL(const string& device, int baud) {
open_port(device);
if ( dev_open ) {
set_baud(baud);
}
}
fgSERIAL::~fgSERIAL() {
close(fd);
}
bool fgSERIAL::open_port(const string& device) {
struct termios config;
if ( (fd = open(device.c_str(), O_RDWR | O_NONBLOCK)) == -1 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Cannot open " << device
<< " for serial I/O" );
return false;
} else {
dev_open = true;
}
// set required port parameters
if ( tcgetattr( fd, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to poll port settings" );
return false;
}
// cfmakeraw( &config );
// cout << "config.c_iflag = " << config.c_iflag << endl;
// software flow control on
// config.c_iflag |= IXON;
// config.c_iflag |= IXOFF;
// disable hardware flow control
// config.c_cflag |= CRTSCTS;
// cout << "config.c_iflag = " << config.c_iflag << endl;
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to update port settings" );
return false;
}
return true;
}
bool fgSERIAL::set_baud(int baud) {
struct termios config;
speed_t speed = B9600;
if ( tcgetattr( fd, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to poll port settings" );
return false;
}
if ( baud == 300 ) {
speed = B300;
} else if ( baud == 1200 ) {
speed = B1200;
} else if ( baud == 2400 ) {
speed = B2400;
} else if ( baud == 4800 ) {
speed = B4800;
} else if ( baud == 9600 ) {
speed = B9600;
} else if ( baud == 19200 ) {
speed = B19200;
} else if ( baud == 38400 ) {
speed = B38400;
} else if ( baud == 57600 ) {
speed = B57600;
} else if ( baud == 115200 ) {
speed = B115200;
#if defined( linux ) || defined( __FreeBSD__ )
} else if ( baud == 230400 ) {
speed = B230400;
#endif
} else {
FG_LOG( FG_SERIAL, FG_ALERT, "Unsupported baud rate " << baud );
return false;
}
if ( cfsetispeed( &config, speed ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Problem setting input baud rate" );
return false;
}
if ( cfsetospeed( &config, speed ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Problem setting output baud rate" );
return false;
}
if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) {
FG_LOG( FG_SERIAL, FG_ALERT, "Unable to update port settings" );
return false;
}
return true;
}
string fgSERIAL::read_port() {
const int max_count = 1024;
char buffer[max_count+1];
int count;
string result;
count = read(fd, buffer, max_count);
// cout << "read " << count << " bytes" << endl;
if ( count < 0 ) {
// error condition
if ( errno != EAGAIN ) {
FG_LOG( FG_SERIAL, FG_ALERT,
"Serial I/O on read, error number = " << errno );
}
return "";
} else {
buffer[count] = '\0';
result = buffer;
return result;
}
}
int fgSERIAL::write_port(const string& value) {
int count;
count = write(fd, value.c_str(), value.length());
// cout << "write '" << value << "' " << count << " bytes" << endl;
if ( (int)count != (int)value.length() ) {
FG_LOG( FG_SERIAL, FG_ALERT,
"Serial I/O on write, error number = " << errno );
}
return count;
}
// $Log$
// Revision 1.5 1998/11/25 01:33:23 curt
// Remove call to cfmakeraw()
//
// Revision 1.4 1998/11/23 21:47:00 curt
// Cygnus tools compatibility tweaks.
//
// Revision 1.3 1998/11/19 13:52:54 curt
// port configuration tweaks & experiments.
//
// Revision 1.2 1998/11/19 03:35:43 curt
// Updates ...
//
// Revision 1.1 1998/11/16 13:53:02 curt
// Initial revision.
//
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModel.h>
mitk::ContourModel::ContourModel()
{
//set to initial state
this->InitializeEmpty();
}
mitk::ContourModel::ContourModel(const mitk::ContourModel &other) :
m_ContourSeries(other.m_ContourSeries), m_lineInterpolation(other.m_lineInterpolation)
{
m_SelectedVertex = NULL;
}
mitk::ContourModel::~ContourModel()
{
m_SelectedVertex = NULL;
this->m_ContourSeries.clear();//TODO check destruction
}
void mitk::ContourModel::AddVertex(mitk::Point3D &vertex, int timestep)
{
if(!this->IsEmptyTimeStep(timestep) )
{
this->AddVertex(vertex, false, timestep);
}
}
void mitk::ContourModel::AddVertex(mitk::Point3D &vertex, bool isActive, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->AddVertex(vertex, isActive);
this->InvokeEvent( ContourModelSizeChangeEvent() );
this->Modified();
}
}
void mitk::ContourModel::InsertVertexAtIndex(mitk::Point3D &vertex, int index, bool isActive, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
if(index > 0 && this->m_ContourSeries[timestep]->GetSize() > index)
{
this->m_ContourSeries[timestep]->InsertVertexAtIndex(vertex, isActive, index);
this->InvokeEvent( ContourModelSizeChangeEvent() );
this->Modified();
}
}
}
int mitk::ContourModel::GetNumberOfVertices( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetSize();
}
return -1;
}
const mitk::ContourModel::VertexType* mitk::ContourModel::GetVertexAt(int index, int timestep) const
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetVertexAt(index);
}
return NULL;
}
void mitk::ContourModel::Close( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->Close();
this->InvokeEvent( ContourModelClosedEvent() );
this->Modified();
}
}
void mitk::ContourModel::Open( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->Open();
this->InvokeEvent( ContourModelClosedEvent() );
this->Modified();
}
}
void mitk::ContourModel::SetIsClosed(bool isClosed, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->SetIsClosed(isClosed);
this->InvokeEvent( ContourModelClosedEvent() );
this->Modified();
}
}
bool mitk::ContourModel::IsEmptyTimeStep( int t) const
{
return (t < 0) || (this->m_ContourSeries.size() <= t);
}
void mitk::ContourModel::Concatenate(mitk::ContourModel* other, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
if( !this->m_ContourSeries[timestep]->IsClosed() )
{
this->m_ContourSeries[timestep]->Concatenate(other->m_ContourSeries[timestep]);
this->InvokeEvent( ContourModelSizeChangeEvent() );
this->Modified();
}
}
}
mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorBegin( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->ConstIteratorBegin();
}
else
{
throw std::exception("invalid timestep");// << timestep << "only " << this->GetTimeSteps() << " available.");
}
}
mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorEnd( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->ConstIteratorEnd();
}
else
{
throw std::exception("invalid timestep");// + timestep + "only " + this->GetTimeSteps() + " available.");
}
}
bool mitk::ContourModel::IsClosed( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IsClosed();
}
return false;
}
bool mitk::ContourModel::SelectVertexAt(int index, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return (this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(index));
}
return false;
}
bool mitk::ContourModel::SelectVertexAt(mitk::Point3D &point, float eps, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(point, eps);
}
return this->m_SelectedVertex != NULL;
}
bool mitk::ContourModel::RemoveVertexAt(int index, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->RemoveVertexAt(index);
this->Modified();
this->InvokeEvent( ContourModelSizeChangeEvent() );
return true;
}
return false;
}
bool mitk::ContourModel::RemoveVertexAt(mitk::Point3D &point, float eps, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->RemoveVertexAt(point, eps);
this->Modified();
this->InvokeEvent( ContourModelSizeChangeEvent() );
return true;
}
return false;
}
void mitk::ContourModel::ShiftSelectedVertex(mitk::Vector3D &translate)
{
if(this->m_SelectedVertex)
{
this->ShiftVertex(this->m_SelectedVertex,translate);
this->Modified();
}
}
void mitk::ContourModel::ShiftContour(mitk::Vector3D &translate, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
VertexListType* vList = this->m_ContourSeries[timestep]->GetVertexList();
VertexIterator it = vList->begin();
VertexIterator end = vList->end();
while(it != end)
{
this->ShiftVertex((*it),translate);
it++;
}
this->Modified();
this->InvokeEvent( ContourModelShiftEvent() );
}
}
void mitk::ContourModel::ShiftVertex(VertexType* vertex, mitk::Vector3D &vector)
{
vertex->Coordinates[0] += vector[0];
vertex->Coordinates[1] += vector[1];
vertex->Coordinates[2] += vector[2];
}
void mitk::ContourModel::Expand( int timeSteps )
{
int oldSize = this->m_ContourSeries.size();
if( timeSteps > 0 && timeSteps > oldSize )
{
Superclass::Expand(timeSteps);
for( int i = oldSize; i < timeSteps; i++)
{
m_ContourSeries.push_back(mitk::ContourModelElement::New());
}
this->InvokeEvent( ContourModelExpandTimeBoundsEvent() );
}
}
void mitk::ContourModel::SetRequestedRegionToLargestPossibleRegion ()
{
//no support for regions
}
bool mitk::ContourModel::RequestedRegionIsOutsideOfTheBufferedRegion ()
{
//no support for regions
return false;
}
bool mitk::ContourModel::VerifyRequestedRegion ()
{
//no support for regions
return true;
}
const mitk::Geometry3D * mitk::ContourModel::GetUpdatedGeometry (int t)
{
return Superclass::GetUpdatedGeometry(t);
}
mitk::Geometry3D* mitk::ContourModel::GetGeometry (int t)const
{
return Superclass::GetGeometry(t);
}
void mitk::ContourModel::SetRequestedRegion (itk::DataObject *data)
{
//no support for regions
}
void mitk::ContourModel::Clear()
{
//clear data and set to initial state again
this->ClearData();
this->InitializeEmpty();
this->Modified();
}
void mitk::ContourModel::ClearData()
{
//call the superclass, this releases the data of BaseData
Superclass::ClearData();
//clear out the time resolved contours
this->m_ContourSeries.clear();
}
void mitk::ContourModel::InitializeEmpty()
{
//clear data at timesteps
this->m_ContourSeries.resize(0);
this->m_ContourSeries.push_back(mitk::ContourModelElement::New());
//set number of timesteps to one
this->InitializeTimeSlicedGeometry(1);
m_SelectedVertex = NULL;
this->m_lineInterpolation = ContourModel::LINEAR;
}
void mitk::ContourModel::UpdateOutputInformation()
{
if ( this->GetSource() )
{
this->GetSource()->UpdateOutputInformation();
}
//update the bounds of the geometry according to the stored vertices
float mitkBounds[6];
//calculate the boundingbox at each timestep
typedef itk::BoundingBox<unsigned long, 3, ScalarType> BoundingBoxType;
typedef BoundingBoxType::PointsContainer PointsContainer;
int timesteps = this->GetTimeSteps();
//iterate over the timesteps
for(int currenTimeStep = 0; currenTimeStep < timesteps; currenTimeStep++)
{
//if no controlPoints are available the boundingbox is 0 in all dimensions
if (this->GetMTime() > this->GetGeometry(currenTimeStep)->GetBoundingBox()->GetMTime())
{
mitkBounds[0] = 0.0;
mitkBounds[1] = 0.0;
mitkBounds[2] = 0.0;
mitkBounds[3] = 0.0;
mitkBounds[4] = 0.0;
mitkBounds[5] = 0.0;
BoundingBoxType::Pointer boundingBox = BoundingBoxType::New();
PointsContainer::Pointer points = PointsContainer::New();
VertexIterator it = this->IteratorBegin(currenTimeStep);
VertexIterator end = this->IteratorEnd(currenTimeStep);
//fill the boundingbox with the points
while(it != end)
{
Point3D currentP = (*it)->Coordinates;
BoundingBoxType::PointType p;
p.CastFrom(currentP);
points->InsertElement(points->Size(), p);
it++;
}
//construct the new boundingBox
boundingBox->SetPoints(points);
boundingBox->ComputeBoundingBox();
BoundingBoxType::BoundsArrayType tmp = boundingBox->GetBounds();
mitkBounds[0] = tmp[0];
mitkBounds[1] = tmp[1];
mitkBounds[2] = tmp[2];
mitkBounds[3] = tmp[3];
mitkBounds[4] = tmp[4];
mitkBounds[5] = tmp[5];
Geometry3D* geometry3d = this->GetGeometry(currenTimeStep);
geometry3d->SetBounds(mitkBounds);
}
}
GetTimeSlicedGeometry()->UpdateInformation();
}
void mitk::ContourModel::ExecuteOperation(mitk::Operation* operation)
{
}<commit_msg>fixed removeAt method and documentation<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModel.h>
mitk::ContourModel::ContourModel()
{
//set to initial state
this->InitializeEmpty();
}
mitk::ContourModel::ContourModel(const mitk::ContourModel &other) :
m_ContourSeries(other.m_ContourSeries), m_lineInterpolation(other.m_lineInterpolation)
{
m_SelectedVertex = NULL;
}
mitk::ContourModel::~ContourModel()
{
m_SelectedVertex = NULL;
this->m_ContourSeries.clear();//TODO check destruction
}
void mitk::ContourModel::AddVertex(mitk::Point3D &vertex, int timestep)
{
if(!this->IsEmptyTimeStep(timestep) )
{
this->AddVertex(vertex, false, timestep);
}
}
void mitk::ContourModel::AddVertex(mitk::Point3D &vertex, bool isActive, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->AddVertex(vertex, isActive);
this->InvokeEvent( ContourModelSizeChangeEvent() );
this->Modified();
}
}
void mitk::ContourModel::InsertVertexAtIndex(mitk::Point3D &vertex, int index, bool isActive, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
if(index > 0 && this->m_ContourSeries[timestep]->GetSize() > index)
{
this->m_ContourSeries[timestep]->InsertVertexAtIndex(vertex, isActive, index);
this->InvokeEvent( ContourModelSizeChangeEvent() );
this->Modified();
}
}
}
int mitk::ContourModel::GetNumberOfVertices( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetSize();
}
return -1;
}
const mitk::ContourModel::VertexType* mitk::ContourModel::GetVertexAt(int index, int timestep) const
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetVertexAt(index);
}
return NULL;
}
void mitk::ContourModel::Close( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->Close();
this->InvokeEvent( ContourModelClosedEvent() );
this->Modified();
}
}
void mitk::ContourModel::Open( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->Open();
this->InvokeEvent( ContourModelClosedEvent() );
this->Modified();
}
}
void mitk::ContourModel::SetIsClosed(bool isClosed, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->SetIsClosed(isClosed);
this->InvokeEvent( ContourModelClosedEvent() );
this->Modified();
}
}
bool mitk::ContourModel::IsEmptyTimeStep( int t) const
{
return (t < 0) || (this->m_ContourSeries.size() <= t);
}
void mitk::ContourModel::Concatenate(mitk::ContourModel* other, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
if( !this->m_ContourSeries[timestep]->IsClosed() )
{
this->m_ContourSeries[timestep]->Concatenate(other->m_ContourSeries[timestep]);
this->InvokeEvent( ContourModelSizeChangeEvent() );
this->Modified();
}
}
}
mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorBegin( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->ConstIteratorBegin();
}
else
{
throw std::exception("invalid timestep");// << timestep << "only " << this->GetTimeSteps() << " available.");
}
}
mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorEnd( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->ConstIteratorEnd();
}
else
{
throw std::exception("invalid timestep");// + timestep + "only " + this->GetTimeSteps() + " available.");
}
}
bool mitk::ContourModel::IsClosed( int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IsClosed();
}
return false;
}
bool mitk::ContourModel::SelectVertexAt(int index, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
return (this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(index));
}
return false;
}
bool mitk::ContourModel::SelectVertexAt(mitk::Point3D &point, float eps, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(point, eps);
}
return this->m_SelectedVertex != NULL;
}
bool mitk::ContourModel::RemoveVertexAt(int index, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->RemoveVertexAt(index);
this->Modified();
this->InvokeEvent( ContourModelSizeChangeEvent() );
return true;
}
return false;
}
bool mitk::ContourModel::RemoveVertexAt(mitk::Point3D &point, float eps, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
if(this->m_ContourSeries[timestep]->RemoveVertexAt(point, eps))
{
this->Modified();
this->InvokeEvent( ContourModelSizeChangeEvent() );
return true;
}
else
{
return false;
}
}
return false;
}
void mitk::ContourModel::ShiftSelectedVertex(mitk::Vector3D &translate)
{
if(this->m_SelectedVertex)
{
this->ShiftVertex(this->m_SelectedVertex,translate);
this->Modified();
}
}
void mitk::ContourModel::ShiftContour(mitk::Vector3D &translate, int timestep)
{
if(!this->IsEmptyTimeStep(timestep))
{
VertexListType* vList = this->m_ContourSeries[timestep]->GetVertexList();
VertexIterator it = vList->begin();
VertexIterator end = vList->end();
//shift all vertices
while(it != end)
{
this->ShiftVertex((*it),translate);
it++;
}
this->Modified();
this->InvokeEvent( ContourModelShiftEvent() );
}
}
void mitk::ContourModel::ShiftVertex(VertexType* vertex, mitk::Vector3D &vector)
{
vertex->Coordinates[0] += vector[0];
vertex->Coordinates[1] += vector[1];
vertex->Coordinates[2] += vector[2];
}
void mitk::ContourModel::Expand( int timeSteps )
{
int oldSize = this->m_ContourSeries.size();
if( timeSteps > 0 && timeSteps > oldSize )
{
Superclass::Expand(timeSteps);
//insert contours for each new timestep
for( int i = oldSize; i < timeSteps; i++)
{
m_ContourSeries.push_back(mitk::ContourModelElement::New());
}
this->InvokeEvent( ContourModelExpandTimeBoundsEvent() );
}
}
void mitk::ContourModel::SetRequestedRegionToLargestPossibleRegion ()
{
//no support for regions
}
bool mitk::ContourModel::RequestedRegionIsOutsideOfTheBufferedRegion ()
{
//no support for regions
return false;
}
bool mitk::ContourModel::VerifyRequestedRegion ()
{
//no support for regions
return true;
}
const mitk::Geometry3D * mitk::ContourModel::GetUpdatedGeometry (int t)
{
return Superclass::GetUpdatedGeometry(t);
}
mitk::Geometry3D* mitk::ContourModel::GetGeometry (int t)const
{
return Superclass::GetGeometry(t);
}
void mitk::ContourModel::SetRequestedRegion (itk::DataObject *data)
{
//no support for regions
}
void mitk::ContourModel::Clear()
{
//clear data and set to initial state again
this->ClearData();
this->InitializeEmpty();
this->Modified();
}
void mitk::ContourModel::ClearData()
{
//call the superclass, this releases the data of BaseData
Superclass::ClearData();
//clear out the time resolved contours
this->m_ContourSeries.clear();
}
void mitk::ContourModel::InitializeEmpty()
{
//clear data at timesteps
this->m_ContourSeries.resize(0);
this->m_ContourSeries.push_back(mitk::ContourModelElement::New());
//set number of timesteps to one
this->InitializeTimeSlicedGeometry(1);
m_SelectedVertex = NULL;
this->m_lineInterpolation = ContourModel::LINEAR;
}
void mitk::ContourModel::UpdateOutputInformation()
{
if ( this->GetSource() )
{
this->GetSource()->UpdateOutputInformation();
}
//update the bounds of the geometry according to the stored vertices
float mitkBounds[6];
//calculate the boundingbox at each timestep
typedef itk::BoundingBox<unsigned long, 3, ScalarType> BoundingBoxType;
typedef BoundingBoxType::PointsContainer PointsContainer;
int timesteps = this->GetTimeSteps();
//iterate over the timesteps
for(int currenTimeStep = 0; currenTimeStep < timesteps; currenTimeStep++)
{
//only update bounds if the contour was modified
if (this->GetMTime() > this->GetGeometry(currenTimeStep)->GetBoundingBox()->GetMTime())
{
mitkBounds[0] = 0.0;
mitkBounds[1] = 0.0;
mitkBounds[2] = 0.0;
mitkBounds[3] = 0.0;
mitkBounds[4] = 0.0;
mitkBounds[5] = 0.0;
BoundingBoxType::Pointer boundingBox = BoundingBoxType::New();
PointsContainer::Pointer points = PointsContainer::New();
VertexIterator it = this->IteratorBegin(currenTimeStep);
VertexIterator end = this->IteratorEnd(currenTimeStep);
//fill the boundingbox with the points
while(it != end)
{
Point3D currentP = (*it)->Coordinates;
BoundingBoxType::PointType p;
p.CastFrom(currentP);
points->InsertElement(points->Size(), p);
it++;
}
//construct the new boundingBox
boundingBox->SetPoints(points);
boundingBox->ComputeBoundingBox();
BoundingBoxType::BoundsArrayType tmp = boundingBox->GetBounds();
mitkBounds[0] = tmp[0];
mitkBounds[1] = tmp[1];
mitkBounds[2] = tmp[2];
mitkBounds[3] = tmp[3];
mitkBounds[4] = tmp[4];
mitkBounds[5] = tmp[5];
//set boundingBox at current timestep
Geometry3D* geometry3d = this->GetGeometry(currenTimeStep);
geometry3d->SetBounds(mitkBounds);
}
}
GetTimeSlicedGeometry()->UpdateInformation();
}
void mitk::ContourModel::ExecuteOperation(mitk::Operation* operation)
{
//not supported yet
}<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2013 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cassert>
#include "Button.h"
#include "Config.h"
#include "DGFontManager.h"
#include "DGTexture.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
Button::Button() :
config(Config::instance()),
fontManager(DGFontManager::instance())
{
_font = fontManager.loadDefault();
this->setFadeSpeed(DGFadeNormal);
this->setType(DGObjectButton);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
Button::~Button() {
if (_hasAction)
delete _action;
if (_hasOnHoverTexture)
delete _onHoverTexture;
}
////////////////////////////////////////////////////////////
// Implementation - Checks
////////////////////////////////////////////////////////////
bool Button::hasAction() {
return _hasAction;
}
bool Button::hasOnHoverTexture() {
return _hasOnHoverTexture;
}
bool Button::hasFont() {
return _hasFont;
}
bool Button::hasText() {
return _hasText;
}
////////////////////////////////////////////////////////////
// Implementation - Gets
////////////////////////////////////////////////////////////
Action Button::action() {
assert(_hasAction == true);
return *_action;
}
DGFont* Button::font() {
return _font;
}
DGTexture* Button::onHoverTexture() {
return _onHoverTexture;
}
std::string Button::text() {
return _text;
}
int Button::textColor() {
return _textColor;
}
////////////////////////////////////////////////////////////
// Implementation - Sets
////////////////////////////////////////////////////////////
void Button::setAction(Action anAction) {
_action = new Action;
*_action = anAction;
_hasAction = true;
}
void Button::setFont(const std::string &fromFileName,
unsigned int heightOfFont) {
// FIXME: Wrong, this can load many repeated fonts!
_font = fontManager.load(fromFileName.c_str(), heightOfFont);
}
void Button::setOnHoverTexture(const std::string &fromFileName) {
// TODO: Important! We should determine first if the texture already exists,
// to avoid repeating resources. Eventually, this would be done via the
// resource manager.
DGTexture* texture;
texture = new DGTexture;
texture->setResource(config.path(kPathResources, fromFileName,
DGObjectImage).c_str());
texture->load();
_onHoverTexture = texture;
_hasOnHoverTexture = true;
}
void Button::setText(std::string text){
_text = text;
_hasText = true;
}
void Button::setTextColor(int aColor) {
// Note this expects one of our pre-generated colors
_textColor = aColor;
}
void Button::updateCursor(int theCursor) {
if (_hasAction) {
_action->cursor = theCursor;
}
}
<commit_msg>Fixed memory leak.<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2013 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cassert>
#include "Button.h"
#include "Config.h"
#include "DGFontManager.h"
#include "DGTexture.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
Button::Button() :
config(Config::instance()),
fontManager(DGFontManager::instance())
{
_font = fontManager.loadDefault();
this->setFadeSpeed(DGFadeNormal);
this->setType(DGObjectButton);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
Button::~Button() {
if (_hasAction)
delete _action;
if (_hasOnHoverTexture)
delete _onHoverTexture;
}
////////////////////////////////////////////////////////////
// Implementation - Checks
////////////////////////////////////////////////////////////
bool Button::hasAction() {
return _hasAction;
}
bool Button::hasOnHoverTexture() {
return _hasOnHoverTexture;
}
bool Button::hasFont() {
return _hasFont;
}
bool Button::hasText() {
return _hasText;
}
////////////////////////////////////////////////////////////
// Implementation - Gets
////////////////////////////////////////////////////////////
Action Button::action() {
assert(_hasAction == true);
return *_action;
}
DGFont* Button::font() {
return _font;
}
DGTexture* Button::onHoverTexture() {
return _onHoverTexture;
}
std::string Button::text() {
return _text;
}
int Button::textColor() {
return _textColor;
}
////////////////////////////////////////////////////////////
// Implementation - Sets
////////////////////////////////////////////////////////////
void Button::setAction(Action anAction) {
_action = new Action;
*_action = anAction;
_hasAction = true;
}
void Button::setFont(const std::string &fromFileName,
unsigned int heightOfFont) {
// FIXME: Wrong, this can load many repeated fonts!
_font = fontManager.load(fromFileName.c_str(), heightOfFont);
}
void Button::setOnHoverTexture(const std::string &fromFileName) {
// TODO: Important! We should determine first if the texture already exists,
// to avoid repeating resources. Eventually, this would be done via the
// resource manager.
_onHoverTexture = new DGTexture;
_onHoverTexture->setResource(config.path(kPathResources, fromFileName,
DGObjectImage).c_str());
_onHoverTexture->load();
_hasOnHoverTexture = true;
}
void Button::setText(std::string text){
_text = text;
_hasText = true;
}
void Button::setTextColor(int aColor) {
// Note this expects one of our pre-generated colors
_textColor = aColor;
}
void Button::updateCursor(int theCursor) {
if (_hasAction) {
_action->cursor = theCursor;
}
}
<|endoftext|>
|
<commit_before>#ifndef CONSTANTS_HPP
#define CONSTANTS_HPP
#include "./Logger.hpp"
static Logger logger(static_cast<std::string>("./logs.log"));
#endif
<commit_msg>Removed Constants.hpp from project.<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include "ShaderResourceBuffer.h"
#include "VectorIndexer.hpp"
#include <memory>
#include "DirectX.h"
#include <assert.h>
namespace Rendering
{
namespace Buffer
{
template<typename T>
class GPUUploadBuffer
{
public:
GPUUploadBuffer() = default;
void Initialize(Device::DirectX& dx, uint count, DXGI_FORMAT format, const void* dummy = nullptr)
{
_srBuffer.Initialize(dx, sizeof(T), count, format, dummy, false, 0, D3D11_USAGE_DYNAMIC);
}
// _srBuffer
void UpdateSRBuffer(Device::DirectX& dx)
{
const void* raw = _pool.data();
_srBuffer.UpdateResourceUsingMapUnMap(dx, raw, _pool.size() * sizeof(T));
}
// _buffer
inline void PushData(T& data) { _pool.push_back(data); }
inline void PushData(T&& data) { _pool.push_back(data); }
inline void DeleteAll() { _pool.clear(); }
inline uint GetSize() const { return _pool.size(); }
inline T& operator[](uint index)
{
assert( (0 <= index) & (index < _pool.size()));
return _pool[index];
}
inline void Delete(uint index)
{
auto iter = _pool.begin() + index;
_pool.erase(iter);
}
GET_ALL_ACCESSOR(ShaderResourceBuffer, auto&, _srBuffer);
private:
std::vector<T> _pool;
ShaderResourceBuffer _srBuffer;
};
}
}
<commit_msg>GPUUploadBuffer - ShaderResourceBuffer::Initialize 수정으로 인한 코드 정리, GET_ALL_ACCESSOR -> GET_ACCESSOR_REF<commit_after>#pragma once
#include "ShaderResourceBuffer.h"
#include "VectorIndexer.hpp"
#include <memory>
#include "DirectX.h"
#include <assert.h>
namespace Rendering
{
namespace Buffer
{
template<typename T>
class GPUUploadBuffer
{
public:
GPUUploadBuffer() = default;
void Initialize(Device::DirectX& dx, uint count, DXGI_FORMAT format, const void* dummy = nullptr)
{
_srBuffer.Initialize(dx, sizeof(T), count, format, dummy, 0, D3D11_USAGE_DYNAMIC);
}
// _srBuffer
void UpdateSRBuffer(Device::DirectX& dx)
{
const void* raw = _pool.data();
_srBuffer.UpdateResourceUsingMapUnMap(dx, raw, _pool.size() * sizeof(T));
}
// _buffer
inline void PushData(T& data) { _pool.push_back(data); }
inline void PushData(T&& data) { _pool.push_back(data); }
inline void DeleteAll() { _pool.clear(); }
inline uint GetSize() const { return _pool.size(); }
inline T& operator[](uint index)
{
assert( (0 <= index) & (index < _pool.size()));
return _pool[index];
}
inline void Delete(uint index)
{
auto iter = _pool.begin() + index;
_pool.erase(iter);
}
GET_ACCESSOR_REF(ShaderResourceBuffer, _srBuffer);
private:
std::vector<T> _pool;
ShaderResourceBuffer _srBuffer;
};
}
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Vladimir Alyamkin. All Rights Reserved.
#include "CrashlyticsKit.h"
#include "CrashlyticsKitCommon.h"
#include "CrashlyticsKitProxy.h"
#include "CrashlyticsKitSettings.h"
#if PLATFORM_IOS
#include "CrashlyticsKit_iOS.h"
#elif PLATFORM_ANDROID
#include "CrashlyticsKit_Android.h"
#endif
#include "UObject/Package.h"
#include "Misc/ConfigCacheIni.h"
#include "ISettingsModule.h"
#define LOCTEXT_NAMESPACE "CrashlyticsKit"
class FCrashlyticsKit : public ICrashlyticsKit
{
/** IModuleInterface implementation */
virtual void StartupModule() override
{
KitSettings = NewObject<UCrashlyticsKitSettings>(GetTransientPackage(), "CrashlyticsKitSettings", RF_Standalone);
KitSettings->AddToRoot();
// We need to manually load the config properties here, as this module is loaded before the UObject system is setup to do this
GConfig->GetBool(TEXT("/Script/CrashlyticsKit.CrashlyticsKitSettings"), TEXT("CrashlyticsManualInit"), KitSettings->bCrashlyticsManualInit, GEngineIni);
// Register settings
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->RegisterSettings("Project", "Plugins", "VaFabricTools",
LOCTEXT("RuntimeSettingsName", "Crashlytics Kit"),
LOCTEXT("RuntimeSettingsDescription", "Configure API keys for Crashlytics"),
KitSettings
);
}
// Proxy class depends on platform
UClass* KitPlatformClass = UCrashlyticsKitProxy::StaticClass();
#if WITH_CRASHLYTICS
#if PLATFORM_IOS
KitPlatformClass = UCrashlyticsKit_iOS::StaticClass();
#elif PLATFORM_ANDROID
KitPlatformClass = UCrashlyticsKit_Android::StaticClass();
#endif
#endif
// Create crashlytics kit proxy and initalize module by default
CrashlyticsKitProxy = NewObject<UCrashlyticsKitProxy>(GetTransientPackage(), KitPlatformClass);
CrashlyticsKitProxy->SetFlags(RF_Standalone);
CrashlyticsKitProxy->AddToRoot();
#if WITH_CRASHLYTICS
// Check for manual kit initialization
if (KitSettings->bCrashlyticsManualInit == false)
{
CrashlyticsKitProxy->InitCrashlytics();
}
#endif
}
virtual void ShutdownModule() override
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->UnregisterSettings("Project", "Plugins", "VaFabricTools");
}
if (!GExitPurge)
{
// If we're in exit purge, this object has already been destroyed
CrashlyticsKitProxy->RemoveFromRoot();
KitSettings->RemoveFromRoot();
}
else
{
CrashlyticsKitProxy = nullptr;
KitSettings = nullptr;
}
}
private:
/** Holds the kit settings */
UCrashlyticsKitSettings* KitSettings;
};
IMPLEMENT_MODULE(FCrashlyticsKit, CrashlyticsKit)
DEFINE_LOG_CATEGORY(LogVftCrashlytics);
#undef LOCTEXT_NAMESPACE
<commit_msg>Fix includes for nativization<commit_after>// Copyright 2016 Vladimir Alyamkin. All Rights Reserved.
#include "CrashlyticsKit.h"
#include "CrashlyticsKitCommon.h"
#include "CrashlyticsKitProxy.h"
#include "CrashlyticsKitSettings.h"
#if PLATFORM_IOS
#include "CrashlyticsKit_iOS.h"
#elif PLATFORM_ANDROID
#include "CrashlyticsKit_Android.h"
#endif
#include "UObject/Package.h"
#include "Misc/ConfigCacheIni.h"
#include "Developer/Settings/Public/ISettingsModule.h"
#define LOCTEXT_NAMESPACE "CrashlyticsKit"
class FCrashlyticsKit : public ICrashlyticsKit
{
/** IModuleInterface implementation */
virtual void StartupModule() override
{
KitSettings = NewObject<UCrashlyticsKitSettings>(GetTransientPackage(), "CrashlyticsKitSettings", RF_Standalone);
KitSettings->AddToRoot();
// We need to manually load the config properties here, as this module is loaded before the UObject system is setup to do this
GConfig->GetBool(TEXT("/Script/CrashlyticsKit.CrashlyticsKitSettings"), TEXT("CrashlyticsManualInit"), KitSettings->bCrashlyticsManualInit, GEngineIni);
// Register settings
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->RegisterSettings("Project", "Plugins", "VaFabricTools",
LOCTEXT("RuntimeSettingsName", "Crashlytics Kit"),
LOCTEXT("RuntimeSettingsDescription", "Configure API keys for Crashlytics"),
KitSettings
);
}
// Proxy class depends on platform
UClass* KitPlatformClass = UCrashlyticsKitProxy::StaticClass();
#if WITH_CRASHLYTICS
#if PLATFORM_IOS
KitPlatformClass = UCrashlyticsKit_iOS::StaticClass();
#elif PLATFORM_ANDROID
KitPlatformClass = UCrashlyticsKit_Android::StaticClass();
#endif
#endif
// Create crashlytics kit proxy and initalize module by default
CrashlyticsKitProxy = NewObject<UCrashlyticsKitProxy>(GetTransientPackage(), KitPlatformClass);
CrashlyticsKitProxy->SetFlags(RF_Standalone);
CrashlyticsKitProxy->AddToRoot();
#if WITH_CRASHLYTICS
// Check for manual kit initialization
if (KitSettings->bCrashlyticsManualInit == false)
{
CrashlyticsKitProxy->InitCrashlytics();
}
#endif
}
virtual void ShutdownModule() override
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->UnregisterSettings("Project", "Plugins", "VaFabricTools");
}
if (!GExitPurge)
{
// If we're in exit purge, this object has already been destroyed
CrashlyticsKitProxy->RemoveFromRoot();
KitSettings->RemoveFromRoot();
}
else
{
CrashlyticsKitProxy = nullptr;
KitSettings = nullptr;
}
}
private:
/** Holds the kit settings */
UCrashlyticsKitSettings* KitSettings;
};
IMPLEMENT_MODULE(FCrashlyticsKit, CrashlyticsKit)
DEFINE_LOG_CATEGORY(LogVftCrashlytics);
#undef LOCTEXT_NAMESPACE
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Execution::ThreadSafetyBuiltinObject
#include "Stroika/Foundation/StroikaPreComp.h"
#include <mutex>
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Containers/Bijection.h"
#include "Stroika/Foundation/Containers/Collection.h"
#include "Stroika/Foundation/Containers/Deque.h"
#include "Stroika/Foundation/Containers/Sequence.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Containers/Stack.h"
#include "Stroika/Foundation/Containers/SortedSet.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Math/Common.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Containers;
using Execution::Thread;
using Execution::WaitableEvent;
namespace {
/*
* To REALLY this this code for thread-safety, use ExternallySynchronizedLock, but to verify it works
* without worrying about races, just use mutex.
*/
struct no_lock_ {
void lock () {}
void unlock () {}
};
}
namespace {
void RunThreads_ (const initializer_list<Thread>& threads)
{
for (Thread i : threads) {
i.Start ();
}
for (Thread i : threads) {
i.WaitForDone ();
}
}
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkIterateOverThread_ (ITERABLE_TYPE* iterable, LOCK_TYPE* lock, unsigned int repeatCount)
{
using ElementType = typename ITERABLE_TYPE::ElementType;
return Thread ([iterable, lock, repeatCount] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
lock_guard<decltype(*lock)> critSec (*lock);
for (ElementType e : *iterable) {
ElementType e2 = e; // do something
}
}
});
};
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkOverwriteThread_ (ITERABLE_TYPE* oneToKeepOverwriting, ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, LOCK_TYPE* lock, unsigned int repeatCount)
{
return Thread ([oneToKeepOverwriting, lock, repeatCount, elt1, elt2] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt1;
}
else {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt2;
}
}
}
});
};
}
namespace {
namespace AssignAndIterateAtSameTimeTest_1_ {
template <typename ITERABLE_TYPE>
void DoItOnce_ (ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, unsigned int repeatCount)
{
no_lock_ lock ;
//mutex lock;
ITERABLE_TYPE oneToKeepOverwriting = elt1;
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, &lock, repeatCount);
Thread overwriteThread = mkOverwriteThread_ (&oneToKeepOverwriting, elt1, elt2, &lock, repeatCount);
RunThreads_ ({iterateThread, overwriteThread});
}
void DoIt ()
{
static const initializer_list<int> kOrigValueInit_ = {1, 3, 4, 5, 6, 33, 12, 13};
static const initializer_list<int> kUpdateValueInit_ = {4, 5, 6, 33, 12, 34, 596, 13, 1, 3, 99, 33, 4, 5};
static const initializer_list<pair<int,int>> kOrigPairValueInit_ = {pair<int,int> (1, 3), pair<int,int> (4, 5), pair<int,int> (6, 33), pair<int,int> (12, 13)};
static const initializer_list<pair<int,int>> kUPairpdateValueInit_ = {pair<int,int> (4, 5), pair<int,int> (6, 33), pair<int,int> (12, 34), pair<int,int> (596, 13), pair<int,int> (1, 3), pair<int,int> (99, 33), pair<int,int> (4, 5)};
Debug::TraceContextBumper traceCtx (SDKSTR ("AssignAndIterateAtSameTimeTest_1_::DoIt ()"));
DoItOnce_<String> (String (L"123456789"), String (L"abcdedfghijkqlmopqrstuvwxyz"), 1000);
DoItOnce_<Bijection<int,int>> (Bijection<int,int> (kOrigPairValueInit_), Bijection<int,int> (kUPairpdateValueInit_), 1000);
DoItOnce_<Collection<int>> (Collection<int> (kOrigValueInit_), Collection<int> (kUpdateValueInit_), 1000);
//DoItOnce_<Deque<int>> (Deque<int> (kOrigValueInit_), Deque<int> (kUpdateValueInit_), 1000);
DoItOnce_<Mapping<int,int>> (Mapping<int,int> (kOrigPairValueInit_), Mapping<int,int> (kUPairpdateValueInit_), 1000);
DoItOnce_<Sequence<int>> (Sequence<int> (kOrigValueInit_), Sequence<int> (kUpdateValueInit_), 1000);
DoItOnce_<Set<int>> (Set<int> (kOrigValueInit_), Set<int> (kUpdateValueInit_), 1000);
DoItOnce_<SortedSet<int>> (SortedSet<int> (kOrigValueInit_), SortedSet<int> (kUpdateValueInit_), 1000);
}
}
}
namespace {
namespace IterateWhileMutatingContainer_Test_2_ {
template <typename ITERABLE_TYPE, typename LOCK, typename MUTATE_FUNCTION>
void DoItOnce_ (LOCK* lock, ITERABLE_TYPE elt1, unsigned int repeatCount, MUTATE_FUNCTION baseMutateFunction)
{
ITERABLE_TYPE oneToKeepOverwriting = elt1;
auto mutateFunction = [&oneToKeepOverwriting, lock, repeatCount, &baseMutateFunction] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
baseMutateFunction (&oneToKeepOverwriting);
}
};
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, lock, repeatCount);
Thread mutateThread = mutateFunction;
RunThreads_ ({iterateThread, mutateThread});
}
void DoIt ()
{
// This test demonstrates the need for qStroika_Foundation_Traveral_IteratorHoldsSharedPtr_
Debug::TraceContextBumper traceCtx (SDKSTR ("IterateWhileMutatingContainer_Test_2_::DoIt ()"));
// @TODO - DEBUG!!!!
//no_lock_ lock;
mutex lock;
DoItOnce_<Set<int>> (
&lock,
Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}),
1000,
[&lock] (Set<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
}
});
}
}
}
namespace {
void DoRegressionTests_ ()
{
AssignAndIterateAtSameTimeTest_1_::DoIt ();
IterateWhileMutatingContainer_Test_2_::DoIt ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>progres enhancing regtest ThreadSafetyBuiltinObject<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Execution::ThreadSafetyBuiltinObject
#include "Stroika/Foundation/StroikaPreComp.h"
#include <mutex>
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Containers/Bijection.h"
#include "Stroika/Foundation/Containers/Collection.h"
#include "Stroika/Foundation/Containers/Deque.h"
#include "Stroika/Foundation/Containers/Queue.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Containers/MultiSet.h"
#include "Stroika/Foundation/Containers/Sequence.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Containers/Stack.h"
#include "Stroika/Foundation/Containers/SortedCollection.h"
#include "Stroika/Foundation/Containers/SortedMapping.h"
#include "Stroika/Foundation/Containers/SortedMultiSet.h"
#include "Stroika/Foundation/Containers/SortedSet.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Math/Common.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Containers;
using Execution::Thread;
using Execution::WaitableEvent;
namespace {
/*
* To REALLY this this code for thread-safety, use ExternallySynchronizedLock, but to verify it works
* without worrying about races, just use mutex.
*/
struct no_lock_ {
void lock () {}
void unlock () {}
};
}
namespace {
void RunThreads_ (const initializer_list<Thread>& threads)
{
for (Thread i : threads) {
i.Start ();
}
for (Thread i : threads) {
i.WaitForDone ();
}
}
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkIterateOverThread_ (ITERABLE_TYPE* iterable, LOCK_TYPE* lock, unsigned int repeatCount)
{
using ElementType = typename ITERABLE_TYPE::ElementType;
return Thread ([iterable, lock, repeatCount] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
lock_guard<decltype(*lock)> critSec (*lock);
for (ElementType e : *iterable) {
ElementType e2 = e; // do something
}
}
});
};
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkOverwriteThread_ (ITERABLE_TYPE* oneToKeepOverwriting, ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, LOCK_TYPE* lock, unsigned int repeatCount)
{
return Thread ([oneToKeepOverwriting, lock, repeatCount, elt1, elt2] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt1;
}
else {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt2;
}
}
}
});
};
}
namespace {
namespace AssignAndIterateAtSameTimeTest_1_ {
template <typename ITERABLE_TYPE>
void DoItOnce_ (ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, unsigned int repeatCount)
{
no_lock_ lock ;
//mutex lock;
ITERABLE_TYPE oneToKeepOverwriting = elt1;
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, &lock, repeatCount);
Thread overwriteThread = mkOverwriteThread_ (&oneToKeepOverwriting, elt1, elt2, &lock, repeatCount);
RunThreads_ ({iterateThread, overwriteThread});
}
void DoIt ()
{
static const initializer_list<int> kOrigValueInit_ = {1, 3, 4, 5, 6, 33, 12, 13};
static const initializer_list<int> kUpdateValueInit_ = {4, 5, 6, 33, 12, 34, 596, 13, 1, 3, 99, 33, 4, 5};
static const initializer_list<pair<int, int>> kOrigPairValueInit_ = {pair<int, int> (1, 3), pair<int, int> (4, 5), pair<int, int> (6, 33), pair<int, int> (12, 13)};
static const initializer_list<pair<int, int>> kUPairpdateValueInit_ = {pair<int, int> (4, 5), pair<int, int> (6, 33), pair<int, int> (12, 34), pair<int, int> (596, 13), pair<int, int> (1, 3), pair<int, int> (99, 33), pair<int, int> (4, 5)};
Debug::TraceContextBumper traceCtx (SDKSTR ("AssignAndIterateAtSameTimeTest_1_::DoIt ()"));
DoItOnce_<String> (String (L"123456789"), String (L"abcdedfghijkqlmopqrstuvwxyz"), 1000);
DoItOnce_<Bijection<int, int>> (Bijection<int, int> (kOrigPairValueInit_), Bijection<int, int> (kUPairpdateValueInit_), 1000);
DoItOnce_<Collection<int>> (Collection<int> (kOrigValueInit_), Collection<int> (kUpdateValueInit_), 1000);
// Queue/Deque NYI here cuz of assign from initializer
//DoItOnce_<Deque<int>> (Deque<int> (kOrigValueInit_), Deque<int> (kUpdateValueInit_), 1000);
//DoItOnce_<Queue<int>> (Queue<int> (kOrigValueInit_), Queue<int> (kUpdateValueInit_), 1000);
DoItOnce_<MultiSet<int>> (MultiSet<int> (kOrigValueInit_), MultiSet<int> (kUpdateValueInit_), 1000);
DoItOnce_<Mapping<int, int>> (Mapping<int, int> (kOrigPairValueInit_), Mapping<int, int> (kUPairpdateValueInit_), 1000);
DoItOnce_<Sequence<int>> (Sequence<int> (kOrigValueInit_), Sequence<int> (kUpdateValueInit_), 1000);
DoItOnce_<Set<int>> (Set<int> (kOrigValueInit_), Set<int> (kUpdateValueInit_), 1000);
DoItOnce_<SortedMapping<int, int>> (SortedMapping<int, int> (kOrigPairValueInit_), SortedMapping<int, int> (kUPairpdateValueInit_), 1000);
DoItOnce_<SortedMultiSet<int>> (SortedMultiSet<int> (kOrigValueInit_), SortedMultiSet<int> (kUpdateValueInit_), 1000);
DoItOnce_<SortedSet<int>> (SortedSet<int> (kOrigValueInit_), SortedSet<int> (kUpdateValueInit_), 1000);
// Stack NYI cuz not enough of stack implemented (op=)
//DoItOnce_<Stack<int>> (Stack<int> (kOrigValueInit_), Stack<int> (kUpdateValueInit_), 1000);
}
}
}
namespace {
namespace IterateWhileMutatingContainer_Test_2_ {
template <typename ITERABLE_TYPE, typename LOCK, typename MUTATE_FUNCTION>
void DoItOnce_ (LOCK* lock, ITERABLE_TYPE elt1, unsigned int repeatCount, MUTATE_FUNCTION baseMutateFunction)
{
ITERABLE_TYPE oneToKeepOverwriting = elt1;
auto mutateFunction = [&oneToKeepOverwriting, lock, repeatCount, &baseMutateFunction] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
baseMutateFunction (&oneToKeepOverwriting);
}
};
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, lock, repeatCount);
Thread mutateThread = mutateFunction;
RunThreads_ ({iterateThread, mutateThread});
}
void DoIt ()
{
// This test demonstrates the need for qStroika_Foundation_Traveral_IteratorHoldsSharedPtr_
Debug::TraceContextBumper traceCtx (SDKSTR ("IterateWhileMutatingContainer_Test_2_::DoIt ()"));
// @TODO - DEBUG!!!!
no_lock_ lock;
//mutex lock;
#if 0
// doesnt work with 'no_lock' but does with mutext lock
// @todo - FIX - cuz of RACE CONDITION STILL
DoItOnce_<Set<int>> (
&lock,
Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}),
1000,
[&lock] (Set<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
}
});
#endif
DoItOnce_<String> (
&lock,
String (L"123456789"),
1000,
[&lock] (String * oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = String {L"abc123"};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = String {L"123abc"};
}
}
});
}
}
}
namespace {
void DoRegressionTests_ ()
{
AssignAndIterateAtSameTimeTest_1_::DoIt ();
IterateWhileMutatingContainer_Test_2_::DoIt ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
// TEST Foundation::DataExchange::Other
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/DataExchange/Atom.h"
#include "Stroika/Foundation/DataExchange/InternetMediaType.h"
#include "Stroika/Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "Stroika/Foundation/DataExchange/OptionsFile.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/ModuleGetterSetter.h"
#include "Stroika/Foundation/IO/FileSystem/PathName.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "Stroika/Foundation/Streams/ExternallyOwnedMemoryInputStream.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchange;
using Execution::ModuleGetterSetter;
namespace {
void Test1_Atom_ ()
{
Debug::TraceContextBumper ctx{"{}::Test1_Atom_"};
{
Atom<> a = L"d";
Atom<> b = L"d";
VerifyTestResult (a == b);
VerifyTestResult (a.GetPrintName () == L"d");
VerifyTestResult (a.As<String> () == L"d");
VerifyTestResult (a.As<wstring> () == L"d");
VerifyTestResult (not a.empty ());
}
{
VerifyTestResult (Atom<> ().empty ());
}
{
Atom<> a = L"d";
Atom<> b = L"e";
VerifyTestResult (a != b);
VerifyTestResult (not a.empty ());
Atom<> c = a;
VerifyTestResult (c == a);
}
}
}
namespace {
void Test2_OptionsFile_ ()
{
Debug::TraceContextBumper ctx{"{}::Test2_OptionsFile_"};
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
OptionsFile of{
L"MyModule",
[] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", StructFieldMetaInfo{&MyData_::fEnabled}},
{L"Last-Synchronized-At", StructFieldMetaInfo{&MyData_::fLastSynchronizedAt}},
});
return mapper;
}(),
OptionsFile::kDefaultUpgrader,
[] (const String& moduleName, const String& fileSuffix) -> filesystem::path {
return IO::FileSystem::WellKnownLocations::GetTemporary () / IO::FileSystem::ToPath (moduleName + fileSuffix);
}};
MyData_ m = of.Read<MyData_> (MyData_ ()); // will return default values if file not present
of.Write (m); // test writing
}
}
namespace {
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
struct ModuleGetterSetter_Implementation_MyData_ {
ModuleGetterSetter_Implementation_MyData_ ()
: fOptionsFile_{
L"MyModule",
[] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", StructFieldMetaInfo{&MyData_::fEnabled}},
{L"Last-Synchronized-At", StructFieldMetaInfo{&MyData_::fLastSynchronizedAt}},
});
return mapper;
}(),
OptionsFile::kDefaultUpgrader,
[] (const String& moduleName, const String& fileSuffix) -> filesystem::path {
// for regression tests write to /tmp
return IO::FileSystem::WellKnownLocations::GetTemporary () / IO::FileSystem::ToPath (moduleName + fileSuffix);
}}
, fActualCurrentConfigData_{fOptionsFile_.Read<MyData_> (MyData_{})}
{
Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date
}
MyData_ Get () const
{
return fActualCurrentConfigData_;
}
void Set (const MyData_& v)
{
fActualCurrentConfigData_ = v;
fOptionsFile_.Write (v);
}
private:
OptionsFile fOptionsFile_;
MyData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized
};
ModuleGetterSetter<MyData_, ModuleGetterSetter_Implementation_MyData_> sModuleConfiguration_;
void Test3_ModuleGetterSetter_ ()
{
Debug::TraceContextBumper ctx{"{}::Test3_ModuleGetterSetter_"};
if (sModuleConfiguration_.Get ().fEnabled) {
auto n = sModuleConfiguration_.Get ();
sModuleConfiguration_.Set (n);
}
}
}
namespace Test4_VariantValue_ {
void RunTests ()
{
Debug::TraceContextBumper ctx{"{}::Test4_VariantValue_"};
Containers::Collection<VariantValue> vc;
VariantValue vv{vc};
}
}
namespace {
namespace Test5_InternetMediaType_ {
void RunTests ()
{
Debug::TraceContextBumper ctx{"{}::Test5_InternetMediaType_"};
{
InternetMediaType ct0{L"text/plain"};
VerifyTestResult (ct0.GetType () == L"text");
VerifyTestResult (ct0.GetSubType () == L"plain");
VerifyTestResult (ct0.GetSuffix () == nullopt);
InternetMediaType ct1{L"text/plain;charset=ascii"};
VerifyTestResult ((ct1.GetParameters () == Containers::Mapping{Common::KeyValuePair<String, String>{L"charset", L"ascii"}}));
VerifyTestResult (ct1.GetSuffix () == nullopt);
InternetMediaType ct2{L"text/plain; charset = ascii"};
VerifyTestResult (ct1 == ct2);
InternetMediaType ct3{L"text/plain; charset = \"ascii\""};
VerifyTestResult (ct1 == ct3);
InternetMediaType ct4{L"text/plain; charset = \"ASCII\""}; // case insensitive compare key, but not value
VerifyTestResult (ct1 != ct4);
InternetMediaType ct5{L"application/vnd.ms-excel"};
VerifyTestResult (ct5.GetType () == L"application");
VerifyTestResult (ct5.GetSubType () == L"vnd.ms-excel");
VerifyTestResult (ct5.GetSuffix () == nullopt);
InternetMediaType ct6{L"application/mathml+xml"};
VerifyTestResult (ct6.GetType () == L"application");
VerifyTestResult (ct6.GetSubType () == L"mathml");
VerifyTestResult (ct6.GetSuffix () == L"xml");
VerifyTestResult (ct6.As<wstring> () == L"application/mathml+xml");
}
{
// Example from https://tools.ietf.org/html/rfc2045#page-10 - comments ignored, and quotes on value
InternetMediaType ct1{L"text/plain; charset=us-ascii (Plain text)"};
InternetMediaType ct2{L"text/plain; charset=\"us-ascii\""};
VerifyTestResult (ct1 == ct2);
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (ct1));
}
{
auto dumpCT = [] (const String& label, InternetMediaType i) {
[[maybe_unused]] InternetMediaTypeRegistry r = InternetMediaTypeRegistry::Get ();
DbgTrace (L"SUFFIX(%s)=%s", label.c_str (), Characters::ToString (r.GetPreferredAssociatedFileSuffix (i)).c_str ());
DbgTrace (L"ASSOCFILESUFFIXES(%s)=%s", label.c_str (), Characters::ToString (r.GetAssociatedFileSuffixes (i)).c_str ());
DbgTrace (L"GetAssociatedPrettyName(%s)=%s", label.c_str (), Characters::ToString (r.GetAssociatedPrettyName (i)).c_str ());
};
auto checkCT = [] (InternetMediaType i, const Set<String>& possibleFileSuffixes) {
[[maybe_unused]] InternetMediaTypeRegistry r = InternetMediaTypeRegistry::Get ();
using namespace Characters;
if (not possibleFileSuffixes.Contains (r.GetPreferredAssociatedFileSuffix (i).value_or (L""))) {
Stroika::TestHarness::WarnTestIssue (
Format (L"File suffix mismatch for %s: got %s, expected %s", ToString (i).c_str (), ToString (r.GetPreferredAssociatedFileSuffix (i)).c_str (), ToString (possibleFileSuffixes).c_str ()).c_str ());
}
if (not possibleFileSuffixes.Any ([&] (String suffix) -> bool { return r.GetAssociatedContentType (suffix) == i; })) {
Stroika::TestHarness::WarnTestIssue (
Format (L"GetAssociatedContentType for fileSuffixes %s (expected %s, got %s)",
ToString (possibleFileSuffixes).c_str (),
ToString (i).c_str (),
ToString (possibleFileSuffixes.Select<InternetMediaType> ([&] (String suffix) { return r.GetAssociatedContentType (suffix); }).As<Set<InternetMediaType>> ()).c_str ())
.c_str ());
}
};
dumpCT (L"PLAINTEXT", InternetMediaTypes::kText_PLAIN);
checkCT (InternetMediaTypes::kText_PLAIN, {L".txt"});
dumpCT (L"HTML", InternetMediaTypes::kHTML);
checkCT (InternetMediaTypes::kHTML, {L".html", L".htm"});
dumpCT (L"JSON", InternetMediaTypes::kJSON);
checkCT (InternetMediaTypes::kJSON, {L".json"});
dumpCT (L"PNG", InternetMediaTypes::kPNG);
checkCT (InternetMediaTypes::kPNG, {L".png"});
{
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsImageFormat (InternetMediaTypes::kPNG));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsImageFormat (InternetMediaTypes::kJSON));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaTypes::kXML));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaTypes::kText_PLAIN));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kText_PLAIN));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kXML));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kHTML));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kJSON));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kPNG));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaType{L"text/foobar"}));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaType{L"text/foobar+xml"}));
}
}
{
Debug::TraceContextBumper ctx1 ("InternetMediaTypeRegistry::Get ().GetMediaTypes()");
// enumerate all content types
for (auto ct : InternetMediaTypeRegistry::Get ().GetMediaTypes ()) {
DbgTrace (L"i=%s", Characters::ToString (ct).c_str ());
}
}
{
Debug::TraceContextBumper ctx1 ("InternetMediaTypeRegistry - updating");
InternetMediaTypeRegistry origRegistry = InternetMediaTypeRegistry::Get ();
InternetMediaTypeRegistry updatedRegistry = origRegistry;
const auto kHFType_ = InternetMediaType{L"application/fake-heatlthframe-phr+xml"};
VerifyTestResult (not InternetMediaTypeRegistry::Get ().GetMediaTypes ().Contains (kHFType_));
updatedRegistry.AddOverride (kHFType_, InternetMediaTypeRegistry::OverrideRecord{nullopt, Containers::Set<String>{L".HPHR"}, L".HPHR"});
InternetMediaTypeRegistry::Set (updatedRegistry);
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsXMLFormat (kHFType_));
VerifyTestResult (InternetMediaTypeRegistry::Get ().GetMediaTypes ().Contains (kHFType_));
VerifyTestResult (not origRegistry.GetMediaTypes ().Contains (kHFType_));
VerifyTestResult (updatedRegistry.GetMediaTypes ().Contains (kHFType_));
}
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Atom_ ();
Test2_OptionsFile_ ();
Test3_ModuleGetterSetter_ ();
Test4_VariantValue_::RunTests ();
Test5_InternetMediaType_::RunTests ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>added Execution::Logger::Activator logMgrActivator; for regtest with OptionsFile<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
// TEST Foundation::DataExchange::Other
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/DataExchange/Atom.h"
#include "Stroika/Foundation/DataExchange/InternetMediaType.h"
#include "Stroika/Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "Stroika/Foundation/DataExchange/OptionsFile.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/ModuleGetterSetter.h"
#include "Stroika/Foundation/Execution/Logger.h"
#include "Stroika/Foundation/IO/FileSystem/PathName.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "Stroika/Foundation/Streams/ExternallyOwnedMemoryInputStream.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchange;
using Execution::ModuleGetterSetter;
namespace {
void Test1_Atom_ ()
{
Debug::TraceContextBumper ctx{"{}::Test1_Atom_"};
{
Atom<> a = L"d";
Atom<> b = L"d";
VerifyTestResult (a == b);
VerifyTestResult (a.GetPrintName () == L"d");
VerifyTestResult (a.As<String> () == L"d");
VerifyTestResult (a.As<wstring> () == L"d");
VerifyTestResult (not a.empty ());
}
{
VerifyTestResult (Atom<> ().empty ());
}
{
Atom<> a = L"d";
Atom<> b = L"e";
VerifyTestResult (a != b);
VerifyTestResult (not a.empty ());
Atom<> c = a;
VerifyTestResult (c == a);
}
}
}
namespace {
void Test2_OptionsFile_ ()
{
Debug::TraceContextBumper ctx{"{}::Test2_OptionsFile_"};
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
OptionsFile of{
L"MyModule",
[] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", StructFieldMetaInfo{&MyData_::fEnabled}},
{L"Last-Synchronized-At", StructFieldMetaInfo{&MyData_::fLastSynchronizedAt}},
});
return mapper;
}(),
OptionsFile::kDefaultUpgrader,
[] (const String& moduleName, const String& fileSuffix) -> filesystem::path {
return IO::FileSystem::WellKnownLocations::GetTemporary () / IO::FileSystem::ToPath (moduleName + fileSuffix);
}};
MyData_ m = of.Read<MyData_> (MyData_ ()); // will return default values if file not present
of.Write (m); // test writing
}
}
namespace {
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
struct ModuleGetterSetter_Implementation_MyData_ {
ModuleGetterSetter_Implementation_MyData_ ()
: fOptionsFile_{
L"MyModule",
[] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", StructFieldMetaInfo{&MyData_::fEnabled}},
{L"Last-Synchronized-At", StructFieldMetaInfo{&MyData_::fLastSynchronizedAt}},
});
return mapper;
}(),
OptionsFile::kDefaultUpgrader,
[] (const String& moduleName, const String& fileSuffix) -> filesystem::path {
// for regression tests write to /tmp
return IO::FileSystem::WellKnownLocations::GetTemporary () / IO::FileSystem::ToPath (moduleName + fileSuffix);
}}
, fActualCurrentConfigData_{fOptionsFile_.Read<MyData_> (MyData_{})}
{
Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date
}
MyData_ Get () const
{
return fActualCurrentConfigData_;
}
void Set (const MyData_& v)
{
fActualCurrentConfigData_ = v;
fOptionsFile_.Write (v);
}
private:
OptionsFile fOptionsFile_;
MyData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized
};
ModuleGetterSetter<MyData_, ModuleGetterSetter_Implementation_MyData_> sModuleConfiguration_;
void Test3_ModuleGetterSetter_ ()
{
Debug::TraceContextBumper ctx{"{}::Test3_ModuleGetterSetter_"};
if (sModuleConfiguration_.Get ().fEnabled) {
auto n = sModuleConfiguration_.Get ();
sModuleConfiguration_.Set (n);
}
}
}
namespace Test4_VariantValue_ {
void RunTests ()
{
Debug::TraceContextBumper ctx{"{}::Test4_VariantValue_"};
Containers::Collection<VariantValue> vc;
VariantValue vv{vc};
}
}
namespace {
namespace Test5_InternetMediaType_ {
void RunTests ()
{
Debug::TraceContextBumper ctx{"{}::Test5_InternetMediaType_"};
{
InternetMediaType ct0{L"text/plain"};
VerifyTestResult (ct0.GetType () == L"text");
VerifyTestResult (ct0.GetSubType () == L"plain");
VerifyTestResult (ct0.GetSuffix () == nullopt);
InternetMediaType ct1{L"text/plain;charset=ascii"};
VerifyTestResult ((ct1.GetParameters () == Containers::Mapping{Common::KeyValuePair<String, String>{L"charset", L"ascii"}}));
VerifyTestResult (ct1.GetSuffix () == nullopt);
InternetMediaType ct2{L"text/plain; charset = ascii"};
VerifyTestResult (ct1 == ct2);
InternetMediaType ct3{L"text/plain; charset = \"ascii\""};
VerifyTestResult (ct1 == ct3);
InternetMediaType ct4{L"text/plain; charset = \"ASCII\""}; // case insensitive compare key, but not value
VerifyTestResult (ct1 != ct4);
InternetMediaType ct5{L"application/vnd.ms-excel"};
VerifyTestResult (ct5.GetType () == L"application");
VerifyTestResult (ct5.GetSubType () == L"vnd.ms-excel");
VerifyTestResult (ct5.GetSuffix () == nullopt);
InternetMediaType ct6{L"application/mathml+xml"};
VerifyTestResult (ct6.GetType () == L"application");
VerifyTestResult (ct6.GetSubType () == L"mathml");
VerifyTestResult (ct6.GetSuffix () == L"xml");
VerifyTestResult (ct6.As<wstring> () == L"application/mathml+xml");
}
{
// Example from https://tools.ietf.org/html/rfc2045#page-10 - comments ignored, and quotes on value
InternetMediaType ct1{L"text/plain; charset=us-ascii (Plain text)"};
InternetMediaType ct2{L"text/plain; charset=\"us-ascii\""};
VerifyTestResult (ct1 == ct2);
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (ct1));
}
{
auto dumpCT = [] (const String& label, InternetMediaType i) {
[[maybe_unused]] InternetMediaTypeRegistry r = InternetMediaTypeRegistry::Get ();
DbgTrace (L"SUFFIX(%s)=%s", label.c_str (), Characters::ToString (r.GetPreferredAssociatedFileSuffix (i)).c_str ());
DbgTrace (L"ASSOCFILESUFFIXES(%s)=%s", label.c_str (), Characters::ToString (r.GetAssociatedFileSuffixes (i)).c_str ());
DbgTrace (L"GetAssociatedPrettyName(%s)=%s", label.c_str (), Characters::ToString (r.GetAssociatedPrettyName (i)).c_str ());
};
auto checkCT = [] (InternetMediaType i, const Set<String>& possibleFileSuffixes) {
[[maybe_unused]] InternetMediaTypeRegistry r = InternetMediaTypeRegistry::Get ();
using namespace Characters;
if (not possibleFileSuffixes.Contains (r.GetPreferredAssociatedFileSuffix (i).value_or (L""))) {
Stroika::TestHarness::WarnTestIssue (
Format (L"File suffix mismatch for %s: got %s, expected %s", ToString (i).c_str (), ToString (r.GetPreferredAssociatedFileSuffix (i)).c_str (), ToString (possibleFileSuffixes).c_str ()).c_str ());
}
if (not possibleFileSuffixes.Any ([&] (String suffix) -> bool { return r.GetAssociatedContentType (suffix) == i; })) {
Stroika::TestHarness::WarnTestIssue (
Format (L"GetAssociatedContentType for fileSuffixes %s (expected %s, got %s)",
ToString (possibleFileSuffixes).c_str (),
ToString (i).c_str (),
ToString (possibleFileSuffixes.Select<InternetMediaType> ([&] (String suffix) { return r.GetAssociatedContentType (suffix); }).As<Set<InternetMediaType>> ()).c_str ())
.c_str ());
}
};
dumpCT (L"PLAINTEXT", InternetMediaTypes::kText_PLAIN);
checkCT (InternetMediaTypes::kText_PLAIN, {L".txt"});
dumpCT (L"HTML", InternetMediaTypes::kHTML);
checkCT (InternetMediaTypes::kHTML, {L".html", L".htm"});
dumpCT (L"JSON", InternetMediaTypes::kJSON);
checkCT (InternetMediaTypes::kJSON, {L".json"});
dumpCT (L"PNG", InternetMediaTypes::kPNG);
checkCT (InternetMediaTypes::kPNG, {L".png"});
{
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsImageFormat (InternetMediaTypes::kPNG));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsImageFormat (InternetMediaTypes::kJSON));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaTypes::kXML));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaTypes::kText_PLAIN));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kText_PLAIN));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kXML));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kHTML));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kJSON));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsTextFormat (InternetMediaTypes::kPNG));
VerifyTestResult (not InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaType{L"text/foobar"}));
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsXMLFormat (InternetMediaType{L"text/foobar+xml"}));
}
}
{
Debug::TraceContextBumper ctx1 ("InternetMediaTypeRegistry::Get ().GetMediaTypes()");
// enumerate all content types
for (auto ct : InternetMediaTypeRegistry::Get ().GetMediaTypes ()) {
DbgTrace (L"i=%s", Characters::ToString (ct).c_str ());
}
}
{
Debug::TraceContextBumper ctx1 ("InternetMediaTypeRegistry - updating");
InternetMediaTypeRegistry origRegistry = InternetMediaTypeRegistry::Get ();
InternetMediaTypeRegistry updatedRegistry = origRegistry;
const auto kHFType_ = InternetMediaType{L"application/fake-heatlthframe-phr+xml"};
VerifyTestResult (not InternetMediaTypeRegistry::Get ().GetMediaTypes ().Contains (kHFType_));
updatedRegistry.AddOverride (kHFType_, InternetMediaTypeRegistry::OverrideRecord{nullopt, Containers::Set<String>{L".HPHR"}, L".HPHR"});
InternetMediaTypeRegistry::Set (updatedRegistry);
VerifyTestResult (InternetMediaTypeRegistry::Get ().IsXMLFormat (kHFType_));
VerifyTestResult (InternetMediaTypeRegistry::Get ().GetMediaTypes ().Contains (kHFType_));
VerifyTestResult (not origRegistry.GetMediaTypes ().Contains (kHFType_));
VerifyTestResult (updatedRegistry.GetMediaTypes ().Contains (kHFType_));
}
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Atom_ ();
Test2_OptionsFile_ ();
Test3_ModuleGetterSetter_ ();
Test4_VariantValue_::RunTests ();
Test5_InternetMediaType_::RunTests ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Execution::Logger::Activator logMgrActivator; // for OptionsFile test
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////
//
// NAME
// WarpSpherical.h -- warp a flat (perspective) image into spherical
// coordinates and/or undo radial lens distortion
//
// SEE ALSO
// WarpSpherical.h longer description
//
// R. Szeliski and H.-Y. Shum.
// Creating full view panoramic image mosaics and texture-mapped models.
// Computer Graphics (SIGGRAPH'97), pages 251-258, August 1997.
//
// Copyright ?Richard Szeliski, 2001. See Copyright.h for more details
// (modified for CSE576 Spring 2005)
//
///////////////////////////////////////////////////////////////////////////
#include "ImageLib/ImageLib.h"
#include "WarpSpherical.h"
#include <math.h>
/******************* TO DO *********************
* warpSphericalField:
* INPUT:
* srcSh: shape (width, height, number of channels) of source image
* dstSh: shape of destination image
* f: focal length in pixels (provided on the project web page, or measured by yourself)
* k1, k2: radial distortion parameters (ditto)
* r: rotation matrix
* OUTPUT:
* Return an image containing (u,v) coordinates for mapping pixels from
* spherical coordinates to planar image coordinates and applying
* radial distortion.
* Note that this is inverse warping, i.e., this routine will be
* actually used to map from planar coordinates with radial distortion
* to spherical coordinates without radial distortion.
*
*/
CFloatImage WarpSphericalField(CShape srcSh, CShape dstSh, float f,
float k1, float k2, const CTransform3x3 &r)
{
// Set up the pixel coordinate image
dstSh.nBands = 2;
CFloatImage uvImg(dstSh); // (u,v) coordinates
CVector3 p;
p[0] = sin(0.0) * cos(0.0);
p[1] = sin(0.0);
p[2] = cos(0.0) * cos(0.0);
p = r * p;
double min_y = p[1];
// Fill in the values
for (int y = 0; y < dstSh.height; y++) {
float *uv = &uvImg.Pixel(0, y, 0);
for (int x = 0; x < dstSh.width; x++, uv += 2) {
// (x,y) is the spherical image coordinates.
// (xf,yf) is the spherical coordinates, e.g., xf is the angle theta
// and yf is the angle phi
float xf = (float) ((x - 0.5f*dstSh.width ) / f);
float yf = (float) ((y - 0.5f*dstSh.height) / f - min_y);
// (xt,yt,zt) are intermediate coordinates to which you can
// apply the spherical correction and radial distortion
float xt, yt;
CVector3 p;
// BEGIN TODO
// add code to apply the spherical correction, i.e.,
// compute the Euclidean coordinates, rotate according to
// r, and project the point to the z=1 plane at
// (xt/zt,yt/zt,1), then distort with radial distortion
// coefficients k1 and k2
// END TODO
// Convert back to regular pixel coordinates and store
float xn = 0.5f*srcSh.width + xt*f;
float yn = 0.5f*srcSh.height + yt*f;
uv[0] = xn;
uv[1] = yn;
}
}
return uvImg;
}
<commit_msg>sphrWarp done<commit_after>///////////////////////////////////////////////////////////////////////////
//
// NAME
// WarpSpherical.h -- warp a flat (perspective) image into spherical
// coordinates and/or undo radial lens distortion
//
// SEE ALSO
// WarpSpherical.h longer description
//
// R. Szeliski and H.-Y. Shum.
// Creating full view panoramic image mosaics and texture-mapped models.
// Computer Graphics (SIGGRAPH'97), pages 251-258, August 1997.
//
// Copyright ?Richard Szeliski, 2001. See Copyright.h for more details
// (modified for CSE576 Spring 2005)
//
///////////////////////////////////////////////////////////////////////////
#include "ImageLib/ImageLib.h"
#include "WarpSpherical.h"
#include <math.h>
/******************* TO DO *********************
* warpSphericalField:
* INPUT:
* srcSh: shape (width, height, number of channels) of source image
* dstSh: shape of destination image
* f: focal length in pixels (provided on the project web page, or measured by yourself)
* k1, k2: radial distortion parameters (ditto)
* r: rotation matrix
* OUTPUT:
* Return an image containing (u,v) coordinates for mapping pixels from
* spherical coordinates to planar image coordinates and applying
* radial distortion.
* Note that this is inverse warping, i.e., this routine will be
* actually used to map from planar coordinates with radial distortion
* to spherical coordinates without radial distortion.
*
*/
CFloatImage WarpSphericalField(CShape srcSh, CShape dstSh, float f,
float k1, float k2, const CTransform3x3 &r)
{
// Set up the pixel coordinate image
dstSh.nBands = 2;
CFloatImage uvImg(dstSh); // (u,v) coordinates
CVector3 p;
p[0] = sin(0.0) * cos(0.0);
p[1] = sin(0.0);
p[2] = cos(0.0) * cos(0.0);
p = r * p;
double min_y = p[1];
// Fill in the values
for (int y = 0; y < dstSh.height; y++) {
float *uv = &uvImg.Pixel(0, y, 0);
for (int x = 0; x < dstSh.width; x++, uv += 2) {
// (x,y) is the spherical image coordinates.
// (xf,yf) is the spherical coordinates, e.g., xf is the angle theta
// and yf is the angle phi
float xf = (float) ((x - 0.5f*dstSh.width ) / f);
float yf = (float) ((y - 0.5f*dstSh.height) / f - min_y);
// (xt,yt,zt) are intermediate coordinates to which you can
// apply the spherical correction and radial distortion
float xt, yt;
CVector3 p;
// BEGIN TODO
// add code to apply the spherical correction, i.e.,
// compute the Euclidean coordinates, rotate according to
// r, and project the point to the z=1 plane at
// (xt/zt,yt/zt,1), then distort with radial distortion
// coefficients k1 and k2
// Compute Euclidean coordinates
p[0] = sin(xf) * cos(yf);
p[1] = sin(yf);
p[2] = cos(xf) * cos(yf);
// Rotate
p = r * p;
// Project
p[0] /= p[2];
p[1] /= p[2];
p[2] = 1;
// Distort
float radius2 = p[0]*p[0] + p[1]*p[1];
xt = p[0] * (1 + k1*radius2 + k2*radius2*radius2);
yt = p[1] * (1 + k1*radius2 + k2*radius2*radius2);
// END TODO
// Convert back to regular pixel coordinates and store
float xn = 0.5f*srcSh.width + xt*f;
float yn = 0.5f*srcSh.height + yt*f;
uv[0] = xn;
uv[1] = yn;
}
}
return uvImg;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbQtLogOutput.h"
int otbQtLogOutputNew(int /*argc*/, char** /*argv[]*/)
{
otb::QtLogOutput::Pointer log = otb::QtLogOutput::New();
return EXIT_SUCCESS;
}
<commit_msg>COMP: fix compilation on windows<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbQtLogOutput.h"
int otbQtLogOutputNew(int /*argc*/, char* /*argv*/ [])
{
otb::QtLogOutput::Pointer log = otb::QtLogOutput::New();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Cards.h>
#include <better-enums/enum.h>
#include <clara.hpp>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace Hearthstonepp;
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
inline std::string ToString(const clara::Opt& opt)
{
std::ostringstream oss;
oss << (clara::Parser() | opt);
return oss.str();
}
inline std::string ToString(const clara::Parser& p)
{
std::ostringstream oss;
oss << p;
return oss.str();
}
inline std::vector<GameTag> CheckAbilityImpl(const std::string& path)
{
std::map<std::string, GameTag> abilityStrMap = {
{ "Charge", GameTag::CHARGE },
{ "DivineShield", GameTag::DIVINE_SHIELD },
{ "Freeze", GameTag::FREEZE },
{ "Poisonous", GameTag::POISONOUS },
{ "Taunt", GameTag::TAUNT },
{ "Windfury", GameTag::WINDFURY }
};
#ifndef HEARTHSTONEPP_MACOSX
const filesystem::path p(
path + "/Tests/UnitTests/Tasks/BasicTasks/CombatTaskTests.cpp");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_regular_file(p))
{
std::cerr << p << " exists, but is not regular file\n";
exit(EXIT_FAILURE);
}
std::ifstream abilityFile;
abilityFile.open(p.string());
if (!abilityFile.is_open())
{
std::cerr << p << " couldn't open\n";
exit(EXIT_FAILURE);
}
std::vector<GameTag> result;
std::string line;
while (std::getline(abilityFile, line))
{
for (auto& ability : abilityStrMap)
{
std::string sentence = "TEST(CombatTask, " + ability.first + ")";
if (line.find(sentence, 0) != std::string::npos)
{
result.emplace_back(ability.second);
break;
}
}
}
#else
std::cerr << "CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return result;
}
inline std::vector<Card> QueryCardSetList(const std::string& projectPath,
CardSet cardSet, bool implCardOnly)
{
if (cardSet == +CardSet::ALL)
{
return Cards::GetInstance()->GetAllCards();
}
std::vector<GameTag> implementedAbilityList{};
if (implCardOnly)
{
implementedAbilityList = CheckAbilityImpl(projectPath);
}
std::vector<Card> result;
for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
{
if (implCardOnly)
{
// TODO: Check abilities in card are all implemented
}
else
{
result.emplace_back(card);
}
}
return result;
}
inline bool CheckCardImpl(const std::string& path, const std::string& id)
{
#ifndef HEARTHSTONEPP_MACOSX
const filesystem::path p(path + "/Tests/UnitTests/CardSets");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_directory(p))
{
std::cerr << p << " exists, but is not directory\n";
exit(EXIT_FAILURE);
}
for (auto&& file : filesystem::recursive_directory_iterator(p))
{
std::regex fileNamePattern(R"(.*\\(.*)\..*$)");
std::smatch match;
std::string pathStr = file.path().string();
if (std::regex_match(pathStr, match, fileNamePattern))
{
if (match[1] == id)
{
return true;
}
}
}
#else
std::cerr
<< "CheckCardImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return false;
}
inline void ExportFile(const std::string& projectPath, std::vector<Card>& cards)
{
std::ofstream outputFile("result.md");
if (outputFile)
{
size_t collectibleCardNum = 0;
size_t implementedCardNum = 0;
outputFile << "Set | ID | Name | Tag | Implemented\n";
outputFile << ":---: | :---: | :---: | :---: | :---:\n";
for (auto& card : cards)
{
if (!card.isCollectible)
{
continue;
}
collectibleCardNum++;
std::string mechanicStr;
for (auto& mechanic : card.mechanics)
{
mechanicStr += mechanic._to_string();
}
const bool isImplemented = CheckCardImpl(projectPath, card.id);
if (isImplemented)
{
implementedCardNum++;
}
outputFile << card.cardSet._to_string() << " | " << card.id << " | "
<< card.name << " | " << mechanicStr << " | "
<< (isImplemented ? 'O' : ' ') << '\n';
}
const size_t implPercent = static_cast<size_t>(
static_cast<double>(implementedCardNum) / collectibleCardNum * 100);
outputFile << '\n';
outputFile << "- Progress: " << implPercent << "% ("
<< implementedCardNum << " of " << collectibleCardNum
<< " Cards)";
std::cout << "Export file is completed.\n";
exit(EXIT_SUCCESS);
}
std::cerr << "Failed to write file result.md\n";
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
// Parse command
bool showHelp = false;
bool isExportAllCard = false;
bool implCardOnly = false;
std::string cardSetName;
std::string projectPath;
// Parsing
auto parser =
clara::Help(showHelp) |
clara::Opt(isExportAllCard)["-a"]["--all"](
"Export a list of all expansion cards") |
clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
"Export a list of specific expansion cards") |
clara::Opt(implCardOnly)["-i"]["--implcardonly"](
"Export a list of cards that need to be implemented") |
clara::Opt(projectPath, "path")["-p"]["--path"](
"Specify Hearthstone++ project path");
auto result = parser.parse(clara::Args(argc, argv));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
exit(EXIT_FAILURE);
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
exit(EXIT_SUCCESS);
}
if (projectPath.empty())
{
std::cout << "You should input Hearthstone++ project path\n";
exit(EXIT_FAILURE);
}
std::vector<Card> cards;
if (isExportAllCard)
{
cards = QueryCardSetList(projectPath, CardSet::ALL, implCardOnly);
}
else if (!cardSetName.empty())
{
const auto maybeCardSet =
CardSet::_from_string_nothrow(cardSetName.c_str());
if (!maybeCardSet)
{
std::cerr << "Invalid card set name: " << cardSetName << '\n';
exit(EXIT_FAILURE);
}
cards = QueryCardSetList(projectPath, *maybeCardSet, implCardOnly);
}
if (cards.empty())
{
std::cerr << "Your search did not generate any hits.\n";
exit(EXIT_SUCCESS);
}
ExportFile(projectPath, cards);
exit(EXIT_SUCCESS);
}<commit_msg>[ci skip] [WIP] feat(improve-tool): Implement QueryCardSetList() func<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Cards.h>
#include <better-enums/enum.h>
#include <clara.hpp>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace Hearthstonepp;
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
inline std::string ToString(const clara::Opt& opt)
{
std::ostringstream oss;
oss << (clara::Parser() | opt);
return oss.str();
}
inline std::string ToString(const clara::Parser& p)
{
std::ostringstream oss;
oss << p;
return oss.str();
}
inline std::vector<GameTag> CheckAbilityImpl(const std::string& path)
{
std::map<std::string, GameTag> abilityStrMap = {
{ "Charge", GameTag::CHARGE },
{ "DivineShield", GameTag::DIVINE_SHIELD },
{ "Freeze", GameTag::FREEZE },
{ "Poisonous", GameTag::POISONOUS },
{ "Taunt", GameTag::TAUNT },
{ "Windfury", GameTag::WINDFURY }
};
#ifndef HEARTHSTONEPP_MACOSX
const filesystem::path p(
path + "/Tests/UnitTests/Tasks/BasicTasks/CombatTaskTests.cpp");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_regular_file(p))
{
std::cerr << p << " exists, but is not regular file\n";
exit(EXIT_FAILURE);
}
std::ifstream abilityFile;
abilityFile.open(p.string());
if (!abilityFile.is_open())
{
std::cerr << p << " couldn't open\n";
exit(EXIT_FAILURE);
}
std::vector<GameTag> result;
std::string line;
while (std::getline(abilityFile, line))
{
for (auto& ability : abilityStrMap)
{
std::string sentence = "TEST(CombatTask, " + ability.first + ")";
if (line.find(sentence, 0) != std::string::npos)
{
result.emplace_back(ability.second);
break;
}
}
}
#else
std::cerr
<< "CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return result;
}
inline std::vector<Card> QueryCardSetList(const std::string& projectPath,
CardSet cardSet, bool implCardOnly)
{
if (cardSet == +CardSet::ALL)
{
return Cards::GetInstance()->GetAllCards();
}
std::vector<GameTag> abilityList{};
if (implCardOnly)
{
abilityList = CheckAbilityImpl(projectPath);
}
std::vector<Card> result;
for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
{
if (implCardOnly)
{
bool isAbilityImpl = true;
for (auto& mechanic : card.mechanics)
{
if (std::find(abilityList.begin(), abilityList.end(),
mechanic) == abilityList.end())
{
isAbilityImpl = false;
break;
}
}
if (!isAbilityImpl)
{
result.emplace_back(card);
}
}
else
{
result.emplace_back(card);
}
}
return result;
}
inline bool CheckCardImpl(const std::string& path, const std::string& id)
{
#ifndef HEARTHSTONEPP_MACOSX
const filesystem::path p(path + "/Tests/UnitTests/CardSets");
if (!filesystem::exists(p))
{
std::cerr << p << " does not exist\n";
exit(EXIT_FAILURE);
}
if (!filesystem::is_directory(p))
{
std::cerr << p << " exists, but is not directory\n";
exit(EXIT_FAILURE);
}
for (auto&& file : filesystem::recursive_directory_iterator(p))
{
std::regex fileNamePattern(R"(.*\\(.*)\..*$)");
std::smatch match;
std::string pathStr = file.path().string();
if (std::regex_match(pathStr, match, fileNamePattern))
{
if (match[1] == id)
{
return true;
}
}
}
#else
std::cerr
<< "CheckCardImpl skip: apple-clang doesn't support <filesystem>\n";
exit(EXIT_FAILURE);
#endif
return false;
}
inline void ExportFile(const std::string& projectPath, std::vector<Card>& cards)
{
std::ofstream outputFile("result.md");
if (outputFile)
{
size_t collectibleCardNum = 0;
size_t implementedCardNum = 0;
outputFile << "Set | ID | Name | Tag | Implemented\n";
outputFile << ":---: | :---: | :---: | :---: | :---:\n";
for (auto& card : cards)
{
if (!card.isCollectible)
{
continue;
}
collectibleCardNum++;
std::string mechanicStr;
for (auto& mechanic : card.mechanics)
{
mechanicStr += mechanic._to_string();
}
const bool isImplemented = CheckCardImpl(projectPath, card.id);
if (isImplemented)
{
implementedCardNum++;
}
outputFile << card.cardSet._to_string() << " | " << card.id << " | "
<< card.name << " | " << mechanicStr << " | "
<< (isImplemented ? 'O' : ' ') << '\n';
}
const size_t implPercent = static_cast<size_t>(
static_cast<double>(implementedCardNum) / collectibleCardNum * 100);
outputFile << '\n';
outputFile << "- Progress: " << implPercent << "% ("
<< implementedCardNum << " of " << collectibleCardNum
<< " Cards)";
std::cout << "Export file is completed.\n";
exit(EXIT_SUCCESS);
}
std::cerr << "Failed to write file result.md\n";
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
// Parse command
bool showHelp = false;
bool isExportAllCard = false;
bool implCardOnly = false;
std::string cardSetName;
std::string projectPath;
// Parsing
auto parser = clara::Help(showHelp) |
clara::Opt(isExportAllCard)["-a"]["--all"](
"Export a list of all expansion cards") |
clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
"Export a list of specific expansion cards") |
clara::Opt(implCardOnly)["-i"]["--implcardonly"](
"Export a list of cards that need to be implemented") |
clara::Opt(projectPath, "path")["-p"]["--path"](
"Specify Hearthstone++ project path");
auto result = parser.parse(clara::Args(argc, argv));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
exit(EXIT_FAILURE);
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
exit(EXIT_SUCCESS);
}
if (projectPath.empty())
{
std::cout << "You should input Hearthstone++ project path\n";
exit(EXIT_FAILURE);
}
std::vector<Card> cards;
if (isExportAllCard)
{
cards = QueryCardSetList(projectPath, CardSet::ALL, implCardOnly);
}
else if (!cardSetName.empty())
{
const auto maybeCardSet =
CardSet::_from_string_nothrow(cardSetName.c_str());
if (!maybeCardSet)
{
std::cerr << "Invalid card set name: " << cardSetName << '\n';
exit(EXIT_FAILURE);
}
cards = QueryCardSetList(projectPath, *maybeCardSet, implCardOnly);
}
if (cards.empty())
{
std::cerr << "Your search did not generate any hits.\n";
exit(EXIT_SUCCESS);
}
ExportFile(projectPath, cards);
exit(EXIT_SUCCESS);
}<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <assert.h>
#include <TDatabasePDG.h>
#include <TLorentzVector.h>
#include <TMCProcess.h>
#include <TPDGCode.h>
#include <TRandom.h>
#include <TVector3.h>
#include "AliConst.h"
#include "AliGenZDC.h"
#include "AliRun.h"
#include "AliMC.h"
ClassImp(AliGenZDC)
//_____________________________________________________________________________
AliGenZDC::AliGenZDC()
:AliGenerator()
{
//
// Default constructor
//
fIpart = 0;
}
//_____________________________________________________________________________
AliGenZDC::AliGenZDC(Int_t npart)
:AliGenerator(npart)
{
//
// Standard constructor
//
fName = "AliGenZDC";
fTitle = "Generation of Test Particles for ZDCs";
fIpart = kNeutron;
fCosx = 0.;
fCosy = 0.;
fCosz = 1.;
fPseudoRapidity = 0.;
fFermiflag = 1;
// LHC values for beam divergence and crossing angle
fBeamDiv = 0.000032;
fBeamCrossAngle = 0.0001;
fBeamCrossPlane = 2;
Int_t i, j;
for(i=0; i<201; i++){
fProbintp[i] = 0;
fProbintn[i] = 0;
}
for(j=0; j<3; j++){
fPp[i] = 0;
}
fDebugOpt = 0;
}
//_____________________________________________________________________________
void AliGenZDC::Init()
{
printf("\n\n AliGenZDC initialized with:\n");
printf(" Fermi flag = %d, Beam Divergence = %f, Crossing Angle "
"= %f, Crossing Plane = %d\n\n", fFermiflag, fBeamDiv, fBeamCrossAngle,
fBeamCrossPlane);
//Initialize Fermi momentum distributions for Pb-Pb
FermiTwoGaussian(207.,fPp,fProbintp,fProbintn);
}
//_____________________________________________________________________________
void AliGenZDC::Generate()
{
//
// Generate one trigger (n or p)
//
Int_t i;
Double_t Mass, pLab[3], fP0, fP[3], fBoostP[3], ddp[3], dddp0, dddp[3];
Float_t fPTrack[3], ptot = fPMin;
Int_t nt;
if(fPseudoRapidity==0.){
pLab[0] = ptot*fCosx;
pLab[1] = ptot*fCosy;
pLab[2] = ptot*fCosz;
}
else{
Float_t scang = 2*TMath::ATan(TMath::Exp(-(fPseudoRapidity)));
pLab[0] = -ptot*TMath::Sin(scang);
pLab[1] = 0.;
pLab[2] = ptot*TMath::Cos(scang);
}
for(i=0; i<=2; i++){
fP[i] = pLab[i];
}
// Beam divergence and crossing angle
if(fBeamCrossAngle!=0.) {
BeamDivCross(1,fBeamDiv,fBeamCrossAngle,fBeamCrossPlane,pLab);
for(i=0; i<=2; i++){
fP[i] = pLab[i];
}
}
if(fBeamDiv!=0.) {
BeamDivCross(0,fBeamDiv,fBeamCrossAngle,fBeamCrossPlane,pLab);
for(i=0; i<=2; i++){
fP[i] = pLab[i];
}
}
// If required apply the Fermi momentum
if(fFermiflag==1){
if((fIpart==kProton) || (fIpart==kNeutron)){
ExtractFermi(fIpart,fPp,fProbintp,fProbintn,ddp);
}
Mass=gAlice->PDGDB()->GetParticle(fIpart)->Mass();
fP0 = TMath::Sqrt(fP[0]*fP[0]+fP[1]*fP[1]+fP[2]*fP[2]+Mass*Mass);
for(i=0; i<=2; i++){
dddp[i] = ddp[i];
}
dddp0 = TMath::Sqrt(dddp[0]*dddp[0]+dddp[1]*dddp[1]+dddp[2]*dddp[2]+Mass*Mass);
TVector3 b(fP[0]/fP0, fP[1]/fP0, fP[2]/fP0);
TLorentzVector pFermi(dddp[0], dddp[1], dddp[2], dddp0);
pFermi.Boost(b);
for(i=0; i<=2; i++){
fBoostP[i] = pFermi[i];
fP[i] = pFermi[i];
}
}
for(i=0; i<=2; i++){
fPTrack[i] = fP[i];
}
Float_t polar[3] = {0,0,0};
gAlice->GetMCApp()->PushTrack(fTrackIt,-1,fIpart,fPTrack,fOrigin.GetArray(),polar,0,
kPPrimary,nt);
if(fDebugOpt == 1){
printf("\n\n Track momentum:\n");
printf("\n fPTrack = %f, %f, %f \n",fPTrack[0],fPTrack[1],fPTrack[2]);
}
}
//_____________________________________________________________________________
void AliGenZDC::FermiTwoGaussian(Float_t A, Double_t *fPp,
Double_t *fProbintp, Double_t *fProbintn)
{
//
// Momenta distributions according to the "double-gaussian"
// distribution (Ilinov) - equal for protons and neutrons
//
fProbintp[0] = 0;
fProbintn[0] = 0;
Double_t sig1 = 0.113;
Double_t sig2 = 0.250;
Double_t alfa = 0.18*(TMath::Power((A/12.),(Float_t)1/3));
Double_t xk = (2*k2PI)/((1.+alfa)*(TMath::Power(k2PI,1.5)));
for(Int_t i=1; i<=200; i++){
Double_t p = i*0.005;
fPp[i] = p;
Double_t e1 = (p*p)/(2.*sig1*sig1);
Double_t e2 = (p*p)/(2.*sig2*sig2);
Double_t f1 = TMath::Exp(-(e1));
Double_t f2 = TMath::Exp(-(e2));
Double_t probp = xk*p*p*(f1/(TMath::Power(sig1,3.))+
alfa*f2/(TMath::Power(sig2,3.)))*0.005;
fProbintp[i] = fProbintp[i-1] + probp;
fProbintn[i] = fProbintp[i];
}
if(fDebugOpt == 1){
printf("\n\n Initialization of Fermi momenta distribution \n");
for(Int_t i=0; i<=200; i++){
printf(" fProbintp[%d] = %f, fProbintn[%d] = %f\n",i,fProbintp[i],i,fProbintn[i]);
}
}
}
//_____________________________________________________________________________
void AliGenZDC::ExtractFermi(Int_t id, Double_t *fPp, Double_t *fProbintp,
Double_t *fProbintn, Double_t *ddp)
{
//
// Compute Fermi momentum for spectator nucleons
//
Int_t i;
Float_t xx = gRandom->Rndm();
assert ( id==kProton || id==kNeutron );
if(id==kProton){
for(i=1; i<=200; i++){
if((xx>=fProbintp[i-1]) && (xx<fProbintp[i])) break;
}
}
else {
for(i=0; i<=200; i++){
if((xx>=fProbintn[i-1]) && (xx<fProbintn[i])) break;
}
}
Float_t pext = fPp[i]+0.001;
Float_t phi = k2PI*(gRandom->Rndm());
Float_t cost = (1.-2.*(gRandom->Rndm()));
Float_t tet = TMath::ACos(cost);
ddp[0] = pext*TMath::Sin(tet)*TMath::Cos(phi);
ddp[1] = pext*TMath::Sin(tet)*TMath::Sin(phi);
ddp[2] = pext*cost;
if(fDebugOpt == 1){
printf("\n\n Extraction of Fermi momentum\n");
printf("\n pxFermi = %f pyFermi = %f pzFermi = %f \n",ddp[0],ddp[1],ddp[2]);
}
}
//_____________________________________________________________________________
void AliGenZDC::BeamDivCross(Int_t icross, Float_t fBeamDiv, Float_t fBeamCrossAngle,
Int_t fBeamCrossPlane, Double_t *pLab)
{
Double_t tetpart, fipart, tetdiv=0, fidiv=0, angleSum[2], tetsum, fisum;
Double_t rvec;
Int_t i;
Double_t pmq = 0.;
for(i=0; i<=2; i++){
pmq = pmq+pLab[i]*pLab[i];
}
Double_t pmod = TMath::Sqrt(pmq);
if(icross==0){
rvec = gRandom->Gaus(0.0,1.0);
tetdiv = fBeamDiv * TMath::Abs(rvec);
fidiv = (gRandom->Rndm())*k2PI;
}
else if(icross==1){
if(fBeamCrossPlane==0.){
tetdiv = 0.;
fidiv = 0.;
}
else if(fBeamCrossPlane==1.){
tetdiv = fBeamCrossAngle;
fidiv = 0.;
}
else if(fBeamCrossPlane==2.){
tetdiv = fBeamCrossAngle;
fidiv = k2PI/4.;
}
}
tetpart = TMath::ATan(TMath::Sqrt(pLab[0]*pLab[0]+pLab[1]*pLab[1])/pLab[2]);
if(pLab[1]!=0. || pLab[0]!=0.){
fipart = TMath::ATan2(pLab[1],pLab[0]);
}
else{
fipart = 0.;
}
if(fipart<0.) {fipart = fipart+k2PI;}
tetdiv = tetdiv*kRaddeg;
fidiv = fidiv*kRaddeg;
tetpart = tetpart*kRaddeg;
fipart = fipart*kRaddeg;
AddAngle(tetpart,fipart,tetdiv,fidiv,angleSum);
tetsum = angleSum[0];
fisum = angleSum[1];
tetsum = tetsum*kDegrad;
fisum = fisum*kDegrad;
pLab[0] = pmod*TMath::Sin(tetsum)*TMath::Cos(fisum);
pLab[1] = pmod*TMath::Sin(tetsum)*TMath::Sin(fisum);
pLab[2] = pmod*TMath::Cos(tetsum);
if(fDebugOpt == 1){
printf("\n\n Beam divergence and crossing angle\n");
for(i=0; i<=2; i++){
printf(" pLab[%d] = %f\n",i,pLab[i]);
}
}
}
//_____________________________________________________________________________
void AliGenZDC::AddAngle(Double_t theta1, Double_t phi1, Double_t theta2,
Double_t phi2, Double_t *angleSum)
{
Double_t temp, conv, cx, cy, cz, ct1, st1, ct2, st2, cp1, sp1, cp2, sp2;
Double_t rtetsum, tetsum, fisum;
temp = -1.;
conv = 180./TMath::ACos(temp);
ct1 = TMath::Cos(theta1/conv);
st1 = TMath::Sin(theta1/conv);
cp1 = TMath::Cos(phi1/conv);
sp1 = TMath::Sin(phi1/conv);
ct2 = TMath::Cos(theta2/conv);
st2 = TMath::Sin(theta2/conv);
cp2 = TMath::Cos(phi2/conv);
sp2 = TMath::Sin(phi2/conv);
cx = ct1*cp1*st2*cp2+st1*cp1*ct2-sp1*st2*sp2;
cy = ct1*sp1*st2*cp2+st1*sp1*ct2+cp1*st2*sp2;
cz = ct1*ct2-st1*st2*cp2;
rtetsum = TMath::ACos(cz);
tetsum = conv*rtetsum;
if(tetsum==0. || tetsum==180.){
fisum = 0.;
return;
}
temp = cx/TMath::Sin(rtetsum);
if(temp>1.) temp=1.;
if(temp<-1.) temp=-1.;
fisum = conv*TMath::ACos(temp);
if(cy<0) {fisum = 360.-fisum;}
angleSum[0] = tetsum;
angleSum[1] = fisum;
}
<commit_msg>Minor change to correct a bug<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <assert.h>
#include <TDatabasePDG.h>
#include <TLorentzVector.h>
#include <TMCProcess.h>
#include <TPDGCode.h>
#include <TRandom.h>
#include <TVector3.h>
#include "AliConst.h"
#include "AliGenZDC.h"
#include "AliRun.h"
#include "AliMC.h"
ClassImp(AliGenZDC)
//_____________________________________________________________________________
AliGenZDC::AliGenZDC()
:AliGenerator()
{
//
// Default constructor
//
fIpart = 0;
}
//_____________________________________________________________________________
AliGenZDC::AliGenZDC(Int_t npart)
:AliGenerator(npart)
{
//
// Standard constructor
//
fName = "AliGenZDC";
fTitle = "Generation of Test Particles for ZDCs";
fIpart = kNeutron;
fCosx = 0.;
fCosy = 0.;
fCosz = 1.;
fPseudoRapidity = 0.;
fFermiflag = 1;
// LHC values for beam divergence and crossing angle
fBeamDiv = 0.000032;
fBeamCrossAngle = 0.0001;
fBeamCrossPlane = 2;
Int_t i, j;
for(i=0; i<201; i++){
fProbintp[i] = 0;
fProbintn[i] = 0;
}
for(j=0; j<3; j++) fPp[i] = 0;
fDebugOpt = 0;
}
//_____________________________________________________________________________
void AliGenZDC::Init()
{
printf("\n\n AliGenZDC initialization:\n");
printf(" Particle: %d, Track cosines: x = %f, y = %f, z = %f \n",
fIpart,fCosx,fCosy,fCosz);
printf(" Fermi flag = %d, Beam divergence = %f, Crossing angle "
"= %f, Crossing plane = %d\n\n", fFermiflag, fBeamDiv, fBeamCrossAngle,
fBeamCrossPlane);
//Initialize Fermi momentum distributions for Pb-Pb
FermiTwoGaussian(207.,fPp,fProbintp,fProbintn);
}
//_____________________________________________________________________________
void AliGenZDC::Generate()
{
//
// Generate one trigger (n or p)
//
Int_t i;
Double_t Mass, pLab[3], fP0, fP[3], fBoostP[3], ddp[3], dddp0, dddp[3];
Float_t fPTrack[3], ptot = fPMin;
Int_t nt;
if(fPseudoRapidity==0.){
pLab[0] = ptot*fCosx;
pLab[1] = ptot*fCosy;
pLab[2] = ptot*fCosz;
}
else{
Float_t scang = 2*TMath::ATan(TMath::Exp(-(fPseudoRapidity)));
pLab[0] = -ptot*TMath::Sin(scang);
pLab[1] = 0.;
pLab[2] = ptot*TMath::Cos(scang);
}
for(i=0; i<=2; i++) fP[i] = pLab[i];
if(fDebugOpt == 1){
printf("\n\n Particle momentum before divergence and crossing\n");
for(i=0; i<=2; i++)printf(" pLab[%d] = %f\n",i,pLab[i]);
}
// Beam divergence and crossing angle
if(fBeamCrossAngle!=0.) {
BeamDivCross(1,fBeamDiv,fBeamCrossAngle,fBeamCrossPlane,pLab);
for(i=0; i<=2; i++) fP[i] = pLab[i];
}
if(fBeamDiv!=0.) {
BeamDivCross(0,fBeamDiv,fBeamCrossAngle,fBeamCrossPlane,pLab);
for(i=0; i<=2; i++) fP[i] = pLab[i];
}
// If required apply the Fermi momentum
if(fFermiflag==1){
if((fIpart==kProton) || (fIpart==kNeutron))
ExtractFermi(fIpart,fPp,fProbintp,fProbintn,ddp);
Mass=gAlice->PDGDB()->GetParticle(fIpart)->Mass();
fP0 = TMath::Sqrt(fP[0]*fP[0]+fP[1]*fP[1]+fP[2]*fP[2]+Mass*Mass);
for(i=0; i<=2; i++) dddp[i] = ddp[i];
dddp0 = TMath::Sqrt(dddp[0]*dddp[0]+dddp[1]*dddp[1]+dddp[2]*dddp[2]+Mass*Mass);
TVector3 b(fP[0]/fP0, fP[1]/fP0, fP[2]/fP0);
TLorentzVector pFermi(dddp[0], dddp[1], dddp[2], dddp0);
pFermi.Boost(b);
for(i=0; i<=2; i++){
fBoostP[i] = pFermi[i];
fP[i] = pFermi[i];
}
}
for(i=0; i<=2; i++) fPTrack[i] = fP[i];
Float_t polar[3] = {0,0,0};
gAlice->GetMCApp()->PushTrack(fTrackIt,-1,fIpart,fPTrack,fOrigin.GetArray(),polar,0,
kPPrimary,nt);
if(fDebugOpt == 1){
printf("\n\n Track momentum:\n");
printf("\n fPTrack = %f, %f, %f \n",fPTrack[0],fPTrack[1],fPTrack[2]);
}
}
//_____________________________________________________________________________
void AliGenZDC::FermiTwoGaussian(Float_t A, Double_t *fPp,
Double_t *fProbintp, Double_t *fProbintn)
{
//
// Momenta distributions according to the "double-gaussian"
// distribution (Ilinov) - equal for protons and neutrons
//
fProbintp[0] = 0;
fProbintn[0] = 0;
Double_t sig1 = 0.113;
Double_t sig2 = 0.250;
Double_t alfa = 0.18*(TMath::Power((A/12.),(Float_t)1/3));
Double_t xk = (2*k2PI)/((1.+alfa)*(TMath::Power(k2PI,1.5)));
for(Int_t i=1; i<=200; i++){
Double_t p = i*0.005;
fPp[i] = p;
Double_t e1 = (p*p)/(2.*sig1*sig1);
Double_t e2 = (p*p)/(2.*sig2*sig2);
Double_t f1 = TMath::Exp(-(e1));
Double_t f2 = TMath::Exp(-(e2));
Double_t probp = xk*p*p*(f1/(TMath::Power(sig1,3.))+
alfa*f2/(TMath::Power(sig2,3.)))*0.005;
fProbintp[i] = fProbintp[i-1] + probp;
fProbintn[i] = fProbintp[i];
}
if(fDebugOpt == 1){
printf("\n\n Initialization of Fermi momenta distribution \n");
//for(Int_t i=0; i<=200; i++)
// printf(" fProbintp[%d] = %f, fProbintn[%d] = %f\n",i,fProbintp[i],i,fProbintn[i]);
}
}
//_____________________________________________________________________________
void AliGenZDC::ExtractFermi(Int_t id, Double_t *fPp, Double_t *fProbintp,
Double_t *fProbintn, Double_t *ddp)
{
//
// Compute Fermi momentum for spectator nucleons
//
Int_t i;
Float_t xx = gRandom->Rndm();
assert ( id==kProton || id==kNeutron );
if(id==kProton){
for(i=1; i<=200; i++){
if((xx>=fProbintp[i-1]) && (xx<fProbintp[i])) break;
}
}
else {
for(i=0; i<=200; i++){
if((xx>=fProbintn[i-1]) && (xx<fProbintn[i])) break;
}
}
Float_t pext = fPp[i]+0.001;
Float_t phi = k2PI*(gRandom->Rndm());
Float_t cost = (1.-2.*(gRandom->Rndm()));
Float_t tet = TMath::ACos(cost);
ddp[0] = pext*TMath::Sin(tet)*TMath::Cos(phi);
ddp[1] = pext*TMath::Sin(tet)*TMath::Sin(phi);
ddp[2] = pext*cost;
if(fDebugOpt == 1){
printf("\n\n Extraction of Fermi momentum\n");
printf("\n pxFermi = %f pyFermi = %f pzFermi = %f \n",ddp[0],ddp[1],ddp[2]);
}
}
//_____________________________________________________________________________
void AliGenZDC::BeamDivCross(Int_t icross, Float_t fBeamDiv, Float_t fBeamCrossAngle,
Int_t fBeamCrossPlane, Double_t *pLab)
{
Double_t tetpart, fipart, tetdiv=0, fidiv=0, angleSum[2], tetsum, fisum;
Double_t rvec;
Int_t sign=0;
if(pLab[2]>=0.) sign=1;
else sign=-1;
Double_t pmq = 0.;
Int_t i;
for(i=0; i<=2; i++) pmq = pmq+pLab[i]*pLab[i];
Double_t pmod = TMath::Sqrt(pmq);
if(icross==0){
rvec = gRandom->Gaus(0.0,1.0);
tetdiv = fBeamDiv * TMath::Abs(rvec);
fidiv = (gRandom->Rndm())*k2PI;
}
else if(icross==1){
if(fBeamCrossPlane==0.){
tetdiv = 0.;
fidiv = 0.;
}
else if(fBeamCrossPlane==1.){
tetdiv = fBeamCrossAngle;
fidiv = 0.;
}
else if(fBeamCrossPlane==2.){
tetdiv = fBeamCrossAngle;
fidiv = k2PI/4.;
}
}
tetpart = TMath::ATan(TMath::Sqrt(pLab[0]*pLab[0]+pLab[1]*pLab[1])/pLab[2]);
if(pLab[1]!=0. || pLab[0]!=0.) fipart = TMath::ATan2(pLab[1],pLab[0]);
else fipart = 0.;
if(fipart<0.) {fipart = fipart+k2PI;}
tetdiv = tetdiv*kRaddeg;
fidiv = fidiv*kRaddeg;
tetpart = tetpart*kRaddeg;
fipart = fipart*kRaddeg;
AddAngle(tetpart,fipart,tetdiv,fidiv,angleSum);
tetsum = angleSum[0];
fisum = angleSum[1];
tetsum = tetsum*kDegrad;
fisum = fisum*kDegrad;
pLab[0] = pmod*TMath::Sin(tetsum)*TMath::Cos(fisum);
pLab[1] = pmod*TMath::Sin(tetsum)*TMath::Sin(fisum);
if(sign==1) pLab[2] = pmod*TMath::Cos(tetsum);
else pLab[2] = -pmod*TMath::Cos(tetsum);
if(fDebugOpt == 1){
printf("\n\n Beam divergence and crossing angle\n");
for(i=0; i<=2; i++)printf(" pLab[%d] = %f\n",i,pLab[i]);
}
}
//_____________________________________________________________________________
void AliGenZDC::AddAngle(Double_t theta1, Double_t phi1, Double_t theta2,
Double_t phi2, Double_t *angleSum)
{
Double_t temp, conv, cx, cy, cz, ct1, st1, ct2, st2, cp1, sp1, cp2, sp2;
Double_t rtetsum, tetsum, fisum;
temp = -1.;
conv = 180./TMath::ACos(temp);
ct1 = TMath::Cos(theta1/conv);
st1 = TMath::Sin(theta1/conv);
cp1 = TMath::Cos(phi1/conv);
sp1 = TMath::Sin(phi1/conv);
ct2 = TMath::Cos(theta2/conv);
st2 = TMath::Sin(theta2/conv);
cp2 = TMath::Cos(phi2/conv);
sp2 = TMath::Sin(phi2/conv);
cx = ct1*cp1*st2*cp2+st1*cp1*ct2-sp1*st2*sp2;
cy = ct1*sp1*st2*cp2+st1*sp1*ct2+cp1*st2*sp2;
cz = ct1*ct2-st1*st2*cp2;
rtetsum = TMath::ACos(cz);
tetsum = conv*rtetsum;
if(tetsum==0. || tetsum==180.){
fisum = 0.;
return;
}
temp = cx/TMath::Sin(rtetsum);
if(temp>1.) temp=1.;
if(temp<-1.) temp=-1.;
fisum = conv*TMath::ACos(temp);
if(cy<0) {fisum = 360.-fisum;}
angleSum[0] = tetsum;
angleSum[1] = fisum;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractCells.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkExtractCells.h"
#include "vtkCellArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
#include "vtkModelMetadata.h"
#include "vtkCell.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkIntArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkExtractCells, "1.3");
vtkStandardNewMacro(vtkExtractCells);
#include <vtkstd/set>
#include <vtkstd/algorithm>
class vtkExtractCellsSTLCloak
{
public:
vtkstd::set<vtkIdType> IdTypeSet;
};
vtkExtractCells::vtkExtractCells()
{
this->SubSetUGridCellArraySize = 0;
this->InputIsUgrid = 0;
this->CellList = new vtkExtractCellsSTLCloak;
}
vtkExtractCells::~vtkExtractCells()
{
this->SetCellList(NULL);
}
void vtkExtractCells::SetCellList(vtkIdList *l)
{
delete this->CellList;
this->CellList = new vtkExtractCellsSTLCloak;
if (l != NULL)
{
this->AddCellList(l);
}
}
void vtkExtractCells::AddCellList(vtkIdList *l)
{
if (l == NULL)
{
return;
}
vtkIdType ncells = l->GetNumberOfIds();
if (ncells == 0)
{
return;
}
for (int i=0; i<ncells; i++)
{
this->CellList->IdTypeSet.insert(l->GetId(i));
}
this->Modified();
return;
}
void vtkExtractCells::AddCellRange(vtkIdType from, vtkIdType to)
{
if (to < from) return;
for (vtkIdType id=from; id <= to; id++)
{
this->CellList->IdTypeSet.insert(id);
}
this->Modified();
return;
}
int vtkExtractCells::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
this->InputIsUgrid =
((vtkUnstructuredGrid::SafeDownCast(input)) != NULL);
vtkModelMetadata *extractMetadata = this->ExtractMetadata(input);
int numCellsInput = input->GetNumberOfCells();
int numCells = this->CellList->IdTypeSet.size();
if (numCells == numCellsInput)
{
#if 0
this->Copy(input, output);
if (extractMetadata)
{
vtkModelMetadata::RemoveMetadata((vtkDataSet *)output);
extractMetadata->Pack(output);
extractMetadata->Delete();
}
return;
#else
// The Copy method seems to have a bug, causing codes using ExtractCells to die
#endif
}
vtkPointData *PD = input->GetPointData();
vtkCellData *CD = input->GetCellData();
if (numCells == 0)
{
// set up a ugrid with same data arrays as input, but
// no points, cells or data.
output->Allocate(1);
output->GetPointData()->CopyGlobalIdsOn();
output->GetPointData()->CopyAllocate(PD, VTK_CELL_SIZE);
output->GetCellData()->CopyGlobalIdsOn();
output->GetCellData()->CopyAllocate(CD, 1);
vtkPoints *pts = vtkPoints::New();
pts->SetNumberOfPoints(0);
output->SetPoints(pts);
pts->Delete();
if (extractMetadata)
{
vtkModelMetadata::RemoveMetadata((vtkDataSet *)output);
extractMetadata->Pack(output);
extractMetadata->Delete();
}
return 1;
}
vtkPointData *newPD = output->GetPointData();
vtkCellData *newCD = output->GetCellData();
vtkIdList *ptIdMap = reMapPointIds(input);
vtkIdType numPoints = ptIdMap->GetNumberOfIds();
newPD->CopyGlobalIdsOn();
newPD->CopyAllocate(PD, numPoints);
newCD->CopyGlobalIdsOn();
newCD->CopyAllocate(CD, numCells);
vtkPoints *pts = vtkPoints::New();
pts->SetNumberOfPoints(numPoints);
for (vtkIdType newId =0; newId<numPoints; newId++)
{
vtkIdType oldId = ptIdMap->GetId(newId);
pts->SetPoint(newId, input->GetPoint(oldId));
newPD->CopyData(PD, oldId, newId);
}
output->SetPoints(pts);
pts->Delete();
if (this->InputIsUgrid)
{
this->CopyCellsUnstructuredGrid(ptIdMap, input, output);
}
else
{
this->CopyCellsDataSet(ptIdMap, input, output);
}
ptIdMap->Delete();
output->Squeeze();
if (extractMetadata)
{
vtkModelMetadata::RemoveMetadata((vtkDataSet *)output);
extractMetadata->Pack(output);
extractMetadata->Delete();
}
return 1;
}
vtkModelMetadata *vtkExtractCells::ExtractMetadata(vtkDataSet *input)
{
vtkModelMetadata *extractedMD = NULL;
int numCells = this->CellList->IdTypeSet.size();
if (vtkModelMetadata::HasMetadata(input))
{
if (numCells == input->GetNumberOfCells())
{
extractedMD = vtkModelMetadata::New();
extractedMD->Unpack(input, 0);
}
else
{
vtkDataArray *c = input->GetCellData()->GetGlobalIds();
vtkDataArray *p = input->GetPointData()->GetGlobalIds();
if (c && p)
{
vtkIdTypeArray *cgids = vtkIdTypeArray::SafeDownCast(c);
if (cgids)
{
vtkIdType *cids = cgids->GetPointer(0);
vtkIdTypeArray *gids = vtkIdTypeArray::New();
gids->SetNumberOfValues(numCells);
int next = 0;
vtkstd::set<vtkIdType>::iterator cellPtr;
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
gids->SetValue(next++, cids[*cellPtr]); // global cell IDs
}
vtkModelMetadata *mmd = vtkModelMetadata::New();
mmd->Unpack(input, 0);
extractedMD = mmd->ExtractModelMetadata(gids, input);
gids->Delete();
mmd->Delete();
}
else
{
vtkWarningMacro(<<
"vtkExtractCells: metadata lost, GlobalElementId array is not a vtkIntArray");
}
}
else
{
vtkWarningMacro(<<
"vtkExtractCells: metadata lost, no GlobalElementId or GlobalNodeId array");
}
}
}
return extractedMD;
}
void vtkExtractCells::Copy(vtkDataSet *input, vtkUnstructuredGrid *output)
{
int i;
if (this->InputIsUgrid)
{
output->DeepCopy(vtkUnstructuredGrid::SafeDownCast(input));
return;
}
int numCells = input->GetNumberOfCells();
vtkPointData *PD = input->GetPointData();
vtkCellData *CD = input->GetCellData();
vtkPointData *newPD = output->GetPointData();
vtkCellData *newCD = output->GetCellData();
int numPoints = input->GetNumberOfPoints();
output->Allocate(numCells);
newPD->CopyAllocate(PD, numPoints);
newCD->CopyAllocate(CD, numCells);
vtkPoints *pts = vtkPoints::New();
pts->SetNumberOfPoints(numPoints);
for (i=0; i<numPoints; i++)
{
pts->SetPoint(i, input->GetPoint(i));
}
newPD->DeepCopy(PD);
output->SetPoints(pts);
pts->Delete();
vtkIdList *cellPoints = vtkIdList::New();
for (vtkIdType cellId=0; cellId < numCells; cellId++)
{
input->GetCellPoints(cellId, cellPoints);
output->InsertNextCell(input->GetCellType(cellId), cellPoints);
}
newCD->DeepCopy(CD);
cellPoints->Delete();
output->Squeeze();
return;
}
vtkIdType vtkExtractCells::findInSortedList(vtkIdList *idList, vtkIdType id)
{
vtkIdType numids = idList->GetNumberOfIds();
if (numids < 8) return idList->IsId(id);
int L, R, M;
L=0;
R=numids-1;
vtkIdType *ids = idList->GetPointer(0);
int loc = -1;
while (R > L)
{
if (R == L+1)
{
if (ids[R] == id)
{
loc = R;
}
else if (ids[L] == id)
{
loc = L;
}
break;
}
M = (R + L) / 2;
if (ids[M] > id)
{
R = M;
continue;
}
else if (ids[M] < id)
{
L = M;
continue;
}
else
{
loc = M;
break;
}
}
return loc;
}
vtkIdList *vtkExtractCells::reMapPointIds(vtkDataSet *grid)
{
int totalPoints = grid->GetNumberOfPoints();
char *temp = new char [totalPoints];
if (!temp)
{
vtkErrorMacro(<< "vtkExtractCells::reMapPointIds memory allocation");
return NULL;
}
memset(temp, 0, totalPoints);
int numberOfIds = 0;
int i;
vtkIdType id;
vtkIdList *ptIds = vtkIdList::New();
vtkstd::set<vtkIdType>::iterator cellPtr;
if (!this->InputIsUgrid)
{
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
grid->GetCellPoints(*cellPtr, ptIds);
vtkIdType nIds = ptIds->GetNumberOfIds();
vtkIdType *ptId = ptIds->GetPointer(0);
for (i=0; i<nIds; i++)
{
id = *ptId++;
if (temp[id] == 0)
{
numberOfIds++;
temp[id] = 1;
}
}
}
}
else
{
vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::SafeDownCast(grid);
this->SubSetUGridCellArraySize = 0;
vtkIdType *cellArray = ugrid->GetCells()->GetPointer();
vtkIdType *locs = ugrid->GetCellLocationsArray()->GetPointer(0);
this->SubSetUGridCellArraySize = 0;
vtkIdType maxid = ugrid->GetCellLocationsArray()->GetMaxId();
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
if (*cellPtr > maxid) continue;
int loc = locs[*cellPtr];
vtkIdType nIds = cellArray[loc++];
this->SubSetUGridCellArraySize += (1 + nIds);
for (i=0; i<nIds; i++)
{
id = cellArray[loc++];
if (temp[id] == 0)
{
numberOfIds++;
temp[id] = 1;
}
}
}
}
ptIds->SetNumberOfIds(numberOfIds);
int next=0;
for (id=0; id<totalPoints; id++)
{
if (temp[id]) ptIds->SetId(next++, id);
}
delete [] temp;
return ptIds;
}
void vtkExtractCells::CopyCellsDataSet(vtkIdList *ptMap, vtkDataSet *input,
vtkUnstructuredGrid *output)
{
output->Allocate(this->CellList->IdTypeSet.size());
vtkCellData *oldCD = input->GetCellData();
vtkCellData *newCD = output->GetCellData();
vtkIdList *cellPoints = vtkIdList::New();
vtkstd::set<vtkIdType>::iterator cellPtr;
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
vtkIdType cellId = *cellPtr;
input->GetCellPoints(cellId, cellPoints);
for (int i=0; i < cellPoints->GetNumberOfIds(); i++)
{
vtkIdType oldId = cellPoints->GetId(i);
vtkIdType newId = vtkExtractCells::findInSortedList(ptMap, oldId);
cellPoints->SetId(i, newId);
}
int newId = output->InsertNextCell(input->GetCellType(cellId), cellPoints);
newCD->CopyData(oldCD, cellId, newId);
}
cellPoints->Delete();
return;
}
void vtkExtractCells::CopyCellsUnstructuredGrid(vtkIdList *ptMap,
vtkDataSet *input,
vtkUnstructuredGrid *output)
{
vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::SafeDownCast(input);
if (ugrid == NULL)
{
this->CopyCellsDataSet(ptMap, input, output);
return;
}
vtkCellData *oldCD = input->GetCellData();
vtkCellData *newCD = output->GetCellData();
int numCells = this->CellList->IdTypeSet.size();
vtkCellArray *cellArray = vtkCellArray::New(); // output
vtkIdTypeArray *newcells = vtkIdTypeArray::New();
newcells->SetNumberOfValues(this->SubSetUGridCellArraySize);
cellArray->SetCells(numCells, newcells);
int cellArrayIdx = 0;
vtkIdTypeArray *locationArray = vtkIdTypeArray::New();
locationArray->SetNumberOfValues(numCells);
vtkUnsignedCharArray *typeArray = vtkUnsignedCharArray::New();
typeArray->SetNumberOfValues(numCells);
int nextCellId = 0;
vtkstd::set<vtkIdType>::iterator cellPtr; // input
vtkIdType *cells = ugrid->GetCells()->GetPointer();
vtkIdType maxid = ugrid->GetCellLocationsArray()->GetMaxId();
vtkIdType *locs = ugrid->GetCellLocationsArray()->GetPointer(0);
vtkUnsignedCharArray *types = ugrid->GetCellTypesArray();
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
if (*cellPtr > maxid) continue;
int oldCellId = *cellPtr;
int loc = locs[oldCellId];
int size = (int)cells[loc];
vtkIdType *pts = cells + loc + 1;
unsigned char type = types->GetValue(oldCellId);
locationArray->SetValue(nextCellId, cellArrayIdx);
typeArray->SetValue(nextCellId, type);
newcells->SetValue(cellArrayIdx++, size);
for (int i=0; i<size; i++)
{
vtkIdType oldId = *pts++;
vtkIdType newId = vtkExtractCells::findInSortedList(ptMap, oldId);
newcells->SetValue(cellArrayIdx++, newId);
}
newCD->CopyData(oldCD, oldCellId, nextCellId);
nextCellId++;
}
output->SetCells(typeArray, locationArray, cellArray);
typeArray->Delete();
locationArray->Delete();
newcells->Delete();
cellArray->Delete();
return;
}
int vtkExtractCells::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
void vtkExtractCells::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<commit_msg>BUG: Fixed memory leak<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractCells.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkExtractCells.h"
#include "vtkCellArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
#include "vtkModelMetadata.h"
#include "vtkCell.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkIntArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkExtractCells, "1.4");
vtkStandardNewMacro(vtkExtractCells);
#include <vtkstd/set>
#include <vtkstd/algorithm>
class vtkExtractCellsSTLCloak
{
public:
vtkstd::set<vtkIdType> IdTypeSet;
};
vtkExtractCells::vtkExtractCells()
{
this->SubSetUGridCellArraySize = 0;
this->InputIsUgrid = 0;
this->CellList = new vtkExtractCellsSTLCloak;
}
vtkExtractCells::~vtkExtractCells()
{
delete this->CellList;
}
void vtkExtractCells::SetCellList(vtkIdList *l)
{
delete this->CellList;
this->CellList = new vtkExtractCellsSTLCloak;
if (l != NULL)
{
this->AddCellList(l);
}
}
void vtkExtractCells::AddCellList(vtkIdList *l)
{
if (l == NULL)
{
return;
}
vtkIdType ncells = l->GetNumberOfIds();
if (ncells == 0)
{
return;
}
for (int i=0; i<ncells; i++)
{
this->CellList->IdTypeSet.insert(l->GetId(i));
}
this->Modified();
return;
}
void vtkExtractCells::AddCellRange(vtkIdType from, vtkIdType to)
{
if (to < from) return;
for (vtkIdType id=from; id <= to; id++)
{
this->CellList->IdTypeSet.insert(id);
}
this->Modified();
return;
}
int vtkExtractCells::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
this->InputIsUgrid =
((vtkUnstructuredGrid::SafeDownCast(input)) != NULL);
vtkModelMetadata *extractMetadata = this->ExtractMetadata(input);
int numCellsInput = input->GetNumberOfCells();
int numCells = this->CellList->IdTypeSet.size();
if (numCells == numCellsInput)
{
#if 0
this->Copy(input, output);
if (extractMetadata)
{
vtkModelMetadata::RemoveMetadata((vtkDataSet *)output);
extractMetadata->Pack(output);
extractMetadata->Delete();
}
return;
#else
// The Copy method seems to have a bug, causing codes using ExtractCells to die
#endif
}
vtkPointData *PD = input->GetPointData();
vtkCellData *CD = input->GetCellData();
if (numCells == 0)
{
// set up a ugrid with same data arrays as input, but
// no points, cells or data.
output->Allocate(1);
output->GetPointData()->CopyGlobalIdsOn();
output->GetPointData()->CopyAllocate(PD, VTK_CELL_SIZE);
output->GetCellData()->CopyGlobalIdsOn();
output->GetCellData()->CopyAllocate(CD, 1);
vtkPoints *pts = vtkPoints::New();
pts->SetNumberOfPoints(0);
output->SetPoints(pts);
pts->Delete();
if (extractMetadata)
{
vtkModelMetadata::RemoveMetadata((vtkDataSet *)output);
extractMetadata->Pack(output);
extractMetadata->Delete();
}
return 1;
}
vtkPointData *newPD = output->GetPointData();
vtkCellData *newCD = output->GetCellData();
vtkIdList *ptIdMap = reMapPointIds(input);
vtkIdType numPoints = ptIdMap->GetNumberOfIds();
newPD->CopyGlobalIdsOn();
newPD->CopyAllocate(PD, numPoints);
newCD->CopyGlobalIdsOn();
newCD->CopyAllocate(CD, numCells);
vtkPoints *pts = vtkPoints::New();
pts->SetNumberOfPoints(numPoints);
for (vtkIdType newId =0; newId<numPoints; newId++)
{
vtkIdType oldId = ptIdMap->GetId(newId);
pts->SetPoint(newId, input->GetPoint(oldId));
newPD->CopyData(PD, oldId, newId);
}
output->SetPoints(pts);
pts->Delete();
if (this->InputIsUgrid)
{
this->CopyCellsUnstructuredGrid(ptIdMap, input, output);
}
else
{
this->CopyCellsDataSet(ptIdMap, input, output);
}
ptIdMap->Delete();
output->Squeeze();
if (extractMetadata)
{
vtkModelMetadata::RemoveMetadata((vtkDataSet *)output);
extractMetadata->Pack(output);
extractMetadata->Delete();
}
return 1;
}
vtkModelMetadata *vtkExtractCells::ExtractMetadata(vtkDataSet *input)
{
vtkModelMetadata *extractedMD = NULL;
int numCells = this->CellList->IdTypeSet.size();
if (vtkModelMetadata::HasMetadata(input))
{
if (numCells == input->GetNumberOfCells())
{
extractedMD = vtkModelMetadata::New();
extractedMD->Unpack(input, 0);
}
else
{
vtkDataArray *c = input->GetCellData()->GetGlobalIds();
vtkDataArray *p = input->GetPointData()->GetGlobalIds();
if (c && p)
{
vtkIdTypeArray *cgids = vtkIdTypeArray::SafeDownCast(c);
if (cgids)
{
vtkIdType *cids = cgids->GetPointer(0);
vtkIdTypeArray *gids = vtkIdTypeArray::New();
gids->SetNumberOfValues(numCells);
int next = 0;
vtkstd::set<vtkIdType>::iterator cellPtr;
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
gids->SetValue(next++, cids[*cellPtr]); // global cell IDs
}
vtkModelMetadata *mmd = vtkModelMetadata::New();
mmd->Unpack(input, 0);
extractedMD = mmd->ExtractModelMetadata(gids, input);
gids->Delete();
mmd->Delete();
}
else
{
vtkWarningMacro(<<
"vtkExtractCells: metadata lost, GlobalElementId array is not a vtkIntArray");
}
}
else
{
vtkWarningMacro(<<
"vtkExtractCells: metadata lost, no GlobalElementId or GlobalNodeId array");
}
}
}
return extractedMD;
}
void vtkExtractCells::Copy(vtkDataSet *input, vtkUnstructuredGrid *output)
{
int i;
if (this->InputIsUgrid)
{
output->DeepCopy(vtkUnstructuredGrid::SafeDownCast(input));
return;
}
int numCells = input->GetNumberOfCells();
vtkPointData *PD = input->GetPointData();
vtkCellData *CD = input->GetCellData();
vtkPointData *newPD = output->GetPointData();
vtkCellData *newCD = output->GetCellData();
int numPoints = input->GetNumberOfPoints();
output->Allocate(numCells);
newPD->CopyAllocate(PD, numPoints);
newCD->CopyAllocate(CD, numCells);
vtkPoints *pts = vtkPoints::New();
pts->SetNumberOfPoints(numPoints);
for (i=0; i<numPoints; i++)
{
pts->SetPoint(i, input->GetPoint(i));
}
newPD->DeepCopy(PD);
output->SetPoints(pts);
pts->Delete();
vtkIdList *cellPoints = vtkIdList::New();
for (vtkIdType cellId=0; cellId < numCells; cellId++)
{
input->GetCellPoints(cellId, cellPoints);
output->InsertNextCell(input->GetCellType(cellId), cellPoints);
}
newCD->DeepCopy(CD);
cellPoints->Delete();
output->Squeeze();
return;
}
vtkIdType vtkExtractCells::findInSortedList(vtkIdList *idList, vtkIdType id)
{
vtkIdType numids = idList->GetNumberOfIds();
if (numids < 8) return idList->IsId(id);
int L, R, M;
L=0;
R=numids-1;
vtkIdType *ids = idList->GetPointer(0);
int loc = -1;
while (R > L)
{
if (R == L+1)
{
if (ids[R] == id)
{
loc = R;
}
else if (ids[L] == id)
{
loc = L;
}
break;
}
M = (R + L) / 2;
if (ids[M] > id)
{
R = M;
continue;
}
else if (ids[M] < id)
{
L = M;
continue;
}
else
{
loc = M;
break;
}
}
return loc;
}
vtkIdList *vtkExtractCells::reMapPointIds(vtkDataSet *grid)
{
int totalPoints = grid->GetNumberOfPoints();
char *temp = new char [totalPoints];
if (!temp)
{
vtkErrorMacro(<< "vtkExtractCells::reMapPointIds memory allocation");
return NULL;
}
memset(temp, 0, totalPoints);
int numberOfIds = 0;
int i;
vtkIdType id;
vtkIdList *ptIds = vtkIdList::New();
vtkstd::set<vtkIdType>::iterator cellPtr;
if (!this->InputIsUgrid)
{
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
grid->GetCellPoints(*cellPtr, ptIds);
vtkIdType nIds = ptIds->GetNumberOfIds();
vtkIdType *ptId = ptIds->GetPointer(0);
for (i=0; i<nIds; i++)
{
id = *ptId++;
if (temp[id] == 0)
{
numberOfIds++;
temp[id] = 1;
}
}
}
}
else
{
vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::SafeDownCast(grid);
this->SubSetUGridCellArraySize = 0;
vtkIdType *cellArray = ugrid->GetCells()->GetPointer();
vtkIdType *locs = ugrid->GetCellLocationsArray()->GetPointer(0);
this->SubSetUGridCellArraySize = 0;
vtkIdType maxid = ugrid->GetCellLocationsArray()->GetMaxId();
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
if (*cellPtr > maxid) continue;
int loc = locs[*cellPtr];
vtkIdType nIds = cellArray[loc++];
this->SubSetUGridCellArraySize += (1 + nIds);
for (i=0; i<nIds; i++)
{
id = cellArray[loc++];
if (temp[id] == 0)
{
numberOfIds++;
temp[id] = 1;
}
}
}
}
ptIds->SetNumberOfIds(numberOfIds);
int next=0;
for (id=0; id<totalPoints; id++)
{
if (temp[id]) ptIds->SetId(next++, id);
}
delete [] temp;
return ptIds;
}
void vtkExtractCells::CopyCellsDataSet(vtkIdList *ptMap, vtkDataSet *input,
vtkUnstructuredGrid *output)
{
output->Allocate(this->CellList->IdTypeSet.size());
vtkCellData *oldCD = input->GetCellData();
vtkCellData *newCD = output->GetCellData();
vtkIdList *cellPoints = vtkIdList::New();
vtkstd::set<vtkIdType>::iterator cellPtr;
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
vtkIdType cellId = *cellPtr;
input->GetCellPoints(cellId, cellPoints);
for (int i=0; i < cellPoints->GetNumberOfIds(); i++)
{
vtkIdType oldId = cellPoints->GetId(i);
vtkIdType newId = vtkExtractCells::findInSortedList(ptMap, oldId);
cellPoints->SetId(i, newId);
}
int newId = output->InsertNextCell(input->GetCellType(cellId), cellPoints);
newCD->CopyData(oldCD, cellId, newId);
}
cellPoints->Delete();
return;
}
void vtkExtractCells::CopyCellsUnstructuredGrid(vtkIdList *ptMap,
vtkDataSet *input,
vtkUnstructuredGrid *output)
{
vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::SafeDownCast(input);
if (ugrid == NULL)
{
this->CopyCellsDataSet(ptMap, input, output);
return;
}
vtkCellData *oldCD = input->GetCellData();
vtkCellData *newCD = output->GetCellData();
int numCells = this->CellList->IdTypeSet.size();
vtkCellArray *cellArray = vtkCellArray::New(); // output
vtkIdTypeArray *newcells = vtkIdTypeArray::New();
newcells->SetNumberOfValues(this->SubSetUGridCellArraySize);
cellArray->SetCells(numCells, newcells);
int cellArrayIdx = 0;
vtkIdTypeArray *locationArray = vtkIdTypeArray::New();
locationArray->SetNumberOfValues(numCells);
vtkUnsignedCharArray *typeArray = vtkUnsignedCharArray::New();
typeArray->SetNumberOfValues(numCells);
int nextCellId = 0;
vtkstd::set<vtkIdType>::iterator cellPtr; // input
vtkIdType *cells = ugrid->GetCells()->GetPointer();
vtkIdType maxid = ugrid->GetCellLocationsArray()->GetMaxId();
vtkIdType *locs = ugrid->GetCellLocationsArray()->GetPointer(0);
vtkUnsignedCharArray *types = ugrid->GetCellTypesArray();
for (cellPtr = this->CellList->IdTypeSet.begin();
cellPtr != this->CellList->IdTypeSet.end();
++cellPtr)
{
if (*cellPtr > maxid) continue;
int oldCellId = *cellPtr;
int loc = locs[oldCellId];
int size = (int)cells[loc];
vtkIdType *pts = cells + loc + 1;
unsigned char type = types->GetValue(oldCellId);
locationArray->SetValue(nextCellId, cellArrayIdx);
typeArray->SetValue(nextCellId, type);
newcells->SetValue(cellArrayIdx++, size);
for (int i=0; i<size; i++)
{
vtkIdType oldId = *pts++;
vtkIdType newId = vtkExtractCells::findInSortedList(ptMap, oldId);
newcells->SetValue(cellArrayIdx++, newId);
}
newCD->CopyData(oldCD, oldCellId, nextCellId);
nextCellId++;
}
output->SetCells(typeArray, locationArray, cellArray);
typeArray->Delete();
locationArray->Delete();
newcells->Delete();
cellArray->Delete();
return;
}
int vtkExtractCells::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
void vtkExtractCells::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<|endoftext|>
|
<commit_before>#ifndef CELL_AUTOMATA_ISING_SYSTEM
#define CELL_AUTOMATA_ISING_SYSTEM
#include "../utilpack/array_matrix.hpp"
#include "spin.hpp"
template<typename spin_T, std::size_t row_Num, std::size_t column_Num, typename simulator_T>
class Ising_system
{
using random_engine_type = simulator_T::random_engine_type;
using numerical_type = simulator_T::numerical_type;
using initializer_type = System_initializer<spin_T>;
using array_matrix =
Utilpack::array_matrix<spin_T*, row_Num, column_Num>;
public:
Ising_system(random_engine_type& ran_e):random_engine(ran_e)
{
typename
uniform_real_distribution<std::size_t>::param_type
param(0, array_matrix.size() - 1);
dist_size.param(param);
initialize();
}
void initialize()
{
System_initializer.initialize(system, tempreture, magnetic_flux_density,
spin_interaction);
return;
}
void reset_states()
{
for(spin_T spin : system)
spin.reset_state();
return;
}
void step()
{
array_matrix.at(dist_size(random_engine)).step();
return;
}
private:
array_matrix system;
numerical_type tempreture, magnetic_flux_density, spin_interaction;
random_engine_type& random_engine;
std::uniform_int_distribution<std::size_t> dist_size;
initializer_type initializer;
};
#endif /* CELL_AUTOMATA_ISING_SYSTEM */
<commit_msg>include system_initializer and edit member name.<commit_after>#ifndef CELL_AUTOMATA_ISING_SYSTEM
#define CELL_AUTOMATA_ISING_SYSTEM
#include "../utilpack/array_matrix.hpp"
#include "spin.hpp"
#include "system_initializer.hpp"
template<typename spin_T, std::size_t row_Num, std::size_t column_Num, typename simulator_T>
class Ising_system
{
using random_engine_type = simulator_T::random_engine_type;
using numerical_type = simulator_T::numerical_type;
using initializer_type = System_initializer<spin_T>;
using array_matrix =
Utilpack::array_matrix<spin_T*, row_Num, column_Num>;
public:
Ising_system(random_engine_type& ran_e):random_engine(ran_e)
{
typename
uniform_real_distribution<std::size_t>::param_type
param(0, array_matrix.size() - 1);
dist_size.param(param);
initialize();
}
void initialize()
{
initializer.initialize(system, tempreture, magnetic_flux_density,
spin_interaction);
return;
}
void reset_states()
{
for(spin_T spin : system)
spin.reset_state();
return;
}
void step()
{
array_matrix.at(dist_size(random_engine)).step();
return;
}
private:
array_matrix system;
numerical_type tempreture, magnetic_flux_density, spin_interaction;
random_engine_type& random_engine;
std::uniform_int_distribution<std::size_t> dist_size;
initializer_type initializer;
};
#endif /* CELL_AUTOMATA_ISING_SYSTEM */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "virtual-keyboard-impl.h"
// EXTERNAL INCLUDES
#include <algorithm>
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include "ecore-virtual-keyboard.h"
#include <adaptor.h>
#include <locale-utils.h>
#include <imf-manager-impl.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace VirtualKeyboard
{
namespace
{
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VIRTUAL_KEYBOARD");
#endif
#define TOKEN_STRING(x) #x
//forward declarations
void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value );
void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value );
// Signals
Dali::VirtualKeyboard::StatusSignalType gKeyboardStatusSignal;
Dali::VirtualKeyboard::VoidSignalType gKeyboardResizeSignal;
Dali::VirtualKeyboard::VoidSignalType gKeyboardLanguageChangedSignal;
void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value )
{
switch (value)
{
case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_SHOW\n" );
gKeyboardStatusSignal.Emit( true );
break;
}
case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_HIDE\n" );
gKeyboardStatusSignal.Emit( false );
break;
}
case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
default:
{
// Do nothing
break;
}
}
}
void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelLanguageChangeCallback" );
// Emit the signal that the language has changed
gKeyboardLanguageChangedSignal.Emit();
}
void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelGeometryChangedCallback\n" );
// Emit signal that the keyboard is resized
gKeyboardResizeSignal.Emit();
}
} // unnamed namespace
void ConnectCallbacks( Ecore_IMF_Context *imfContext )
{
if( imfContext )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ConnectPanelCallbacks\n" );
ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, NULL );
ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, NULL );
ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, NULL );
}
}
void DisconnectCallbacks( Ecore_IMF_Context *imfContext )
{
if( imfContext )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB DisconnectPanelCallbacks\n" );
ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback );
ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback );
ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback );
}
}
void Show()
{
Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) to show the keyboard
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if( imfContext )
{
ecore_imf_context_input_panel_show( imfContext );
}
}
void Hide()
{
if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance*/ )
{
Dali::ImfManager imfManager = ImfManager::Get();
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if( imfContext )
{
ecore_imf_context_input_panel_hide( imfContext );
}
}
}
bool IsVisible()
{
if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance */ )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "IMF IsVisible\n" );
Dali::ImfManager imfManager = ImfManager::Get();
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
if (ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_SHOW ||
ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW)
{
return true;
}
}
}
return false;
}
void ApplySettings( const Property::Map& settingsMap )
{
using namespace InputMethod; // Allows exclusion of namespace in TOKEN_STRING.
for ( unsigned int i = 0, count = settingsMap.Count(); i < count; ++i )
{
std::string key = settingsMap.GetKey( i );
Property::Value item = settingsMap.GetValue(i);
if ( key == TOKEN_STRING( ACTION_BUTTON ) )
{
if ( item.GetType() == Property::INTEGER )
{
int value = item.Get< int >();
VirtualKeyboard::SetReturnKeyType( static_cast<InputMethod::ActionButton>(value) );
}
}
else
{
DALI_LOG_INFO( gLogFilter, Debug::General, "Provided Settings Key not supported\n" );
}
}
}
void EnablePrediction(const bool enable)
{
Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when enabling prediction
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
ecore_imf_context_prediction_allow_set( imfContext, (enable)? EINA_TRUE : EINA_FALSE);
}
}
bool IsPredictionEnabled()
{
if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManger */ )
{
Dali::ImfManager imfManager = ImfManager::Get();
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
// predictive text is enabled.
if ( ecore_imf_context_input_panel_enabled_get( imfContext ) == EINA_TRUE )
{
return true;
}
}
}
return false;
}
Rect<int> GetSizeAndPosition()
{
int xPos, yPos, width, height;
width = height = xPos = yPos = 0;
Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) as we may need to do some size related setup in the application
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if( imfContext )
{
ecore_imf_context_input_panel_geometry_get(imfContext, &xPos, &yPos, &width, &height);
}
else
{
DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
// return 0 as real size unknown.
}
return Rect<int>(xPos,yPos,width,height);
}
Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal()
{
return gKeyboardStatusSignal;
}
Dali::VirtualKeyboard::VoidSignalType& ResizedSignal()
{
return gKeyboardResizeSignal;
}
Dali::VirtualKeyboard::VoidSignalType& LanguageChangedSignal()
{
return gKeyboardLanguageChangedSignal;
}
Dali::VirtualKeyboard::TextDirection GetTextDirection()
{
Dali::VirtualKeyboard::TextDirection direction ( Dali::VirtualKeyboard::LeftToRight );
if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
{
Dali::ImfManager imfManager = ImfManager::Get();
if ( imfManager )
{
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
char* locale( NULL );
ecore_imf_context_input_panel_language_locale_get( imfContext, &locale );
if ( locale )
{
direction = Locale::GetTextDirection( std::string( locale ) );
free( locale );
}
}
}
}
return direction;
}
} // namespace VirtualKeyboard
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<commit_msg>Handle NULL pointer for UTC on target<commit_after>/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "virtual-keyboard-impl.h"
// EXTERNAL INCLUDES
#include <algorithm>
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include "ecore-virtual-keyboard.h"
#include <adaptor.h>
#include <locale-utils.h>
#include <imf-manager-impl.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace VirtualKeyboard
{
namespace
{
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VIRTUAL_KEYBOARD");
#endif
#define TOKEN_STRING(x) #x
//forward declarations
void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value );
void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value );
// Signals
Dali::VirtualKeyboard::StatusSignalType gKeyboardStatusSignal;
Dali::VirtualKeyboard::VoidSignalType gKeyboardResizeSignal;
Dali::VirtualKeyboard::VoidSignalType gKeyboardLanguageChangedSignal;
void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value )
{
switch (value)
{
case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_SHOW\n" );
gKeyboardStatusSignal.Emit( true );
break;
}
case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_HIDE\n" );
gKeyboardStatusSignal.Emit( false );
break;
}
case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
default:
{
// Do nothing
break;
}
}
}
void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelLanguageChangeCallback" );
// Emit the signal that the language has changed
gKeyboardLanguageChangedSignal.Emit();
}
void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelGeometryChangedCallback\n" );
// Emit signal that the keyboard is resized
gKeyboardResizeSignal.Emit();
}
} // unnamed namespace
void ConnectCallbacks( Ecore_IMF_Context *imfContext )
{
if( imfContext )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ConnectPanelCallbacks\n" );
ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, NULL );
ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, NULL );
ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, NULL );
}
}
void DisconnectCallbacks( Ecore_IMF_Context *imfContext )
{
if( imfContext )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "VKB DisconnectPanelCallbacks\n" );
ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback );
ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback );
ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback );
}
}
void Show()
{
Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) to show the keyboard
if( imfManager )
{
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if( imfContext )
{
ecore_imf_context_input_panel_show( imfContext );
}
}
}
void Hide()
{
if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance*/ )
{
Dali::ImfManager imfManager = ImfManager::Get();
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if( imfContext )
{
ecore_imf_context_input_panel_hide( imfContext );
}
}
}
bool IsVisible()
{
if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance */ )
{
DALI_LOG_INFO( gLogFilter, Debug::General, "IMF IsVisible\n" );
Dali::ImfManager imfManager = ImfManager::Get();
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
if (ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_SHOW ||
ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW)
{
return true;
}
}
}
return false;
}
void ApplySettings( const Property::Map& settingsMap )
{
using namespace InputMethod; // Allows exclusion of namespace in TOKEN_STRING.
for ( unsigned int i = 0, count = settingsMap.Count(); i < count; ++i )
{
std::string key = settingsMap.GetKey( i );
Property::Value item = settingsMap.GetValue(i);
if ( key == TOKEN_STRING( ACTION_BUTTON ) )
{
if ( item.GetType() == Property::INTEGER )
{
int value = item.Get< int >();
VirtualKeyboard::SetReturnKeyType( static_cast<InputMethod::ActionButton>(value) );
}
}
else
{
DALI_LOG_INFO( gLogFilter, Debug::General, "Provided Settings Key not supported\n" );
}
}
}
void EnablePrediction(const bool enable)
{
Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when enabling prediction
if( imfManager )
{
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
ecore_imf_context_prediction_allow_set( imfContext, (enable)? EINA_TRUE : EINA_FALSE);
}
}
}
bool IsPredictionEnabled()
{
if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManger */ )
{
Dali::ImfManager imfManager = ImfManager::Get();
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
// predictive text is enabled.
if ( ecore_imf_context_input_panel_enabled_get( imfContext ) == EINA_TRUE )
{
return true;
}
}
}
return false;
}
Rect<int> GetSizeAndPosition()
{
int xPos, yPos, width, height;
width = height = xPos = yPos = 0;
Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) as we may need to do some size related setup in the application
if( imfManager )
{
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if( imfContext )
{
ecore_imf_context_input_panel_geometry_get(imfContext, &xPos, &yPos, &width, &height);
}
else
{
DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
// return 0 as real size unknown.
}
}
return Rect<int>(xPos,yPos,width,height);
}
Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal()
{
return gKeyboardStatusSignal;
}
Dali::VirtualKeyboard::VoidSignalType& ResizedSignal()
{
return gKeyboardResizeSignal;
}
Dali::VirtualKeyboard::VoidSignalType& LanguageChangedSignal()
{
return gKeyboardLanguageChangedSignal;
}
Dali::VirtualKeyboard::TextDirection GetTextDirection()
{
Dali::VirtualKeyboard::TextDirection direction ( Dali::VirtualKeyboard::LeftToRight );
if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
{
Dali::ImfManager imfManager = ImfManager::Get();
if ( imfManager )
{
Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
if ( imfContext )
{
char* locale( NULL );
ecore_imf_context_input_panel_language_locale_get( imfContext, &locale );
if ( locale )
{
direction = Locale::GetTextDirection( std::string( locale ) );
free( locale );
}
}
}
}
return direction;
}
} // namespace VirtualKeyboard
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<|endoftext|>
|
<commit_before>/* Copyright 2017 Kristofer Björnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file Plotter.cpp
*
* @author Kristofer Björnson
*/
#include "../../../include/Utilities/Plotter/PlotCanvas.h"
#include "Smooth.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
namespace TBTK{
namespace Plot{
PlotCanvas::PlotCanvas(){
width = 600;
height = 400;
paddingLeft = 100;
paddingRight = 40;
paddingBottom = 30;
paddingTop = 20;
showColorBox = false;
minColor = 0;
maxColor = 0;
}
PlotCanvas::~PlotCanvas(){
}
void PlotCanvas::drawAxes(){
//Axes
line(
canvas,
getCVPoint(minX, minY),
getCVPoint(maxX, minY),
Scalar(0, 0, 0),
2,
CV_AA
);
line(
canvas,
getCVPoint(minX, minY),
getCVPoint(minX, maxY),
Scalar(0, 0, 0),
2,
CV_AA
);
//Axes values
stringstream ss;
ss.precision(1);
ss << scientific << minX;
string minXString = ss.str();
ss.str("");
ss << scientific << maxX;
string maxXString = ss.str();
ss.str("");
ss << scientific << minY;
string minYString = ss.str();
ss.str("");
ss << scientific << maxY;
string maxYString = ss.str();
int minXStringBaseLine;
int maxXStringBaseLine;
int minYStringBaseLine;
int maxYStringBaseLine;
Size minXStringSize = getTextSize(
minXString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&minXStringBaseLine
);
Size maxXStringSize = getTextSize(
maxXString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&maxXStringBaseLine
);
Size minYStringSize = getTextSize(
minYString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&minYStringBaseLine
);
Size maxYStringSize = getTextSize(
maxYString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&maxYStringBaseLine
);
putText(
canvas,
minXString,
Point(
paddingLeft - minXStringSize.width/2,
canvas.rows - (paddingBottom - 1.5*minXStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
maxXString,
Point(
canvas.cols - (paddingRight + showColorBox*COLOR_BOX_WINDOW_WIDTH + maxXStringSize.width/2),
canvas.rows - (paddingBottom - 1.5*maxXStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
minYString,
Point(
paddingLeft - minYStringSize.width - 10,
canvas.rows - paddingBottom
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
maxYString,
Point(
paddingLeft - maxYStringSize.width - 10,
paddingTop + maxYStringSize.height
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
//Labels
int labelXStringBaseLine;
int labelYStringBaseLine;
Size labelXStringSize = getTextSize(
labelX,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&labelXStringBaseLine
);
Size labelYStringSize = getTextSize(
labelY,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&labelYStringBaseLine
);
putText(
canvas,
labelX,
Point(
paddingLeft + (canvas.cols - paddingLeft - paddingRight - showColorBox*COLOR_BOX_WINDOW_WIDTH)/2 - labelXStringSize.width/2,
canvas.rows - (paddingBottom - 1.5*minXStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
labelY,
Point(
paddingLeft - labelYStringSize.width - 10,
paddingBottom + (canvas.rows - paddingBottom - paddingTop)/2 - labelYStringSize.height/2
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
if(showColorBox)
drawColorBox();
}
void PlotCanvas::drawColorBox(){
stringstream ss;
ss.precision(1);
ss << scientific << maxColor;
string maxColorString = ss.str();
int maxColorStringBaseLine;
Size maxColorStringSize = getTextSize(
maxColorString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&maxColorStringBaseLine
);
putText(
canvas,
maxColorString,
Point(
canvas.cols - COLOR_BOX_WINDOW_WIDTH/2 - maxColorStringSize.width/2,
paddingTop + 1.5*maxColorStringSize.height
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
ss.str("");
ss << scientific << minColor;
string minColorString = ss.str();
int minColorStringBaseLine;
Size minColorStringSize = getTextSize(
minColorString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&minColorStringBaseLine
);
putText(
canvas,
minColorString,
Point(
canvas.cols - COLOR_BOX_WINDOW_WIDTH/2 - minColorStringSize.width/2,
canvas.rows - (paddingBottom - 1.5*minColorStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
double minX = canvas.cols - 3*COLOR_BOX_WINDOW_WIDTH/4;
double maxX = canvas.cols - COLOR_BOX_WINDOW_WIDTH/4;
double minY = paddingTop + 2.5*maxColorStringSize.height;
double maxY = canvas.rows - paddingBottom;
for(
unsigned int y = minY;
y < maxY;
y++
){
for(
unsigned int x = minX;
x < maxX;
x++
){
double value = minColor + (maxColor - minColor)*(maxY - y)/(maxY - minY);
canvas.at<Vec3b>(y, x)[0] = 255;
canvas.at<Vec3b>(y, x)[1] = (255 - 255*(value - minColor)/(maxColor + minColor));
canvas.at<Vec3b>(y, x)[2] = (255 - 255*(value - minColor)/(maxColor + minColor));
}
}
}
}; //End of namespace Plot
}; //End of namespace TBTK
<commit_msg>Corrected mistake with color scaling in PlotCanvas::drawColorBox().<commit_after>/* Copyright 2017 Kristofer Björnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file Plotter.cpp
*
* @author Kristofer Björnson
*/
#include "../../../include/Utilities/Plotter/PlotCanvas.h"
#include "Smooth.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
namespace TBTK{
namespace Plot{
PlotCanvas::PlotCanvas(){
width = 600;
height = 400;
paddingLeft = 100;
paddingRight = 40;
paddingBottom = 30;
paddingTop = 20;
showColorBox = false;
minColor = 0;
maxColor = 0;
}
PlotCanvas::~PlotCanvas(){
}
void PlotCanvas::drawAxes(){
//Axes
line(
canvas,
getCVPoint(minX, minY),
getCVPoint(maxX, minY),
Scalar(0, 0, 0),
2,
CV_AA
);
line(
canvas,
getCVPoint(minX, minY),
getCVPoint(minX, maxY),
Scalar(0, 0, 0),
2,
CV_AA
);
//Axes values
stringstream ss;
ss.precision(1);
ss << scientific << minX;
string minXString = ss.str();
ss.str("");
ss << scientific << maxX;
string maxXString = ss.str();
ss.str("");
ss << scientific << minY;
string minYString = ss.str();
ss.str("");
ss << scientific << maxY;
string maxYString = ss.str();
int minXStringBaseLine;
int maxXStringBaseLine;
int minYStringBaseLine;
int maxYStringBaseLine;
Size minXStringSize = getTextSize(
minXString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&minXStringBaseLine
);
Size maxXStringSize = getTextSize(
maxXString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&maxXStringBaseLine
);
Size minYStringSize = getTextSize(
minYString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&minYStringBaseLine
);
Size maxYStringSize = getTextSize(
maxYString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&maxYStringBaseLine
);
putText(
canvas,
minXString,
Point(
paddingLeft - minXStringSize.width/2,
canvas.rows - (paddingBottom - 1.5*minXStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
maxXString,
Point(
canvas.cols - (paddingRight + showColorBox*COLOR_BOX_WINDOW_WIDTH + maxXStringSize.width/2),
canvas.rows - (paddingBottom - 1.5*maxXStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
minYString,
Point(
paddingLeft - minYStringSize.width - 10,
canvas.rows - paddingBottom
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
maxYString,
Point(
paddingLeft - maxYStringSize.width - 10,
paddingTop + maxYStringSize.height
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
//Labels
int labelXStringBaseLine;
int labelYStringBaseLine;
Size labelXStringSize = getTextSize(
labelX,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&labelXStringBaseLine
);
Size labelYStringSize = getTextSize(
labelY,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&labelYStringBaseLine
);
putText(
canvas,
labelX,
Point(
paddingLeft + (canvas.cols - paddingLeft - paddingRight - showColorBox*COLOR_BOX_WINDOW_WIDTH)/2 - labelXStringSize.width/2,
canvas.rows - (paddingBottom - 1.5*minXStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
putText(
canvas,
labelY,
Point(
paddingLeft - labelYStringSize.width - 10,
paddingBottom + (canvas.rows - paddingBottom - paddingTop)/2 - labelYStringSize.height/2
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
if(showColorBox)
drawColorBox();
}
void PlotCanvas::drawColorBox(){
stringstream ss;
ss.precision(1);
ss << scientific << maxColor;
string maxColorString = ss.str();
int maxColorStringBaseLine;
Size maxColorStringSize = getTextSize(
maxColorString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&maxColorStringBaseLine
);
putText(
canvas,
maxColorString,
Point(
canvas.cols - COLOR_BOX_WINDOW_WIDTH/2 - maxColorStringSize.width/2,
paddingTop + 1.5*maxColorStringSize.height
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
ss.str("");
ss << scientific << minColor;
string minColorString = ss.str();
int minColorStringBaseLine;
Size minColorStringSize = getTextSize(
minColorString,
FONT_HERSHEY_SIMPLEX,
0.5,
1,
&minColorStringBaseLine
);
putText(
canvas,
minColorString,
Point(
canvas.cols - COLOR_BOX_WINDOW_WIDTH/2 - minColorStringSize.width/2,
canvas.rows - (paddingBottom - 1.5*minColorStringSize.height)
),
FONT_HERSHEY_SIMPLEX,
0.5,
Scalar(0, 0, 0),
2,
false
);
double minX = canvas.cols - 3*COLOR_BOX_WINDOW_WIDTH/4;
double maxX = canvas.cols - COLOR_BOX_WINDOW_WIDTH/4;
double minY = paddingTop + 2.5*maxColorStringSize.height;
double maxY = canvas.rows - paddingBottom;
for(
unsigned int y = minY;
y < maxY;
y++
){
for(
unsigned int x = minX;
x < maxX;
x++
){
double value = minColor + (maxColor - minColor)*(maxY - y)/(maxY - minY);
canvas.at<Vec3b>(y, x)[0] = 255;
canvas.at<Vec3b>(y, x)[1] = (255 - 255*(value - minColor)/(maxColor - minColor));
canvas.at<Vec3b>(y, x)[2] = (255 - 255*(value - minColor)/(maxColor - minColor));
}
}
}
}; //End of namespace Plot
}; //End of namespace TBTK
<|endoftext|>
|
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define Paint_Menu_dialog 17000
#define Paint_Menu_option 17001
class Paint_Menu
{
idd = Paint_Menu_dialog;
movingEnable=1;
onLoad = "uiNamespace setVariable ['Paint_Menu', _this select 0]";
class controlsBackground {
class Paint_Menu_background:w_RscPicture
{
idc=-1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
x=0.28;
y=0.10;
w=0.3505;
h=0.70;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = {A3W_UICOLOR_R, A3W_UICOLOR_G, A3W_UICOLOR_B, 0.8};
x=0.28;
y=0.10;
w=0.3505;
h=0.05;
};
class Paint_Menu_Title:w_RscText
{
idc=-1;
text="Paint Uniform Menu";
x=0.30;
y=0.098;
w=0.31;
h=0.035;
};
class Paint_Menu_Title2:w_RscText
{
idc=-1;
text="$ 500 per paint job (Doesn't work on all uniforms)";
x=0.30;
y=0.116;
w=0.31;
h=0.035;
};
};
class controls {
class Paint_Menu_options:w_Rsclist
{
idc = Paint_Menu_option;
x=0.30;
y=0.18;
w=0.31;
h=0.49;
};
class Paint_Menu_activate:w_RscButton
{
idc=-1;
text="Select";
onButtonClick = "[0] execVM 'addons\UniformPainter\UniformPainter_optionSelect.sqf'";
x=0.325;
y=0.70;
w=0.11;
h=0.071;
};
class Paint_Menu_deactivate:w_RscButton
{
idc=-1;
text="Close";
onButtonClick = "closeDialog 0;";
x=0.475;
y=0.70;
w=0.11;
h=0.071;
};
};
};
<commit_msg>Undo changes to uniformpainter titlebar color<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define Paint_Menu_dialog 17000
#define Paint_Menu_option 17001
class Paint_Menu
{
idd = Paint_Menu_dialog;
movingEnable=1;
onLoad = "uiNamespace setVariable ['Paint_Menu', _this select 0]";
class controlsBackground {
class Paint_Menu_background:w_RscPicture
{
idc=-1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
x=0.28;
y=0.10;
w=0.3505;
h=0.70;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.45,0.005,0,1)";
x=0.28;
y=0.10;
w=0.3505;
h=0.05;
};
class Paint_Menu_Title:w_RscText
{
idc=-1;
text="Paint Uniform Menu";
x=0.30;
y=0.098;
w=0.31;
h=0.035;
};
class Paint_Menu_Title2:w_RscText
{
idc=-1;
text="$ 500 per paint job (Doesn't work on all uniforms)";
x=0.30;
y=0.116;
w=0.31;
h=0.035;
};
};
class controls {
class Paint_Menu_options:w_Rsclist
{
idc = Paint_Menu_option;
x=0.30;
y=0.18;
w=0.31;
h=0.49;
};
class Paint_Menu_activate:w_RscButton
{
idc=-1;
text="Select";
onButtonClick = "[0] execVM 'addons\UniformPainter\UniformPainter_optionSelect.sqf'";
x=0.325;
y=0.70;
w=0.11;
h=0.071;
};
class Paint_Menu_deactivate:w_RscButton
{
idc=-1;
text="Close";
onButtonClick = "closeDialog 0;";
x=0.475;
y=0.70;
w=0.11;
h=0.071;
};
};
};
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
//#include "hip_estimator.h"
#include "nthash.hpp"
using namespace std;
namespace opt {
unsigned threads=1;
unsigned kmerLen=64;
const unsigned nhash=4;
}
void printBin(uint64_t n) {
int count=0,count1=0;
while (++count<=64) {
if (n & ((uint64_t)1<<63)) {
printf("1");
++count1;
}
else
printf("0");
n <<= 1;
}
printf("\n");
}
void test() {
uint64_t hVal= 0x00F000000000FF0;
printBin(hVal);
cout << __builtin_clzll(hVal) << "\n";
cout << __builtin_ctzll(hVal) << "\n";
exit(0);
}
/*void hipTest(const char *inName, const int opt::kmerLen){
hip_estimator::hip_estimator<std::string> h;
std::ifstream in(inName);
string hseq,seq;
while(getline(in,hseq)) {
getline(in,seq);
getline(in,hseq);
getline(in,hseq);
for(unsigned i=0; i<seq.length()-opt::kmerLen+1;i++)
h.insert(seq.substr(i,opt::kmerLen));
}
in.close();
std::cout << h.count() << std::endl;
}*/
void nthTest(const char *inName) {
std::ifstream in(inName);
#pragma omp parallel
{
uint64_t mVec[opt::nhash];
for (unsigned j=0; j<opt::nhash; j++) mVec[j]=0;
uint64_t hVec[opt::nhash];
bool good = true;
for(string seq, hseq; good;) {
#pragma omp critical(in)
{
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
}
if(good) {
string kmer = seq.substr(0, opt::kmerLen);
NTM64(kmer.c_str(), opt::kmerLen, opt::nhash, hVec); // initial hash vector
if(hVec[0])
for (unsigned j=0; j<opt::nhash; j++) {
//if(!hVec[j]) continue;
int run0 = __builtin_clzll(hVec[j]);
if(run0 > mVec[j]) mVec[j] = run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
NTM64(seq[i], seq[i+opt::kmerLen], opt::kmerLen, opt::nhash, hVec); // consecutive hash vectors
if(hVec[0])
for (unsigned j=0; j<opt::nhash; j++) {
//if(!hVec[j]) continue;
int run0 = __builtin_clzll(hVec[j]);
if(run0 > mVec[j]) mVec[j] = run0;
}
}
}
}
double avg=0.0;
for (unsigned j=0; j<opt::nhash; j++)
avg+=mVec[j];
std::cout << std::fixed << std::setprecision(11) << pow(2,avg/opt::nhash) << "\n";
for (unsigned j=0; j<opt::nhash; j++)
printf("%d\t",mVec[j]);//cerr << mVec[j] << "\n";
}
/*string hseq,seq;
uint64_t hVec[opt::nhash]={0,0,0,0};
int mVec[opt::nhash]={0,0,0,0};
while(getline(in,hseq)) {
getline(in,seq);
getline(in,hseq);
getline(in,hseq);
string kmer = seq.substr(0, opt::kmerLen);
NTM64(kmer.c_str(), opt::kmerLen, opt::nhash, hVec); // initial hash vector
for (unsigned j=0; j<opt::nhash; j++) {
if(!hVec[j]) continue;
int run0 = __builtin_clzll(hVec[j]);
// GreaterThanCAS
while(true) {
int oVal = mVec[j];
if(run0<=oVal) break;
if(__sync_bool_compare_and_swap(mVec+j,oVal,run0)) break;
}
//atomic
//if(run0 > mVec[j]) mVec[j] = run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
NTM64(seq[i], seq[i+opt::kmerLen], opt::kmerLen, opt::nhash, hVec); // consecutive hash vectors
for (unsigned j=0; j<opt::nhash; j++) {
if(!hVec[j]) continue;
int run0 = __builtin_clzll(hVec[j]);
//if(run0 > mVec[j]) mVec[j] = run0;
// GreaterThanCAS
while(true) {
int oVal = mVec[j];
if(run0<=oVal) break;
if(__sync_bool_compare_and_swap(mVec+j,oVal,run0)) break;
}
}
}
}*/
in.close();
//int sum=0;
//for (unsigned j=0; j<opt::nhash; j++)
//sum+=mVec[j];
//cout << sum/4.0 << "\n";
//return sum;
}
int main(int argc, const char *argv[]){
///test();
// hipTest(argv[1], atoi(argv[2]));
nthTest(argv[1]);
return 0;
}
<commit_msg>ntcard first working version<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include "nthash.hpp"
using namespace std;
namespace opt {
unsigned threads=1;
unsigned kmerLen=64;
const unsigned nhash=7;
const unsigned nbuck=512;
const unsigned nbits=9;
}
void qSort(uint64_t a[], int l, int r) {
long i = l-1, j = r, v = a[r];
int tmp;
if (r <= l) return;
for (;;) {
while (a[++i] > v);
while (v > a[--j]) if (j == l) break;
if (i >= j) break;
tmp = a[i];
a[i] = a[j];
a[j]=tmp;
}
tmp = a[i];
a[i] = a[r];
a[r]=tmp;
qSort(a, l, i-1);
qSort(a, i+1, r);
}
void nthTest(const char *inName) {
std::ifstream in(inName);
uint64_t mVec[opt::nhash];
for (unsigned j=0; j<opt::nhash; j++) mVec[j]=0;
uint64_t hVec[opt::nhash];
bool good = true;
for(string seq, hseq; good;) {
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
if(good) {
string kmer = seq.substr(0, opt::kmerLen);
NTM64(kmer.c_str(), opt::kmerLen, opt::nhash, hVec); // initial hash vector
if(hVec[0])
for (unsigned j=0; j<opt::nhash; j++) {
//int run0 = __builtin_clzll(hVec[j]);
int run0 = std::max(__builtin_clzll(hVec[j]),__builtin_ctzll(hVec[j]));
if(run0 > mVec[j]) mVec[j] = run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
NTM64(seq[i], seq[i+opt::kmerLen], opt::kmerLen, opt::nhash, hVec); // consecutive hash vectors
if(hVec[0])
for (unsigned j=0; j<opt::nhash; j++) {
//int run0 = __builtin_clzll(hVec[j]);
int run0 = std::max(__builtin_clzll(hVec[j]),__builtin_ctzll(hVec[j]));
if(run0 > mVec[j]) mVec[j] = run0;
}
}
}
}
in.close();
double avg=0.0;
for (unsigned j=0; j<opt::nhash; j++)
avg+=mVec[j];
std::cout << std::fixed << std::setprecision(11) << pow(2,avg/opt::nhash) << "\n";
for (unsigned j=0; j<opt::nhash; j++)
cout << mVec[j] << "\n";
}
void nthTestBuff(const char *inName) {
std::ifstream in(inName);
uint64_t mVec[opt::nhash][opt::nbuck];
for (unsigned i=0; i<opt::nhash; i++)
for (unsigned j=0; j<opt::nbuck; j++)
mVec[i][j]=0;
uint64_t hVec[opt::nhash];
bool good = true;
for(string seq, hseq; good;) {
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
if(good) {
string kmer = seq.substr(0, opt::kmerLen);
NTM64(kmer.c_str(), opt::kmerLen, opt::nhash, hVec); // initial hash vector
if(hVec[0])
for (unsigned j=0; j<opt::nhash; j++) {
int run0 = std::max(__builtin_clzll(hVec[j]),__builtin_ctzll(hVec[j]));
if(run0 > mVec[j][hVec[j]&(opt::nbuck-1)]) mVec[j][hVec[j]&(opt::nbuck-1)] = run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
NTM64(seq[i], seq[i+opt::kmerLen], opt::kmerLen, opt::nhash, hVec); // consecutive hash vectors
if(hVec[0])
for (unsigned j=0; j<opt::nhash; j++) {
int run0 = std::max(__builtin_clzll(hVec[j]),__builtin_ctzll(hVec[j]));
if(run0 > mVec[j][hVec[j]&(opt::nbuck-1)]) mVec[j][hVec[j]&(opt::nbuck-1)] = run0;
}
}
}
}
in.close();
//double avg=0.0;
//for (unsigned j=0; j<opt::nhash; j++)
//avg+=mVec[j];
//std::cout << std::fixed << std::setprecision(11) << pow(2,avg/opt::nhash) << "\n";
//for (unsigned j=0; j<opt::nhash; j++)
//cout << mVec[j] << "\n";
cerr << "Done.\n";
for (unsigned i=0; i<opt::nhash; i++)
qSort(mVec[i],0,opt::nbuck-1);
for (unsigned i=0; i<opt::nhash; i++) {
for (unsigned j=0; j<4; j++)
cout << mVec[i][j] << " ";
cout << "\n";
}
}
void ntCardBuff(const char *inName) {
std::ifstream in(inName);
uint64_t tVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
tVec[j]=0;
#pragma omp parallel
{
uint64_t mVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
mVec[j]=0;
bool good = true;
for(string seq, hseq; good;) {
#pragma omp critical(in)
{
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
}
if(good) {
string kmer = seq.substr(0, opt::kmerLen);
uint64_t hVal = NTP64(kmer.c_str(), opt::kmerLen); // initial hash vector
if(hVal>>opt::nbits) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
hVal = NTP64(hVal, seq[i], seq[i+opt::kmerLen], opt::kmerLen); // consecutive hash vectors
if(hVal&(~(uint64_t)opt::nbuck-1)) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));;
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
}
}
}
#pragma omp critical(out)
{
for (unsigned j=0; j<opt::nbuck; j++)
if(tVec[j] < mVec[j]) tVec[j] = mVec[j];
}
}
in.close();
//double avg=0.0;
//for (unsigned j=0; j<opt::nhash; j++)
//avg+=mVec[j];
//std::cout << std::fixed << std::setprecision(11) << pow(2,avg/opt::nhash) << "\n";
//for (unsigned j=0; j<opt::nhash; j++)
//cout << mVec[j] << "\n";
//qSort(mVec,0,15);
double pEst = 0.0, zEst = 0.0, eEst = 0.0, alpha = 0.0;
if(opt::nbuck==16)
alpha = 2*0.673;
else if (opt::nbuck == 32)
alpha = 2*0.697;
else if(opt::nbuck==64)
alpha = 2*0.709;
else
alpha = 2*0.7213/(1 + 1.079/opt::nbuck);
for (unsigned j=0; j<opt::nbuck-1; j++)
pEst += 1.0/((uint64_t)1<<tVec[j]);
zEst = 1.0/pEst;
eEst = alpha * opt::nbuck * opt::nbuck * zEst;
//std::cout << std::fixed << std::setprecision(10) << eEst << "\n";
std::cout << (unsigned long long) eEst << "\n";
//for (unsigned j=0; j<opt::nbuck-1; j++)
//cout << mVec[j] << " ";
cout << "\n";
}
int main(int argc, const char *argv[]){
//ntCardBuff(argv[1]);
std::ifstream in(argv[1]);
uint64_t tVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
tVec[j]=0;
#pragma omp parallel
{
uint64_t mVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
mVec[j]=0;
bool good = true;
for(string seq, hseq; good;) {
#pragma omp critical(in)
{
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
}
if(good) {
string kmer = seq.substr(0, opt::kmerLen);
uint64_t hVal = NTP64(kmer.c_str(), opt::kmerLen); // initial hash vector
if(hVal>>opt::nbits) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
hVal = NTP64(hVal, seq[i], seq[i+opt::kmerLen], opt::kmerLen); // consecutive hash vectors
if(hVal&(~(uint64_t)opt::nbuck-1)) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));;
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
}
}
}
#pragma omp critical(out)
{
for (unsigned j=0; j<opt::nbuck; j++)
if(tVec[j] < mVec[j]) tVec[j] = mVec[j];
}
}
in.close();
//double avg=0.0;
//for (unsigned j=0; j<opt::nhash; j++)
//avg+=mVec[j];
//std::cout << std::fixed << std::setprecision(11) << pow(2,avg/opt::nhash) << "\n";
//for (unsigned j=0; j<opt::nhash; j++)
//cout << mVec[j] << "\n";
//qSort(mVec,0,15);
double pEst = 0.0, zEst = 0.0, eEst = 0.0, alpha = 0.0;
if(opt::nbuck==16)
alpha = 2*0.673;
else if (opt::nbuck == 32)
alpha = 2*0.697;
else if(opt::nbuck==64)
alpha = 2*0.709;
else
alpha = 2*0.7213/(1 + 1.079/opt::nbuck);
for (unsigned j=0; j<opt::nbuck-1; j++)
pEst += 1.0/((uint64_t)1<<tVec[j]);
zEst = 1.0/pEst;
eEst = alpha * opt::nbuck * opt::nbuck * zEst;
//std::cout << std::fixed << std::setprecision(10) << eEst << "\n";
std::cout << (unsigned long long) eEst << "\n";
//for (unsigned j=0; j<opt::nbuck-1; j++)
//cout << mVec[j] << " ";
cout << "\n";
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef ALGORITHM_HPP
# define ALGORUTHM_HPP
# pragma once
#include <cstddef>
#include <type_traits>
#include <utility>
#include "meta.hpp"
namespace generic
{
// min, max
template <typename T>
inline constexpr T max(T const a, T const b) noexcept
{
return a > b ? a : b;
}
template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<bool(sizeof...(A)) &&
all_of<::std::is_same<typename ::std::decay<T>::type, A>...>{},
T
>::type
max(T const a, T const b, A&& ...args) noexcept
{
return a > b ?
max(a, ::std::forward<A>(args)...) :
max(b, ::std::forward<A>(args)...);
}
template <typename T>
constexpr inline T min(T const a, T const b) noexcept
{
return a < b ? a : b;
}
template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<bool(sizeof...(A)) &&
all_of<::std::is_same<typename ::std::decay<T>::type, A>...>{},
T
>::type
min(T const a, T const b, A&& ...args) noexcept
{
return a < b ?
min(a, ::std::forward<A>(args)...) :
min(b, ::std::forward<A>(args)...);
}
template <typename ...A>
constexpr inline typename ::std::enable_if<bool(sizeof...(A)) &&
all_of<::std::is_same<
typename ::std::decay<typename front<A...>::type>::type, A>...
>{},
::std::pair<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<typename front<A...>::type>::type
>
>::type
minmax(A&& ...args) noexcept
{
return {
min(::std::forward<A>(args)...),
max(::std::forward<A>(args)...)
};
}
}
#endif // ALGORITHM_HPP
<commit_msg>some fixes<commit_after>#ifndef ALGORITHM_HPP
# define ALGORUTHM_HPP
# pragma once
#include <cstddef>
#include <type_traits>
#include <utility>
#include "meta.hpp"
namespace generic
{
// min, max
template <typename T>
constexpr inline T const& max(T const& a, T const& b) noexcept
{
return a > b ? a : b;
}
template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<T>::type,
typename ::std::decay<A>::type
>...
>{},
T
>::type
max(T const a, T const b, A&& ...args) noexcept
{
return a > b ?
max(a, ::std::forward<A>(args)...) :
max(b, ::std::forward<A>(args)...);
}
template <typename T>
constexpr inline T const& min(T const& a, T const& b) noexcept
{
return a < b ? a : b;
}
template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<T>::type,
typename ::std::decay<A>::type
>...
>{},
T
>::type
min(T const a, T const b, A&& ...args) noexcept
{
return a < b ?
min(a, ::std::forward<A>(args)...) :
min(b, ::std::forward<A>(args)...);
}
template <typename ...A>
constexpr inline typename ::std::enable_if<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<A>::type
>...
>{},
::std::pair<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<typename front<A...>::type>::type
>
>::type
minmax(A&& ...args) noexcept
{
return {
min(::std::forward<A>(args)...),
max(::std::forward<A>(args)...)
};
}
}
#endif // ALGORITHM_HPP
<|endoftext|>
|
<commit_before>#include "alignment.hpp"
#include "stream.hpp"
namespace vg {
int hts_for_each(string& filename, function<void(Alignment&)> lambda) {
samFile *in = hts_open(filename.c_str(), "r");
if (in == NULL) return 0;
bam_hdr_t *hdr = sam_hdr_read(in);
map<string, string> rg_sample;
parse_rg_sample_map(hdr->text, rg_sample);
bam1_t *b = bam_init1();
while (sam_read1(in, hdr, b) >= 0) {
Alignment a = bam_to_alignment(b, rg_sample);
lambda(a);
}
bam_destroy1(b);
bam_hdr_destroy(hdr);
hts_close(in);
return 1;
}
int hts_for_each_parallel(string& filename, function<void(Alignment&)> lambda) {
samFile *in = hts_open(filename.c_str(), "r");
if (in == NULL) return 0;
bam_hdr_t *hdr = sam_hdr_read(in);
map<string, string> rg_sample;
parse_rg_sample_map(hdr->text, rg_sample);
int thread_count = get_thread_count();
vector<bam1_t*> bs; bs.resize(thread_count);
for (auto& b : bs) {
b = bam_init1();
}
bool more_data = true;
#pragma omp parallel shared(in, hdr, more_data, rg_sample)
{
int tid = omp_get_thread_num();
while (more_data) {
bam1_t* b = bs[tid];
#pragma omp critical (hts_input)
if (more_data) {
more_data = sam_read1(in, hdr, b) >= 0;
}
if (more_data) {
Alignment a = bam_to_alignment(b, rg_sample);
lambda(a);
}
}
}
for (auto& b : bs) bam_destroy1(b);
bam_hdr_destroy(hdr);
hts_close(in);
return 1;
}
bam_hdr_t* hts_file_header(string& filename, string& header) {
samFile *in = hts_open(filename.c_str(), "r");
if (in == NULL) {
cerr << "[vg::alignment] could not open " << filename << endl;
exit(1);
}
bam_hdr_t *hdr = sam_hdr_read(in);
header = hdr->text;
bam_hdr_destroy(hdr);
hts_close(in);
return hdr;
}
bam_hdr_t* hts_string_header(string& header,
map<string, int64_t>& path_length,
map<string, string>& rg_sample) {
stringstream hdr;
hdr << "@HD\tVN:1.5\tSO:unknown\n";
for (auto& p : path_length) {
hdr << "@SQ\tSN:" << p.first << "\t" << "LN:" << p.second << "\n";
}
for (auto& s : rg_sample) {
hdr << "@RG\tID:" << s.first << "\t" << "SM:" << s.second << "\n";
}
hdr << "@PG\tID:0\tPN:vg\n";
header = hdr.str();
string sam = "data:" + header;
samFile *in = sam_open(sam.c_str(), "r");
bam_hdr_t *h = sam_hdr_read(in);
sam_close(in);
return h;
}
void parse_rg_sample_map(char* hts_header, map<string, string>& rg_sample) {
string header(hts_header);
vector<string> header_lines = split(header, '\n');
for (auto& line : header_lines) {
// get next line from header, skip if empty
if ( line.empty() ) { continue; }
// lines of the header look like:
// "@RG ID:- SM:NA11832 CN:BCM PL:454"
// ^^^^^^^\ is our sample name
if (line.find("@RG") == 0) {
vector<string> rg_parts = split(line, "\t ");
string name;
string rg_id;
for (auto& part : rg_parts) {
size_t colpos = part.find(":");
if (colpos != string::npos) {
string fieldname = part.substr(0, colpos);
if (fieldname == "SM") {
name = part.substr(colpos+1);
} else if (fieldname == "ID") {
rg_id = part.substr(colpos+1);
}
}
}
if (name.empty()) {
cerr << "[vg::alignment] Error: could not find 'SM' in @RG line " << endl << line << endl;
exit(1);
}
if (rg_id.empty()) {
cerr << "[vg::alignment] Error: could not find 'ID' in @RG line " << endl << line << endl;
exit(1);
}
map<string, string>::iterator s = rg_sample.find(rg_id);
if (s != rg_sample.end()) {
if (s->second != name) {
cerr << "[vg::alignment] Error: multiple samples (SM) map to the same read group (RG)" << endl
<< endl
<< "samples " << name << " and " << s->second << " map to " << rg_id << endl
<< endl
<< "It will not be possible to determine what sample an alignment belongs to" << endl
<< "at runtime." << endl
<< endl
<< "To resolve the issue, ensure that RG ids are unique to one sample" << endl
<< "across all the input files to freebayes." << endl
<< endl
<< "See bamaddrg (https://github.com/ekg/bamaddrg) for a method which can" << endl
<< "add RG tags to alignments." << endl;
exit(1);
}
}
// if it's the same sample name and RG combo, no worries
rg_sample[rg_id] = name;
}
}
}
void write_alignments(std::ostream& out, vector<Alignment>& buf) {
function<Alignment(uint64_t)> lambda =
[&buf] (uint64_t n) {
return buf[n];
};
stream::write(cout, buf.size(), lambda);
}
short quality_char_to_short(char c) {
return static_cast<short>(c) - 33;
}
char quality_short_to_char(short i) {
return static_cast<char>(i + 33);
}
void alignment_quality_short_to_char(Alignment& alignment) {
alignment.set_quality(string_quality_short_to_char(alignment.quality()));
}
string string_quality_short_to_char(const string& quality) {
string squality;
std::transform(quality.begin(), quality.end(), squality.begin(),
[](char c) { return (char)quality_short_to_char(c); });
return squality;
}
void alignment_quality_char_to_short(Alignment& alignment) {
alignment.set_quality(string_quality_char_to_short(alignment.quality()));
}
string string_quality_char_to_short(const string& quality) {
string squality;
std::transform(quality.begin(), quality.end(), squality.begin(),
[](char c) { return (char)quality_char_to_short(c); });
return squality;
}
// remember to clean up with bam_destroy1(b);
bam1_t* alignment_to_bam(const string& sam_header,
const Alignment& alignment,
const string& refseq,
const int32_t refpos,
const string& cigar,
const string& mateseq,
const int32_t matepos,
const int32_t tlen) {
string sam_file = "data:" + sam_header + alignment_to_sam(alignment, refseq, refpos, cigar, mateseq, matepos, tlen);
const char* sam = sam_file.c_str();
samFile *in = sam_open(sam, "r");
bam_hdr_t *header = sam_hdr_read(in);
bam1_t *aln = bam_init1();
if (sam_read1(in, header, aln) >= 0) {
bam_hdr_destroy(header);
sam_close(in); // clean up
return aln;
} else {
cerr << "[vg::alignment] Failure to parse SAM record" << endl
<< sam << endl;
exit(1);
}
}
string alignment_to_sam(const Alignment& alignment,
const string& refseq,
const int32_t refpos,
const string& cigar,
const string& mateseq,
const int32_t matepos,
const int32_t tlen) {
stringstream sam;
sam << (alignment.has_name() ? alignment.name() : "null") << "\t"
<< sam_flag(alignment) << "\t"
<< refseq << "\t"
<< refpos + 1 << "\t" // positions are 1-based in SAM
<< alignment.mapping_quality() << "\t"
<< cigar << "\t"
<< (mateseq == refseq ? "=" : mateseq) << "\t"
<< matepos + 1 << "\t"
<< tlen << "\t"
<< alignment.sequence() << "\t";
if (alignment.has_quality()) {
const string& quality = alignment.quality();
for (int i = 0; i < quality.size(); ++i) {
sam << quality_short_to_char(quality[i]);
}
sam << "\t";
} else {
sam << string(alignment.sequence().size(), 'I') << "\t";
}
//<< (alignment.has_quality() ? string_quality_short_to_char(alignment.quality()) : string(alignment.sequence().size(), 'I'));
if (alignment.has_read_group()) sam << "\tRG:Z:" << alignment.read_group();
sam << "\n";
return sam.str();
}
// act like the path this is against is the reference
// and generate an equivalent cigar
string cigar_against_path(const Alignment& alignment) {
vector<pair<int, char> > cigar;
const Path& path = alignment.path();
int l = 0;
for (const auto& mapping : path.mapping()) {
for (const auto& edit : mapping.edit()) {
if (edit.has_from_length()) {
if (!edit.has_to_length()) {
// *matches* from_length == to_length, or from_length > 0 and offset unset
// match state
cigar.push_back(make_pair(edit.from_length(), 'M'));
} else {
// mismatch/sub state
// *snps* from_length == to_length; sequence = alt
if (edit.from_length() == edit.to_length()) {
cigar.push_back(make_pair(edit.from_length(), 'M'));
} else if (edit.from_length() == 0 && !edit.has_sequence()) {
// *skip* from_length == 0, to_length > 0; implies "soft clip" or sequence skip
cigar.push_back(make_pair(edit.to_length(), 'S'));
} else if (edit.from_length() > edit.to_length()) {
// *deletions* from_length > to_length; sequence may be unset or empty
int32_t del = edit.from_length() - edit.to_length();
int32_t eq = edit.to_length();
if (eq) cigar.push_back(make_pair(eq, 'M'));
cigar.push_back(make_pair(del, 'D'));
} else if (edit.from_length() < edit.to_length()) {
// *insertions* from_length < to_length; sequence contains relative insertion
int32_t ins = edit.to_length() - edit.from_length();
int32_t eq = edit.from_length();
if (eq) cigar.push_back(make_pair(eq, 'M'));
cigar.push_back(make_pair(ins, 'I'));
}
}
}
}
}
vector<pair<int, char> > cigar_comp;
pair<int, char> cur = make_pair(0, '\0');
for (auto& e : cigar) {
if (cur == make_pair(0, '\0')) {
cur = e;
} else {
if (cur.second == e.second) {
cur.first += e.first;
} else {
cigar_comp.push_back(cur);
cur = e;
}
}
}
cigar_comp.push_back(cur);
stringstream cigarss;
for (auto& e : cigar_comp) {
cigarss << e.first << e.second;
}
return cigarss.str();
}
int32_t sam_flag(const Alignment& alignment) {
int16_t flag = 0;
if (alignment.score() == 0) {
// unmapped
flag |= BAM_FUNMAP;
} else {
// correctly aligned
flag |= BAM_FPROPER_PAIR;
}
if (alignment.is_reverse()) {
flag |= BAM_FREVERSE;
}
return flag;
}
Alignment bam_to_alignment(const bam1_t *b, map<string, string>& rg_sample) {
Alignment alignment;
// get the sequence and qual
int32_t lqseq = b->core.l_qseq;
string sequence; sequence.resize(lqseq);
uint8_t* qualptr = bam_get_qual(b);
string quality;//(lqseq, 0);
quality.assign((char*)qualptr, lqseq);
// process the sequence into chars
uint8_t* seqptr = bam_get_seq(b);
for (int i = 0; i < lqseq; ++i) {
sequence[i] = "=ACMGRSVTWYHKDBN"[bam_seqi(seqptr, i)];
}
// get the read group and sample name
uint8_t *rgptr = bam_aux_get(b, "RG");
char* rg = (char*) (rgptr+1);
//if (!rg_sample
string sname;
if (!rg_sample.empty()) {
sname = rg_sample[string(rg)];
}
// add features to the alignment
alignment.set_name(bam_get_qname(b));
alignment.set_sequence(sequence);
alignment.set_quality(quality);
alignment.set_is_reverse(bam_is_rev(b));
if (sname.size()) {
alignment.set_sample_name(sname);
alignment.set_read_group(rg);
}
return alignment;
}
int to_length(Mapping& m) {
int l = 0;
for (int i = 0; i < m.edit_size(); ++i) {
const Edit& e = m.edit(i);
l += e.to_length();
}
return l;
}
int from_length(Mapping& m) {
int l = 0;
for (int i = 0; i < m.edit_size(); ++i) {
const Edit& e = m.edit(i);
l += e.from_length();
}
return l;
}
}
<commit_msg>fix SAM aux field<commit_after>#include "alignment.hpp"
#include "stream.hpp"
namespace vg {
int hts_for_each(string& filename, function<void(Alignment&)> lambda) {
samFile *in = hts_open(filename.c_str(), "r");
if (in == NULL) return 0;
bam_hdr_t *hdr = sam_hdr_read(in);
map<string, string> rg_sample;
parse_rg_sample_map(hdr->text, rg_sample);
bam1_t *b = bam_init1();
while (sam_read1(in, hdr, b) >= 0) {
Alignment a = bam_to_alignment(b, rg_sample);
lambda(a);
}
bam_destroy1(b);
bam_hdr_destroy(hdr);
hts_close(in);
return 1;
}
int hts_for_each_parallel(string& filename, function<void(Alignment&)> lambda) {
samFile *in = hts_open(filename.c_str(), "r");
if (in == NULL) return 0;
bam_hdr_t *hdr = sam_hdr_read(in);
map<string, string> rg_sample;
parse_rg_sample_map(hdr->text, rg_sample);
int thread_count = get_thread_count();
vector<bam1_t*> bs; bs.resize(thread_count);
for (auto& b : bs) {
b = bam_init1();
}
bool more_data = true;
#pragma omp parallel shared(in, hdr, more_data, rg_sample)
{
int tid = omp_get_thread_num();
while (more_data) {
bam1_t* b = bs[tid];
#pragma omp critical (hts_input)
if (more_data) {
more_data = sam_read1(in, hdr, b) >= 0;
}
if (more_data) {
Alignment a = bam_to_alignment(b, rg_sample);
lambda(a);
}
}
}
for (auto& b : bs) bam_destroy1(b);
bam_hdr_destroy(hdr);
hts_close(in);
return 1;
}
bam_hdr_t* hts_file_header(string& filename, string& header) {
samFile *in = hts_open(filename.c_str(), "r");
if (in == NULL) {
cerr << "[vg::alignment] could not open " << filename << endl;
exit(1);
}
bam_hdr_t *hdr = sam_hdr_read(in);
header = hdr->text;
bam_hdr_destroy(hdr);
hts_close(in);
return hdr;
}
bam_hdr_t* hts_string_header(string& header,
map<string, int64_t>& path_length,
map<string, string>& rg_sample) {
stringstream hdr;
hdr << "@HD\tVN:1.5\tSO:unknown\n";
for (auto& p : path_length) {
hdr << "@SQ\tSN:" << p.first << "\t" << "LN:" << p.second << "\n";
}
for (auto& s : rg_sample) {
hdr << "@RG\tID:" << s.first << "\t" << "SM:" << s.second << "\n";
}
hdr << "@PG\tID:0\tPN:vg\n";
header = hdr.str();
string sam = "data:" + header;
samFile *in = sam_open(sam.c_str(), "r");
bam_hdr_t *h = sam_hdr_read(in);
sam_close(in);
return h;
}
void parse_rg_sample_map(char* hts_header, map<string, string>& rg_sample) {
string header(hts_header);
vector<string> header_lines = split(header, '\n');
for (auto& line : header_lines) {
// get next line from header, skip if empty
if ( line.empty() ) { continue; }
// lines of the header look like:
// "@RG ID:- SM:NA11832 CN:BCM PL:454"
// ^^^^^^^\ is our sample name
if (line.find("@RG") == 0) {
vector<string> rg_parts = split(line, "\t ");
string name;
string rg_id;
for (auto& part : rg_parts) {
size_t colpos = part.find(":");
if (colpos != string::npos) {
string fieldname = part.substr(0, colpos);
if (fieldname == "SM") {
name = part.substr(colpos+1);
} else if (fieldname == "ID") {
rg_id = part.substr(colpos+1);
}
}
}
if (name.empty()) {
cerr << "[vg::alignment] Error: could not find 'SM' in @RG line " << endl << line << endl;
exit(1);
}
if (rg_id.empty()) {
cerr << "[vg::alignment] Error: could not find 'ID' in @RG line " << endl << line << endl;
exit(1);
}
map<string, string>::iterator s = rg_sample.find(rg_id);
if (s != rg_sample.end()) {
if (s->second != name) {
cerr << "[vg::alignment] Error: multiple samples (SM) map to the same read group (RG)" << endl
<< endl
<< "samples " << name << " and " << s->second << " map to " << rg_id << endl
<< endl
<< "It will not be possible to determine what sample an alignment belongs to" << endl
<< "at runtime." << endl
<< endl
<< "To resolve the issue, ensure that RG ids are unique to one sample" << endl
<< "across all the input files to freebayes." << endl
<< endl
<< "See bamaddrg (https://github.com/ekg/bamaddrg) for a method which can" << endl
<< "add RG tags to alignments." << endl;
exit(1);
}
}
// if it's the same sample name and RG combo, no worries
rg_sample[rg_id] = name;
}
}
}
void write_alignments(std::ostream& out, vector<Alignment>& buf) {
function<Alignment(uint64_t)> lambda =
[&buf] (uint64_t n) {
return buf[n];
};
stream::write(cout, buf.size(), lambda);
}
short quality_char_to_short(char c) {
return static_cast<short>(c) - 33;
}
char quality_short_to_char(short i) {
return static_cast<char>(i + 33);
}
void alignment_quality_short_to_char(Alignment& alignment) {
alignment.set_quality(string_quality_short_to_char(alignment.quality()));
}
string string_quality_short_to_char(const string& quality) {
string squality;
std::transform(quality.begin(), quality.end(), squality.begin(),
[](char c) { return (char)quality_short_to_char(c); });
return squality;
}
void alignment_quality_char_to_short(Alignment& alignment) {
alignment.set_quality(string_quality_char_to_short(alignment.quality()));
}
string string_quality_char_to_short(const string& quality) {
string squality;
std::transform(quality.begin(), quality.end(), squality.begin(),
[](char c) { return (char)quality_char_to_short(c); });
return squality;
}
// remember to clean up with bam_destroy1(b);
bam1_t* alignment_to_bam(const string& sam_header,
const Alignment& alignment,
const string& refseq,
const int32_t refpos,
const string& cigar,
const string& mateseq,
const int32_t matepos,
const int32_t tlen) {
string sam_file = "data:" + sam_header + alignment_to_sam(alignment, refseq, refpos, cigar, mateseq, matepos, tlen);
const char* sam = sam_file.c_str();
samFile *in = sam_open(sam, "r");
bam_hdr_t *header = sam_hdr_read(in);
bam1_t *aln = bam_init1();
if (sam_read1(in, header, aln) >= 0) {
bam_hdr_destroy(header);
sam_close(in); // clean up
return aln;
} else {
cerr << "[vg::alignment] Failure to parse SAM record" << endl
<< sam << endl;
exit(1);
}
}
string alignment_to_sam(const Alignment& alignment,
const string& refseq,
const int32_t refpos,
const string& cigar,
const string& mateseq,
const int32_t matepos,
const int32_t tlen) {
stringstream sam;
sam << (alignment.has_name() ? alignment.name() : "null") << "\t"
<< sam_flag(alignment) << "\t"
<< refseq << "\t"
<< refpos + 1 << "\t" // positions are 1-based in SAM
<< alignment.mapping_quality() << "\t"
<< cigar << "\t"
<< (mateseq == refseq ? "=" : mateseq) << "\t"
<< matepos + 1 << "\t"
<< tlen << "\t"
<< alignment.sequence() << "\t";
if (alignment.has_quality()) {
const string& quality = alignment.quality();
for (int i = 0; i < quality.size(); ++i) {
sam << quality_short_to_char(quality[i]);
}
} else {
sam << string(alignment.sequence().size(), 'I');
}
//<< (alignment.has_quality() ? string_quality_short_to_char(alignment.quality()) : string(alignment.sequence().size(), 'I'));
if (alignment.has_read_group()) sam << "\tRG:Z:" << alignment.read_group();
sam << "\n";
return sam.str();
}
// act like the path this is against is the reference
// and generate an equivalent cigar
string cigar_against_path(const Alignment& alignment) {
vector<pair<int, char> > cigar;
const Path& path = alignment.path();
int l = 0;
for (const auto& mapping : path.mapping()) {
for (const auto& edit : mapping.edit()) {
if (edit.has_from_length()) {
if (!edit.has_to_length()) {
// *matches* from_length == to_length, or from_length > 0 and offset unset
// match state
cigar.push_back(make_pair(edit.from_length(), 'M'));
} else {
// mismatch/sub state
// *snps* from_length == to_length; sequence = alt
if (edit.from_length() == edit.to_length()) {
cigar.push_back(make_pair(edit.from_length(), 'M'));
} else if (edit.from_length() == 0 && !edit.has_sequence()) {
// *skip* from_length == 0, to_length > 0; implies "soft clip" or sequence skip
cigar.push_back(make_pair(edit.to_length(), 'S'));
} else if (edit.from_length() > edit.to_length()) {
// *deletions* from_length > to_length; sequence may be unset or empty
int32_t del = edit.from_length() - edit.to_length();
int32_t eq = edit.to_length();
if (eq) cigar.push_back(make_pair(eq, 'M'));
cigar.push_back(make_pair(del, 'D'));
} else if (edit.from_length() < edit.to_length()) {
// *insertions* from_length < to_length; sequence contains relative insertion
int32_t ins = edit.to_length() - edit.from_length();
int32_t eq = edit.from_length();
if (eq) cigar.push_back(make_pair(eq, 'M'));
cigar.push_back(make_pair(ins, 'I'));
}
}
}
}
}
vector<pair<int, char> > cigar_comp;
pair<int, char> cur = make_pair(0, '\0');
for (auto& e : cigar) {
if (cur == make_pair(0, '\0')) {
cur = e;
} else {
if (cur.second == e.second) {
cur.first += e.first;
} else {
cigar_comp.push_back(cur);
cur = e;
}
}
}
cigar_comp.push_back(cur);
stringstream cigarss;
for (auto& e : cigar_comp) {
cigarss << e.first << e.second;
}
return cigarss.str();
}
int32_t sam_flag(const Alignment& alignment) {
int16_t flag = 0;
if (alignment.score() == 0) {
// unmapped
flag |= BAM_FUNMAP;
} else {
// correctly aligned
flag |= BAM_FPROPER_PAIR;
}
if (alignment.is_reverse()) {
flag |= BAM_FREVERSE;
}
return flag;
}
Alignment bam_to_alignment(const bam1_t *b, map<string, string>& rg_sample) {
Alignment alignment;
// get the sequence and qual
int32_t lqseq = b->core.l_qseq;
string sequence; sequence.resize(lqseq);
uint8_t* qualptr = bam_get_qual(b);
string quality;//(lqseq, 0);
quality.assign((char*)qualptr, lqseq);
// process the sequence into chars
uint8_t* seqptr = bam_get_seq(b);
for (int i = 0; i < lqseq; ++i) {
sequence[i] = "=ACMGRSVTWYHKDBN"[bam_seqi(seqptr, i)];
}
// get the read group and sample name
uint8_t *rgptr = bam_aux_get(b, "RG");
char* rg = (char*) (rgptr+1);
//if (!rg_sample
string sname;
if (!rg_sample.empty()) {
sname = rg_sample[string(rg)];
}
// add features to the alignment
alignment.set_name(bam_get_qname(b));
alignment.set_sequence(sequence);
alignment.set_quality(quality);
alignment.set_is_reverse(bam_is_rev(b));
if (sname.size()) {
alignment.set_sample_name(sname);
alignment.set_read_group(rg);
}
return alignment;
}
int to_length(Mapping& m) {
int l = 0;
for (int i = 0; i < m.edit_size(); ++i) {
const Edit& e = m.edit(i);
l += e.to_length();
}
return l;
}
int from_length(Mapping& m) {
int l = 0;
for (int i = 0; i < m.edit_size(); ++i) {
const Edit& e = m.edit(i);
l += e.from_length();
}
return l;
}
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFPluginLoader.cpp
// @Author : LvSheng.Huang
// @Date :
// @Module : NFPluginLoader
//
// -------------------------------------------------------------------------
#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include "NFCActorManager.h"
#include "NFComm/Config/NFConfig.h"
#include "NFComm/NFCore/NFPlatform.h"
#include "boost/thread.hpp"
#pragma comment( lib, "DbgHelp" )
// Dumpļ
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
// Dumpļ
HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// DumpϢ
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
// дDumpļ
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
// Unhandled ExceptionĻص
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
time_t t = time(0);
char szDmupName[MAX_PATH];
tm* ptm = localtime(&t);
sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
CreateDumpFile(szDmupName, pException);
FatalAppExit(-1, szDmupName);
return EXCEPTION_EXECUTE_HANDLER;
}
void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
HWND hWnd = GetConsoleWindow();
if(hWnd)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
}
#endif
}
bool bExitApp = false;
boost::thread gThread;
void ThreadFunc()
{
while ( !bExitApp )
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::string s;
std::cin >> s;
if ( 0 == stricmp( s.c_str(), "exit" ) )
{
bExitApp = true;
}
}
}
void CreateBackThread()
{
gThread = boost::thread(boost::bind(&ThreadFunc));
//std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}
void PrintfLogo()
{
std::cout << "\n" << std::endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
std::cout << "" << std::endl;
std::cout << " " << std::endl;
std::cout << " NoahFrame " << std::endl;
std::cout << " Copyright (c) 2011 kytoo " << std::endl;
std::cout << " All rights reserved. " << std::endl;
std::cout << " " << std::endl;
std::cout << " www.yowoyo.com " << std::endl;
std::cout << " " << std::endl;
std::cout << "\n" << std::endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
std::cout << "\n" << std::endl;
}
<<<<<<< HEAD
unsigned long unStartTickTime = 0;
unsigned long unLastTickTime = 0;
=======
unsigned long nStartTickTime = 0;
unsigned long nLastTickTime = 0;
>>>>>>> fc41e1f3b83190429904de8a9203e116d5ec564e
#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
int main()
#elif NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
{
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
NFCActorManager::GetSingletonPtr()->Init();
NFCActorManager::GetSingletonPtr()->AfterInit();
NFCActorManager::GetSingletonPtr()->CheckConfig();
PrintfLogo();
CloseXButton();
CreateBackThread();
nStartTickTime = ::NF_GetTickCount();
nLastTickTime = nStartTickTime;
while (!bExitApp) //DEBUG汾RELEASE
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
while (true)
{
if (bExitApp)
{
break;
}
unsigned long unNowTickTime = ::NF_GetTickCount();
float fStartedTime = float(unNowTickTime - unStartTickTime) / 1000;
float fLastTime = float(unNowTickTime - unLastTickTime) / 1000;
if (fStartedTime < 0.001f)
{
fStartedTime = 0.0f;
}
if (fLastTime < 0.001f)
{
fLastTime = 0.0f;
}
__try
{
<<<<<<< HEAD
NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);
unLastTickTime = unNowTickTime;
=======
unsigned long nNowTickTime = ::NF_GetTickCount();
float fStartedTime = float(nNowTickTime - nStartTickTime) / 1000;
float fLastTime = float(nNowTickTime - nLastTickTime) / 1000;
if (fStartedTime < 0.001f)
{
fStartedTime = 0.0f;
}
if (fLastTime < 0.001f)
{
fLastTime = 0.0f;
}
NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);
>>>>>>> fc41e1f3b83190429904de8a9203e116d5ec564e
}
__except (ApplicationCrashHandler(GetExceptionInformation()))
{
}
}
}
NFCActorManager::GetSingletonPtr()->BeforeShut();
NFCActorManager::GetSingletonPtr()->Shut();
NFCActorManager::GetSingletonPtr()->ReleaseInstance();
return 0;
}<commit_msg>solve conflict<commit_after>// -------------------------------------------------------------------------
// @FileName : NFPluginLoader.cpp
// @Author : LvSheng.Huang
// @Date :
// @Module : NFPluginLoader
//
// -------------------------------------------------------------------------
#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include "NFCActorManager.h"
#include "NFComm/Config/NFConfig.h"
#include "NFComm/NFCore/NFPlatform.h"
#include "boost/thread.hpp"
#pragma comment( lib, "DbgHelp" )
// Dumpļ
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
// Dumpļ
HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// DumpϢ
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
// дDumpļ
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
// Unhandled ExceptionĻص
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
time_t t = time(0);
char szDmupName[MAX_PATH];
tm* ptm = localtime(&t);
sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
CreateDumpFile(szDmupName, pException);
FatalAppExit(-1, szDmupName);
return EXCEPTION_EXECUTE_HANDLER;
}
void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
HWND hWnd = GetConsoleWindow();
if(hWnd)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
}
#endif
}
bool bExitApp = false;
boost::thread gThread;
void ThreadFunc()
{
while ( !bExitApp )
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::string s;
std::cin >> s;
if ( 0 == stricmp( s.c_str(), "exit" ) )
{
bExitApp = true;
}
}
}
void CreateBackThread()
{
gThread = boost::thread(boost::bind(&ThreadFunc));
//std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}
void PrintfLogo()
{
std::cout << "\n" << std::endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
std::cout << "" << std::endl;
std::cout << " " << std::endl;
std::cout << " NoahFrame " << std::endl;
std::cout << " Copyright (c) 2011 kytoo " << std::endl;
std::cout << " All rights reserved. " << std::endl;
std::cout << " " << std::endl;
std::cout << " www.yowoyo.com " << std::endl;
std::cout << " " << std::endl;
std::cout << "\n" << std::endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
std::cout << "\n" << std::endl;
}
unsigned long unStartTickTime = 0;
unsigned long unLastTickTime = 0;
#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
int main()
#elif NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
{
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
NFCActorManager::GetSingletonPtr()->Init();
NFCActorManager::GetSingletonPtr()->AfterInit();
NFCActorManager::GetSingletonPtr()->CheckConfig();
PrintfLogo();
CloseXButton();
CreateBackThread();
unStartTickTime = ::NF_GetTickCount();
unLastTickTime = unStartTickTime;
while (!bExitApp) //DEBUG汾RELEASE
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
while (true)
{
if (bExitApp)
{
break;
}
unsigned long unNowTickTime = ::NF_GetTickCount();
float fStartedTime = float(unNowTickTime - unStartTickTime) / 1000;
float fLastTime = float(unNowTickTime - unLastTickTime) / 1000;
if (fStartedTime < 0.001f)
{
fStartedTime = 0.0f;
}
if (fLastTime < 0.001f)
{
fLastTime = 0.0f;
}
__try
{
NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);
unLastTickTime = unNowTickTime;
}
__except (ApplicationCrashHandler(GetExceptionInformation()))
{
}
}
}
NFCActorManager::GetSingletonPtr()->BeforeShut();
NFCActorManager::GetSingletonPtr()->Shut();
NFCActorManager::GetSingletonPtr()->ReleaseInstance();
return 0;
}<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFPluginLoader.cpp
// @Author : LvSheng.Huang
// @Date :
// @Module : NFPluginLoader
//
// -------------------------------------------------------------------------
//#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <future>
#include <functional>
#include <atomic>
#include "NFCPluginManager.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_LINUX
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/prctl.h>
#endif
bool bExitApp = false;
std::thread gThread;
std::string strArgvList;
std::string strPluginName;
std::string strAppName;
std::string strAppID;
std::string strTitleName;
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "DbgHelp" )
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
//Dump
HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
time_t t = time(0);
char szDmupName[MAX_PATH];
tm* ptm = localtime(&t);
sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
CreateDumpFile(szDmupName, pException);
FatalAppExit(-1, szDmupName);
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
HWND hWnd = GetConsoleWindow();
if (hWnd)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
}
#endif
}
void ThreadFunc()
{
while (!bExitApp)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::string s;
std::cin >> s;
if ( 0 == stricmp( s.c_str(), "exit" ) )
{
bExitApp = true;
gThread.detach();
}
}
}
void CreateBackThread()
{
gThread = std::thread(std::bind(&ThreadFunc));
auto f = std::async (std::launch::deferred, std::bind(ThreadFunc));
std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}
void InitDaemon()
{
#if NF_PLATFORM == NF_PLATFORM_LINUX
daemon(1, 0);
// ignore signals
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTERM, SIG_IGN);
#endif
}
void PrintfLogo()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
std::cout << "\n" << std::endl;
std::cout << "************************************************" << std::endl;
std::cout << "** **" << std::endl;
std::cout << "** NoahFrame **" << std::endl;
std::cout << "** Copyright (c) 2011, LvSheng.Huang **" << std::endl;
std::cout << "** All rights reserved. **" << std::endl;
std::cout << "** **" << std::endl;
std::cout << "************************************************" << std::endl;
std::cout << "\n" << std::endl;
std::cout << "-d Run itas daemon mode, only on linux" << std::endl;
std::cout << "-x Closethe 'X' button, only on windows" << std::endl;
std::cout << "Instance: name.xml File's name to instead of \"Plugin.xml\" when programs be launched, all platform" << std::endl;
std::cout << "Instance: \"ID=number\", \"Server=GameServer\" when programs be launched, all platform" << std::endl;
std::cout << "\n" << std::endl;
#if NF_PLATFORM == NF_PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
}
void ProcessParameter(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
strArgvList += " ";
strArgvList += argv[i];
}
#if NF_PLATFORM == NF_PLATFORM_WIN
if (strArgvList.find("-x") != string::npos)
{
CloseXButton();
}
#elif NF_PLATFORM == NF_PLATFORM_LINUX
//run it as a daemon process
if (strArgvList.find("-d") != string::npos)
{
InitDaemon();
}
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
#endif
if (strArgvList.find(".xml") != string::npos)
{
for (int i = 0; i < argc; i++)
{
strPluginName = argv[i];
if (strPluginName.find(".xml") != string::npos)
{
break;
}
}
NFCPluginManager::GetSingletonPtr()->SetConfigName(strPluginName);
}
if (strArgvList.find("Server=") != string::npos)
{
for (int i = 0; i < argc; i++)
{
strAppName = argv[i];
if (strAppName.find("Server=") != string::npos)
{
strAppName.erase(0, 7);
break;
}
}
NFCPluginManager::GetSingletonPtr()->SetAppName(strAppName);
}
if (strArgvList.find("ID=") != string::npos)
{
for (int i = 0; i < argc; i++)
{
strAppID = argv[i];
if (strAppID.find("ID=") != string::npos)
{
strAppID.erase(0, 3);
break;
}
}
int nAppID = 0;
if(NF_StrTo(strAppID, nAppID))
{
NFCPluginManager::GetSingletonPtr()->SetAppID(nAppID);
}
}
strTitleName = strAppName + strAppID;// +" PID" + NFGetPID();
strTitleName.replace(strTitleName.find("Server"), 6, "");
strTitleName = "NF" + strTitleName;
#if NF_PLATFORM == NF_PLATFORM_WIN
SetConsoleTitle(strTitleName.c_str());
#else
prctl(PR_SET_NAME, strTitleName.c_str());
//setproctitle(strTitleName.c_str());
#endif
}
int main(int argc, char* argv[])
{
#if NF_PLATFORM == NF_PLATFORM_WIN
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
#elif NF_PLATFORM == NF_PLATFORM_LINUX
#endif
ProcessParameter(argc, argv);
PrintfLogo();
CreateBackThread();
NFCPluginManager::GetSingletonPtr()->Awake();
NFCPluginManager::GetSingletonPtr()->Init();
NFCPluginManager::GetSingletonPtr()->AfterInit();
NFCPluginManager::GetSingletonPtr()->CheckConfig();
NFCPluginManager::GetSingletonPtr()->ReadyExecute();
while (!bExitApp)
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (bExitApp)
{
break;
}
#if NF_PLATFORM == NF_PLATFORM_WIN
__try
{
#endif
NFCPluginManager::GetSingletonPtr()->Execute();
#if NF_PLATFORM == NF_PLATFORM_WIN
}
__except (ApplicationCrashHandler(GetExceptionInformation()))
{
}
#endif
}
}
NFCPluginManager::GetSingletonPtr()->BeforeShut();
NFCPluginManager::GetSingletonPtr()->Shut();
NFCPluginManager::GetSingletonPtr()->Finalize();
NFCPluginManager::GetSingletonPtr()->ReleaseInstance();
return 0;
}
<commit_msg>cell manager<commit_after>// -------------------------------------------------------------------------
// @FileName : NFPluginLoader.cpp
// @Author : LvSheng.Huang
// @Date :
// @Module : NFPluginLoader
//
// -------------------------------------------------------------------------
//#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <future>
#include <functional>
#include <atomic>
#include "NFCCellManager.h"
#include "NFCPluginManager.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_LINUX
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/prctl.h>
#endif
bool bExitApp = false;
std::thread gThread;
std::string strArgvList;
std::string strPluginName;
std::string strAppName;
std::string strAppID;
std::string strTitleName;
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "DbgHelp" )
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
//Dump
HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
time_t t = time(0);
char szDmupName[MAX_PATH];
tm* ptm = localtime(&t);
sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
CreateDumpFile(szDmupName, pException);
FatalAppExit(-1, szDmupName);
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
HWND hWnd = GetConsoleWindow();
if (hWnd)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
}
#endif
}
void ThreadFunc()
{
while (!bExitApp)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::string s;
std::cin >> s;
if ( 0 == stricmp( s.c_str(), "exit" ) )
{
bExitApp = true;
gThread.detach();
}
}
}
void CreateBackThread()
{
gThread = std::thread(std::bind(&ThreadFunc));
auto f = std::async (std::launch::deferred, std::bind(ThreadFunc));
std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}
void InitDaemon()
{
#if NF_PLATFORM == NF_PLATFORM_LINUX
daemon(1, 0);
// ignore signals
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTERM, SIG_IGN);
#endif
}
void PrintfLogo()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
std::cout << "\n" << std::endl;
std::cout << "************************************************" << std::endl;
std::cout << "** **" << std::endl;
std::cout << "** NoahFrame **" << std::endl;
std::cout << "** Copyright (c) 2011, LvSheng.Huang **" << std::endl;
std::cout << "** All rights reserved. **" << std::endl;
std::cout << "** **" << std::endl;
std::cout << "************************************************" << std::endl;
std::cout << "\n" << std::endl;
std::cout << "-d Run itas daemon mode, only on linux" << std::endl;
std::cout << "-x Closethe 'X' button, only on windows" << std::endl;
std::cout << "Instance: name.xml File's name to instead of \"Plugin.xml\" when programs be launched, all platform" << std::endl;
std::cout << "Instance: \"ID=number\", \"Server=GameServer\" when programs be launched, all platform" << std::endl;
std::cout << "\n" << std::endl;
#if NF_PLATFORM == NF_PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
}
void ProcessParameter(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
strArgvList += " ";
strArgvList += argv[i];
}
#if NF_PLATFORM == NF_PLATFORM_WIN
if (strArgvList.find("-x") != string::npos)
{
CloseXButton();
}
#elif NF_PLATFORM == NF_PLATFORM_LINUX
//run it as a daemon process
if (strArgvList.find("-d") != string::npos)
{
InitDaemon();
}
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
#endif
if (strArgvList.find(".xml") != string::npos)
{
for (int i = 0; i < argc; i++)
{
strPluginName = argv[i];
if (strPluginName.find(".xml") != string::npos)
{
break;
}
}
NFCPluginManager::GetSingletonPtr()->SetConfigName(strPluginName);
}
if (strArgvList.find("Server=") != string::npos)
{
for (int i = 0; i < argc; i++)
{
strAppName = argv[i];
if (strAppName.find("Server=") != string::npos)
{
strAppName.erase(0, 7);
break;
}
}
NFCPluginManager::GetSingletonPtr()->SetAppName(strAppName);
}
if (strArgvList.find("ID=") != string::npos)
{
for (int i = 0; i < argc; i++)
{
strAppID = argv[i];
if (strAppID.find("ID=") != string::npos)
{
strAppID.erase(0, 3);
break;
}
}
int nAppID = 0;
if(NF_StrTo(strAppID, nAppID))
{
NFCPluginManager::GetSingletonPtr()->SetAppID(nAppID);
}
}
strTitleName = strAppName + strAppID;// +" PID" + NFGetPID();
strTitleName.replace(strTitleName.find("Server"), 6, "");
strTitleName = "NF" + strTitleName;
#if NF_PLATFORM == NF_PLATFORM_WIN
SetConsoleTitle(strTitleName.c_str());
#else
prctl(PR_SET_NAME, strTitleName.c_str());
//setproctitle(strTitleName.c_str());
#endif
}
int main(int argc, char* argv[])
{
#if NF_PLATFORM == NF_PLATFORM_WIN
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
#elif NF_PLATFORM == NF_PLATFORM_LINUX
#endif
ProcessParameter(argc, argv);
PrintfLogo();
CreateBackThread();
NFCPluginManager::GetSingletonPtr()->Awake();
NFCPluginManager::GetSingletonPtr()->Init();
NFCPluginManager::GetSingletonPtr()->AfterInit();
NFCPluginManager::GetSingletonPtr()->CheckConfig();
NFCPluginManager::GetSingletonPtr()->ReadyExecute();
while (!bExitApp)
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (bExitApp)
{
break;
}
#if NF_PLATFORM == NF_PLATFORM_WIN
__try
{
#endif
NFCPluginManager::GetSingletonPtr()->Execute();
#if NF_PLATFORM == NF_PLATFORM_WIN
}
__except (ApplicationCrashHandler(GetExceptionInformation()))
{
}
#endif
}
}
NFCPluginManager::GetSingletonPtr()->BeforeShut();
NFCPluginManager::GetSingletonPtr()->Shut();
NFCPluginManager::GetSingletonPtr()->Finalize();
NFCPluginManager::GetSingletonPtr()->ReleaseInstance();
return 0;
}
<|endoftext|>
|
<commit_before>#include <profile>
#include <hw/pit.hpp>
#include <kernel/elf.hpp>
#include <kernel/irq_manager.hpp>
#include <deque>
#include <unordered_map>
#include <cassert>
#include <algorithm>
#define BUFFER_COUNT 6000
template <typename T, int N>
struct fixedvector {
void add(const T& e) noexcept {
assert(count < N);
element[count] = e;
count++;
}
void clear() noexcept {
count = 0;
}
uint32_t size() const noexcept {
return count;
}
T* first() noexcept {
return &element[0];
}
T* end() noexcept {
return &element[count];
}
void clone(T* src, uint32_t size) {
assert(size <= N);
memcpy(element, src, size * sizeof(T));
count = size;
}
uint32_t count = 0;
T element[N];
};
static fixedvector<uintptr_t, BUFFER_COUNT>* sampler_queue;
static fixedvector<uintptr_t, BUFFER_COUNT>* transfer_queue;
static void* event_loop_addr;
typedef uint32_t func_sample;
std::unordered_map<uintptr_t, func_sample> sampler_dict;
static func_sample sampler_total = 0;
static int lockless_sampler = 0;
extern "C" {
void parasite_interrupt_handler();
void profiler_stack_sampler();
void gather_stack_sampling();
}
void begin_stack_sampling(uint16_t gather_period_ms)
{
// make room for these only when requested
#define blargh(T) std::remove_pointer<decltype(T)>::type;
sampler_queue = new blargh(sampler_queue);
transfer_queue = new blargh(transfer_queue);
sampler_total = 0;
// we want to ignore event loop at FIXME the HLT location (0x198)
event_loop_addr = (void*) ((char*) &OS::event_loop + 0x198);
// begin sampling
IRQ_manager::cpu(0).set_irq_handler(0, parasite_interrupt_handler);
// gather every second
using namespace std::chrono;
hw::PIT::instance().on_repeated_timeout(milliseconds(gather_period_ms),
[] { gather_stack_sampling(); });
}
void profiler_stack_sampler()
{
void* ra = __builtin_return_address(1);
// maybe qemu, maybe some bullshit we don't care about
if (ra == nullptr) return;
// ignore event loop
if (ra == event_loop_addr) return;
// add to queue
sampler_queue->add((uintptr_t) ra);
// return when its not our turn
if (lockless_sampler) return;
// transfer all the built up samplings
transfer_queue->clone(sampler_queue->first(), sampler_queue->size());
sampler_queue->clear();
lockless_sampler = 1;
}
void gather_stack_sampling()
{
// gather results on our turn only
if (lockless_sampler == 1)
{
for (auto* addr = transfer_queue->first(); addr < transfer_queue->end(); addr++)
{
// convert return address to function entry address
uintptr_t resolved = Elf::resolve_addr(*addr);
// insert into unordered map
auto it = sampler_dict.find(resolved);
if (it != sampler_dict.end()) {
it->second++;
}
else {
// add to dictionary
sampler_dict.emplace(
std::piecewise_construct,
std::forward_as_tuple(resolved),
std::forward_as_tuple(1));
}
}
sampler_total += transfer_queue->size();
lockless_sampler = 0;
}
}
void print_heap_info()
{
static intptr_t last = 0;
// show information on heap status, to discover leaks etc.
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
intptr_t heap_size = heap_end - heap_begin;
last = heap_size - last;
printf("[!] Heap information:\n");
printf("[!] begin %#x size %#x (%u Kb)\n", heap_begin, heap_size, heap_size / 1024);
printf("[!] end %#x diff %#x (%d Kb)\n", heap_end, last, last / 1024);
last = (int32_t) heap_size;
}
void print_stack_sampling()
{
using sample_pair = std::pair<uintptr_t, func_sample>;
// sort by count
std::vector<sample_pair> vec(sampler_dict.begin(), sampler_dict.end());
std::sort(vec.begin(), vec.end(),
[] (const sample_pair& sample1, const sample_pair& sample2) -> int {
return sample1.second > sample2.second;
});
size_t results = 12;
results = (results > sampler_dict.size()) ? sampler_dict.size() : results;
printf("*** Listing %d results (%u samples) ***\n", results, sampler_total);
for (auto& sa : vec)
{
// resolve the addr
auto func = Elf::resolve_symbol(sa.first);
float f = (float) sa.second / sampler_total * 100;
// print some shits
printf("%5.2f%% %*u: %s\n",
f, 8, sa.second, func.name.c_str());
if (results-- == 0) break;
}
printf("*** ---------------------- ***\n");
}
void __panic_failure(char const* where, size_t id)
{
printf("\n[FAILURE] %s, id=%u\n", where, id);
print_heap_info();
while (true)
asm volatile("cli; hlt");
}
void __validate_backtrace(char const* where, size_t id)
{
func_offset func;
func = Elf::resolve_symbol((void*) &__validate_backtrace);
if (func.name != "__validate_backtrace")
__panic_failure(where, id);
func = Elf::resolve_symbol((void*) &print_stack_sampling);
if (func.name != "print_stack_sampling()")
__panic_failure(where, id);
}
<commit_msg>profile: Stop taking samples at max, instead of panic<commit_after>#include <profile>
#include <hw/pit.hpp>
#include <kernel/elf.hpp>
#include <kernel/irq_manager.hpp>
#include <unordered_map>
#include <cassert>
#include <algorithm>
#define BUFFER_COUNT 2048
template <typename T, int N>
struct fixedvector {
void add(const T& e) noexcept {
assert(count < N);
element[count] = e;
count++;
}
void clear() noexcept {
count = 0;
}
uint32_t size() const noexcept {
return count;
}
T* first() noexcept {
return &element[0];
}
T* end() noexcept {
return &element[count];
}
bool free_capacity() const noexcept {
return count < N;
}
void clone(T* src, uint32_t size) {
memcpy(element, src, size * sizeof(T));
count = size;
}
uint32_t count = 0;
T element[N];
};
static fixedvector<uintptr_t, BUFFER_COUNT>* sampler_queue;
static fixedvector<uintptr_t, BUFFER_COUNT>* transfer_queue;
static void* event_loop_addr;
typedef uint32_t func_sample;
std::unordered_map<uintptr_t, func_sample> sampler_dict;
static func_sample sampler_total = 0;
static int lockless_sampler = 0;
extern "C" {
void parasite_interrupt_handler();
void profiler_stack_sampler();
void gather_stack_sampling();
}
void begin_stack_sampling(uint16_t gather_period_ms)
{
// make room for these only when requested
#define blargh(T) std::remove_pointer<decltype(T)>::type;
sampler_queue = new blargh(sampler_queue);
transfer_queue = new blargh(transfer_queue);
sampler_total = 0;
// we want to ignore event loop at FIXME the HLT location (0x198)
event_loop_addr = (void*) ((char*) &OS::event_loop + 0x198);
// begin sampling
IRQ_manager::cpu(0).set_irq_handler(0, parasite_interrupt_handler);
// gather every second
using namespace std::chrono;
hw::PIT::instance().on_repeated_timeout(milliseconds(gather_period_ms),
[] { gather_stack_sampling(); });
}
void profiler_stack_sampler()
{
void* ra = __builtin_return_address(1);
// maybe qemu, maybe some bullshit we don't care about
if (ra == nullptr) return;
// ignore event loop
if (ra == event_loop_addr) return;
// need free space to take more samples
if (sampler_queue->free_capacity())
sampler_queue->add((uintptr_t) ra);
// return when its not our turn
if (lockless_sampler) return;
// transfer all the built up samplings
transfer_queue->clone(sampler_queue->first(), sampler_queue->size());
sampler_queue->clear();
lockless_sampler = 1;
}
void gather_stack_sampling()
{
// gather results on our turn only
if (lockless_sampler == 1)
{
for (auto* addr = transfer_queue->first(); addr < transfer_queue->end(); addr++)
{
// convert return address to function entry address
uintptr_t resolved = Elf::resolve_addr(*addr);
// insert into unordered map
auto it = sampler_dict.find(resolved);
if (it != sampler_dict.end()) {
it->second++;
}
else {
// add to dictionary
sampler_dict.emplace(
std::piecewise_construct,
std::forward_as_tuple(resolved),
std::forward_as_tuple(1));
}
}
sampler_total += transfer_queue->size();
lockless_sampler = 0;
}
}
void print_heap_info()
{
static intptr_t last = 0;
// show information on heap status, to discover leaks etc.
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
intptr_t heap_size = heap_end - heap_begin;
last = heap_size - last;
printf("[!] Heap information:\n");
printf("[!] begin %#x size %#x (%u Kb)\n", heap_begin, heap_size, heap_size / 1024);
printf("[!] end %#x diff %#x (%d Kb)\n", heap_end, last, last / 1024);
last = (int32_t) heap_size;
}
void print_stack_sampling()
{
using sample_pair = std::pair<uintptr_t, func_sample>;
// sort by count
std::vector<sample_pair> vec(sampler_dict.begin(), sampler_dict.end());
std::sort(vec.begin(), vec.end(),
[] (const sample_pair& sample1, const sample_pair& sample2) -> int {
return sample1.second > sample2.second;
});
size_t results = 12;
results = (results > sampler_dict.size()) ? sampler_dict.size() : results;
printf("*** Listing %d results (%u samples) ***\n", results, sampler_total);
for (auto& sa : vec)
{
// resolve the addr
auto func = Elf::resolve_symbol(sa.first);
float f = (float) sa.second / sampler_total * 100;
// print some shits
printf("%5.2f%% %*u: %s\n",
f, 8, sa.second, func.name.c_str());
if (results-- == 0) break;
}
printf("*** ---------------------- ***\n");
}
void __panic_failure(char const* where, size_t id)
{
printf("\n[FAILURE] %s, id=%u\n", where, id);
print_heap_info();
while (true)
asm volatile("cli; hlt");
}
void __validate_backtrace(char const* where, size_t id)
{
func_offset func;
func = Elf::resolve_symbol((void*) &__validate_backtrace);
if (func.name != "__validate_backtrace")
__panic_failure(where, id);
func = Elf::resolve_symbol((void*) &print_stack_sampling);
if (func.name != "print_stack_sampling()")
__panic_failure(where, id);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: combtransition.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:50:51 $
*
* 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
*
************************************************************************/
#include "combtransition.hxx"
#include "canvas/debug.hxx"
#include "basegfx/polygon/b2dpolygontools.hxx"
#include "basegfx/polygon/b2dpolypolygontools.hxx"
namespace presentation {
namespace internal {
namespace {
basegfx::B2DPolyPolygon createClipPolygon(
const ::basegfx::B2DVector& rDirection,
const ::basegfx::B2DSize& rSlideSize,
int nNumStrips, int nOffset )
{
// create clip polygon in standard orientation (will later
// be rotated to match direction vector)
::basegfx::B2DPolyPolygon aClipPoly;
// create nNumStrips/2 vertical strips
for( int i=nOffset; i<nNumStrips; i+=2 )
{
aClipPoly.append(
::basegfx::tools::createPolygonFromRect(
::basegfx::B2DRectangle( (double)i/nNumStrips, 0.0,
(double)(i+1)/nNumStrips, 1.0) ) );
}
// rotate polygons, such that the strips are parallel to
// the given direction vector
const ::basegfx::B2DVector aUpVec(0.0, 1.0);
::basegfx::B2DHomMatrix aMatrix;
aMatrix.translate( -0.5, -0.5 );
aMatrix.rotate( aUpVec.angle( rDirection ) );
aMatrix.translate( 0.5, 0.5 );
// blow up clip polygon to slide size
aMatrix.scale( rSlideSize.getX(),
rSlideSize.getY() );
aClipPoly.transform( aMatrix );
return aClipPoly;
}
}
CombTransition::CombTransition(
boost::optional<SlideSharedPtr> const & leavingSlide,
const SlideSharedPtr& pEnteringSlide,
const SoundPlayerSharedPtr& pSoundPlayer,
const ::basegfx::B2DVector& rPushDirection,
sal_Int32 nNumStripes )
: SlideChangeBase( leavingSlide, pEnteringSlide, pSoundPlayer,
false /* no leaving sprite */,
false /* no entering sprite */ ),
maPushDirectionUnit( rPushDirection ),
mnNumStripes( nNumStripes )
{
}
void CombTransition::renderComb(
double t, UnoViewSharedPtr const & pView ) const
{
const cppcanvas::CanvasSharedPtr pCanvas_ = pView->getCanvas();
// calc bitmap offsets. The enter/leaving bitmaps are only
// as large as the actual slides. For scaled-down
// presentations, we have to move the left, top edge of
// those bitmaps to the actual position, governed by the
// given view transform. The aBitmapPosPixel local
// variable is already in device coordinate space
// (i.e. pixel).
ENSURE_AND_THROW( pCanvas_.get(),
"CombTransition::renderComb(): Invalid canvas" );
// TODO(F2): Properly respect clip here. Might have to be transformed, too.
const basegfx::B2DHomMatrix viewTransform( pCanvas_->getTransformation() );
const basegfx::B2DPoint pageOrigin( viewTransform * basegfx::B2DPoint() );
// change transformation on cloned canvas to be in
// device pixel
cppcanvas::CanvasSharedPtr pCanvas( pCanvas_->clone() );
basegfx::B2DHomMatrix transform;
basegfx::B2DPoint p;
// TODO(Q2): Use basegfx bitmaps here
// TODO(F1): SlideBitmap is not fully portable between different canvases!
const basegfx::B2DSize enteringSizePixel(
getEnteringSizePixel(pView) );
const basegfx::B2DVector aPushDirection = basegfx::B2DVector(
enteringSizePixel * maPushDirectionUnit );
const basegfx::B2DPolyPolygon aClipPolygon1 = basegfx::B2DPolyPolygon(
createClipPolygon( maPushDirectionUnit,
enteringSizePixel,
mnNumStripes, 0 ) );
const basegfx::B2DPolyPolygon aClipPolygon2 = basegfx::B2DPolyPolygon(
createClipPolygon( maPushDirectionUnit,
enteringSizePixel,
mnNumStripes, 1 ) );
SlideBitmapSharedPtr const & pLeavingBitmap = getLeavingBitmap();
if (pLeavingBitmap.get() != 0) {
// render odd strips:
pLeavingBitmap->clip( aClipPolygon1 );
// don't modify bitmap object (no move!):
p = basegfx::B2DPoint( pageOrigin + (t * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pLeavingBitmap->draw( pCanvas );
// render even strips:
pLeavingBitmap->clip( aClipPolygon2 );
// don't modify bitmap object (no move!):
transform.identity();
p = basegfx::B2DPoint( pageOrigin - (t * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pLeavingBitmap->draw( pCanvas );
}
// TODO(Q2): Use basegfx bitmaps here
// TODO(F1): SlideBitmap is not fully portable between different canvases!
// render odd strips:
SlideBitmapSharedPtr const & pEnteringBitmap = getEnteringBitmap();
pEnteringBitmap->clip( aClipPolygon1 );
// don't modify bitmap object (no move!):
transform.identity();
p = basegfx::B2DPoint( pageOrigin + ((t - 1.0) * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pEnteringBitmap->draw( pCanvas );
// render even strips:
pEnteringBitmap->clip( aClipPolygon2 );
// don't modify bitmap object (no move!):
transform.identity();
p = basegfx::B2DPoint( pageOrigin + ((1.0 - t) * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pEnteringBitmap->draw( pCanvas );
}
bool CombTransition::operator()( double t )
{
SlideBitmapSharedPtr const & pSlideBitmap = getEnteringBitmap();
if (pSlideBitmap.get() == 0)
return false;
for_each_view( boost::bind( &CombTransition::renderComb, this, t, _1 ) );
return true;
}
} // namespace internal
} // namespace presentation
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.50); FILE MERGED 2006/09/01 17:39:40 kaib 1.5.50.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: combtransition.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:38:40 $
*
* 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_slideshow.hxx"
#include "combtransition.hxx"
#include "canvas/debug.hxx"
#include "basegfx/polygon/b2dpolygontools.hxx"
#include "basegfx/polygon/b2dpolypolygontools.hxx"
namespace presentation {
namespace internal {
namespace {
basegfx::B2DPolyPolygon createClipPolygon(
const ::basegfx::B2DVector& rDirection,
const ::basegfx::B2DSize& rSlideSize,
int nNumStrips, int nOffset )
{
// create clip polygon in standard orientation (will later
// be rotated to match direction vector)
::basegfx::B2DPolyPolygon aClipPoly;
// create nNumStrips/2 vertical strips
for( int i=nOffset; i<nNumStrips; i+=2 )
{
aClipPoly.append(
::basegfx::tools::createPolygonFromRect(
::basegfx::B2DRectangle( (double)i/nNumStrips, 0.0,
(double)(i+1)/nNumStrips, 1.0) ) );
}
// rotate polygons, such that the strips are parallel to
// the given direction vector
const ::basegfx::B2DVector aUpVec(0.0, 1.0);
::basegfx::B2DHomMatrix aMatrix;
aMatrix.translate( -0.5, -0.5 );
aMatrix.rotate( aUpVec.angle( rDirection ) );
aMatrix.translate( 0.5, 0.5 );
// blow up clip polygon to slide size
aMatrix.scale( rSlideSize.getX(),
rSlideSize.getY() );
aClipPoly.transform( aMatrix );
return aClipPoly;
}
}
CombTransition::CombTransition(
boost::optional<SlideSharedPtr> const & leavingSlide,
const SlideSharedPtr& pEnteringSlide,
const SoundPlayerSharedPtr& pSoundPlayer,
const ::basegfx::B2DVector& rPushDirection,
sal_Int32 nNumStripes )
: SlideChangeBase( leavingSlide, pEnteringSlide, pSoundPlayer,
false /* no leaving sprite */,
false /* no entering sprite */ ),
maPushDirectionUnit( rPushDirection ),
mnNumStripes( nNumStripes )
{
}
void CombTransition::renderComb(
double t, UnoViewSharedPtr const & pView ) const
{
const cppcanvas::CanvasSharedPtr pCanvas_ = pView->getCanvas();
// calc bitmap offsets. The enter/leaving bitmaps are only
// as large as the actual slides. For scaled-down
// presentations, we have to move the left, top edge of
// those bitmaps to the actual position, governed by the
// given view transform. The aBitmapPosPixel local
// variable is already in device coordinate space
// (i.e. pixel).
ENSURE_AND_THROW( pCanvas_.get(),
"CombTransition::renderComb(): Invalid canvas" );
// TODO(F2): Properly respect clip here. Might have to be transformed, too.
const basegfx::B2DHomMatrix viewTransform( pCanvas_->getTransformation() );
const basegfx::B2DPoint pageOrigin( viewTransform * basegfx::B2DPoint() );
// change transformation on cloned canvas to be in
// device pixel
cppcanvas::CanvasSharedPtr pCanvas( pCanvas_->clone() );
basegfx::B2DHomMatrix transform;
basegfx::B2DPoint p;
// TODO(Q2): Use basegfx bitmaps here
// TODO(F1): SlideBitmap is not fully portable between different canvases!
const basegfx::B2DSize enteringSizePixel(
getEnteringSizePixel(pView) );
const basegfx::B2DVector aPushDirection = basegfx::B2DVector(
enteringSizePixel * maPushDirectionUnit );
const basegfx::B2DPolyPolygon aClipPolygon1 = basegfx::B2DPolyPolygon(
createClipPolygon( maPushDirectionUnit,
enteringSizePixel,
mnNumStripes, 0 ) );
const basegfx::B2DPolyPolygon aClipPolygon2 = basegfx::B2DPolyPolygon(
createClipPolygon( maPushDirectionUnit,
enteringSizePixel,
mnNumStripes, 1 ) );
SlideBitmapSharedPtr const & pLeavingBitmap = getLeavingBitmap();
if (pLeavingBitmap.get() != 0) {
// render odd strips:
pLeavingBitmap->clip( aClipPolygon1 );
// don't modify bitmap object (no move!):
p = basegfx::B2DPoint( pageOrigin + (t * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pLeavingBitmap->draw( pCanvas );
// render even strips:
pLeavingBitmap->clip( aClipPolygon2 );
// don't modify bitmap object (no move!):
transform.identity();
p = basegfx::B2DPoint( pageOrigin - (t * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pLeavingBitmap->draw( pCanvas );
}
// TODO(Q2): Use basegfx bitmaps here
// TODO(F1): SlideBitmap is not fully portable between different canvases!
// render odd strips:
SlideBitmapSharedPtr const & pEnteringBitmap = getEnteringBitmap();
pEnteringBitmap->clip( aClipPolygon1 );
// don't modify bitmap object (no move!):
transform.identity();
p = basegfx::B2DPoint( pageOrigin + ((t - 1.0) * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pEnteringBitmap->draw( pCanvas );
// render even strips:
pEnteringBitmap->clip( aClipPolygon2 );
// don't modify bitmap object (no move!):
transform.identity();
p = basegfx::B2DPoint( pageOrigin + ((1.0 - t) * aPushDirection) );
transform.translate( p.getX(), p.getY() );
pCanvas->setTransformation( transform );
pEnteringBitmap->draw( pCanvas );
}
bool CombTransition::operator()( double t )
{
SlideBitmapSharedPtr const & pSlideBitmap = getEnteringBitmap();
if (pSlideBitmap.get() == 0)
return false;
for_each_view( boost::bind( &CombTransition::renderComb, this, t, _1 ) );
return true;
}
} // namespace internal
} // namespace presentation
<|endoftext|>
|
<commit_before>// $Id$
//
// Task to filter Esd tracks and propagate to Emcal surface.
//
// Author: C.Loizides
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <AliAnalysisManager.h>
#include <AliESDEvent.h>
#include <AliESDtrackCuts.h>
#include <AliMagF.h>
#include <AliTrackerBase.h>
#include <AliEMCALRecoUtils.h>
#include "AliEmcalEsdTrackFilterTask.h"
ClassImp(AliEmcalEsdTrackFilterTask)
//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask() :
AliAnalysisTaskSE("AliEmcalEsdTrackFilterTask"),
fEsdTrackCuts(0),
fDoSpdVtxCon(0),
fHybridTrackCuts(0),
fTracksName(),
fIncludeNoITS(kTRUE),
fDoPropagation(kFALSE),
fDist(440),
fEsdEv(0),
fTracks(0)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask(const char *name) :
AliAnalysisTaskSE(name),
fEsdTrackCuts(0),
fDoSpdVtxCon(0),
fHybridTrackCuts(0),
fTracksName("EsdTracksOut"),
fIncludeNoITS(kTRUE),
fDoPropagation(kFALSE),
fDist(440),
fEsdEv(0),
fTracks(0)
{
// Constructor.
if (!name)
return;
SetName(name);
fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks";
}
//________________________________________________________________________
AliEmcalEsdTrackFilterTask::~AliEmcalEsdTrackFilterTask()
{
//Destructor
delete fEsdTrackCuts;
}
//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserCreateOutputObjects()
{
// Create histograms.
fTracks = new TClonesArray("AliESDtrack");
fTracks->SetName(fTracksName);
if (!fEsdTrackCuts) {
AliInfo("No track cuts given, creating default (standard only TPC) cuts");
fEsdTrackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
fEsdTrackCuts->SetPtRange(0.15,1e3);
}
}
//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserExec(Option_t *)
{
// Main loop, called for each event.
fEsdEv = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fEsdEv) {
AliError("Task works only on ESD events, returning");
return;
}
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
if (!am) {
AliError("Manager zero, returning");
return;
}
// add tracks to event if not yet there
fTracks->Delete();
if (!(InputEvent()->FindListObject(fTracksName)))
InputEvent()->AddObject(fTracks);
if (!fHybridTrackCuts) { // contrain TPC tracks to SPD vertex if fDoSpdVtxCon==kTRUE
am->LoadBranch("AliESDRun.");
am->LoadBranch("AliESDHeader.");
am->LoadBranch("Tracks");
if (fDoSpdVtxCon) {
if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
fEsdEv->InitMagneticField();
}
am->LoadBranch("SPDVertex.");
const AliESDVertex *vtxSPD = fEsdEv->GetPrimaryVertexSPD();
if (!vtxSPD) {
AliError("No SPD vertex, returning");
return;
}
Int_t ntr = fEsdEv->GetNumberOfTracks();
for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
AliESDtrack *etrack = fEsdEv->GetTrack(i);
if (!etrack)
continue;
if (!fEsdTrackCuts->AcceptTrack(etrack))
continue;
AliESDtrack *ntrack = AliESDtrackCuts::GetTPCOnlyTrack(fEsdEv,etrack->GetID());
if (!ntrack)
continue;
if (ntrack->Pt()<=0) {
delete ntrack;
continue;
}
Double_t bfield[3] = {0,0,0};
ntrack->GetBxByBz(bfield);
AliExternalTrackParam exParam;
Bool_t relate = ntrack->RelateToVertexBxByBz(vtxSPD,bfield,kVeryBig,&exParam);
if (!relate) {
delete ntrack;
continue;
}
// set the constraint parameters to the track
ntrack->Set(exParam.GetX(),exParam.GetAlpha(),exParam.GetParameter(),exParam.GetCovariance());
if (ntrack->Pt()<=0) {
delete ntrack;
continue;
}
new ((*fTracks)[ntrnew++]) AliESDtrack(*ntrack);
delete ntrack;
}
} else { /* no spd vtx constraint */
Int_t ntr = fEsdEv->GetNumberOfTracks();
for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
AliESDtrack *etrack = fEsdEv->GetTrack(i);
if (!etrack)
continue;
if (!fEsdTrackCuts->AcceptTrack(etrack))
continue;
new ((*fTracks)[ntrnew++]) AliESDtrack(*etrack);
}
}
} else { // use hybrid track cuts
am->LoadBranch("Tracks");
Int_t ntr = fEsdEv->GetNumberOfTracks();
for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
AliESDtrack *etrack = fEsdEv->GetTrack(i);
if (!etrack)
continue;
if (fEsdTrackCuts->AcceptTrack(etrack)) {
AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
if (fDoPropagation)
AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
newTrack->SetBit(BIT(20),0);
newTrack->SetBit(BIT(21),0);
++ntrnew;
} else if (fHybridTrackCuts->AcceptTrack(etrack)) {
UInt_t status = etrack->GetStatus();
if (etrack->GetConstrainedParam() && (((status&AliESDtrack::kITSrefit)!=0) || fIncludeNoITS)) {
cout << "test " << fIncludeNoITS << endl;
AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
const AliExternalTrackParam* constrainParam = etrack->GetConstrainedParam();
newTrack->Set(constrainParam->GetX(),
constrainParam->GetAlpha(),
constrainParam->GetParameter(),
constrainParam->GetCovariance());
if ((status&AliESDtrack::kITSrefit)==0) {
newTrack->SetBit(BIT(20),0); //type 2
newTrack->SetBit(BIT(21),1);
} else {
newTrack->SetBit(BIT(20),1); //type 1
newTrack->SetBit(BIT(21),0);
}
if (fDoPropagation)
AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
++ntrnew;
}
}
}
}
}
<commit_msg>remove print<commit_after>// $Id$
//
// Task to filter Esd tracks and propagate to Emcal surface.
//
// Author: C.Loizides
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <AliAnalysisManager.h>
#include <AliESDEvent.h>
#include <AliESDtrackCuts.h>
#include <AliMagF.h>
#include <AliTrackerBase.h>
#include <AliEMCALRecoUtils.h>
#include "AliEmcalEsdTrackFilterTask.h"
ClassImp(AliEmcalEsdTrackFilterTask)
//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask() :
AliAnalysisTaskSE("AliEmcalEsdTrackFilterTask"),
fEsdTrackCuts(0),
fDoSpdVtxCon(0),
fHybridTrackCuts(0),
fTracksName(),
fIncludeNoITS(kTRUE),
fDoPropagation(kFALSE),
fDist(440),
fEsdEv(0),
fTracks(0)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask(const char *name) :
AliAnalysisTaskSE(name),
fEsdTrackCuts(0),
fDoSpdVtxCon(0),
fHybridTrackCuts(0),
fTracksName("EsdTracksOut"),
fIncludeNoITS(kTRUE),
fDoPropagation(kFALSE),
fDist(440),
fEsdEv(0),
fTracks(0)
{
// Constructor.
if (!name)
return;
SetName(name);
fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks";
}
//________________________________________________________________________
AliEmcalEsdTrackFilterTask::~AliEmcalEsdTrackFilterTask()
{
//Destructor
delete fEsdTrackCuts;
}
//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserCreateOutputObjects()
{
// Create histograms.
fTracks = new TClonesArray("AliESDtrack");
fTracks->SetName(fTracksName);
if (!fEsdTrackCuts) {
AliInfo("No track cuts given, creating default (standard only TPC) cuts");
fEsdTrackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
fEsdTrackCuts->SetPtRange(0.15,1e3);
}
}
//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserExec(Option_t *)
{
// Main loop, called for each event.
fEsdEv = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fEsdEv) {
AliError("Task works only on ESD events, returning");
return;
}
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
if (!am) {
AliError("Manager zero, returning");
return;
}
// add tracks to event if not yet there
fTracks->Delete();
if (!(InputEvent()->FindListObject(fTracksName)))
InputEvent()->AddObject(fTracks);
if (!fHybridTrackCuts) { // contrain TPC tracks to SPD vertex if fDoSpdVtxCon==kTRUE
am->LoadBranch("AliESDRun.");
am->LoadBranch("AliESDHeader.");
am->LoadBranch("Tracks");
if (fDoSpdVtxCon) {
if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
fEsdEv->InitMagneticField();
}
am->LoadBranch("SPDVertex.");
const AliESDVertex *vtxSPD = fEsdEv->GetPrimaryVertexSPD();
if (!vtxSPD) {
AliError("No SPD vertex, returning");
return;
}
Int_t ntr = fEsdEv->GetNumberOfTracks();
for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
AliESDtrack *etrack = fEsdEv->GetTrack(i);
if (!etrack)
continue;
if (!fEsdTrackCuts->AcceptTrack(etrack))
continue;
AliESDtrack *ntrack = AliESDtrackCuts::GetTPCOnlyTrack(fEsdEv,etrack->GetID());
if (!ntrack)
continue;
if (ntrack->Pt()<=0) {
delete ntrack;
continue;
}
Double_t bfield[3] = {0,0,0};
ntrack->GetBxByBz(bfield);
AliExternalTrackParam exParam;
Bool_t relate = ntrack->RelateToVertexBxByBz(vtxSPD,bfield,kVeryBig,&exParam);
if (!relate) {
delete ntrack;
continue;
}
// set the constraint parameters to the track
ntrack->Set(exParam.GetX(),exParam.GetAlpha(),exParam.GetParameter(),exParam.GetCovariance());
if (ntrack->Pt()<=0) {
delete ntrack;
continue;
}
new ((*fTracks)[ntrnew++]) AliESDtrack(*ntrack);
delete ntrack;
}
} else { /* no spd vtx constraint */
Int_t ntr = fEsdEv->GetNumberOfTracks();
for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
AliESDtrack *etrack = fEsdEv->GetTrack(i);
if (!etrack)
continue;
if (!fEsdTrackCuts->AcceptTrack(etrack))
continue;
new ((*fTracks)[ntrnew++]) AliESDtrack(*etrack);
}
}
} else { // use hybrid track cuts
am->LoadBranch("Tracks");
Int_t ntr = fEsdEv->GetNumberOfTracks();
for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
AliESDtrack *etrack = fEsdEv->GetTrack(i);
if (!etrack)
continue;
if (fEsdTrackCuts->AcceptTrack(etrack)) {
AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
if (fDoPropagation)
AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
newTrack->SetBit(BIT(20),0);
newTrack->SetBit(BIT(21),0);
++ntrnew;
} else if (fHybridTrackCuts->AcceptTrack(etrack)) {
UInt_t status = etrack->GetStatus();
if (etrack->GetConstrainedParam() && (((status&AliESDtrack::kITSrefit)!=0) || fIncludeNoITS)) {
AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
const AliExternalTrackParam* constrainParam = etrack->GetConstrainedParam();
newTrack->Set(constrainParam->GetX(),
constrainParam->GetAlpha(),
constrainParam->GetParameter(),
constrainParam->GetCovariance());
if ((status&AliESDtrack::kITSrefit)==0) {
newTrack->SetBit(BIT(20),0); //type 2
newTrack->SetBit(BIT(21),1);
} else {
newTrack->SetBit(BIT(20),1); //type 1
newTrack->SetBit(BIT(21),0);
}
if (fDoPropagation)
AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
++ntrnew;
}
}
}
}
}
<|endoftext|>
|
<commit_before>#include "Headache.h"
#include "../GameManager.h"
#include "../sound/SoundManager.h"
namespace Symp {
void Headache::execute(){
if(time(NULL) - m_uiLastExecution >= m_uiTimeToTriggerRandomHeadache && !isActivated()) {
// With these values, the the rotation occures 10 times in 2 minutes
float random = rand() % 10000; // between 0 and 9999
float treshold = 10000 - (time(NULL) - m_uiLastExecution);
if(random > treshold) {
m_iRotationAngle = rand() % m_iMaxRotationAngle + m_iMinRotationAngle;
activate();
// Render Invisible Platforms visible
for(size_t i = 0; i < EntityManager::getInstance()->getPhysicalEntityArray().size(); i++) {
PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntity(i);
if(pEntity != nullptr
&& pEntity->getType() == PhysicalType::InvisibleObject) {
std::vector<RenderEntity*> rEntityArray = EntityManager::getInstance()->getRenderEntityArray().at(i);
rEntityArray.at(0)->setShow(true);
}
}
// Sound
SoundManager::getInstance()->playSound(EntityManager::getInstance()->getSoundDino()[DinoAction::HeadacheAction]);
}
}
if(isActivated()){
forceExecution();
}
}
void Headache::forceExecution(){
// Increase the step
if(m_iRotationAngle>0) m_iInterpolateAngle += m_uiStep;
else m_iInterpolateAngle -= m_uiStep;
if(abs(m_iInterpolateAngle)>abs(m_iRotationAngle) && m_bChangeSens){ // if the interpolate angle is bigger than the rotation angle
m_iRotationNewAngle=abs(m_iRotationAngle)-abs(m_iRotationAngle*0.20); // Compute new angle
m_bChangeSens = false;
m_iRotationAngle*=-1; // change the direction of rotation
}
else if(abs(m_iInterpolateAngle)<=abs(m_iRotationNewAngle) && m_iRotationNewAngle!=0){
if(m_iRotationAngle<0) m_iRotationAngle = -m_iRotationNewAngle;
else m_iRotationAngle = m_iRotationNewAngle;
m_bChangeSens = true;
}
// Change the step value
if(abs(m_iInterpolateAngle)>abs(m_iRotationAngle)*0.20 && abs(m_iInterpolateAngle)<abs(m_iRotationAngle)*0.80) m_uiStep = 5;
else m_uiStep = 1;
if(abs(m_iRotationAngle)<5){
deactivate();
// Render Invisible Platforms
for(size_t i = 0; i < EntityManager::getInstance()->getPhysicalEntityArray().size(); i++) {
PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntity(i);
if(pEntity != nullptr
&& pEntity->getType() == PhysicalType::InvisibleObject) {
std::vector<RenderEntity*> rEntityArray = EntityManager::getInstance()->getRenderEntityArray().at(i);
rEntityArray.at(0)->setShow(false);
}
}
// Sound
SoundManager::getInstance()->stopSound(EntityManager::getInstance()->getSoundDino()[DinoAction::HeadacheAction]);
m_uiLastExecution = time(NULL);
// Reset the camera
m_iInterpolateAngle = 0;
m_iRotationNewAngle = 0;
m_bChangeSens = true;
m_uiStep = 1;
// Increase the minimum rotation angle if necessary
if(m_iMinRotationAngle-30<m_iMaxRotationAngle) m_iMinRotationAngle += 10;
}
// Rotate the camera
GameManager::getInstance()->getRender()->setCameraAngle(m_iInterpolateAngle);
}
}<commit_msg>set headache random<commit_after>#include "Headache.h"
#include "../GameManager.h"
#include "../sound/SoundManager.h"
namespace Symp {
void Headache::execute(){
if(time(NULL) - m_uiLastExecution >= m_uiTimeToTriggerRandomHeadache && !isActivated()) {
// With these values, the the rotation occures 10 times in 2 minutes
float random = rand() % 1000; // between 0 and 9999
float treshold = 1000 - (time(NULL) - m_uiLastExecution);
if(random > treshold) {
m_iRotationAngle = rand() % m_iMaxRotationAngle + m_iMinRotationAngle;
activate();
// Render Invisible Platforms visible
for(size_t i = 0; i < EntityManager::getInstance()->getPhysicalEntityArray().size(); i++) {
PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntity(i);
if(pEntity != nullptr
&& pEntity->getType() == PhysicalType::InvisibleObject) {
std::vector<RenderEntity*> rEntityArray = EntityManager::getInstance()->getRenderEntityArray().at(i);
rEntityArray.at(0)->setShow(true);
}
}
// Sound
SoundManager::getInstance()->playSound(EntityManager::getInstance()->getSoundDino()[DinoAction::HeadacheAction]);
}
}
if(isActivated()){
forceExecution();
}
}
void Headache::forceExecution(){
// Increase the step
if(m_iRotationAngle>0) m_iInterpolateAngle += m_uiStep;
else m_iInterpolateAngle -= m_uiStep;
if(abs(m_iInterpolateAngle)>abs(m_iRotationAngle) && m_bChangeSens){ // if the interpolate angle is bigger than the rotation angle
m_iRotationNewAngle=abs(m_iRotationAngle)-abs(m_iRotationAngle*0.20); // Compute new angle
m_bChangeSens = false;
m_iRotationAngle*=-1; // change the direction of rotation
}
else if(abs(m_iInterpolateAngle)<=abs(m_iRotationNewAngle) && m_iRotationNewAngle!=0){
if(m_iRotationAngle<0) m_iRotationAngle = -m_iRotationNewAngle;
else m_iRotationAngle = m_iRotationNewAngle;
m_bChangeSens = true;
}
// Change the step value
if(abs(m_iInterpolateAngle)>abs(m_iRotationAngle)*0.20 && abs(m_iInterpolateAngle)<abs(m_iRotationAngle)*0.80) m_uiStep = 5;
else m_uiStep = 1;
if(abs(m_iRotationAngle)<5){
deactivate();
// Render Invisible Platforms
for(size_t i = 0; i < EntityManager::getInstance()->getPhysicalEntityArray().size(); i++) {
PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntity(i);
if(pEntity != nullptr
&& pEntity->getType() == PhysicalType::InvisibleObject) {
std::vector<RenderEntity*> rEntityArray = EntityManager::getInstance()->getRenderEntityArray().at(i);
rEntityArray.at(0)->setShow(false);
}
}
// Sound
SoundManager::getInstance()->stopSound(EntityManager::getInstance()->getSoundDino()[DinoAction::HeadacheAction]);
m_uiLastExecution = time(NULL);
// Reset the camera
m_iInterpolateAngle = 0;
m_iRotationNewAngle = 0;
m_bChangeSens = true;
m_uiStep = 1;
// Increase the minimum rotation angle if necessary
if(m_iMinRotationAngle-30<m_iMaxRotationAngle) m_iMinRotationAngle += 10;
}
// Rotate the camera
GameManager::getInstance()->getRender()->setCameraAngle(m_iInterpolateAngle);
}
}<|endoftext|>
|
<commit_before>#include <FAST/Data/Tensor.hpp>
#include <FAST/Data/Image.hpp>
#include "TensorToImage.hpp"
namespace fast {
TensorToImage::TensorToImage(std::vector<int> channels) {
createInputPort<Tensor>(0);
createOutputPort<Image>(0);
m_channels = channels;
createIntegerAttribute("channels", "Channels", "Channels to use from tensor", -1);
}
void TensorToImage::execute() {
auto tensor = getInputData<Tensor>();
const auto shape = tensor->getShape();
auto access = tensor->getAccess(ACCESS_READ);
const int dims = shape.getDimensions();
const int channelsInTensor = shape[dims-1];
const int outputWidth = shape[dims-2];
const int outputHeight = shape[dims-3];
int outputDepth = 1;
if(dims == 5) {
outputDepth = shape[dims - 4];
}
float* tensorData = access->getRawData();
Image::pointer image;
if(m_channels.empty()) {
if(outputDepth == 1) {
image = Image::create(outputWidth, outputHeight, TYPE_FLOAT, channelsInTensor, tensorData);
} else {
image = Image::create(outputWidth, outputHeight, outputDepth, TYPE_FLOAT, channelsInTensor, tensorData);
}
} else {
// Select specific channels from tensor data
auto newTensorData = make_uninitialized_unique<float[]>(outputWidth*outputHeight*outputDepth*m_channels.size());
if(outputDepth == 1) {
auto tensorData = access->getData<3>();
int counter = 0;
for(int channel : m_channels) {
Eigen::array<int, 3> offsets = {0, 0, channel};
Eigen::array<int, 3> extents = {outputHeight, outputWidth, 1};
Eigen::Tensor<float, 3, Eigen::RowMajor, int> res = tensorData.slice(offsets, extents);
std::memcpy(&newTensorData[outputWidth*outputHeight*counter], res.data(), sizeof(float)*outputWidth*outputHeight);
++counter;
}
image = Image::create(outputWidth, outputHeight, TYPE_FLOAT, m_channels.size(), std::move(newTensorData));
} else {
auto tensorData = access->getData<4>();
for(int channel : m_channels) {
Eigen::array<int, 4> offsets = {0, 0, 0, channel};
Eigen::array<int, 4> extents = {outputDepth, outputHeight, outputWidth, 1};
Eigen::Tensor<float, 4, Eigen::RowMajor, int> res = tensorData.slice(offsets, extents);
std::memcpy(&newTensorData[outputWidth*outputHeight*outputDepth*channel], res.data(), sizeof(float)*outputWidth*outputHeight*outputDepth);
}
image = Image::create(outputWidth, outputHeight, outputDepth, TYPE_FLOAT, m_channels.size(), std::move(newTensorData));
}
}
image->setSpacing(tensor->getSpacing());
SceneGraph::setParentNode(image, tensor);
addOutputData(0, image);
}
void TensorToImage::loadAttributes() {
auto channels = getIntegerListAttribute("channels");
if(!channels.empty() && channels[0] >= 0) {
setChannels(channels);
}
}
void TensorToImage::setChannels(std::vector<int> channels) {
m_channels = channels;
setModified(true);
}
}<commit_msg>Fixed bug in previous commit for 3D as well<commit_after>#include <FAST/Data/Tensor.hpp>
#include <FAST/Data/Image.hpp>
#include "TensorToImage.hpp"
namespace fast {
TensorToImage::TensorToImage(std::vector<int> channels) {
createInputPort<Tensor>(0);
createOutputPort<Image>(0);
m_channels = channels;
createIntegerAttribute("channels", "Channels", "Channels to use from tensor", -1);
}
void TensorToImage::execute() {
auto tensor = getInputData<Tensor>();
const auto shape = tensor->getShape();
auto access = tensor->getAccess(ACCESS_READ);
const int dims = shape.getDimensions();
const int channelsInTensor = shape[dims-1];
const int outputWidth = shape[dims-2];
const int outputHeight = shape[dims-3];
int outputDepth = 1;
if(dims == 5) {
outputDepth = shape[dims - 4];
}
float* tensorData = access->getRawData();
Image::pointer image;
if(m_channels.empty()) {
if(outputDepth == 1) {
image = Image::create(outputWidth, outputHeight, TYPE_FLOAT, channelsInTensor, tensorData);
} else {
image = Image::create(outputWidth, outputHeight, outputDepth, TYPE_FLOAT, channelsInTensor, tensorData);
}
} else {
// Select specific channels from tensor data
auto newTensorData = make_uninitialized_unique<float[]>(outputWidth*outputHeight*outputDepth*m_channels.size());
int counter = 0;
if(outputDepth == 1) {
auto tensorData = access->getData<3>();
for(int channel : m_channels) {
Eigen::array<int, 3> offsets = {0, 0, channel};
Eigen::array<int, 3> extents = {outputHeight, outputWidth, 1};
Eigen::Tensor<float, 3, Eigen::RowMajor, int> res = tensorData.slice(offsets, extents);
std::memcpy(&newTensorData[outputWidth*outputHeight*counter], res.data(), sizeof(float)*outputWidth*outputHeight);
++counter;
}
image = Image::create(outputWidth, outputHeight, TYPE_FLOAT, m_channels.size(), std::move(newTensorData));
} else {
auto tensorData = access->getData<4>();
for(int channel : m_channels) {
Eigen::array<int, 4> offsets = {0, 0, 0, channel};
Eigen::array<int, 4> extents = {outputDepth, outputHeight, outputWidth, 1};
Eigen::Tensor<float, 4, Eigen::RowMajor, int> res = tensorData.slice(offsets, extents);
std::memcpy(&newTensorData[outputWidth*outputHeight*outputDepth*counter], res.data(), sizeof(float)*outputWidth*outputHeight*outputDepth);
++counter;
}
image = Image::create(outputWidth, outputHeight, outputDepth, TYPE_FLOAT, m_channels.size(), std::move(newTensorData));
}
}
image->setSpacing(tensor->getSpacing());
SceneGraph::setParentNode(image, tensor);
addOutputData(0, image);
}
void TensorToImage::loadAttributes() {
auto channels = getIntegerListAttribute("channels");
if(!channels.empty() && channels[0] >= 0) {
setChannels(channels);
}
}
void TensorToImage::setChannels(std::vector<int> channels) {
m_channels = channels;
setModified(true);
}
}<|endoftext|>
|
<commit_before>#include <gloperate/pipelines/AbstractPipeline.h>
#include <cassert>
#include <string>
#include <gloperate/util/collection.hpp>
#include <algorithm>
#include <map>
#include <iostream>
#include <gloperate/pipelines/AbstractStage.h>
#include <gloperate/pipelines/AbstractInputSlot.h>
#include <gloperate/pipelines/AbstractData.h>
#include <gloperate/pipelines/AbstractData.h>
#include <gloperate/pipelines/Data.h>
using namespace collection;
namespace gloperate
{
AbstractPipeline::AbstractPipeline(const std::string & name)
: m_initialized(false)
, m_name(name)
, m_dependenciesSorted(false)
{
}
AbstractPipeline::~AbstractPipeline()
{
for (AbstractStage* stage : m_stages)
{
delete stage;
}
for (AbstractData* data : m_constantParameters)
{
delete data;
}
}
const std::string & AbstractPipeline::name() const
{
return m_name;
}
void AbstractPipeline::setName(const std::string & name)
{
m_name = name;
}
bool AbstractPipeline::hasName() const
{
return !m_name.empty();
}
std::string AbstractPipeline::asPrintable() const
{
if (!hasName())
return "<unnamed>";
std::string n = name();
std::replace(n.begin(), n.end(), ' ', '_');
return n;
}
void AbstractPipeline::addStages()
{
}
void AbstractPipeline::addStage(AbstractStage* stage)
{
m_stages.push_back(stage);
stage->dependenciesChanged.connect([this]() { m_dependenciesSorted = false; });
}
void AbstractPipeline::addParameter(AbstractData * parameter)
{
m_parameters.push_back(parameter);
}
void AbstractPipeline::shareData(const AbstractData* data)
{
assert(data != nullptr);
m_sharedData.push_back(data);
}
void AbstractPipeline::shareDataFrom(const AbstractInputSlot& slot)
{
shareData(slot.connectedData());
}
void AbstractPipeline::addParameter(const std::string & name, AbstractData * parameter)
{
parameter->setName(name);
addParameter(parameter);
}
const std::vector<AbstractStage*>& AbstractPipeline::stages() const
{
return m_stages;
}
const std::vector<AbstractData*> & AbstractPipeline::parameters() const
{
return m_parameters;
}
std::vector<AbstractInputSlot*> AbstractPipeline::allInputs() const
{
return flatten(collect(m_stages, [](const AbstractStage * stage) { return stage->allInputs(); }));
}
std::vector<AbstractData*> AbstractPipeline::allOutputs() const
{
return flatten(collect(m_stages, [](const AbstractStage * stage) { return stage->allOutputs(); }));
}
AbstractData * AbstractPipeline::findParameter(const std::string & name) const
{
return detect(m_parameters, [&name](AbstractData * parameter) { return parameter->matchesName(name); }, nullptr);
}
std::vector<AbstractData *> AbstractPipeline::findOutputs(const std::string & name) const
{
return select(allOutputs(), [&name](AbstractData * data) { return data->matchesName(name); });
}
void AbstractPipeline::execute()
{
if (!m_initialized)
{
return;
}
if (!m_dependenciesSorted)
{
sortDependencies();
}
for (AbstractStage* stage: m_stages)
{
stage->execute();
}
}
bool AbstractPipeline::isInitialized() const
{
return m_initialized;
}
void AbstractPipeline::initialize()
{
if (m_initialized)
return;
initializeStages();
m_initialized = true;
}
void AbstractPipeline::initializeStages()
{
if (!m_dependenciesSorted)
{
sortDependencies();
}
for (AbstractStage * stage : m_stages)
{
stage->initialize();
}
}
void AbstractPipeline::sortDependencies()
{
if (m_dependenciesSorted)
return;
tsort(m_stages);
m_dependenciesSorted = true;
}
void AbstractPipeline::tsort(std::vector<AbstractStage*>& stages)
{
std::vector<AbstractStage*> sorted(stages.size(), nullptr);
auto iterator = sorted.rbegin();
std::map<AbstractStage*, unsigned char> marks;
std::function<void(AbstractStage*)> visit = [&](AbstractStage* stage)
{
if (marks[stage] == 1)
{
std::cerr << "Pipeline is not a directed acyclic graph" << std::endl;
return;
}
if (marks[stage] == 0)
{
marks[stage] = 1;
for (auto nextStage : stages)
{
if (nextStage->requires(stage, false))
{
visit(nextStage);
}
}
marks[stage] = 2;
*iterator = stage;
++iterator;
}
};
while (iterator != sorted.rend())
{
for (auto stage : stages)
{
if (marks[stage] == 0)
{
visit(stage);
}
}
}
stages.swap(sorted);
}
} // namespace gloperate
<commit_msg>Fix order of stages in a pipeline<commit_after>#include <gloperate/pipelines/AbstractPipeline.h>
#include <cassert>
#include <string>
#include <gloperate/util/collection.hpp>
#include <algorithm>
#include <map>
#include <iostream>
#include <gloperate/pipelines/AbstractStage.h>
#include <gloperate/pipelines/AbstractInputSlot.h>
#include <gloperate/pipelines/AbstractData.h>
#include <gloperate/pipelines/AbstractData.h>
#include <gloperate/pipelines/Data.h>
using namespace collection;
namespace gloperate
{
AbstractPipeline::AbstractPipeline(const std::string & name)
: m_initialized(false)
, m_name(name)
, m_dependenciesSorted(false)
{
}
AbstractPipeline::~AbstractPipeline()
{
for (AbstractStage* stage : m_stages)
{
delete stage;
}
for (AbstractData* data : m_constantParameters)
{
delete data;
}
}
const std::string & AbstractPipeline::name() const
{
return m_name;
}
void AbstractPipeline::setName(const std::string & name)
{
m_name = name;
}
bool AbstractPipeline::hasName() const
{
return !m_name.empty();
}
std::string AbstractPipeline::asPrintable() const
{
if (!hasName())
return "<unnamed>";
std::string n = name();
std::replace(n.begin(), n.end(), ' ', '_');
return n;
}
void AbstractPipeline::addStages()
{
}
void AbstractPipeline::addStage(AbstractStage* stage)
{
m_stages.push_back(stage);
stage->dependenciesChanged.connect([this]() { m_dependenciesSorted = false; });
}
void AbstractPipeline::addParameter(AbstractData * parameter)
{
m_parameters.push_back(parameter);
}
void AbstractPipeline::shareData(const AbstractData* data)
{
assert(data != nullptr);
m_sharedData.push_back(data);
}
void AbstractPipeline::shareDataFrom(const AbstractInputSlot& slot)
{
shareData(slot.connectedData());
}
void AbstractPipeline::addParameter(const std::string & name, AbstractData * parameter)
{
parameter->setName(name);
addParameter(parameter);
}
const std::vector<AbstractStage*>& AbstractPipeline::stages() const
{
return m_stages;
}
const std::vector<AbstractData*> & AbstractPipeline::parameters() const
{
return m_parameters;
}
std::vector<AbstractInputSlot*> AbstractPipeline::allInputs() const
{
return flatten(collect(m_stages, [](const AbstractStage * stage) { return stage->allInputs(); }));
}
std::vector<AbstractData*> AbstractPipeline::allOutputs() const
{
return flatten(collect(m_stages, [](const AbstractStage * stage) { return stage->allOutputs(); }));
}
AbstractData * AbstractPipeline::findParameter(const std::string & name) const
{
return detect(m_parameters, [&name](AbstractData * parameter) { return parameter->matchesName(name); }, nullptr);
}
std::vector<AbstractData *> AbstractPipeline::findOutputs(const std::string & name) const
{
return select(allOutputs(), [&name](AbstractData * data) { return data->matchesName(name); });
}
void AbstractPipeline::execute()
{
if (!m_initialized)
{
return;
}
if (!m_dependenciesSorted)
{
sortDependencies();
}
for (AbstractStage* stage: m_stages)
{
stage->execute();
}
}
bool AbstractPipeline::isInitialized() const
{
return m_initialized;
}
void AbstractPipeline::initialize()
{
if (m_initialized)
return;
initializeStages();
m_initialized = true;
}
void AbstractPipeline::initializeStages()
{
if (!m_dependenciesSorted)
{
sortDependencies();
}
for (AbstractStage * stage : m_stages)
{
stage->initialize();
}
}
void AbstractPipeline::sortDependencies()
{
if (m_dependenciesSorted)
return;
tsort(m_stages);
m_dependenciesSorted = true;
}
void AbstractPipeline::tsort(std::vector<AbstractStage*>& stages)
{
std::vector<AbstractStage*> sorted;
std::map<AbstractStage*, unsigned char> marks;
std::function<void(AbstractStage*)> visit = [&](AbstractStage * stage)
{
if (marks[stage] == 1)
{
std::cerr << "Pipeline is not a directed acyclic graph" << std::endl;
return;
}
if (marks[stage] == 0)
{
marks[stage] = 1;
for (auto nextStage : stages)
{
if (nextStage->requires(stage, false))
{
visit(nextStage);
}
}
marks[stage] = 2;
sorted.push_back(stage);
}
};
while (sorted.size() < stages.size())
{
for (auto stage : stages)
{
if (marks[stage] == 0)
{
visit(stage);
}
}
}
stages.swap(sorted);
}
} // namespace gloperate
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.